Programs & Examples On #Warehouse

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

String or binary data would be truncated. The statement has been terminated

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int)
RETURNS
AS
   SELECT ta.item, ta.warehouse, ta.price 
   FROM   stock ta
   WHERE  ta.price >= @price;

Of course, you could just use a normal SELECT statement..

@Cacheable key on multiple method arguments

After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}. This can also include null values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)

I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse) 
...

@Cacheable(value="bookCache", 
  key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...

Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:

<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />

...with:

public class CacheKeyGenerator 
  implements org.springframework.cache.interceptor.KeyGenerator {

    @Override
    public Object generate(final Object target, final Method method, 
      final Object... params) {

        final List<Object> key = new ArrayList<>();
        key.add(method.getDeclaringClass().getName());
        key.add(method.getName());

        for (final Object o : params) {
            key.add(o);
        }
        return key;
    }
}

javascript - pass selected value from popup window to parent window input box

use: opener.document.<id of document>.innerHTML = xmlhttp.responseText;

How to load data to hive from HDFS without removing the source file?

from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

create external table table_name (
  id int,
  myfields string
)
location '/my/location/in/hdfs';

Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

row format delimited fields terminated by ','

What is the difference between a database and a data warehouse?

See in simple words : Dataware --> Huge data using for Analytical/storage/ copy and Analysis . Database --> CRUD operation with Frequently used data .

Dataware house is Kind of storage which u are not using on daily basis & Database is something which your dealing frequently .

Eg. If we are asking statement of bank then it gives us for last 3/4/6/more months bcoz it is in database. If you want more than that it stores on Dataware house.

How to convert C# nullable int to int

It will assign value of v1 to v2 if it is not null, else it will take a default value as zero.

v2=v1??0

Or below is the other way to write it.

v2 = v1.HasValue?v1:0

How do I run pip on python for windows?

I have a Mac, but luckily this should work the same way:

pip is a command-line thing. You don't run it in python.

For example, on my Mac, I just say:

$pip install somelib

pretty easy!

How do I get the function name inside a function in PHP?

The accurate way is to use the __FUNCTION__ predefined magic constant.

Example:

class Test {
    function MethodA(){
        echo __FUNCTION__;
    }
}

Result: MethodA.

php form action php self

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">

</form>

Also, you can omit the action attribute and it will work as expected.

Can dplyr package be used for conditional mutating?

dplyr now has a function case_when that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor.

df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                     a %in% c(0,1,3,4) | c == 4 ~ 3L, 
                     TRUE~as.integer(NA)))

EDIT: If you're using dplyr::case_when() from before version 0.7.0 of the package, then you need to precede variable names with '.$' (e.g. write .$a == 1 inside case_when).

Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:

require(data.table) 
require(mosaic) 
require(dplyr)
require(microbenchmark)

set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)

DPLYR_case_when <- function(DF) {
  DF %>%
  mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                       a %in% c(0,1,3,4) | c==4 ~ 3L, 
                       TRUE~as.integer(NA)))
}

DT_fun <- function(DT) {
  DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
  DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
  mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
                    ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

mosa_fun <- function(DF) {
  mutate(DF, g = derivedFactor(
    "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
    "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
    .method = "first",
    .default = NA
  ))
}

perf_results <- microbenchmark(
  dt_fun <- DT_fun(copy(DT)),
  dplyr_ifelse <- DPLYR_fun(copy(DF)),
  dplyr_case_when <- DPLYR_case_when(copy(DF)),
  mosa <- mosa_fun(copy(DF)),
  times = 100L
)

This gives:

print(perf_results)
Unit: milliseconds
           expr        min         lq       mean     median         uq        max neval
         dt_fun   1.391402    1.560751   1.658337   1.651201   1.716851   2.383801   100
   dplyr_ifelse   1.172601    1.230351   1.331538   1.294851   1.390351   1.995701   100
dplyr_case_when   1.648201    1.768002   1.860968   1.844101   1.958801   2.207001   100
           mosa 255.591301  281.158350 291.391586 286.549802 292.101601 545.880702   100

Remove trailing newline from the elements of a string list

list comprehension? [x.strip() for x in lst]

Changing website favicon dynamically

Why not?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

python JSON only get keys in first level

A good way to check whether a python object is an instance of a type is to use isinstance() which is Python's 'built-in' function. For Python 3.6:

dct = {
       "1": "a", 
       "3": "b", 
       "8": {
            "12": "c", 
            "25": "d"
           }
      }

for key in dct.keys():
    if isinstance(dct[key], dict)== False:
       print(key, dct[key])
#shows:
# 1 a
# 3 b

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

How to initialize an array's length in JavaScript?

As explained above, using new Array(size) is somewhat dangerous. Instead of using it directly, place it inside an "array creator function". You can easily make sure that this function is bug-free and you avoid the danger of calling new Array(size) directly. Also, you can give it an optional default initial value. This createArray function does exactly that:

function createArray(size, defaultVal) {
    const arr = new Array(size);
    if (defaultVal !== undefined) {
        // optional default value
        for (let i = 0; i < size; ++i) {
            arr[i] = defaultVal;
        }
    }
    return arr;
}

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

How to Add a Dotted Underline Beneath HTML Text

You can try this method:

<h2 style="text-decoration: underline; text-underline-position: under; text-decoration-style: dotted">Hello World!</h2>

Please note that without text-underline-position: under; you still will have a dotted underline but this property will give it more breathing space.

This is assuming you want to embed everything inside an HTML file using inline styling and not to use a separate CSS file or tag.

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

Leaving another way here

git branch newbranch
git checkout master 
git merge newbranch 

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

How to move Docker containers between different hosts?

You cannot move a running docker container from one host to another.

You can commit the changes in your container to an image with docker commit, move the image onto a new host, and then start a new container with docker run. This will preserve any data that your application has created inside the container.

Nb: It does not preserve data that is stored inside volumes; you need to move data volumes manually to new host.

How to run Tensorflow on CPU

If the above answers don't work, try:

os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

Onclick event to remove default value in a text input field

In addition to placeholder="your text" you could also do onclick="this.value='';

So it would look something like:

<input name="Name" value="Enter Your Name" onclick="this.value='';>

How to remove leading zeros using C#

Using the following will return a single 0 when input is all 0.

string s = "0000000"
s = int.Parse(s).ToString();

How to change Angular CLI favicon

we can change angular CLI favicon icon. we have to put icon file in "assets" folder and give that path in index.html.

<link rel="icon" type="image/x-icon" href="./assets/images/favicon.png"> It's work for me.

How to convert object to Dictionary<TKey, TValue> in C#?

This code securely works to convert Object to Dictionary (having as premise that the source object comes from a Dictionary):

    private static Dictionary<TKey, TValue> ObjectToDictionary<TKey, TValue>(object source)
    {
        Dictionary<TKey, TValue> result = new Dictionary<TKey, TValue>();

        TKey[] keys = { };
        TValue[] values = { };

        bool outLoopingKeys = false, outLoopingValues = false;

        foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
        {
            object value = property.GetValue(source);
            if (value is Dictionary<TKey, TValue>.KeyCollection)
            {
                keys = ((Dictionary<TKey, TValue>.KeyCollection)value).ToArray();
                outLoopingKeys = true;
            }
            if (value is Dictionary<TKey, TValue>.ValueCollection)
            {
                values = ((Dictionary<TKey, TValue>.ValueCollection)value).ToArray();
                outLoopingValues = true;
            }
            if(outLoopingKeys & outLoopingValues)
            {
                break;
            }
        }

        for (int i = 0; i < keys.Length; i++)
        {
            result.Add(keys[i], values[i]);
        }

        return result;
    }

What are the special dollar sign shell variables?

  • $1, $2, $3, ... are the positional parameters.
  • "$@" is an array-like construct of all positional parameters, {$1, $2, $3 ...}.
  • "$*" is the IFS expansion of all positional parameters, $1 $2 $3 ....
  • $# is the number of positional parameters.
  • $- current options set for the shell.
  • $$ pid of the current shell (not subshell).
  • $_ most recent parameter (or the abs path of the command to start the current shell immediately after startup).
  • $IFS is the (input) field separator.
  • $? is the most recent foreground pipeline exit status.
  • $! is the PID of the most recent background command.
  • $0 is the name of the shell or shell script.

Most of the above can be found under Special Parameters in the Bash Reference Manual. There are all the environment variables set by the shell.

For a comprehensive index, please see the Reference Manual Variable Index.

Copy a file in a sane, safe and efficient way

With C++17 the standard way to copy a file will be including the <filesystem> header and using:

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to);

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,
                std::filesystem::copy_options options);

The first form is equivalent to the second one with copy_options::none used as options (see also copy_file).

The filesystem library was originally developed as boost.filesystem and finally merged to ISO C++ as of C++17.

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

Get to UIViewController from UIView?

It's surely a bad idea and a wrong design, but I'm sure we can all enjoy a Swift solution of the best answer proposed by @Phil_M:

static func firstAvailableUIViewController(fromResponder responder: UIResponder) -> UIViewController? {
    func traverseResponderChainForUIViewController(responder: UIResponder) -> UIViewController? {
        if let nextResponder = responder.nextResponder() {
            if let nextResp = nextResponder as? UIViewController {
                return nextResp
            } else {
                return traverseResponderChainForUIViewController(nextResponder)
            }
        }
        return nil
    }

    return traverseResponderChainForUIViewController(responder)
}

If your intention is to do simple things, as showing a modal dialog or tracking data, that doesn't justify the use of a protocol. I personally store this function in an utility object, you can use it from anything that implement the UIResponder protocol as:

if let viewController = MyUtilityClass.firstAvailableUIViewController(self) {}

All credit to @Phil_M

Can you change what a symlink points to after it is created?

AFAIK, no, you can't. You have to remove it and recreate it. Actually, you can overwrite a symlink and thus update the pathname referenced by it:

$ ln -s .bashrc test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 7 2009-09-23 17:12 test -> .bashrc
$ ln -s .profile test
ln: creating symbolic link `test': File exists
$ ln -s -f .profile test
$ ls -al test
lrwxrwxrwx 1 pascal pascal 8 2009-09-23 17:12 test -> .profile

EDIT: As the OP pointed out in a comment, using the --force option will make ln perform a system call to unlink() before symlink(). Below, the output of strace on my linux box proving it:

$ strace -o /tmp/output.txt ln -s -f .bash_aliases test
$ grep -C3 ^unlink /tmp/output.txt 
lstat64("test", {st_mode=S_IFLNK|0777, st_size=7, ...}) = 0
stat64(".bash_aliases", {st_mode=S_IFREG|0644, st_size=2043, ...}) = 0
symlink(".bash_aliases", "test")        = -1 EEXIST (File exists)
unlink("test")                          = 0
symlink(".bash_aliases", "test")        = 0
close(0)                                = 0
close(1)                                = 0

So I guess the final answer is "no".

EDIT: The following is copied from Arto Bendiken's answer over on unix.stackexchange.com, circa 2016.

This can indeed be done atomically with rename(2), by first creating the new symlink under a temporary name and then cleanly overwriting the old symlink in one go. As the man page states:

If newpath refers to a symbolic link the link will be overwritten.

In the shell, you would do this with mv -T as follows:

$ mkdir a b
$ ln -s a z
$ ln -s b z.new
$ mv -T z.new z

You can strace that last command to make sure it is indeed using rename(2) under the hood:

$ strace mv -T z.new z
lstat64("z.new", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
lstat64("z", {st_mode=S_IFLNK|0777, st_size=1, ...}) = 0
rename("z.new", "z")                    = 0

Note that in the above, both mv -T and strace are Linux-specific.

On FreeBSD, use mv -h alternately.

Editor's note: This is how Capistrano has done it for years now, ever since ~2.15. See this pull request.

How do I check to see if my array includes an object?

This ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
   @suggested_horses<< horse
end

Should probably be this ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
   @suggested_horses<< horse
end

How to do a JUnit assert on a message in a logger

Thanks a lot for these (surprisingly) quick and helpful answers; they put me on the right way for my solution.

The codebase were I want to use this, uses java.util.logging as its logger mechanism, and I don't feel at home enough in those codes to completely change that to log4j or to logger interfaces/facades. But based on these suggestions, I 'hacked-up' a j.u.l.handler extension and that works as a treat.

A short summary follows. Extend java.util.logging.Handler:

class LogHandler extends Handler
{
    Level lastLevel = Level.FINEST;

    public Level  checkLevel() {
        return lastLevel;
    }    

    public void publish(LogRecord record) {
        lastLevel = record.getLevel();
    }

    public void close(){}
    public void flush(){}
}

Obviously, you can store as much as you like/want/need from the LogRecord, or push them all into a stack until you get an overflow.

In the preparation for the junit-test, you create a java.util.logging.Logger and add such a new LogHandler to it:

@Test tester() {
    Logger logger = Logger.getLogger("my junit-test logger");
    LogHandler handler = new LogHandler();
    handler.setLevel(Level.ALL);
    logger.setUseParentHandlers(false);
    logger.addHandler(handler);
    logger.setLevel(Level.ALL);

The call to setUseParentHandlers() is to silence the normal handlers, so that (for this junit-test run) no unnecessary logging happens. Do whatever your code-under-test needs to use this logger, run the test and assertEquality:

    libraryUnderTest.setLogger(logger);
    methodUnderTest(true);  // see original question.
    assertEquals("Log level as expected?", Level.INFO, handler.checkLevel() );
}

(Of course, you would move large part of this work into a @Before method and make assorted other improvements, but that would clutter this presentation.)

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {
        ...
      }
    )
  }
  ...
}

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on pipable (previously known as lettable) operators for more info.

Executing Javascript from Python

quickjs should be the best option after quickjs come out. Just pip install quickjs and you are ready to go.

modify based on the example on README.

from quickjs import Function

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
escramble_758()
}
"""

escramble_758 = Function('escramble_758', js.replace("document.write", "return "))

print(escramble_758())

https://github.com/PetterS/quickjs

Changing Placeholder Text Color with Swift

Xcode 9.2 Swift 4

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

Query for documents where array size is greater than 1

You can use aggregate, too:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

// you add "size_of_name" to transit document and use it to filter the size of the name

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

What is the difference between Swing and AWT?

Swing vs AWT. Basically AWT came first and is a set of heavyweight UI components (meaning they are wrappers for operating system objects) whereas Swing built on top of AWT with a richer set of lightweight components.

Any serious Java UI work is done in Swing not AWT, which was primarily used for applets.

How to get the current location in Google Maps Android API v2?

Try This

public class MyLocationListener implements LocationListener
{

 @Override

public void onLocationChanged(Location loc)
{

loc.getLatitude();

loc.getLongitude();

String Text = “My current location is: ” +

“Latitud = ” + loc.getLatitude() +

“Longitud = ” + loc.getLongitude();

Toast.makeText( getApplicationContext(),Text,   Toast.LENGTH_SHORT).show();



tvlat.setText(“”+loc.getLatitude());

tvlong.setText(“”+loc.getLongitude());

this.gpsCurrentLocation();

}

Launching Spring application Address already in use

I was looking for a solution for Windows but didn't found any. Finally, figured out that that there is a dangling java application using the port. Maybe it's the earlier instance of the spring application and ended the process.

I used tcpview from Microsoft. It shows services/applications using which port on your computer.

enter image description here

You can end the process. And Done!

docker : invalid reference format

For others come to here:
If you happen to put your docker command in a file, say run.sh, check your line separator. In Linux, it should be LR, otherwise you would get the same error.

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Insert text with single quotes in PostgreSQL

In postgresql if you want to insert values with ' in it then for this you have to give extra '

 insert into test values (1,'user''s log');
 insert into test values (2,'''my users''');
 insert into test values (3,'customer''s');

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

Git stash pop- needs merge, unable to refresh index

Well, initially, we should know what caused the error to happen, then the solution will be easy. The reason have already been pointed out by the accepted answer, but it is somehow incomplete (also the solution).

The problem is, one or more files had conflict(s) previously, but Git sees them as unresolved. Yes, you might already edited those files and resolved the conflicts, but Git does not know about that. You should tell Git "Hey, there are no more conflicts from the previous merge!". Note that, the merge is not necessarily caused by a git merge, but also by a git stash pop, for example.

Remember, git status can tell you what Git knows now. If there are some unresolved merge conflicts to Git, then it is shown in a separated Unmerged paths section, with the files marked as both modified (always?). If you have noticed, this section is between two staged and unstaged sections. From this, I personally understand that, "Unmerged paths are those you should either move into staged or unstaged areas, as Git can work only with these two areas".

So, to tell Git the conflicts have been resolved, you should either move these changes to staged or unstaged areas. In recent versions of Git, when you do a git status, it tells you how (woah! You should ask yourself how you haven't seen this yet?):

$ git status
...
Unmerged paths:
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   path/to/file.txt
...

So, to stage it (and maybe commit it):

$ git add path/to/file.txt

And to make it unstaged (e.g. you don't want to commit it now):

$ git restore --staged path/to/file.txt

Note: Forgetting to write --staged option possibly could spawn a super-hungry dragon to eat your past two days, in the case of not using a good text-editor or IDE.

Note: While git restore command is experimental yet, it should be stable enough to be used (thanks to a comment by @VonC, refer to it for more details on that).

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

Programmatically Check an Item in Checkboxlist where text is equal to what I want

All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)

Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.

private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
    ListItem listItem = lst.Items.FindByValue(valueToSelect);
    //ListItem listItem = lst.Items.FindByText(valueToSelect);
    if (listItem != null) listItem.Selected = true;
}

//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`

SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`

The term 'ng' is not recognized as the name of a cmdlet

For VSCode Terminal First open cmd and install angular-cli as global

npm install -g @angular/cli

Then update your Environment Variables following this step

  1. win + s // this will open search box
  2. Type Edit Environment Variables
  3. Open Environment Variables
  4. Add %AppData%\npm inside PATH
  5. Click OK and close.

Now you can restart your VSCode and it will work as it will normally do.

How do I convert an existing callback API to promises?

es6-promisify converts callback-based functions to Promise-based functions.

const promisify = require('es6-promisify');

const promisedFn = promisify(callbackedFn, args);

Ref: https://www.npmjs.com/package/es6-promisify

macro - open all files in a folder

You have to add this line just before loop

    MyFile = Dir
Loop

How do you stop tracking a remote branch in Git?

You can delete the remote-tracking branch using

git branch -d -r origin/<remote branch name>

as VonC mentions above. However, if you keep your local copy of the branch, git push will still try to push that branch (which could give you a non-fast-forward error as it did for ruffin). This is because the config push.default defaults to matching which means:

matching - push all matching branches. All branches having the same name in both ends are considered to be matching. This is the default.

(see http://git-scm.com/docs/git-config under push.default)

Seeing as this is probably not what you wanted when you deleted the remote-tracking branch, you can set push.default to upstream (or tracking if you have git < 1.7.4.3)

upstream - push the current branch to its upstream branch.

using

git config push.default upstream

and git will stop trying to push branches that you have "stopped tracking."

Note: The simpler solution would be to just rename your local branch to something else. That would eliminate some potential for confusion, as well.

How to make MySQL table primary key auto increment with some prefix

Create a table with a normal numeric auto_increment ID, but either define it with ZEROFILL, or use LPAD to add zeroes when selecting. Then CONCAT the values to get your intended behavior. Example #1:

create table so (
 id int(3) unsigned zerofill not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', id) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

Example #2:

create table so (
 id int unsigned not null auto_increment primary key,
 name varchar(30) not null
);

insert into so set name = 'John';
insert into so set name = 'Mark';

select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id      | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+

java.lang.ClassNotFoundException on working app

I recently invested some time in a similar error report that reached me through the play store error reports.

An overview of some possible causes.

Missing Library

Since my app is tested before release and the issue only occurs approx. once a week I'm pretty sure mine isn’t a library issue. You should think in this direction if a build on your system fails and installing the app using ADB results in error on launch.

Cleaning and building your project could help if this is a local issue and make sure you have the latest version of both SDK and IDE.

In these cases it’s one class of your app or a library used in your app that triggers the error. This is an important difference with the next point where the entry point (Activity with MAIN intent or your custom service/Application object) of your app is not found.

If so look into the following questions & answers I’ve selected. They all have an accepted answer.

unable to instantiate application - ClassNotFoundException Android Activity ClassNotFoundException - tried everything Android ClassNotFoundException

Main Activity or Application not found

Misconfiguration of AndroidManifest.xml

More like a beginners mistake was quoted here before in one of the answers talking about the android manifest file.

Important here is that this error would always block your app from loading. It should build though but crash on the first use.

I’ve edited that answer, this is the important part:

Do not use the android:name attribute! unless you've implemented a custom Application object.

The application:name attribute has nothing to do with the name of your app. This is the name of a specific class to load as your Application instance. That's why you would get the ClassNotFoundException if that class wouldn't exist.

For the name of the app use the android:label attribute on this same application node instead.

Suppressed: java.io.IOException: unable to open DEX file

Now it’s getting interesting! This was part of the stack trace logged in my case through the playstore. So I can create a build and execute that on my device without errors (whereas all previous errors would prevent any run).

An important comment was made to the following SO question Android Application ClassNotFoundException, Unable to instantiate application

Looks like the system has trouble opening your application dex file java.io.IOException: unable to open DEX file, this is before any of your classes are loaded, so it doesn't have anything to do with how you define your application class in the Manifest. – user2046264 Feb 27 '14 at 2:25

The important part here is the suppressed IOException. This indicates that an IO operation failed. Examples of IO operations are network and storage calls.

Another error report that goes into that direction is listed at Android to Unable to instantiate Application java.lang.ClassNotFoundException: where the role of the external storage provided by an sdcard is mentioned.

Some other similar questions indicate that this can be a user error. "/mnt/asec/..." indicates that the app is running from the sdcard. If the sdcard is removed it could cause this error. 3rd party apps or rooted devices can probably move an app to the sdcard even if its not allowed by the manifest.

If you’re desperate read all the answers to that question since there are some other paths listed also. Think of full package specification, use of singletons and more.

The point here is that both network and storage are IO.

For my specific case I checked all the devices that reported this error and found that they all have external storage support. So a user could install the app and move it to external storage, have the SD card removed and get this error (just a theory, not tested).

For more info on the installLocation options see http://developer.android.com/guide/topics/data/install-location.html

I also considered the network. On top of the stack trace detail page at the play store reports you get an overview of the occurrences of the error over time.

It appeared to me that the error occurred more around the times an update was released. This could support the theory that the user gets an update of the app, downloads this update that somehow gets corrupted. The installation goes fine but the first execution of the app results in the error (again just a theory, not tested).

Other resources

Finally 2 non SO resources that might help you:

https://groups.google.com/forum/#!topic/android-developers/JC7_qqwBRjo https://code.google.com/p/android/issues/detail?id=72121

How to center-justify the last line of text in CSS?

Solution (not the best, but still working for some cases) for non-dinamic text with fixed width.Usefull for situations when there are a little space to "stretch" text to the end of the penultimate line. Make some symbols in the end of the paragraph (experiment with their length) and hide it; apply to the paragraph absolute position or just correct free space with padding/marging.

Good compabitity/crossbrowser way for center-justifying text.

Example (paragraph before):

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
}_x000D_
_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna,<br><center>vel scelerisque nisl consectetur et.</center></div>
_x000D_
_x000D_
_x000D_

And after the fix:

_x000D_
_x000D_
.paragraph {_x000D_
    width:455px;_x000D_
    text-align:justify;_x000D_
    position:relative;_x000D_
}_x000D_
.center{_x000D_
  display:block;_x000D_
  text-align:center;_x000D_
  margin-top:-17px;_x000D_
}_x000D_
.paragraph b{_x000D_
  opacity:0;_x000D_
_x000D_
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";_x000D_
filter: alpha(opacity=0);_x000D_
-moz-opacity: 0;_x000D_
-khtml-opacity: 0;_x000D_
}
_x000D_
<div class="paragraph">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Nullam id dolor id nibh ultricies vehicula ut id elit. Etiam porta sem malesuada magna mollis euismod. Nullam id dolor id nibh ultricies vehicula ut id elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, <b>__</b><br><div class="center">vel scelerisque nisl consectetur et.</div></div>
_x000D_
_x000D_
_x000D_

Global variables in c#.net

Use a public static class and access it from anywhere.

public static class MyGlobals {
    public const string Prefix = "ID_"; // cannot change
    public static int Total = 5; // can change because not const
}

used like so, from master page or anywhere:

string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();

You don't need to make an instance of the class; in fact you can't because it's static. new Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because const is implicitly static by nature.

The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)

You can make as many static classes as you like and name them whatever you want.


Sometimes programmers like to group their constants by using nested static classes. For example,

public static class Globals {
    public static class DbProcedures {
        public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
        public const string Sp_Get_Names = "dbo.[Get_First_Names]";
    }
    public static class Commands {
        public const string Go = "go";
        public const string SubmitPage = "submit_now";
    }
}

and access them like so:

MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;

Python Pandas iterate over rows and access column names

I also like itertuples()

for row in df.itertuples():
    print(row.A)
    print(row.Index)

since row is a named tuples, if you meant to access values on each row this should be MUCH faster

speed run :

df = pd.DataFrame([x for x in range(1000*1000)], columns=['A'])
st=time.time()
for index, row in df.iterrows():
    row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
    row.A
print(time.time() - st)
0.48400020599365234

bootstrap 4 file input doesn't show the file name

Johann-S solution works great. (And it looks like he created the awesome plugin)

The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input

Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.

$(document).ready(function () {
  bsCustomFileInput.init()
})

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Hey Please use / in your web.xml (instead of /*)

Where is my m2 folder on Mac OS X Mavericks

You can try searching for local .m2 repository by using the command in the project directory.

mvn help:evaluate -Dexpression=settings.localRepository

your output will be similar to below and you can see local .m2 directory path as shown below: /Users/arai/.m2/repository

Downloading from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar
Downloaded from central: https://repo.maven.apache.org/maven2/net/sf/jtidy/jtidy/r938/jtidy-r938.jar (250 kB at 438 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar (335 kB at 530 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar (305 kB at 430 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/commons/commons-lang3/3.7/commons-lang3-3.7.jar (500 kB at 595 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar (621 kB at 671 kB/s)
[INFO] No artifact parameter specified, using 'org.apache.maven:standalone-pom:pom:1' as project.
[INFO]
/Users/arai/.m2/repository
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.540 s
[INFO] Finished at: 2019-01-23T13:57:54-05:00
[INFO] ------------------------------------------------------------------------

What is Linux’s native GUI API?

The linux kernel graphical operations are in /include/linux/fb.h as struct fb_ops. Eventually this is what add-ons like X11, Wayland, or DRM appear to reference. As these operations are only for video cards, not vector or raster hardcopy or tty oriented terminal devices, their usefulness as a GUI is limited; it's just not entirely true you need those add-ons to get graphical output if you don't mind using some assembler to bypass syscall as necessary.

Command line input in Python

If you're using Python 3, raw_input has changed to input

Python 3 example:

line = input('Enter a sentence:')

Android intent for playing video?

from the debug info, it seems that the VideoIntent from the MainActivity cannot send the path of the video to VideoActivity. It gives a NullPointerException error from the uriString. I think some of that code from VideoActivity:

Intent myIntent = getIntent();
String uri = myIntent.getStringExtra("uri");
Bundle b = myIntent.getExtras();

startVideo(b.getString(uri));

Cannot receive the uri from here:

public void playsquirrelmp4(View v) {
    Intent VideoIntent = (new Intent(this, VideoActivity.class));
    VideoIntent.putExtra("android.resource://" + getPackageName()
        + "/"+   R.raw.squirrel, uri);
    startActivity(VideoIntent);
}

Xcode project not showing list of simulators

Install iOS Simulator if you're missing one.

Click here to see how.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.

Perform followings steps to do the needful.

  1. Get Name of all Constraints using sp_helpconstraint which is a system stored procedure utility - execute following exec sp_helpconstraint '<your table name>'
  2. Once you get the name of the constraint then copy that constraint name and execute next statement i.e alter table <your_table_name> drop constraint <constraint_name_that_you_copied_in_1> (It'll be something like this only or similar format)
  3. Once you delete the constraint then you can delete 1 or more columns by using conventional method i.e Alter table <YourTableName> Drop column column1, column2 etc

How get all values in a column using PHP?

Here is a simple way to do this using either PDO or mysqli

$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);

or, using mysqli

$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
    $array[] = $row['column'];
}
print_r($array);

Array
(
    [0] => 7960
    [1] => 7972
    [2] => 8028
    [3] => 8082
    [4] => 8233
)

How to start automatic download of a file in Internet Explorer?

I hate when sites complicate download so much and use hacks instead of a good old link.

Dead simple version:

<a href="file.zip">Start automatic download!</a>

It works! In every browser!


If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it):

<a href="report-generator.php" download="result.xls">Download</a>

Version with a "thanks" page:

If you want to display "thanks" after download, then use:

<a href="file.zip" 
   onclick="if (event.button==0) 
     setTimeout(function(){document.body.innerHTML='thanks!'},500)">
 Start automatic download!
</a>

Function in that setTimeout might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location or activate other links).

The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited color, doesn't re-download if page is left open after browser restart, etc.

That's what I use for ImageOptim

Convert python datetime to epoch with strftime

if you just need a timestamp in unix /epoch time, this one line works:

created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L

and depends only on datetime works in python2 and python3

Using an integer as a key in an associative array in JavaScript

Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:

var test = {}
test[2300] = 20;
console.log(test["2300"]);

Resolving instances with ASP.NET Core DI from within ConfigureServices

The IServiceCollection interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider instance which you can use to resolve services. You can inject an IServiceProvider into any class. The IApplicationBuilder and HttpContext classes can provide the service provider as well, via their ApplicationServices or RequestServices properties respectively.

IServiceProvider defines a GetService(Type type) method to resolve a service:

var service = (IFooService)serviceProvider.GetService(typeof(IFooService));

There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>() (add a using for Microsoft.Extensions.DependencyInjection).

Resolving services inside the startup class

Injecting dependencies

The runtime's hosting service provider can inject certain services into the constructor of the Startup class, such as IConfiguration, IWebHostEnvironment (IHostingEnvironment in pre-3.0 versions), ILoggerFactory and IServiceProvider. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.

The ConfigureServices() method does not allow injecting services, it only accepts an IServiceCollection argument. This makes sense because ConfigureServices() is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    // Use Configuration here
}

Any services registered in ConfigureServices() can then be injected into the Configure() method; you can add an arbitrary number of services after the IApplicationBuilder parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IFooService>();
}

public void Configure(IApplicationBuilder app, IFooService fooService)
{
    fooService.Bar();
}

Manually resolving dependencies

If you need to manually resolve services, you should preferably use the ApplicationServices provided by IApplicationBuilder in the Configure() method:

public void Configure(IApplicationBuilder app)
{
    var serviceProvider = app.ApplicationServices;
    var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}

It is possible to pass and directly use an IServiceProvider in the constructor of your Startup class, but as above this will contain a limited subset of services, and thus has limited utility:

public Startup(IServiceProvider serviceProvider)
{
    var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}

If you must resolve services in the ConfigureServices() method, a different approach is required. You can build an intermediate IServiceProvider from the IServiceCollection instance which contains the services which have been registered up to that point:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IFooService, FooService>();

    // Build the intermediate service provider
    var sp = services.BuildServiceProvider();

    // This will succeed.
    var fooService = sp.GetService<IFooService>();
    // This will fail (return null), as IBarService hasn't been registered yet.
    var barService = sp.GetService<IBarService>();
}

Please note: Generally you should avoid resolving services inside the ConfigureServices() method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions> instance. You can accomplish this by binding the values from the IConfiguration instance to an instance of MyOptions (which is essentially what the options framework does):

public void ConfigureServices(IServiceCollection services)
{
    var myOptions = new MyOptions();
    Configuration.GetSection("SomeSection").Bind(myOptions);
}

Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.

String comparison - Android

In Java we don't compare string as you are doing above... Here is String comparison...

    if (gender.equalsIgnoreCase("Male")) {
        salutation = "Mr.";
    } else if (gender.equalsIgnoreCase("Female")) {
        salutation = "Ms.";
    }

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

python dict to numpy structured array

Let me propose an improved method when the values of the dictionnary are lists with the same lenght :

import numpy

def dctToNdarray (dd, szFormat = 'f8'):
    '''
    Convert a 'rectangular' dictionnary to numpy NdArray
    entry 
        dd : dictionnary (same len of list 
    retrun
        data : numpy NdArray 
    '''
    names = dd.keys()
    firstKey = dd.keys()[0]
    formats = [szFormat]*len(names)
    dtype = dict(names = names, formats=formats)
    values = [tuple(dd[k][0] for k in dd.keys())]
    data = numpy.array(values, dtype=dtype)
    for i in range(1,len(dd[firstKey])) :
        values = [tuple(dd[k][i] for k in dd.keys())]
        data_tmp = numpy.array(values, dtype=dtype)
        data = numpy.concatenate((data,data_tmp))
    return data

dd = {'a':[1,2.05,25.48],'b':[2,1.07,9],'c':[3,3.01,6.14]}
data = dctToNdarray(dd)
print data.dtype.names
print data

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

This is a late answer, but I just came across this... To get the indenting correct on any lines that wrap, try it this way:

ul {
  list-style: none;
  margin-left: 0;
  padding-left: 0;
}

li {
  padding-left: 1em;
  text-indent: -1em;
}

li:before {
  content: "+";
  padding-right: 5px;
}

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

I have seen this error , for me the issue was there was a space in the absolute path of the persistance.xml , removal of the same helped me.

Copy existing project with a new name in Android Studio

In Android Studio 4.0 you need only these few steps:

  • in File Manager copy the project directory and rename the new one
  • enter in it and change applicationId inside app/build.gradle
  • open the existing new project in Android Studio
  • open one class file and highlight the package name part to change (e.g. from com.domain.appname to com.domain.newappname highlight appname)
  • right click on it -> "refactor" -> "rename"
  • choose "rename package"
  • in the dialog choose "Scope: all places" and click "preview" or "refactor"

Extract / Identify Tables from PDF python

After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!

I hope you are using Linux;

pdftotext -layout NAME_OF_PDF.pdf

AMAZING!!

Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..

It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!

Using COALESCE to handle NULL values in PostgreSQL

You can use COALESCE in conjunction with NULLIF for a short, efficient solution:

COALESCE( NULLIF(yourField,'') , '0' )

The NULLIF function will return null if yourField is equal to the second value ('' in the example), making the COALESCE function fully working on all cases:

                 QUERY                     |                RESULT 
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null  ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF(''    ,''),'0')     |                 '0'
SELECT COALESCE(NULLIF('foo' ,''),'0')     |                 'foo'

Database, Table and Column Naming Conventions?

I work in a database support team with three DBAs and our considered options are:

  1. Any naming standard is better than no standard.
  2. There is no "one true" standard, we all have our preferences
  3. If there is standard already in place, use it. Don't create another standard or muddy the existing standards.

We use singular names for tables. Tables tend to be prefixed with the name of the system (or its acronym). This is useful if the system complex as you can change the prefix to group the tables together logically (ie. reg_customer, reg_booking and regadmin_limits).

For fields we'd expect field names to be include the prefix/acryonm of the table (i.e. cust_address1) and we also prefer the use of a standard set of suffixes ( _id for the PK, _cd for "code", _nm for "name", _nb for "number", _dt for "Date").

The name of the Foriegn key field should be the same as the Primary key field.

i.e.

SELECT cust_nm, cust_add1, booking_dt
FROM reg_customer
INNER JOIN reg_booking
ON reg_customer.cust_id = reg_booking.cust_id

When developing a new project, I'd recommend you write out all the preferred entity names, prefixes and acronyms and give this document to your developers. Then, when they decide to create a new table, they can refer to the document rather than "guess" what the table and fields should be called.

How to replace a set of tokens in a Java String?

Unfortunately the comfortable method String.format mentioned above is only available starting with Java 1.5 (which should be pretty standard nowadays, but you never know). Instead of that you might also use Java's class MessageFormat for replacing the placeholders.

It supports placeholders in the form '{number}', so your message would look like "Hello {0} Please find attached {1} which is due on {2}". These Strings can easily be externalized using ResourceBundles (e. g. for localization with multiple locales). The replacing would be done using the static'format' method of class MessageFormat:

String msg = "Hello {0} Please find attached {1} which is due on {2}";
String[] values = {
  "John Doe", "invoice #123", "2009-06-30"
};
System.out.println(MessageFormat.format(msg, values));

How to manually send HTTP POST requests from Firefox or Chrome browser?

Try Runscope. A free tool sampling their service is provided at https://www.hurl.it/ . You can set the method, authentication, headers, parameters, and body. Response shows status code, headers, and body. The response body can be formatted from JSON with a collapsable heirarchy. Paid accounts can automate test API calls and use return data to build new test calls. COI disclosure: I have no relationship to Runscope.

Close a MessageBox after several seconds

Try the following approach:

AutoClosingMessageBox.Show("Text", "Caption", 1000);

Where the AutoClosingMessageBox class implemented as following:

public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        using(_timeoutTimer)
            MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout) {
        new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Update: If you want to get the return value of the underlying MessageBox when user selects something before the timeout you can use the following version of this code:

var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);
if(userResult == System.Windows.Forms.DialogResult.Yes) { 
    // do something
}
...
public class AutoClosingMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
    }
    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }
    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        _result = _timerResult;
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Yet another Update

I have checked the @Jack's case with YesNo buttons and discovered that the approach with sending the WM_CLOSE message does not work at all.
I will provide a fix in the context of the separate AutoclosingMessageBox library. This library contains redesigned approach and, I believe, can be useful to someone.
It also available via NuGet package:

Install-Package AutoClosingMessageBox

Release Notes (v1.0.0.2):
- New Show(IWin32Owner) API to support most popular scenarios (in the context of #1 );
- New Factory() API to provide full control on MessageBox showing;

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

Connect with SSH through a proxy

Here's how to do Richard Christensen's answer as a one-liner, no file editing required (replace capitalized with your own settings, PROXYPORT is frequently 80):

 ssh USER@FINAL_DEST -o "ProxyCommand=nc -X connect -x PROXYHOST:PROXYPORT %h %p"

You can use the same -o ... option for scp as well, see https://superuser.com/a/752621/39364

If you get this in OS X:

 nc: invalid option -- X
 Try `nc --help' for more information.

it may be that you're accidentally using the homebrew version of netcat (you can see by doing a which -a nc command--/usr/bin/nc should be listed first). If there are two then one workaround is to specify the full path to the nc you want, like ProxyCommand=/usr/bin/nc ...

For CentOS nc has the same problem of invalid option --X. connect-proxy is an alternative, easy to install using yum and works --

ssh -o ProxyCommand="connect-proxy -S PROXYHOST:PROXYPORT %h %p" USER@FINAL_DEST

How do I disable form resizing for users?

I would set the maximum size, minimum size and remove the gripper icon of the window.

Set properties (MaximumSize, MinimumSize, and SizeGripStyle):

this.MaximumSize = new System.Drawing.Size(500, 550);
this.MinimumSize = new System.Drawing.Size(500, 550);
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;

Select data between a date/time range

You must search date defend on how you insert that game_date data on your database.. for example if you inserted date value on long date or short.

SELECT * FROM hockey_stats WHERE game_date >= "6/11/2018" AND game_date <= "6/17/2018"

You can also use BETWEEN:

SELECT * FROM hockey_stats WHERE game_date BETWEEN "6/11/2018" AND "6/17/2018"

simple as that.

Limiting Python input strings to certain characters and lengths

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

print "Your input was:", input_str

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

Keep in mind that it's the user that is running the oracle database that must have write permissions to the /defaultdir directory, not the user logged into oracle. Typically you're running the database as the user "Oracle". It's not the same user (necessarily) that you created the external table with.

Check your directory permissions, too.

How to fetch all Git branches

For Windows users using PowerShell:

git branch -r | ForEach-Object {
    # Skip default branch, this script assumes
    # you already checked-out that branch when cloned the repo
    if (-not ($_ -match " -> ")) {
        $localBranch = ($_ -replace "^.*?/", "")
        $remoteBranch = $_.Trim()
        git branch --track "$localBranch" "$remoteBranch"
    }
}
git fetch --all
git pull --all

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Extract only right most n letters from a string

I use the Min to prevent the negative situations and also handle null strings

// <summary>
    /// Returns a string containing a specified number of characters from the right side of a string.
    /// </summary>
    public static string Right(this string value, int length)
    {
        string result = value;
        if (value != null)
            result = value.Substring(0, Math.Min(value.Length, length));
        return result;
    }

How to add click event to a iframe with JQuery

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

Multi-key dictionary in c#?

I've googled for this one: http://www.codeproject.com/KB/recipes/multikey-dictionary.aspx. I guess it's main feature compared to using struct to contain 2 keys in regular dictionary is that you can later reference by one of the keys, instead of having to supply 2 keys.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

How to access to the parent object in c#

I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

os.walk without digging into directories below

Use the walklevel function.

import os

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go.

How to enable CORS in AngularJs

Try using the resource service to consume flickr jsonp:

var MyApp = angular.module('MyApp', ['ng', 'ngResource']);

MyApp.factory('flickrPhotos', function ($resource) {
    return $resource('http://api.flickr.com/services/feeds/photos_public.gne', { format: 'json', jsoncallback: 'JSON_CALLBACK' }, { 'load': { 'method': 'JSONP' } });
});

MyApp.directive('masonry', function ($parse) {
    return {
        restrict: 'AC',
        link: function (scope, elem, attrs) {
            elem.masonry({ itemSelector: '.masonry-item', columnWidth: $parse(attrs.masonry)(scope) });
        }
    };        
});

MyApp.directive('masonryItem', function () {
    return {
        restrict: 'AC',
        link: function (scope, elem, attrs) {
            elem.imagesLoaded(function () {
               elem.parents('.masonry').masonry('reload');
            });
        }
    };        
});

MyApp.controller('MasonryCtrl', function ($scope, flickrPhotos) {
    $scope.photos = flickrPhotos.load({ tags: 'dogs' });
});

Template:

<div class="masonry: 240;" ng-controller="MasonryCtrl">
    <div class="masonry-item" ng-repeat="item in photos.items">
        <img ng-src="{{ item.media.m }}" />
    </div>
</div>

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is right way to do it.

String s = "something", t = "maybe something else";
 if (s == t)      // Legal, but usually results WRONG.
 if (s.equals(t)) // RIGHT way to check the two strings
  /* == will fail in following case:*/
 String s1 = new String("abc");
 String s2 = new String("abc");

 if(s1==s2) //it will return false

Best way to check if an PowerShell Object exist?

I had the same Problem. This solution works for me.

$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
    $Word = new-object -ComObject word.application
}

https://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.getactiveobject(v=vs.110).aspx

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

Make sure you don't add or uncomment the AllowNoPassword option after the $i++ line.

/* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */

 $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

throwing exceptions out of a destructor

From the ISO draft for C++ (ISO/IEC JTC 1/SC 22 N 4411)

So destructors should generally catch exceptions and not let them propagate out of the destructor.

3 The process of calling destructors for automatic objects constructed on the path from a try block to a throw- expression is called “stack unwinding.” [ Note: If a destructor called during stack unwinding exits with an exception, std::terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]

How to know Hive and Hadoop versions from command prompt?

$ hive --version
Hive version 0.8.1.3

EDIT: added another '-' before the version. Doesn't work for newer versions. Hope it works for all now.

Known to work in the following distributions:

  • HortonWorks distribution: $ hive --version Hive 0.14.0.2.2.0.0-2041
  • CDH 5.3

It does not work:

  • CDH 4.3
  • HDinsight (Azure)

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

How to export data to CSV in PowerShell?

simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8

so use it so:

$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8

-Append is required if you want to write in the file more then once.

Is there a decent wait function in C++?

Lots of people have suggested POSIX sleep, Windows Sleep, Windows system("pause"), C++ cin.get()… there's even a DOS getch() in there, from roughly the late 1920s.

Please don't do any of these.

None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)

Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.

Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.

An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram> or <myprogram>, to cmd.exe /K <myprogram>. The /K switch to cmd.exe makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.


I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.

What is the difference between 'git pull' and 'git fetch'?

Trying to be clear and simple.

The git pull command is actually a shortcut for git fetch followed by the git merge or the git rebase command depending on your configuration. You can configure your Git repository so that git pull is a fetch followed by a rebase.

Why does Node.js' fs.readFile() return a buffer instead of string?

Async:

fs.readFile('test.txt', 'utf8', callback);

Sync:

var content = fs.readFileSync('test.txt', 'utf8');

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

Searching if value exists in a list of objects using Linq

Using Linq you have many possibilities, here one without using lambdas:

//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
         where customer.FirstName == "John"
         select customer).Any();

Passing Parameters JavaFX FXML

I realize this is a very old post and has some great answers already, but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.

In this example, we will use 5 files:

  1. Main.java - Simply used to start the application and call the first controller.
  2. Controller1.java - The controller for the first FXML layout.
  3. Controller2.java - The controller for the second FXML layout.
  4. Layout1.fxml - The FXML layout for the first scene.
  5. Layout2.fxml - The FXML layout for the second scene.

All files are listed in their entirety at the bottom of this post.

The Goal: To demonstrate passing values from Controller1 to Controller2 and vice versa.

The Program Flow:

  • The first scene contains a TextField, a Button, and a Label. When the Button is clicked, the second window is loaded and displayed, including the text entered in the TextField.
  • Within the second scene, there is also a TextField, a Button, and a Label. The Label will display the text entered in the TextField on the first scene.
  • Upon entering text in the second scene's TextField and clicking its Button, the first scene's Label is updated to show the entered text.

This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.

The code itself is also commented with some details of what is happening and how.

THE CODE

Main.java:

import javafx.application.Application;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Create the first controller, which loads Layout1.fxml within its own constructor
        Controller1 controller1 = new Controller1();

        // Show the new stage
        controller1.showStage();

    }
}

Controller1.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller1 {

    // Holds this controller's Stage
    private final Stage thisStage;

    // Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
    @FXML
    private TextField txtToSecondController;
    @FXML
    private Button btnOpenLayout2;
    @FXML
    private Label lblFromController2;

    public Controller1() {

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout1");

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

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    /**
     * The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
     */
    @FXML
    private void initialize() {

        // Add an action for the "Open Layout2" button
        btnOpenLayout2.setOnAction(event -> openLayout2());
    }

    /**
     * Performs the action of loading and showing Layout2
     */
    private void openLayout2() {

        // Create the second controller, which loads its own FXML file. We pass a reference to this controller
        // using the keyword [this]; that allows the second controller to access the methods contained in here.
        Controller2 controller2 = new Controller2(this);

        // Show the new stage/window
        controller2.showStage();

    }

    /**
     * Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
     */
    public String getEnteredText() {
        return txtToSecondController.getText();
    }

    /**
     * Allows other controllers to set the text of this layout's Label
     */
    public void setTextFromController2(String text) {
        lblFromController2.setText(text);
    }
}

Controller2.java:

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.IOException;

public class Controller2 {

    // Holds this controller's Stage
    private Stage thisStage;

    // Will hold a reference to the first controller, allowing us to access the methods found there.
    private final Controller1 controller1;

    // Add references to the controls in Layout2.fxml
    @FXML
    private Label lblFromController1;
    @FXML
    private TextField txtToFirstController;
    @FXML
    private Button btnSetLayout1Text;

    public Controller2(Controller1 controller1) {
        // We received the first controller, now let's make it usable throughout this controller.
        this.controller1 = controller1;

        // Create the new stage
        thisStage = new Stage();

        // Load the FXML file
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));

            // Set this class as the controller
            loader.setController(this);

            // Load the scene
            thisStage.setScene(new Scene(loader.load()));

            // Setup the window/stage
            thisStage.setTitle("Passing Controllers Example - Layout2");

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

    /**
     * Show the stage that was loaded in the constructor
     */
    public void showStage() {
        thisStage.showAndWait();
    }

    @FXML
    private void initialize() {

        // Set the label to whatever the text entered on Layout1 is
        lblFromController1.setText(controller1.getEnteredText());

        // Set the action for the button
        btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
    }

    /**
     * Calls the "setTextFromController2()" method on the first controller to update its Label
     */
    private void setTextOnLayout1() {
        controller1.setTextFromController2(txtToFirstController.getText());
    }

}

Layout1.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToSecondController"/>
            <Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
        </HBox>
        <VBox alignment="CENTER">
            <Label text="Text From Controller2:"/>
            <Label fx:id="lblFromController2" text="Nothing Yet!"/>
        </VBox>
    </VBox>
</AnchorPane>

Layout2.fxml:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
    <VBox alignment="CENTER" spacing="10.0">
        <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
        </padding>
        <Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
        <VBox alignment="CENTER">
            <Label text="Text From Controller1:"/>
            <Label fx:id="lblFromController1" text="Nothing Yet!"/>
        </VBox>
        <HBox alignment="CENTER_LEFT" spacing="10.0">
            <Label text="Enter Text:"/>
            <TextField fx:id="txtToFirstController"/>
            <Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
        </HBox>
    </VBox>
</AnchorPane>

How to call a SOAP web service on Android

I would suggest checking out a very useful tool that helped me a lot. The guys who take care of that project were very helpful, too. www.wsdl2code.com/

How to write to a CSV line by line?

What about this:

with open("your_csv_file.csv", "w") as f:
    f.write("\n".join(text))

str.join() Return a string which is the concatenation of the strings in iterable. The separator between elements is the string providing this method.

How to use multiple LEFT JOINs in SQL?

Yes, but the syntax is different than what you have

SELECT
    <fields>
FROM
    <table1>
    LEFT JOIN <table2>
        ON <criteria for join>
        AND <other criteria for join>
    LEFT JOIN <table3> 
        ON <criteria for join>
        AND <other criteria for join>

How to get error information when HttpWebRequest.GetResponse() fails

I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.

The Response property on WebException will be of type FtpWebResponse on which you can check its StatusCode property to see which FTP error you have.

Here's the code I ended up with:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

ExpressJS - throw er Unhandled error event

If you're on Linux, this problem can also occur if Nodejs is not running as root.

Change from this:

nodejs /path/to/script.js

To this:

sudo nodejs /path/to/script.js

Just happened to me and none of the other suggestions here fixed it. Luckily I remembered the script was working the other day when running as root. Hope this helps someone!

Disclaimer: This probably isn't the best solution for a production environment. Starting your service as root may introduce some security holes to your server/application. In my case, this was a solution for a local service, but I'd encourage others to spend some more time trying to isolate the cause.

How to Display blob (.pdf) in an AngularJS app

Adding responseType to the request that is made from angular is indeed the solution, but for me it didn't work until I've set responseType to blob, not to arrayBuffer. The code is self explanatory:

    $http({
            method : 'GET',
            url : 'api/paperAttachments/download/' + id,
            responseType: "blob"
        }).then(function successCallback(response) {
            console.log(response);
             var blob = new Blob([response.data]);
             FileSaver.saveAs(blob, getFileNameFromHttpResponse(response));
        }, function errorCallback(response) {   
        });

Using DataContractSerializer to serialize, but can't deserialize back

Other solution is:

public static T Deserialize<T>(string rawXml)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(rawXml)))
    {
        DataContractSerializer formatter0 = 
            new DataContractSerializer(typeof(T));
        return (T)formatter0.ReadObject(reader);
    }
}

One remark: sometimes it happens that raw xml contains e.g.:

<?xml version="1.0" encoding="utf-16"?>

then of course you can't use UTF8 encoding used in other examples..

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

Can Windows Containers be hosted on linux?

Unlike Virtualization, containerization uses the same host os. So the container built on linux can not be run on windows and vice versa.

In windows, you have to take help of virtuallization (using Hyper-v) to have same os as your containers's os and then you should be able to run the same.

Docker for windows is similar app which is built on Hyper-v and helps in running linux docker container on windows. But as far as I know, there is nothing as such which helps run windows containers on linux.

Filtering a list of strings based on contents

This simple filtering can be achieved in many ways with Python. The best approach is to use "list comprehensions" as follows:

>>> lst = ['a', 'ab', 'abc', 'bac']
>>> [k for k in lst if 'ab' in k]
['ab', 'abc']

Another way is to use the filter function. In Python 2:

>>> filter(lambda k: 'ab' in k, lst)
['ab', 'abc']

In Python 3, it returns an iterator instead of a list, but you can cast it:

>>> list(filter(lambda k: 'ab' in k, lst))
['ab', 'abc']

Though it's better practice to use a comprehension.

Linq Syntax - Selecting multiple columns

 var employee =  (from res in _db.EMPLOYEEs
 where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
 select new {res.EMAIL, res.USERNAME} );

OR you can use

 var employee =  (from res in _db.EMPLOYEEs
 where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
 select new {email=res.EMAIL, username=res.USERNAME} );

Explanation :

  1. Select employee from the db as res.

  2. Filter the employee details as per the where condition.

  3. Select required fields from the employee object by creating an Anonymous object using new { }

How to make an HTML back link?

The easiest way is to use history.go(-1);

Try this:

_x000D_
_x000D_
<a href="#" onclick="history.go(-1)">Go Back</a>
_x000D_
_x000D_
_x000D_

How to avoid using Select in Excel VBA

I noticed that none of these answers mention the .Offset Property. This also can be used to avoid using the Select action when manipulating certain cells, particularly in reference to a selected cell (as the OP mentions with ActiveCell).

Here are a couple examples.

I will also assume the "ActiveCell" is J4.

ActiveCell.Offset(2, 0).Value = 12

  • This will change the cell J6 to be a value of 12
  • A minus -2 would have referenced J2

ActiveCell.Offset(0,1).Copy ActiveCell.Offset(,2)

  • This will copy the cell in k4 to L4.
  • Note that "0" is not needed in the offset parameter if not needed (,2)
  • Similar to the previous example a minus 1 would be i4

ActiveCell.Offset(, -1).EntireColumn.ClearContents

  • This will clear values in all cells in the column k.

These aren't to say they are "better" than the above options, but just listing alternatives.

How to disable sort in DataGridView?

It's very simple:

foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
    dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

How do I log a Python error with debug information?

If you use plain logs - all your log records should correspond this rule: one record = one line. Following this rule you can use grep and other tools to process your log files.

But traceback information is multi-line. So my answer is an extended version of solution proposed by zangw above in this thread. The problem is that traceback lines could have \n inside, so we need to do an extra work to get rid of this line endings:

import logging


logger = logging.getLogger('your_logger_here')

def log_app_error(e: BaseException, level=logging.ERROR) -> None:
    e_traceback = traceback.format_exception(e.__class__, e, e.__traceback__)
    traceback_lines = []
    for line in [line.rstrip('\n') for line in e_traceback]:
        traceback_lines.extend(line.splitlines())
    logger.log(level, traceback_lines.__str__())

After that (when you'll be analyzing your logs) you could copy / paste required traceback lines from your log file and do this:

ex_traceback = ['line 1', 'line 2', ...]
for line in ex_traceback:
    print(line)

Profit!

Remove all HTMLtags in a string (with the jquery text() function)

Another option:

 $("<p>").html(myContent).text();

MySQL query to get column names?

SHOW COLUMNS in mysql 5.1 (not 5.5) uses a temporary disk table.

So it can be considered slow for some cases. At least, it can bump up your created_tmp_disk_tables value. Imagine one temporary disk table per connection or per each page request.

SHOW COLUMNS is not really so slow, possibly because it uses file system cache. Phpmyadmin says ~0.5ms consistently. This is nothing compared to 500ms-1000ms of serving a wordpress page. But still, there are times it matters. There is a disk system involvement, you never know what happens when server is busy, cache is full, hdd is stalled etc.

Retrieving column names through SELECT * FROM ... LIMIT 1 was around ~0.1ms, and it can use query cache as well.

So here is my little optimized code to get column names from a table, without using show columns if possible:

function db_columns_ar($table)
{
//returns Array('col1name'=>'col1name','col2name'=>'col2name',...)
if(!$table) return Array();
if(!is_string($table)) return Array();

global $db_columns_ar_cache;
if(!empty($db_columns_ar_cache[$table]))
    return $db_columns_ar_cache[$table];


//IMPORTANT show columns creates a temp disk table
$cols=Array();
$row=db_row_ar($q1="SELECT * FROM `$table` LIMIT 1");
if($row)
    {
    foreach($row as $name=>$val)
        $cols[$name]=$name;
    }
else
    {
    $coldata=db_rows($q2="SHOW COLUMNS FROM `$table`");
    if($coldata)
        foreach($coldata as $row)
            $cols[$row->Field]=$row->Field;
    }
$db_columns_ar_cache[$table]=$cols;
//debugexit($q1,$q2,$row,$coldata,$cols);
return $cols;
}

Notes:

  • As long as your tables first row does not contain megabyte range of data, it should work fine.
  • The function names db_rows and db_row_ar should be replaced with your specific database setup.

How to find the duration of difference between two dates in java?

This is a program I wrote, which gets the number of days between 2 dates(no time here).

import java.util.Scanner;
public class HelloWorld {
 public static void main(String args[]) {
  Scanner s = new Scanner(System.in);
  System.out.print("Enter starting date separated by dots: ");
  String inp1 = s.nextLine();
  System.out.print("Enter ending date separated by dots: ");
  String inp2 = s.nextLine();
  int[] nodim = {
   0,
   31,
   28,
   31,
   30,
   31,
   30,
   31,
   31,
   30,
   31,
   30,
   31
  };
  String[] inpArr1 = split(inp1);
  String[] inpArr2 = split(inp2);
  int d1 = Integer.parseInt(inpArr1[0]);
  int m1 = Integer.parseInt(inpArr1[1]);
  int y1 = Integer.parseInt(inpArr1[2]);
  int d2 = Integer.parseInt(inpArr2[0]);
  int m2 = Integer.parseInt(inpArr2[1]);
  int y2 = Integer.parseInt(inpArr2[2]);
  if (y1 % 4 == 0) nodim[2] = 29;
  int diff = m1 == m2 && y1 == y2 ? d2 - (d1 - 1) : (nodim[m1] - (d1 - 1));
  int mm1 = m1 + 1, mm2 = m2 - 1, yy1 = y1, yy2 = y2;
  for (; yy1 <= yy2; yy1++, mm1 = 1) {
   mm2 = yy1 == yy2 ? (m2 - 1) : 12;
   if (yy1 % 4 == 0) nodim[2] = 29;
   else nodim[2] = 28;
   if (mm2 == 0) {
    mm2 = 12;
    yy2 = yy2 - 1;
   }
   for (; mm1 <= mm2 && yy1 <= yy2; mm1++) diff = diff + nodim[mm1];
  }
  System.out.print("No. of days from " + inp1 + " to " + inp2 + " is " + diff);
 }
 public static String[] split(String s) {
  String[] retval = {
   "",
   "",
   ""
  };
  s = s + ".";
  s = s + " ";
  for (int i = 0; i <= 2; i++) {
   retval[i] = s.substring(0, s.indexOf("."));
   s = s.substring((s.indexOf(".") + 1), s.length());
  }
  return retval;
 }
}

http://pastebin.com/HRsjTtUf

Saving and Reading Bitmaps/Images from Internal memory in Android

Use the below code to save the image to internal directory.

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
         // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {           
            fos = new FileOutputStream(mypath);
       // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
              e.printStackTrace();
        } finally {
            try {
              fos.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
        } 
        return directory.getAbsolutePath();
    }

Explanation :

1.The Directory will be created with the given name. Javadocs is for to tell where exactly it will create the directory.

2.You will have to give the image name by which you want to save it.

To Read the file from internal memory. Use below code

private void loadImageFromStorage(String path)
{

    try {
        File f=new File(path, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView img=(ImageView)findViewById(R.id.imgPicker);
        img.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

}

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Encrypt and decrypt a String in java

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Here's an example that uses the class:

try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

Where to get this Java.exe file for a SQL Developer installation

Please provide full path >

In mines case it was E:\app\ankitmittal01\product\11.2.0\dbhome_1\jdk\bin\java.exe

From : http://www.javamadesoeasy.com/2015/07/oracle-11g-and-sql-developer.html

constant pointer vs pointer on a constant value

Above are great answers. Here is an easy way to remember this:

a is a pointer

*a is the value

Now if you say "const a" then the pointer is const. (i.e. char * const a;)

If you say "const *a" then the value is const. (i.e. const char * a;)

How to get html to print return value of javascript function?

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

Android Camera : data intent returns null

Probably because you had something like this?

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);                        
Uri fileUri =  CommonUtilities.getTBCameraOutputMediaFileUri();                  
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);                        
startActivityForResult(takePictureIntent, 2);

However you must not put the extra output into the intent, because then the data goes into the URI instead of the data variable. For that reason, you have to take the two lines in the middle out, so that you have

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 2);

That´s what caused the problem for me, hope that helped.

How can I get dictionary key as variable directly in Python (not by searching from value)?

if you just need to get a key-value from a simple dictionary like e.g:

os_type = {'ubuntu': '20.04'}

use popitem() method:

os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'

Check if current date is between two dates Oracle SQL

SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.* 
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS') 
ORDER BY emp_login_date

Can you find all classes in a package using reflection?

Google Guava 14 includes a new class ClassPath with three methods to scan for top level classes:

  • getTopLevelClasses()
  • getTopLevelClasses(String packageName)
  • getTopLevelClassesRecursive(String packageName)

See the ClassPath javadocs for more info.

`col-xs-*` not working in Bootstrap 4

In Bootstrap 4.3, col-xs-{value} is replaced by col-{value}

There is no change in sm, md, lg, xl remains the same.

.col-{value}
.col-sm-{value}
.col-md-{value}
.col-lg-{value}
.col-xl-{value}

Differences between Microsoft .NET 4.0 full Framework and Client Profile

A list of assemblies is available at Assemblies in the .NET Framework Client Profile on MSDN (the list is too long to include here).

If you're more interested in features, .NET Framework Client Profile on MSDN lists the following as being included:

  • common language runtime (CLR)
  • ClickOnce
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Entity Framework
  • Windows Workflow Foundation
  • Speech
  • XSLT support
  • LINQ to SQL
  • Runtime design libraries for Entity Framework and WCF Data Services
  • Managed Extensibility Framework (MEF)
  • Dynamic types
  • Parallel-programming features, such as Task Parallel Library (TPL), Parallel LINQ (PLINQ), and Coordination Data Structures (CDS)
  • Debugging client applications

And the following as not being included:

  • ASP.NET
  • Advanced Windows Communication Foundation (WCF) functionality
  • .NET Framework Data Provider for Oracle
  • MSBuild for compiling

What is the best way to get the minimum or maximum value from an Array of numbers?

Unless the array is sorted, that's the best you're going to get. If it is sorted, just take the first and last elements.

Of course, if it's not sorted, then sorting first and grabbing the first and last is guaranteed to be less efficient than just looping through once. Even the best sorting algorithms have to look at each element more than once (an average of O(log N) times for each element. That's O(N*Log N) total. A simple scan once through is only O(N).

If you are wanting quick access to the largest element in a data structure, take a look at heaps for an efficient way to keep objects in some sort of order.

Dynamic classname inside ngClass in angular 2

more elegant solution is to use && (using NgFor and its first, its free to use ur own matching tho):

    <div 
        *ngFor="let day of days;
                let first = first;"
        class="day"
        [ngClass]="first && ('day--' + day)"
    </div>

will turn out as:

class="day day--monday"

TypeError: 'NoneType' object is not iterable in Python

You're calling write_file with arguments like this:

write_file(foo, bar)

But you haven't defined 'foo' correctly, or you have a typo in your code so that it's creating a new empty variable and passing it in.

How to use ArrayList's get() method

ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

public Element get(int index)

Example : In below example we are getting few elements of an arraylist by using get method.

package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
   public static void main(String[] args) {
       ArrayList<String> al = new ArrayList<String>();
       al.add("pen");
       al.add("pencil");
       al.add("ink");
       al.add("notebook");
       al.add("book");
       al.add("books");
       al.add("paper");
       al.add("white board");

       System.out.println("First element of the ArrayList: "+al.get(0));
       System.out.println("Third element of the ArrayList: "+al.get(2));
       System.out.println("Sixth element of the ArrayList: "+al.get(5));
       System.out.println("Fourth element of the ArrayList: "+al.get(3));
   }
}

Output:

First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook

How to run function of parent window when child window closes?

Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer

How to check if Receiver is registered in Android?

You have several options

  1. You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.

  2. Create a class that extends the Receiver and there you can use:

    1. Singleton pattern for only have one instance of this class in your project.

    2. Implement the methods for know if the Receiver is register.

MySQL dump by query

Combining much of above here is my real practical example, selecting records based on both meterid & timestamp. I have needed this command for years. Executes really quickly.

mysqldump -uuser -ppassword main_dbo trHourly --where="MeterID =5406 AND TIMESTAMP<'2014-10-13 05:00:00'" --no-create-info --skip-extended-insert | grep  '^INSERT' > 5406.sql

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Go to Android SDK Manager and install the latest version of below two libraries

  1. Google Play Services
  2. Google Repository

disable textbox using jquery?

I'm guessing you probably want to bind a "click" event to a number of radio buttons, read the value of the clicked radiobutton and depending on the value, disable/enable a checkbox and or textbox.

function enableInput(class){
    $('.' + class + ':input').attr('disabled', false);
}

function disableInput(class){
    $('.' + class + ':input').attr('disabled', true);
}

$(document).ready(function(){
    $(".changeBoxes").click(function(event){
        var value = $(this).val();
        if(value == 'x'){
            enableInput('foo'); //with class foo
            enableInput('bar'); //with class bar
        }else{
            disableInput('foo'); //with class foo
            disableInput('bar'); //with class bar
        }
    });
});

What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

Rails does not use the stdlib's ERB by default, it uses erubis. Sources: this dev's comment, ActionView's gemspec, accepted merge request I did while writing this.

There are behavior differences between them, in particular on how the hyphen operators %- and -% work.

Documentation is scarce, Where is Ruby's ERB format "officially" defined? so what follows are empirical conclusions.

All tests suppose:

require 'erb'
require 'erubis'

When you can use -

  • ERB: you must pass - to trim_mode option of ERB.new to use it.
  • erubis: enabled by default.

Examples:

begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a' -%>\nb"  , nil, '-') .result == 'ab'  or raise
Erubis::Eruby.new("<%= 'a' -%>  \n b").result == 'a b' or raise

What -% does:

  • ERB: remove the next character if it is a newline.

  • erubis:

    • in <% %> (without =), - is useless because <% %> and <% -%> are the same. <% %> removes the current line if it only contains whitespaces, and does nothing otherwise.

    • in <%= -%> (with =):

      • remove the entire line if it only contains whitespaces
      • else, if there is a non-space before the tag, and only whitesapces after, remove the whitespces that come after
      • else, there is a non-space after the tag: do nothing

Examples:

# Remove
ERB.new("a \nb <% 0 -%>\n c", nil, '-').result == "a \nb  c" or raise

# Don't do anything: not followed by newline, but by space:
ERB.new("a\n<% 0 -%> \nc", nil, '-').result == "a\nb \nc" or raise

# Remove the current line because only whitesapaces:
Erubis::Eruby.new(" <% 0 %> \nb").result == 'b' or raise

# Same as above, thus useless because longer.
Erubis::Eruby.new(" <% 0 -%> \nb").result == 'b' or raise

# Don't do anything because line not empty.
Erubis::Eruby.new("a <% 0 %> \nb").result == "a  \nb" or raise
Erubis::Eruby.new(" <% 0 %> a\nb").result == "  a\nb" or raise
Erubis::Eruby.new(" <% 0 -%> a\nb").result == "  a\nb" or raise

# Don't remove the current line because of `=`:
Erubis::Eruby.new(" <%= 0 %> \nb").result == " 0 \nb" or raise

# Remove the current line even with `=`:
Erubis::Eruby.new(" <%= 0 -%> \nb").result == " 0b"   or raise

# Remove forward only because of `-` and non space before:
Erubis::Eruby.new("a <%= 0 -%> \nb").result == "a 0b"   or raise

# Don't do anything because non-whitespace forward:
Erubis::Eruby.new(" <%= 0 -%> a\nb").result == " 0 a\nb"   or raise

What %- does:

  • ERB: remove whitespaces before tag and after previous newlines, but only if there are only whitespaces before.

  • erubis: useless because <%- %> is the same as <% %> (without =), and this cannot be used with = which is the only case where -% can be useful. So never use this.

Examples:

# Remove
ERB.new("a \n  <%- 0 %> b\n c", nil, '-').result == "a \n b\n c" or raise

# b is not whitespace: do nothing:
ERB.new("a \nb  <%- 0 %> c\n d", nil, '-').result == "a \nb   c\n d" or raise

What %- and -% do together

The exact combination of both effects separately.

Adjust icon size of Floating action button (fab)

As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center" in your ImageButton to avoid auto resize.

Count distinct values

Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then

SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:

+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.

Different class for the last element in ng-repeat

You can use $last variable within ng-repeat directive. Take a look at doc.

You can do it like this:

 <div ng-repeat="file in files" ng-class="computeCssClass($last)">
 {{file.name}}
 </div>

Where computeCssClass is function of controller which takes sole argument and returns 'last' or null.

Or

  <div ng-repeat="file in files" ng-class="{'last':$last}">
  {{file.name}}
  </div>

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How do I display Ruby on Rails form validation error messages one at a time?

After experimenting for a few hours I figured it out.

<% if @user.errors.full_messages.any? %>
  <% @user.errors.full_messages.each do |error_message| %>
    <%= error_message if @user.errors.full_messages.first == error_message %> <br />
  <% end %>
<% end %>

Even better:

<%= @user.errors.full_messages.first if @user.errors.any? %>

Check if an array item is set in JS

TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)

function arrayIndexExists(array, index){
    if ( typeof index !== 'number' && index === parseInt(index).toString()) {
        index = parseInt(index);
    } else {
        return false;//to avoid checking typeof again
    }
    return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}

The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.

Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)

Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.

This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);

var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"

This shows that associative keys are not used to access elements in the array, but for properties of the object.

foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3

This shows that checking typeof doesn't allow you to see if an element has been set.

var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined

This shows the exception I mentioned above and why you can't just use parseInt();

If you want to use associative arrays, you are better off using simple objects as other answers have recommended.

Docker container will automatically stop after "docker run -d"

if you want to operate on the container, you need to run it in foreground to keep it alive.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

In addition to the other answers using HTML (either in Markdown or using the %%HTML magic:

If you need to specify the image height, this will not work:

<img src="image.png" height=50> <-- will not work

That is because the CSS styling in Jupyter uses height: auto per default for the img tags, which overrides the HTML height attribute. You need need to overwrite the CSS height attribute instead:

<img src="image.png" style="height:50px"> <-- works

Defining a percentage width for a LinearLayout?

I think Emiam's approach is right. But also agree with Simon Veloper (one of commentators of Emiam's answer) : When we need the buttons in 70% of width, we should use horizontal orientation for Linearlayout and set width of each Relativelayout to 0dip and their weight as specified So I suggest this version :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/layoutContainer" android:orientation="horizontal">
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="14">

            //This is where you add buttons. You can make them "fill_parent".
    </RelativeLayout>
    <RelativeLayout
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="3">
    </RelativeLayout>
</LinearLayout>

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

How to clone git repository with specific revision/changeset?

UPDATE 2 Since Git 2.5.0 the feature described below can be enabled on server side with configuration variable uploadpack.allowReachableSHA1InWant, here the GitHub feature request and the GitHub commit enabling this feature. Note that some Git servers activate this option by default, e.g. Bitbucket Server enabled it since version 5.5+. See this answer on Stackexchange for a exmple of how to activate the configuration option.

UPDATE 1 For Git versions 1.7 < v < 2.5 use git clone and git reset, as described in Vaibhav Bajpai's answer

If you don't want to fetch the full repository then you probably shouldn't be using clone. You can always just use fetch to choose the branch that you want to fetch. I'm not an hg expert so I don't know the details of -r but in git you can do something like this.

# make a new blank repository in the current directory
git init

# add a remote
git remote add origin url://to/source/repository

# fetch a commit (or branch or tag) of interest
# Note: the full history up to this commit will be retrieved unless 
#       you limit it with '--depth=...' or '--shallow-since=...'
git fetch origin <sha1-of-commit-of-interest>

# reset this repository's master branch to the commit of interest
git reset --hard FETCH_HEAD

How do I register a DLL file on Windows 7 64-bit?

If the DLL is 32 bit:

  1. Copy the DLL to C:\Windows\SysWoW64\
  2. In elevated cmd: %windir%\SysWoW64\regsvr32.exe %windir%\SysWoW64\namedll.dll

if the DLL is 64 bit:

  1. Copy the DLL to C:\Windows\System32\
  2. In elevated cmd: %windir%\System32\regsvr32.exe %windir%\System32\namedll.dll

Drawing Isometric game worlds

Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.

After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".

How to get value by class name in JavaScript or jquery?

Without jQuery:

textContent:

var text = document.querySelector('.someClassname').textContent;

Markup:

var text = document.querySelector('.someClassname').innerHTML;

Markup including the matched element:

var text = document.querySelector('.someClassname').outerHTML;

though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.

How to enter command with password for git pull?

Using the credentials helper command-line option:

git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

I've recently stumbled upon the following solution to this problem:

Source: Multiple versions of Chrome

...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):

  1. Install Chrome 2, you'll find it Application Data folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:

    C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
    

    and run Chrome

  2. Open registry and save

    [HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
    

    keys, put them into one chrome2.reg file and copy this file next to chrome.exe (ChromeDir\Application)

  3. Rename Chrome folder to something else (e.g. Chrome2)

  4. Install Chrome 3, it will install to Chrome folder again and run Chrome

  5. Save the same keys (there are changes due to different version) and save it to the chrome3.reg file next to chrome.exe file of this new version again
  6. Rename the folder again (e.g. Chrome3)

    the result would be that there is no Chrome dir (only Chrome2 and Chrome3)

  7. Go to the Application folder of Chrome2, create chrome.bat file with this content:

    @echo off
    regedit /S chrome2.reg
    START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data"
    rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
    

    the first line is generic batch command, the second line will update registry with the content of chrome2.reg file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.

    Notice short name format passed as -user-data-dir parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)

  8. Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3

Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.

Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.

Bronislav Klucka

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Data at the root level is invalid

This:

doc.LoadXml(HttpContext.Current.Server.MapPath("officeList.xml"));

should be:

doc.Load(HttpContext.Current.Server.MapPath("officeList.xml"));

LoadXml() is for loading an XML string, not a file name.

Limit Get-ChildItem recursion depth

As of powershell 5.0, you can now use the -Depth parameter in Get-ChildItem!

You combine it with -Recurse to limit the recursion.

Get-ChildItem -Recurse -Depth 2

Copy and Paste a set range in the next empty row

The reason the code isn't working is because lastrow is measured from whatever sheet is currently active, and "A:A500" (or other number) is not a valid range reference.

Private Sub CommandButton1_Click()
    Dim lastrow As Long

    lastrow = Sheets("Summary Info").Range("A65536").End(xlUp).Row    ' or + 1
    Range("A3:E3").Copy Destination:=Sheets("Summary Info").Range("A" & lastrow)
End Sub

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

rotate image with css

Perform rotation using transform: rotate(xdeg) and also apply overflow: hidden to the parent component to avoid overlapping effect

.div-parent {
   overflow: hidden
}

.div-child {
   transform: rotate(270deg);
}

How to change the DataTable Column Name?

Rename the Column by doing the following:

dataTable.Columns["ColumnName"].ColumnName = "newColumnName";

How set the android:gravity to TextView from Java side in Android

textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.

Best way to overlay an ESRI shapefile on google maps?

I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.

Google Maps API supports only a subset of the KML standard. One limitation is file size.

To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.

Then you can select your layer and do a "save as kml" on it.

If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.

Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

<parent>
        <groupId>com.test.vaquar.khan</groupId>
        <artifactId>vk-parent</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../projectname/pom.xml</relativePath>
    </parent>

Add following line in parent

<relativePath>../projectname/pom.xml</relativePath>

You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client

gem install jenkins_api_client

require "rubygems"
require "jenkins_api_client"

# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
  :server_ip => "127.0.0.1",
  :username => "awesomeuser",
  :password => "awesomepassword"
)

# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
  client.job.create_freestyle(:name => "test_job_#{num}")
end

# The jobs in Jenkins can be listed using
client.job.list_all

The API client can be used to perform a lot of operations.

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

PuTTY scripting to log onto host

mputty can do that but it does not seem to work always. (if that wait period is too slow)

mputty uses putty and it extends putty. There is an option to run a script. If it does not work, make sure that wait period before typing is a high value or increase that value. See putty sessions , then name of session, right mouse button,properties/script page.

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);

}

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

} catch (MessagingException e) {
    e.printStackTrace();
}



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Angular JS break ForEach

I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.

How to make MySQL handle UTF-8 properly

To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. USE ALTER DATABASE.. Replace DBNAME with the database name:

ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;

This is a duplicate of this question How to convert an entire MySQL database characterset and collation to UTF-8?

What does body-parser do with express?

If you don't want to use seperate npm package body-parser, latest express (4.16+) has built-in body-parser middleware and can be used like this,

const app = express();
app.use(express.json({ limit: '100mb' }));

p.s. Not all functionalities of body parse are present in the express. Refer documentation for full usage here

Problems with jQuery getJSON using local files in Chrome

You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.

How to center icon and text in a android button with width set to "fill parent"

What happens if you try android:gravity="center_horizontal"?

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

How to watch for a route change in AngularJS?

If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});

jQuery ajax call to REST service

From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

The url for the rest api would be http://localhost/restws/json/product/get

Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

How to add new contacts in android

There are several good articles on the subject on dev2qa.com site, about Contacts Provider API:

How To Add Contact In Android Programmatically

How To Update Delete Android Contacts Programmatically

How To Get Contact List In Android Programmatically

Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure

Official Google documentation on Contacts Provider here

How do you split a list into evenly sized chunks?

Simple yet elegant

l = range(1, 1000)
print [l[x:x+10] for x in xrange(0, len(l), 10)]

or if you prefer:

def chunks(l, n): return [l[x: x+n] for x in xrange(0, len(l), n)]
chunks(l, 10)

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

psql: FATAL: Peer authentication failed for user "dev"

pg_dump -h localhost -U postgres -F c -b -v -f mydb.backup mydb

.htaccess - how to force "www." in a generic way?

RewriteEngine On

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

This redirects example.com to www.example.com excluding subdomains.

Why don’t my SVG images scale using the CSS "width" property?

  1. If the svg file has a height and width already defined width="100" height="100" in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100" while keeping the already defined width="100" height="100".
  2. Then you can scale the svg in your css file by using a selector in your case img so you could then do this: img{height: 20px; width: 20px;} and the image will scale.

recursively use scp but excluding some folders

If you use a pem file to authenticate u can use the following command (which will exclude files with something extension):

rsync -Lavz -e "ssh -i <full-path-to-pem> -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --exclude "*.something" --progress <path inside local host> <user>@<host>:<path inside remote host>

The -L means follow links (copy files not links). Use full path to your pem file and not relative.

Using sshfs is not recommended since it works slowly. Also, the combination of find and scp that was presented above is also a bad idea since it will open a ssh session per file which is too expensive.