Programs & Examples On #Objectdisposedexception

The exception that is thrown when an operation is performed on a disposed object.

Equivalent of explode() to work with strings in MySQL

First of all you should change database structure - the score in this case is some kind of composite value and should be stored in two columns, eg. score_host, score_guest.


MySQL doesn't provide explode() equivalent however in this case you could use SUBSTRING() and LOCATE() to cut off score of a host and a guest.

SELECT 
   CONVERT(SUBSTRING(score, 1, LOCATE('-',score) - 2) USING INTEGER) as score_host,
   CONVERT(SUBSTRING(score, LOCATE('-',score)+2) USING INTEGER) as score_guest
FROM ...;

CONVERT() is used to cast a string "23" into number 23.

How to modify a specified commit?

Automated interactive rebase edit followed by commit revert ready for a do-over

I found myself fixing a past commit frequently enough that I wrote a script for it.

Here's the workflow:

  1. git commit-edit <commit-hash>
    

    This will drop you at the commit you want to edit.

  2. Fix and stage the commit as you wish it had been in the first place.

    (You may want to use git stash save to keep any files you're not committing)

  3. Redo the commit with --amend, eg:

    git commit --amend
    
  4. Complete the rebase:

    git rebase --continue
    

For the above to work, put the below script into an executable file called git-commit-edit somewhere in your $PATH:

#!/bin/bash

set -euo pipefail

script_name=${0##*/}

warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }

[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"

# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")
message=$(git log -1 --format='%h %s' "$commit")

if [[ $OSTYPE =~ ^darwin ]]; then
  sed_inplace=(sed -Ei "")
else
  sed_inplace=(sed -Ei)
fi

export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)"  # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty  #  Commit an empty commit so that that cache diffs are un-reversed

echo
echo "Editing commit: $message" >&2
echo

setting an environment variable in virtualenv

Install autoenv either by

$ pip install autoenv

(or)

$ brew install autoenv

And then create .env file in your virtualenv project folder

$ echo "source bin/activate" > .env

Now everything works fine.

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

Empty an array in Java / processing

I just want to add something to Mark's comment. If you want to reuse array without additional allocation, just use it again and override existing values with new ones. It will work if you fill the array sequentially. In this case just remember the last initialized element and use array until this index. It is does not matter that there is some garbage in the end of the array.

What is the meaning of 'No bundle URL present' in react-native?

I have found the easiest/quickest way to bypass this is to exit the app within the simulator (2 x Cmd + Shift + H) and re-launch.

Run Function After Delay

I searched and found the solution in the following URL is better.

http://www.tutorialrepublic.com/faq/call-a-function-after-some-time-in-jquery.php

It worth to try.

It adds your given function to the queue of functions to be executed on the matched element which is currently this.

 $(this).delay(1000).queue(function() {

     // your Code | Function here
     
     $(this).dequeue();
  
  });

and then execute the next function on the queue for the matched element(s) which is currently this again.

-- EDIT [ POSSIBLE EXPLANATION FOR THE DEQUEUE COMMAND ]

Take a look at the command

We command the jQuery engine to add a function in internal queue and then after a specific amount of time we command it to call that function, BUT so far we never told it to dequeue it from engine. Right?! And then after every thing is done we are dequeue it from jQuery engine manually. I hope the explanation could help.

Change the color of cells in one column when they don't match cells in another column

In my case I had to compare column E and I.

I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.

Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"

In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.

how to add or embed CKEditor in php page

If you have downloaded the latest Version 4.3.4 then just follow these steps.

  • Download the package, unzip and place in your web directory or root folder.
  • Provide the read write permissions to that folder (preferably Ubuntu machines )
  • Create view page test.php
  • Paste the below mentioned code it should work fine.

Load the mentioned js file

<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<textarea class="ckeditor" name="editor"></textarea>

Top 5 time-consuming SQL queries in Oracle

You could take the average buffer gets per execution during a period of activity of the instance:

SELECT username,
       buffer_gets,
       disk_reads,
       executions,
       buffer_get_per_exec,
       parse_calls,
       sorts,
       rows_processed,
       hit_ratio,
       module,
       sql_text
       -- elapsed_time, cpu_time, user_io_wait_time, ,
  FROM (SELECT sql_text,
               b.username,
               a.disk_reads,
               a.buffer_gets,
               trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
               a.parse_calls,
               a.sorts,
               a.executions,
               a.rows_processed,
               100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
               module
               -- cpu_time, elapsed_time, user_io_wait_time
          FROM v$sqlarea a, dba_users b
         WHERE a.parsing_user_id = b.user_id
           AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
           AND a.buffer_gets > 10000
         ORDER BY buffer_get_per_exec DESC)
 WHERE ROWNUM <= 20

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

Why do we have to normalize the input for an artificial neural network?

In neural networks, it is good idea not just to normalize data but also to scale them. This is intended for faster approaching to global minima at error surface. See the following pictures: error surface before and after normalization

error surface before and after scaling

Pictures are taken from the coursera course about neural networks. Author of the course is Geoffrey Hinton.

Java JTable getting the data of the selected row

Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you use windows authentication, and you don't know a password to login as a user via username and password, you can do this: on the login-screen on SSMS click options at the bottom right, then go to the connection properties tab. Then you can type in manually the name of another database you have access to, over where it says , which will let you connect. Then follow the other advice for changing your default database

https://gyazo.com/c3d04c600311c08cb685bb668b569a67

How to disable gradle 'offline mode' in android studio?

@mikepenz has the right one.

You could just hit SHIFT+COMMAND+A (if you're using OSX and 1.4 android studio) and enter OFFLINE in the search box.

Then you'll see what mike have shown you.

Just deselect offline.

Show data on mouseover of circle

This concise example demonstrates common way how to create custom tooltip in d3.

_x000D_
_x000D_
var w = 500;_x000D_
var h = 150;_x000D_
_x000D_
var dataset = [5, 10, 15, 20, 25];_x000D_
_x000D_
// firstly we create div element that we can use as_x000D_
// tooltip container, it have absolute position and_x000D_
// visibility: hidden by default_x000D_
_x000D_
var tooltip = d3.select("body")_x000D_
  .append("div")_x000D_
  .attr('class', 'tooltip');_x000D_
_x000D_
var svg = d3.select("body")_x000D_
  .append("svg")_x000D_
  .attr("width", w)_x000D_
  .attr("height", h);_x000D_
_x000D_
// here we add some circles on the page_x000D_
_x000D_
var circles = svg.selectAll("circle")_x000D_
  .data(dataset)_x000D_
  .enter()_x000D_
  .append("circle");_x000D_
_x000D_
circles.attr("cx", function(d, i) {_x000D_
    return (i * 50) + 25;_x000D_
  })_x000D_
  .attr("cy", h / 2)_x000D_
  .attr("r", function(d) {_x000D_
    return d;_x000D_
  })_x000D_
  _x000D_
  // we define "mouseover" handler, here we change tooltip_x000D_
  // visibility to "visible" and add appropriate test_x000D_
  _x000D_
  .on("mouseover", function(d) {_x000D_
    return tooltip.style("visibility", "visible").text('radius = ' + d);_x000D_
  })_x000D_
  _x000D_
  // we move tooltip during of "mousemove"_x000D_
  _x000D_
  .on("mousemove", function() {_x000D_
    return tooltip.style("top", (event.pageY - 30) + "px")_x000D_
      .style("left", event.pageX + "px");_x000D_
  })_x000D_
  _x000D_
  // we hide our tooltip on "mouseout"_x000D_
  _x000D_
  .on("mouseout", function() {_x000D_
    return tooltip.style("visibility", "hidden");_x000D_
  });
_x000D_
.tooltip {_x000D_
    position: absolute;_x000D_
    z-index: 10;_x000D_
    visibility: hidden;_x000D_
    background-color: lightblue;_x000D_
    text-align: center;_x000D_
    padding: 4px;_x000D_
    border-radius: 4px;_x000D_
    font-weight: bold;_x000D_
    color: orange;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.11.0/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

T-SQL query to show table definition?

Have you tried sp_help?

sp_help 'TableName'

Printing Python version in output

If you are using jupyter notebook Try:

!python --version

If you are using terminal Try:

 python --version

What method in the String class returns only the first N characters?

string.Substring(0,n); // 0 - start index and n - number of characters

Why did my Git repo enter a detached HEAD state?

The other way to get in a git detached head state is to try to commit to a remote branch. Something like:

git fetch
git checkout origin/foo
vi bar
git commit -a -m 'changed bar'

Note that if you do this, any further attempt to checkout origin/foo will drop you back into a detached head state!

The solution is to create your own local foo branch that tracks origin/foo, then optionally push.

This probably has nothing to do with your original problem, but this page is high on the google hits for "git detached head" and this scenario is severely under-documented.

How to check if X server is running?

One trick I use to tell if X is running is:

telnet 127.0.0.1 6000

If it connects, you have an X server running and its accepting inbound TCP connections (not usually the default these days)....

Deprecated Java HttpClient - How hard can it be?

You could add the following Maven dependency.

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>

You could use following import in your java code.

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGett;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.methods.HttpUriRequest;

You could use following code block in your java code.

HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest httpUriRequest = new HttpGet("http://example.domain/someuri");

HttpResponse response = client.execute(httpUriRequest);
System.out.println("Response:"+response);

How do I turn a C# object into a JSON string in .NET?

A new JSON serializer is available in the System.Text.Json namespace. It's included in the .NET Core 3.0 shared framework and is in a NuGet package for projects that target .NET Standard or .NET Framework or .NET Core 2.x.

Example code:

using System;
using System.Text.Json;

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public MyDate DateOfBirth { get; set; }
}

class Program
{
    static void Main()
    {
        var lad = new Lad
        {
            FirstName = "Markoff",
            LastName = "Chaney",
            DateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = JsonSerializer.Serialize(lad);
        Console.WriteLine(json);
    }
}

In this example the classes to be serialized have properties rather than fields; the System.Text.Json serializer currently doesn't serialize fields.

Documentation:

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Who ever also stumbles over this post.

I belive is the correct way:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

How to check which locks are held on a table

I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.

(MUST switch to the Database you want to observe to get object_id)

SELECT 
     TL.resource_type,
     TL.resource_database_id,
     TL.resource_associated_entity_id,
     TL.request_mode,
     TL.request_session_id,
     WT.blocking_session_id,
     O.name AS [object name],
     O.type_desc AS [object descr],
     P.partition_id AS [partition id],
     P.rows AS [partition/page rows],
     AU.type_desc AS [index descr],
     AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT 
 ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O 
 ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P 
 ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU 
 ON AU.allocation_unit_id = TL.resource_associated_entity_id;

How to run a makefile in Windows?

You can install GNU make with chocolatey, a well-maintained package manager, which will add make to the global path and runs on all CLIs (powershell, git bash, cmd, etc…) saving you a ton of time in both maintenance and initial setup to get make running.

  1. Install the chocolatey package manager for Windows
    compatible to Windows 7+ / Windows Server 2003+

  2. Run choco install make

I am not affiliated with choco, but I highly recommend it, so far it has never let me down and I do have a talent for breaking software unintentionally.

Get UserDetails object from Security Context in Spring MVC controller

If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {

    ModelAndView mv = new ModelAndView("index");

    String userName = "not logged in"; // Any default user  name
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        userName = principal.getName();
    }

    mv.addObject("username", userName);

    // By adding a little code (same way) you can check if user has any
    // roles you need, for example:

    boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
    mv.addObject("isAdmin", fAdmin);

    return mv;
}

Note "HttpServletRequest request" parameter added.

Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

I tried this:

        long now = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            new Date().getTime();
        }
        long result = System.currentTimeMillis() - now;

        System.out.println("Date(): " + result);

        now = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            System.currentTimeMillis();
        }
        result = System.currentTimeMillis() - now;

        System.out.println("currentTimeMillis(): " + result);

And result was:

Date(): 199

currentTimeMillis(): 3

How to resolve 'unrecognized selector sent to instance'?

Mine was something simple/stupid. Newbie mistake, for anyone that has converted their NSManagedObject to a normal NSObject.

I had:

@dynamic order_id;

when i should have had:

@synthesize order_id;

Pass a data.frame column name to a function

You can just use the column name directly:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[,column])
}
fun1(df, "B")
fun1(df, c("B","A"))

There's no need to use substitute, eval, etc.

You can even pass the desired function as a parameter:

fun1 <- function(x, column, fn) {
  fn(x[,column])
}
fun1(df, "B", max)

Alternatively, using [[ also works for selecting a single column at a time:

df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
  max(x[[column]])
}
fun1(df, "B")

Using python's eval() vs. ast.literal_eval()?

eval: This is very powerful, but is also very dangerous if you accept strings to evaluate from untrusted input. Suppose the string being evaluated is "os.system('rm -rf /')" ? It will really start deleting all the files on your computer.

ast.literal_eval: Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None, bytes and sets.

Syntax:

eval(expression, globals=None, locals=None)
import ast
ast.literal_eval(node_or_string)

Example:

# python 2.x - doesn't accept operators in string format
import ast
ast.literal_eval('[1, 2, 3]')  # output: [1, 2, 3]
ast.literal_eval('1+1') # output: ValueError: malformed string


# python 3.0 -3.6
import ast
ast.literal_eval("1+1") # output : 2
ast.literal_eval("{'a': 2, 'b': 3, 3:'xyz'}") # output : {'a': 2, 'b': 3, 3:'xyz'}
# type dictionary
ast.literal_eval("",{}) # output : Syntax Error required only one parameter
ast.literal_eval("__import__('os').system('rm -rf /')") # output : error

eval("__import__('os').system('rm -rf /')") 
# output : start deleting all the files on your computer.
# restricting using global and local variables
eval("__import__('os').system('rm -rf /')",{'__builtins__':{}},{})
# output : Error due to blocked imports by passing  '__builtins__':{} in global

# But still eval is not safe. we can access and break the code as given below
s = """
(lambda fc=(
lambda n: [
    c for c in 
        ().__class__.__bases__[0].__subclasses__() 
        if c.__name__ == n
    ][0]
):
fc("function")(
    fc("code")(
        0,0,0,0,"KABOOM",(),(),(),"","",0,""
    ),{}
)()
)()
"""
eval(s, {'__builtins__':{}})

In the above code ().__class__.__bases__[0] nothing but object itself. Now we instantiated all the subclasses, here our main enter code hereobjective is to find one class named n from it.

We need to code object and function object from instantiated subclasses. This is an alternative way from CPython to access subclasses of object and attach the system.

From python 3.7 ast.literal_eval() is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. link

Batch file to move files to another directory

Try:

move "C:\files\*.txt" "C:\txt"

Spring MVC: How to perform validation?

I would like to extend nice answer of Jerome Dalbert. I found very easy to write your own annotation validators in JSR-303 way. You are not limited to have "one field" validation. You can create your own annotation on type level and have complex validation (see examples below). I prefer this way because I don't need mix different types of validation (Spring and JSR-303) like Jerome do. Also this validators are "Spring aware" so you can use @Inject/@Autowire out of box.

Example of custom object validation:

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { YourCustomObjectValidator.class })
public @interface YourCustomObjectValid {

    String message() default "{YourCustomObjectValid.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

public class YourCustomObjectValidator implements ConstraintValidator<YourCustomObjectValid, YourCustomObject> {

    @Override
    public void initialize(YourCustomObjectValid constraintAnnotation) { }

    @Override
    public boolean isValid(YourCustomObject value, ConstraintValidatorContext context) {

        // Validate your complex logic 

        // Mark field with error
        ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
        cvb.addNode(someField).addConstraintViolation();

        return true;
    }
}

@YourCustomObjectValid
public YourCustomObject {
}

Example of generic fields equality:

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ TYPE, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { FieldsEqualityValidator.class })
public @interface FieldsEquality {

    String message() default "{FieldsEquality.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Name of the first field that will be compared.
     * 
     * @return name
     */
    String firstFieldName();

    /**
     * Name of the second field that will be compared.
     * 
     * @return name
     */
    String secondFieldName();

    @Target({ TYPE, ANNOTATION_TYPE })
    @Retention(RUNTIME)
    public @interface List {
        FieldsEquality[] value();
    }
}




import java.lang.reflect.Field;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

public class FieldsEqualityValidator implements ConstraintValidator<FieldsEquality, Object> {

    private static final Logger log = LoggerFactory.getLogger(FieldsEqualityValidator.class);

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(FieldsEquality constraintAnnotation) {
        firstFieldName = constraintAnnotation.firstFieldName();
        secondFieldName = constraintAnnotation.secondFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null)
            return true;

        try {
            Class<?> clazz = value.getClass();

            Field firstField = ReflectionUtils.findField(clazz, firstFieldName);
            firstField.setAccessible(true);
            Object first = firstField.get(value);

            Field secondField = ReflectionUtils.findField(clazz, secondFieldName);
            secondField.setAccessible(true);
            Object second = secondField.get(value);

            if (first != null && second != null && !first.equals(second)) {
                    ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(firstFieldName).addConstraintViolation();

          ConstraintViolationBuilder cvb = context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate());
          cvb.addNode(someField).addConstraintViolation(secondFieldName);

                return false;
            }
        } catch (Exception e) {
            log.error("Cannot validate fileds equality in '" + value + "'!", e);
            return false;
        }

        return true;
    }
}

@FieldsEquality(firstFieldName = "password", secondFieldName = "confirmPassword")
public class NewUserForm {

    private String password;

    private String confirmPassword;

}

In angular $http service, How can I catch the "status" of error?

Since $http.get returns a 'promise' with the extra convenience methods success and error (which just wrap the result of then) you should be able to use (regardless of your Angular version):

$http.get('/someUrl')
    .then(function success(response) {
        console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
    }, function error(response) {
        console.log('failed', response); // supposed to have: data, status, headers, config, statusText
    })

Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments, even if you don't know the appropriate method signature:

$http.get('/someUrl')
  .success(function(data, foo, bar) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  })
  .error(function(baz, foo, bar, idontknow) {
    console.log(arguments); // includes data, status, etc including unlisted ones if present
  });

Then, based on whatever you find, you can 'fix' the function arguments to match.

How do I get the name of the current executable in C#?

For windows apps (forms and console) I use this:

Add a reference to System.Windows.Forms in VS then:

using System.Windows.Forms;
namespace whatever
{
    class Program
    {
        static string ApplicationName = Application.ProductName.ToString();
        static void Main(string[] args)
        {
            ........
        }
    }
}

This works correctly for me whether I am running the actual executable or debugging within VS.

Note that it returns the application name without the extension.

John

PHP session lost after redirect

Now that GDPR is a thing, people visiting this question probably use a cookie script. Well, that script caused the problem for me. Apparently, PHP uses a cookie called PHPSESSID to track the session. If that script deletes it, you lose your data.

I used this cookie script. It has an option to enable "essential" cookies. I added PHPSESSID to the list, the script stopped deleting the cookie, and everything started to work again.

You could probably enable some PHP setting to avoid using PHPSESSID, but if your cookie script is the cause of the problem, why not fix that.

cannot find zip-align when publishing app

Normally the zipalign.exe is close of the "Android manager"(also, "Android", "Android SDK" etc), so you can search for "Android Manager" in windows search and give a righ-click above the command and open file location. You probably are in: something\ Android\android-sdk\tools. Then is just necessary return a folder and go to Android\android-sdk\build-tools\23.0.3. The zipalign is there, you maybe be not able to use it with double-click, so you have to copy all the path of the zipalign file to use in CMD, the final code that you have to input will be something like:

C:\Users\heitor\AppData\Local\Android\android-sdk\build-tools\23.0.1\zipalign.exe -v 4 android.apk android2.apk

Angular2 *ngIf check object array length in template

<div class="row" *ngIf="teamMembers?.length > 0">

This checks first if teamMembers has a value and if teamMembers doesn't have a value, it doesn't try to access length of undefined because the first part of the condition already fails.

How to return JSON data from spring Controller using @ResponseBody

I was using groovy+springboot and got this error.

Adding getter/setter is enough if we are using below dependency.

implementation 'org.springframework.boot:spring-boot-starter-web'

As Jackson core classes come with it.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

What can be the reasons of connection refused errors?

Connection refused means that the port you are trying to connect to is not actually open.

So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.

A common mistake is not specifying the port number when binding or connecting in network byte order...

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I faced the same error, but in my case, the problem was resolved after deleting the /target folder and nbactions.xml file.

fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

If your solution has lib projects check Target Machine property in Property->Librarian->General

Find a class somewhere inside dozens of JAR files?

Following script will help you out

for file in *.jar
do
  # do something on "$file"
  echo "$file"
  /usr/local/jdk/bin/jar -tvf "$file" | grep '$CLASSNAME'
done

Eloquent Collection: Counting and Detect Empty

------SOLVED------

in this case you want to check two type of count for two cace

case 1:

if result contain only one record other word select single row from database using ->first()

 if(count($result)){
     
       ...record is exist true...
  }

case 2:

if result contain set of multiple row other word using ->get() or ->all()

  if($result->count()) {
    
         ...record is exist true...
  }

Batch file to delete folders older than 10 days in Windows 7

If you want using it with parameter (ie. delete all subdirs under the given directory), then put this two lines into a *.bat or *.cmd file:

@echo off
for /f "delims=" %%d in ('dir %1 /s /b /ad ^| sort /r') do rd "%%d" 2>nul && echo rmdir %%d

and add script-path to your PATH environment variable. In this case you can call your batch file from any location (I suppose UNC path should work, too).

Eg.:

YourBatchFileName c:\temp

(you may use quotation marks if needed)

will remove all empty subdirs under c:\temp folder

YourBatchFileName

will remove all empty subdirs under the current directory.

Why does overflow:hidden not work in a <td>?

Here is the same problem.

You need to set table-layout:fixed and a suitable width on the table element, as well as overflow:hidden and white-space: nowrap on the table cells.


Examples

Fixed width columns

The width of the table has to be the same (or smaller) than the fixed width cell(s).

With one fixed width column:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 100px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

With multiple fixed width columns:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 200px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Fixed and fluid width columns

A width for the table must be set, but any extra width is simply taken by the fluid cell(s).

With multiple columns, fixed width and fluid width:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}
td {
  background: #F00;
  padding: 20px;
  border: solid 1px #000;
}
tr td:first-child {
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Oracle: If Table Exists

Another method is to define an exception and then only catch that exception letting all others propagate.

Declare
   eTableDoesNotExist Exception;
   PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
   EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
   When eTableDoesNotExist Then
      DBMS_Output.Put_Line('Table already does not exist.');
End;

"unrecognized import path" with go get

I installed Go with brew on OSX 10.11, and found I had to set GOROOT to:

/usr/local/Cellar/go/1.5.1/libexec

(Of course replace the version in this path with go version you have)

Brew uses symlinks, which were fooling the gotool. So follow the links home.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

You can either use the prepareStatement method taking an additional int parameter

PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)

For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:

PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

How do I read from parameters.yml in a controller in symfony2?

In Symfony 2.6 and older versions, to get a parameter in a controller - you should get the container first, and then - the needed parameter.

$this->container->getParameter('api_user');

This documentation chapter explains it.

While $this->get() method in a controller will load a service (doc)

In Symfony 2.7 and newer versions, to get a parameter in a controller you can use the following:

$this->getParameter('api_user');

Convert between UIImage and Base64 string

Swift 5

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image!
}

Note: Tested in xcode 10.2

Swift 4

Encoding

func convertImageToBase64String (img: UIImage) -> String {
    let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

Decoding

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image
}

Note: Tested in xcode 9.4.1

How to write multiple conditions of if-statement in Robot Framework

The below code worked fine:

Run Keyword if    '${value1}' \ \ == \ \ '${cost1}' \ and \ \ '${value2}' \ \ == \ \ 'cost2'    LOG    HELLO

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

Case-insensitive search in Rails model

Another approach that no one has mentioned is to add case insensitive finders into ActiveRecord::Base. Details can be found here. The advantage of this approach is that you don't have to modify every model, and you don't have to add the lower() clause to all your case insensitive queries, you just use a different finder method instead.

Showing empty view when ListView is empty

It should be like this:

<TextView android:id="@android:id/empty"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="No Results" />

Note the id attribute.

PDF Editing in PHP?

There is a free and easy to use PDF class to create PDF documents. It's called FPDF. In combination with FPDI (http://www.setasign.de/products/pdf-php-solutions/fpdi) it is even possible to edit PDF documents. The following code shows how to use FPDF and FPDI to fill an existing gift coupon with the user data.

require_once('fpdf.php'); 
require_once('fpdi.php'); 
$pdf = new FPDI();

$pdf->AddPage(); 

$pdf->setSourceFile('gift_coupon.pdf'); 
// import page 1 
$tplIdx = $this->pdf->importPage(1); 
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page 
$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); 

// now write some text above the imported page 
$this->pdf->SetFont('Arial', '', '13'); 
$this->pdf->SetTextColor(0,0,0);
//set position in pdf document
$this->pdf->SetXY(20, 20);
//first parameter defines the line height
$this->pdf->Write(0, 'gift code');
//force the browser to download the output
$this->pdf->Output('gift_coupon_generated.pdf', 'D');

TypeScript static classes

You can create a class in Typescript as follows:

export class coordinate {
        static x: number;
        static y: number;
        static gradient() {
            return y/x;
        }
    }

and reference it's properties and methods "without" instantiation so:

coordinate.x = 10;
coordinate.y = 10;
console.log(`x of ${coordinate.x} and y of ${coordinate.y} has gradient of ${coordinate.gradient()}`);

Fyi using backticks `` in conjunction with interpolation syntax ${} allows ease in mixing code with text :-)

Disabling of EditText in Android

Set below properties in class:

editText.setFocusable(false);
editText.setEnabled(false);

It will work smoothly as you required.

Setting selected option in laravel form

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

View the change history of a file using Git versioning

If you are using eclipse with the git plugin, it has an excellent comparison view with history. Right click the file and select "compare with"=> "history"

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Where to download visual studio express 2005?

You can still get it, from microsoft servers, see my answer on this question: Where is Visual Studio 2005 Express?

How can I convert a string to a number in Perl?

Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use. $a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777.

There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;.
Dump:'foo' => '42'

If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;.
Dump:'foo' => 42

After $2+0 Perl notices that you've treated $2 as a number, because you used a numeric operator.

I noticed this whilst trying to compare two hashes with Data::Dumper.

What is a good way to handle exceptions when trying to read a file in python?

Adding to @Josh's example;

fName = [FILE TO OPEN]
if os.path.exists(fName):
    with open(fName, 'rb') as f:
        #add you code to handle the file contents here.
elif IOError:
    print "Unable to open file: "+str(fName)

This way you can attempt to open the file, but if it doesn't exist (if it raises an IOError), alert the user!

insert data from one table to another in mysql

  INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
  VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC))

How to deserialize JS date using Jackson?

I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?

Here's what I did:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
    @Override
    public Date deserialize(JsonParser jsonParser,
            DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        String date = jsonParser.getText();
        try {
            return format.parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

}

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class)

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

Why .NET String is immutable?

Strings are not really immutable. They are just publicly immutable. It means you cannot modify them from their public interface. But in the inside the are actually mutable.

If you don't believe me look at the String.Concat definition using reflector. The last lines are...

int length = str0.Length;
string dest = FastAllocateString(length + str1.Length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, length, str1);
return dest;

As you can see the FastAllocateString returns an empty but allocated string and then it is modified by FillStringChecked

Actually the FastAllocateString is an extern method and the FillStringChecked is unsafe so it uses pointers to copy the bytes.

Maybe there are better examples but this is the one I have found so far.

What is the difference between Tomcat, JBoss and Glassfish?

Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.

Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Sorting options elements alphabetically using jQuery

Malakgeorge answer is nice an can be easily wrapped into a jQuery function:

$.fn.sortSelectByText = function(){
    this.each(function(){
        var selected = $(this).val(); 
        var opts_list = $(this).find('option');
        opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
        $(this).html('').append(opts_list);
        $(this).val(selected); 
    })
    return this;        
}

postgresql: INSERT INTO ... (SELECT * ...)

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

How to search if dictionary value contains certain string with Python

Following is one liner for accepted answer ... (for one line lovers ..)

def search_dict(my_dict,searchFor):
    s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]    
    return s_val

Using Eloquent ORM in Laravel to perform search of database using LIKE

FYI, the list of operators (containing like and all others) is in code:

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
);

disclaimer:

Joel Larson's answer is correct. Got my upvote.

I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.

How to create RecyclerView with multiple view type?

I recommend this library from Hannes Dorfmann. It encapsulates all the logic related to particular view type in a separate object called "AdapterDelegate". https://github.com/sockeqwe/AdapterDelegates

public class CatAdapterDelegate extends AdapterDelegate<List<Animal>> {

  private LayoutInflater inflater;

  public CatAdapterDelegate(Activity activity) {
    inflater = activity.getLayoutInflater();
  }

  @Override public boolean isForViewType(@NonNull List<Animal> items, int position) {
    return items.get(position) instanceof Cat;
  }

  @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
    return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false));
  }

  @Override public void onBindViewHolder(@NonNull List<Animal> items, int position,
      @NonNull RecyclerView.ViewHolder holder, @Nullable List<Object> payloads) {

    CatViewHolder vh = (CatViewHolder) holder;
    Cat cat = (Cat) items.get(position);

    vh.name.setText(cat.getName());
  }

  static class CatViewHolder extends RecyclerView.ViewHolder {

    public TextView name;

    public CatViewHolder(View itemView) {
      super(itemView);
      name = (TextView) itemView.findViewById(R.id.name);
    }
  }
}

public class AnimalAdapter extends ListDelegationAdapter<List<Animal>> {

  public AnimalAdapter(Activity activity, List<Animal> items) {

    // DelegatesManager is a protected Field in ListDelegationAdapter
    delegatesManager.addDelegate(new CatAdapterDelegate(activity))
                    .addDelegate(new DogAdapterDelegate(activity))
                    .addDelegate(new GeckoAdapterDelegate(activity))
                    .addDelegate(23, new SnakeAdapterDelegate(activity));

    // Set the items from super class.
    setItems(items);
  }
}

Group a list of objects by an attribute

you can use guava's Multimaps

@Canonical
class Persion {
     String name
     Integer age
}
List<Persion> list = [
   new Persion("qianzi", 100),
   new Persion("qianzi", 99),
   new Persion("zhijia", 99)
]
println Multimaps.index(list, { Persion p -> return p.name })

it print:

[qianzi:[com.ctcf.message.Persion(qianzi, 100),com.ctcf.message.Persion(qianzi, 88)],zhijia:[com.ctcf.message.Persion(zhijia, 99)]]

Filter dataframe rows if value in column is in a set list of values

you can also use ranges by using:

b = df[(df['a'] > 1) & (df['a'] < 5)]

What arguments are passed into AsyncTask<arg1, arg2, arg3>?

Google's Android Documentation Says that :

An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

AsyncTask's generic types :

The three types used by an asynchronous task are the following:

Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

You Can further refer : http://developer.android.com/reference/android/os/AsyncTask.html

Or You Can clear whats the role of AsyncTask by refering Sankar-Ganesh's Blog

Well The structure of a typical AsyncTask class goes like :

private class MyTask extends AsyncTask<X, Y, Z>

    protected void onPreExecute(){

    }

This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.

    protected Z doInBackground(X...x){

    }

The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.

   protected void onProgressUpdate(Y y){

   }

This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.

  protected void onPostExecute(Z z){

  }

This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.

What about the X, Y and Z types?

As you can deduce from the above structure:

 X – The type of the input variables value you want to set to the background process. This can be an array of objects.

 Y – The type of the objects you are going to enter in the onProgressUpdate method.

 Z – The type of the result from the operations you have done in the background process.

How do we call this task from an outside class? Just with the following two lines:

MyTask myTask = new MyTask();

myTask.execute(x);

Where x is the input parameter of the type X.

Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.

 myTask.getStatus();

and we can receive the following status:

RUNNING - Indicates that the task is running.

PENDING - Indicates that the task has not been executed yet.

FINISHED - Indicates that onPostExecute(Z) has finished.

Hints about using AsyncTask

  1. Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.

  2. You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.

  3. The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).

  4. The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

Twitter Bootstrap - full width navbar

I'm very late to the party but this answer pulls up top in Google search results.

Bootstrap 3 has an answer for this built in, set your container div in your navbar to container-fluid and it'll fall to screen width.

Like so:

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
  <div class="container-fluid">
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li><a href="/">More Stuff</a></li>
      </ul>
    </div>
  </div>
</div>

Could not connect to React Native development server on Android

This is applicable to Android 9.0+ according to the Network Security Configuration. Well, so after trying all possible solutions I found on the web, I decided to investigate the native Android logcat manually. Even after adding android:usesCleartextTraffic="true", I found this in the logcat:

06-25 02:32:34.561 32001 32001 E unknown:ReactNative: Caused by: java.net.UnknownServiceException: CLEARTEXT communication to 192.168.29.96 not permitted by network security policy

So, I tried to inspect my react-native app's source. I found that in debug variant, there is already a network-security-config which is defined by react-native guys, that conflicts with the main variant.

There's an easy solution to this. Go to <app-src>/android/app/src/debug/res/xml/react_native_config.xml Add a new line with your own IP address in the like:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
    ***<domain includeSubdomains="false">192.168.29.96</domain>***
  </domain-config>
</network-security-config>

As my computer's local IP (check from ifconfig for linux) is 192.168.29.96, I added the above line in ***

Then, you need to clean and rebuild for Android!

cd <app-src>/android
./gradlew clean
cd <app-src>
react-native run-android

I hope this works for you.

Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

Curl : connection refused

Make sure you have a service started and listening on the port.

netstat -ln | grep 8080

and

sudo netstat -tulpn

height: 100% for <div> inside <div> with display: table-cell

Define your .table and .cell height:100%;

    .table {
        display: table;
        height:100%;
    }

    .cell {
        border: 1px solid black;
        display: table-cell;
        vertical-align:top;
height: 100%;

    }

    .container {
        height: 100%;
        border: 10px solid green;

    }

Demo

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

Equivalent of jQuery .hide() to set visibility: hidden

Here's one implementation, what works like $.prop(name[,value]) or $.attr(name[,value]) function. If b variable is filled, visibility is set according to that, and this is returned (allowing to continue with other properties), otherwise it returns visibility value.

jQuery.fn.visible = function (b) {
    if(b === undefined)
        return this.css('visibility')=="visible";
    else {
        this.css('visibility', b? 'visible' : 'hidden');
        return this;
    }
}

Example:

$("#result").visible(true).on('click',someFunction);
if($("#result").visible())
    do_something;

Assign output to variable in Bash

Same with something more complex...getting the ec2 instance region from within the instance.

INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")

echo $INSTANCE_REGION

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

$this->db->count_all_results is part of an Active Record query (preparing the query, to only return the number, not the actual results).

$query->num_rows() is performed on a resultset object (after returning results from the DB).

Difference between opening a file in binary vs text

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

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

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

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

Global variables in Java

// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).

// the first class
public class farm{

  int eggs; // an integer to be set by constructor
  fox afox; // declaration of a fox object

  // the constructor inits
  farm(){
    eggs = 4;
    afox = new fox(); // an instance of a fox object

    // show count of eggs before the fox arrives
    System.out.println("Count of eggs before: " + eggs);

    // call class fox, afox method, pass myFarm as a reference
    afox.stealEgg(this);

    // show the farm class, myFarm, primitive value
    System.out.println("Count of eggs after : " + eggs);

  } // end constructor

  public static void main(String[] args){

    // instance of a farm class object
    farm myFarm = new farm();

  }; // end main

} // end class

// the second class
public class fox{

  // theFarm is the myFarm object instance
  // any public, protected, or "no modifier" variable is accessible
  void stealEgg(farm theFarm){ --theFarm.eggs; }

} // end class

How to resize JLabel ImageIcon?

I agree this code works, to size an ImageIcon from a file for display while keeping the aspect ratio I have used the below.

/*
 * source File of image, maxHeight pixels of height available, maxWidth pixels of width available
 * @return an ImageIcon for adding to a label
 */


public ImageIcon rescaleImage(File source,int maxHeight, int maxWidth)
{
    int newHeight = 0, newWidth = 0;        // Variables for the new height and width
    int priorHeight = 0, priorWidth = 0;
    BufferedImage image = null;
    ImageIcon sizeImage;

    try {
            image = ImageIO.read(source);        // get the image
    } catch (Exception e) {

            e.printStackTrace();
            System.out.println("Picture upload attempted & failed");
    }

    sizeImage = new ImageIcon(image);

    if(sizeImage != null)
    {
        priorHeight = sizeImage.getIconHeight(); 
        priorWidth = sizeImage.getIconWidth();
    }

    // Calculate the correct new height and width
    if((float)priorHeight/(float)priorWidth > (float)maxHeight/(float)maxWidth)
    {
        newHeight = maxHeight;
        newWidth = (int)(((float)priorWidth/(float)priorHeight)*(float)newHeight);
    }
    else 
    {
        newWidth = maxWidth;
        newHeight = (int)(((float)priorHeight/(float)priorWidth)*(float)newWidth);
    }


    // Resize the image

    // 1. Create a new Buffered Image and Graphic2D object
    BufferedImage resizedImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();

    // 2. Use the Graphic object to draw a new image to the image in the buffer
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(image, 0, 0, newWidth, newHeight, null);
    g2.dispose();

    // 3. Convert the buffered image into an ImageIcon for return
    return (new ImageIcon(resizedImg));
}

Update records using LINQ

Yes, you have to get all records, update them and then call SaveChanges.

SQL Server query - Selecting COUNT(*) with DISTINCT

SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE push_number=@push_number 
GROUP BY program_type

Where can I find the API KEY for Firebase Cloud Messaging?

You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key

how to compare the Java Byte[] array?

You can also use a ByteArrayComparator from Apache Directory. In addition to equals it lets you compare if one array is greater than the other.

Removing a non empty directory programmatically in C or C++

//======================================================
// Recursely Delete files using:
//   Gnome-Glib & C++11
//======================================================

#include <iostream>
#include <string>
#include <glib.h>
#include <glib/gstdio.h>

using namespace std;

int DirDelete(const string& path)
{
   const gchar*    p;
   GError*   gerr;
   GDir*     d;
   int       r;
   string    ps;
   string    path_i;
   cout << "open:" << path << "\n";
   d        = g_dir_open(path.c_str(), 0, &gerr);
   r        = -1;

   if (d) {
      r = 0;

      while (!r && (p=g_dir_read_name(d))) {
          ps = string{p};
          if (ps == "." || ps == "..") {
            continue;
          }

          path_i = path + string{"/"} + p;


          if (g_file_test(path_i.c_str(), G_FILE_TEST_IS_DIR) != 0) {
            cout << "recurse:" << path_i << "\n";
            r = DirDelete(path_i);
          }
          else {
            cout << "unlink:" << path_i << "\n";
            r = g_unlink(path_i.c_str());
          }
      }

      g_dir_close(d);
   }

   if (r == 0) {
      r = g_rmdir(path.c_str());
     cout << "rmdir:" << path << "\n";

   }

   return r;
}

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

What worked for me was just typing the command passive and ftp went into passive mode from active mode.

Div height 100% and expands to fit content

This question may be old, but it deserves an update. Here is another way to do that:

#yourdiv {
    display: flex;
    width:100%;
    height:100%;
}

How to add leading zeros?

For other circumstances in which you want the number string to be consistent, I made a function.

Someone may find this useful:

idnamer<-function(x,y){#Alphabetical designation and number of integers required
    id<-c(1:y)
    for (i in 1:length(id)){
         if(nchar(id[i])<2){
            id[i]<-paste("0",id[i],sep="")
         }
    }
    id<-paste(x,id,sep="")
    return(id)
}
idnamer("EF",28)

Sorry about the formatting.

Is JavaScript guaranteed to be single-threaded?

I've tried @bobince's example with a slight modifications:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <textarea id="log" rows="20" cols="40"></textarea>
    <br />
    <button id="act">Run</button>
    <script type="text/javascript">
        let l= document.getElementById('log');
        let b = document.getElementById('act');
        let s = 0;

        b.addEventListener('click', function() {
            l.value += 'click begin\n';

            s = 10;
            let s2 = s;

            alert('alert!');

            s = s + s2;

            l.value += 'click end\n';
            l.value += `result = ${s}, should be ${s2 + s2}\n`;
            l.value += '----------\n';
        });

        window.addEventListener('resize', function() {
            if (s === 10) {
                s = 5;
            }

            l.value+= 'resize\n';
        });
    </script>
</body>
</html>

So, when you press Run, close alert popup and do a "single thread", you should see something like this:

click begin
click end
result = 20, should be 20

But if you try to run this in Opera or Firefox stable on Windows and minimize/maximize window with alert popup on screen, then there will be something like this:

click begin
resize
click end
result = 15, should be 20

I don't want to say, that this is "multithreading", but some piece of code had executed in a wrong time with me not expecting this, and now I have a corrupted state. And better to know about this behavior.

How to convert HTML file to word?

When doing this I found it easiest to:

  1. Visit the page in a web browser
  2. Save the page using the web browser with .htm extension (and maybe a folder with support files)
  3. Start Word and open the saved htmfile (Word will open it correctly)
  4. Make any edits if needed
  5. Select Save As and then choose the extension you would like doc, docx, etc.

Breaking out of a for loop in Java

How about

for (int k = 0; k < 10; k = k + 2) {
    if (k == 2) {
        break;
    }

    System.out.println(k);
}

The other way is a labelled loop

myloop:  for (int i=0; i < 5; i++) {

              for (int j=0; j < 5; j++) {

                if (i * j > 6) {
                  System.out.println("Breaking");
                  break myloop;
                }

                System.out.println(i + " " + j);
              }
          }

For an even better explanation you can check here

How to test for $null array in PowerShell

How do you want things to behave?

If you want arrays with no elements to be treated the same as unassigned arrays, use:

[array]$foo = @() #example where we'd want TRUE to be returned
@($foo).Count -eq 0

If you want a blank array to be seen as having a value (albeit an empty one), use:

[array]$foo = @() #example where we'd want FALSE to be returned
$foo.PSObject -eq $null

If you want an array which is populated with only null values to be treated as null:

[array]$foo = $null,$null
@($foo | ?{$_.PSObject}).Count -eq 0 

NB: In the above I use $_.PSObject over $_ to avoid [bool]$false, [int]0, [string]'', etc from being filtered out; since here we're focussed solely on nulls.

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

sql use statement with variable

Just wanted to thank KM for his valuable solution. I implemented it myself to reduce the amount of lines in a shrinkdatabase request on SQLServer. Here is my SQL request if it can help anyone :

-- Declare the variable to be used
DECLARE @Query varchar (1000)
DECLARE @MyDBN varchar(11);
-- Initializing the @MyDBN variable (possible values : db1, db2, db3, ...)
SET @MyDBN = 'db1';
-- Creating the request to execute
SET @Query='use '+ @MyDBN +'; ALTER DATABASE '+ @MyDBN +' SET RECOVERY SIMPLE WITH NO_WAIT; DBCC SHRINKDATABASE ('+ @MyDBN +', 1, TRUNCATEONLY); ALTER DATABASE '+ @MyDBN +' SET RECOVERY FULL WITH NO_WAIT'
-- 
EXEC (@Query)

Python str vs unicode types

Unicode and encodings are completely different, unrelated things.

Unicode

Assigns a numeric ID to each character:

  • 0x41 ? A
  • 0xE1 ? á
  • 0x414 ? ?

So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.

Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.

You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.

These numbers assigned to all characters by Unicode are called code points.

The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?

Note that Unicode code points are usually formatted with a leading U+, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.

Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).

The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.

Encodings

Map characters to bit patterns.

These bit patterns are used to represent the characters in computer memory or on disk.

There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:

ASCII

Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.

Example:

  • a ? 1100001 (0x61)

You can see all the mappings in this table.

ISO 8859-1 (aka Latin-1)

Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.

Example:

  • a ? 01100001 (0x61)
  • á ? 11100001 (0xE1)

You can see all the mappings in this table.

UTF-8

Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).

Example:

  • a ? 01100001 (0x61)
  • á ? 11000011 10100001 (0xC3 0xA1)
  • ? ? 11100010 10001001 10100000 (0xE2 0x89 0xA0)
  • ? 11110000 10011111 10011000 10000010 (0xF0 0x9F 0x98 0x82)

The way UTF-8 encodes characters to bit strings is very well described here.

Unicode and Encodings

Looking at the above examples, it becomes clear how Unicode is useful.

For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:

"I encode that a with an aigu (or however you call that rising bar) as 11100001"

But I can just say:

"I encode U+00E1 as 11100001"

And if I'm UTF-8, I can say:

"Me, in turn, I encode U+00E1 as 11000011 10100001"

And it's unambiguously clear to everybody which character we mean.

Now to the often arising confusion

It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.

For example:

  • ASCII encodes a as 1100001, which you can interpret as the hexadecimal number 0x61, and the Unicode code point of a is U+0061.
  • Latin-1 encodes á as 11100001, which you can interpret as the hexadecimal number 0xE1, and the Unicode code point of á is U+00E1.

Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.

Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.

Back to your question

The encoding used by your Python interpreter is UTF-8.

Here's what's going on in your examples:

Example 1

The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a.

>>> a = 'á'

When you look at the value of a, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1':

>>> a
'\xc3\xa1'

Example 2

The following saves the Unicode code point of á, which is U+00E1, in the variable ua (we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):

>>> ua = u'á'

When you look at the value of ua, Python tells you that it contains the code point U+00E1:

>>> ua
u'\xe1'

Example 3

The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:

>>> ua.encode('utf-8')
'\xc3\xa1'

Example 4

The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:

>>> ua.encode('latin1')
'\xe1'

There's no relation between the Unicode object ua and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.

HTML Tags in Javascript Alert() method

This is not possible.

Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.

IF Statement multiple conditions, same statement

Pretty old question but check this for a more clustered way of checking conditions:

private bool IsColumn(string col, params string[] names) => names.Any(n => n == col);

usage:

private void CheckColumn()
{
     if(!IsColumn(ColName, "Column A", "Column B", "Column C"))
    {
     //not A B C column
    }

}

'negative' pattern matching in python

Use a negative match. (Also note that whitespace is significant, by default, inside a regex so don't space things out. Alternatively, use re.VERBOSE.)

for item in output:
    matchObj = re.search("^(OK|\\.)", item)
    if not matchObj:
        print "got item " + item

Commit empty folder structure (with git)

Simply add file named as .keep in images folder.you can now stage and commit and also able to add folder to version control.

Create a empty file in images folder $ touch .keep

$ git status

On branch master
Your branch is up-to-date with 'origin/master'.

Untracked files:
  (use "git add ..." to include in what will be committed)

    images/

nothing added to commit but untracked files present (use "git add" to track)

$ git add .

$ git commit -m "adding empty folder"

log4j configuration via JVM argument(s)?

Do you have a log4j configuration file ? Just reference it using

-Dlog4j.configuration={path to file}

where {path to file} should be prefixed with file:

Edit: If you are working with log4j2, you need to use

-Dlog4j.configurationFile={path to file}

Taken from answer https://stackoverflow.com/a/34001970/552525

How to ensure that there is a delay before a service is started in systemd?

The systemd way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|

You might be able to do something inline like

ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here in an ExecStartPost

Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.

(May want to increase TimeoutStartSec from the default 90s as well)

Dynamically creating keys in a JavaScript associative array

In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).

A quick Google search brings up hash tables in JavaScript.

Example code for looping over values in a hash (from the aforementioned link):

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

using awk with column value conditions

This method uses regexp, it should work:

awk '$2 ~ /findtext/ {print $3}' <infile>

Avoid web.config inheritance in child web application using inheritInChildApplications

We were getting an error related to this after a recent release of code to one of our development environments. We have an application that is a child of another application. This relationship has been working fine for YEARS until yesterday.

The problem:
We were getting a yellow stack trace error due to duplicate keys being entered. This is because both the web.config for the child and parent applications had this key. But this existed for many years like this without change. Why all of sudden its an issue now?

The solution:
The reason this was never a problem is because the keys AND values were always the same. Yesterday we updated our SQL connection strings to include the Application Name in the connection string. This made the string unique and all of sudden started to fail.

Without doing any research on the exact reason for this, I have to assume that when the child application inherits the parents web.config values, it ignores identical key/value pairs.

We were able to solve it by wrapping the connection string like this

    <location path="." inheritInChildApplications="false">
        <connectionStrings>
            <!-- Updated connection strings go here -->
        </connectionStrings>
    </location>

Edit: I forgot to mention that I added this in the PARENTS web.config. I didn't have to modify the child's web.config.

Thanks for everyones help on this, saved our butts.

Setting width and height

Use this, it works fine.

<canvas id="totalschart" style="height:400px;width: content-box;"></canvas>

and under options,

responsive:true,

How to use color picker (eye dropper)?

Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.

However, I'm able to grab colors easily in Firefox.

  1. Open page in Firefox
  2. Hamburger Menu -> Web Developer -> Eyedropper
  3. Drag eyedropper tool over the image... Click.
    Color is copied to your clipboard, and eyedropper tool goes away.
  4. Paste color code

In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

How to keep one variable constant with other one changing with row in excel

You put it as =(B0+4)/($A$0)

You can also go across WorkSheets with Sheet1!$a$0

How to create a pivot query in sql server without aggregate function

Check this out as well: using xml path and pivot

SQLFIDDLE DEMO

| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
|   Asset |  205 |  142 |  421 |
|  Equity |  365 |  214 |  163 |
|  Profit |  524 |  421 |  325 |

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period) 
            FROM demo c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT account, ' + @cols + ' from 
            (
                select account
                    , value
                    , period
                from demo
           ) x
            pivot 
            (
                 max(value)
                for period in (' + @cols + ')
            ) p '


execute(@query)

How to get the file name from a full path using JavaScript?

Ates, your solution doesn't protect against an empty string as input. In that case, it fails with TypeError: /([^(\\|\/|\:)]+)$/.exec(fullPath) has no properties.

bobince, here's a version of nickf's that handles DOS, POSIX, and HFS path delimiters (and empty strings):

return fullPath.replace(/^.*(\\|\/|\:)/, '');

Is it possible to view RabbitMQ message contents directly from the command line?

a bit late to this, but yes rabbitmq has a build in tracer that allows you to see the incomming messages in a log. When enabled, you can just tail -f /var/tmp/rabbitmq-tracing/.log (on mac) to watch the messages.

the detailed discription is here http://www.mikeobrien.net/blog/tracing-rabbitmq-messages

Google Maps: Auto close open InfoWindows?

alternative solution for this with using many infowindows: save prev opened infowindow in a variable and then close it when new window opened

var prev_infowindow =false; 
...
base.attachInfo = function(marker, i){
    var infowindow = new google.maps.InfoWindow({
        content: 'yourmarkerinfocontent'
    });

    google.maps.event.addListener(marker, 'click', function(){
        if( prev_infowindow ) {
           prev_infowindow.close();
        }

        prev_infowindow = infowindow;
        infowindow.open(base.map, marker);
    });
}

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How to calculate moving average without keeping the count and data-total?

A neat Python solution based on the above answers:

class RunningAverage():
    def __init__(self):
        self.average = 0
        self.n = 0
        
    def __call__(self, new_value):
        self.n += 1
        self.average = (self.average * (self.n-1) + new_value) / self.n 
        
    def __float__(self):
        return self.average
    
    def __repr__(self):
        return "average: " + str(self.average)

usage:

x = RunningAverage()
x(0)
x(2)
x(4)
print(x)

Android: ProgressDialog.show() crashes with getApplicationContext

Which API version are you using? If I'm right about what the problem is then this was fixed in Android 1.6 (API version 4).

It looks like the object reference that getApplicationContext() is returning just points to null. I think you're having a problem similar to one I had in that some of the code in the onCreate() is being run before the window is actually done being built. This is going to be a hack, but try launching a new Thread in a few hundred milliseconds (IIRC: 300-400 seemed to work for me, but you'll need to tinker) that opens your ProgressDialog and starts anything else you needed (eg. network IO). Something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    // do all your other stuff here

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mProgressDialog = ProgressDialog.show(
               YouTube.this.getApplicationContext(), "",
               YouTube.this.getString(R.string.loading), true);

            // start time consuming background process here
        }
    }, 1000); // starting it in 1 second
}

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

Getting all documents from one collection in Firestore

Here's a simple version of the top answer, but going into an object with the document ids:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    return snapshot.docs.reduce(function (acc, doc, i) {
              acc[doc.id] = doc.data();
              return acc;
            }, {});
}

Java: Integer equals vs. ==

Integer refers to the reference, that is, when comparing references you're comparing if they point to the same object, not value. Hence, the issue you're seeing. The reason it works so well with plain int types is that it unboxes the value contained by the Integer.

May I add that if you're doing what you're doing, why have the if statement to begin with?

mismatch = ( cdiCt != null && cdsCt != null && !cdiCt.equals( cdsCt ) );

How to rename a component in Angular CLI?

If you are using VS Code, you can rename the .ts, .html, .css/.scss, .spec.ts files and the IDE will take care of the imports for you. Therefore there will be no complaints from the files that import files from your component (such as app.module.ts). However, you will still have to rename the component name everywhere it is being used.

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

I ran into this problem! I accidentally installed the 32-bit version of Miniconda3. Make sure you choose the 64 bit version!

Python Pylab scatter plot error bars (the error on each point is unique)

This is almost like the other answer but you don't need a scatter plot at all, you can simply specify a scatter-plot-like format (fmt-parameter) for errorbar:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
e = [0.5, 1., 1.5, 2.]
plt.errorbar(x, y, yerr=e, fmt='o')
plt.show()

Result:

enter image description here

A list of the avaiable fmt parameters can be found for example in the plot documentation:

character   description
'-'     solid line style
'--'    dashed line style
'-.'    dash-dot line style
':'     dotted line style
'.'     point marker
','     pixel marker
'o'     circle marker
'v'     triangle_down marker
'^'     triangle_up marker
'<'     triangle_left marker
'>'     triangle_right marker
'1'     tri_down marker
'2'     tri_up marker
'3'     tri_left marker
'4'     tri_right marker
's'     square marker
'p'     pentagon marker
'*'     star marker
'h'     hexagon1 marker
'H'     hexagon2 marker
'+'     plus marker
'x'     x marker
'D'     diamond marker
'd'     thin_diamond marker
'|'     vline marker
'_'     hline marker

Facebook OAuth "The domain of this URL isn't included in the app's domain"

Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings.

I had this issue today, I find the Facebook documentation and SDK disrespectful and arogant towards other developers to say the least.

Besides having the "app domains" in two different locations without much information (3 if you add a "web" platform), you also need to go to app products / facebook login / settings and add your redirect URL under Valid OAuth Redirect URIs

The error says NOTHING about the oauth settings.

How do I unload (reload) a Python module?

Edit (Answer V2)

The solution from before is good for just getting the reset information, but it will not change all the references (more than reload but less then required). To actually set all the references as well, I had to go into the garbage collector, and rewrite the references there. Now it works like a charm!

Note that this will not work if the GC is turned off, or if reloading data that's not monitored by the GC. If you don't want to mess with the GC, the original answer might be enough for you.

New code:

import importlib
import inspect
import gc
from weakref import ref


def reset_module(module, inner_modules_also=True):
    """
    This function is a stronger form of importlib's `reload` function. What it does, is that aside from reloading a
    module, it goes to the old instance of the module, and sets all the (not read-only) attributes, functions and classes
    to be the reloaded-module's
    :param module: The module to reload (module reference, not the name)
    :param inner_modules_also: Whether to treat ths module as a package as well, and reload all the modules within it.
    """

    # For the case when the module is actually a package
    if inner_modules_also:
        submods = {submod for _, submod in inspect.getmembers(module)
                   if (type(submod).__name__ == 'module') and (submod.__package__.startswith(module.__name__))}
        for submod in submods:
            reset_module(submod, True)

    # First, log all the references before reloading (because some references may be changed by the reload operation).
    module_tree = _get_tree_references_to_reset_recursively(module, module.__name__)

    new_module = importlib.reload(module)
    _reset_item_recursively(module, module_tree, new_module)


def _update_referrers(item, new_item):
    refs = gc.get_referrers(item)

    weak_ref_item = ref(item)
    for coll in refs:
        if type(coll) == dict:
            enumerator = coll.keys()
        elif type(coll) == list:
            enumerator = range(len(coll))
        else:
            continue

        for key in enumerator:

            if weak_ref_item() is None:
                # No refs are left in the GC
                return

            if coll[key] is weak_ref_item():
                coll[key] = new_item

def _get_tree_references_to_reset_recursively(item, module_name, grayed_out_item_ids = None):
    if grayed_out_item_ids is None:
        grayed_out_item_ids = set()

    item_tree = dict()
    attr_names = set(dir(item)) - _readonly_attrs
    for sub_item_name in attr_names:

        sub_item = getattr(item, sub_item_name)
        item_tree[sub_item_name] = [sub_item, None]

        try:
            # Will work for classes and functions defined in that module.
            mod_name = sub_item.__module__
        except AttributeError:
            mod_name = None

        # If this item was defined within this module, deep-reset
        if (mod_name is None) or (mod_name != module_name) or (id(sub_item) in grayed_out_item_ids) \
                or isinstance(sub_item, EnumMeta):
            continue

        grayed_out_item_ids.add(id(sub_item))
        item_tree[sub_item_name][1] = \
            _get_tree_references_to_reset_recursively(sub_item, module_name, grayed_out_item_ids)

    return item_tree


def _reset_item_recursively(item, item_subtree, new_item):

    # Set children first so we don't lose the current references.
    if item_subtree is not None:
        for sub_item_name, (sub_item, sub_item_tree) in item_subtree.items():

            try:
                new_sub_item = getattr(new_item, sub_item_name)
            except AttributeError:
                # The item doesn't exist in the reloaded module. Ignore.
                continue

            try:
                # Set the item
                _reset_item_recursively(sub_item, sub_item_tree, new_sub_item)
            except Exception as ex:
                pass

    _update_referrers(item, new_item)

Original Answer

As written in @bobince's answer, if there's already a reference to that module in another module (especially if it was imported with the as keyword like import numpy as np), that instance will not be overwritten.

This proved quite problematic to me when applying tests that required a "clean-slate" state of the configuration modules, so I've written a function named reset_module that uses importlib's reload function and recursively overwrites all the declared module's attributes. It has been tested with Python version 3.6.

import importlib
import inspect
from enum import EnumMeta

_readonly_attrs = {'__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',
               '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__',
               '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__',
               '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__',
               '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__',
               '__subclasshook__', '__weakref__', '__members__', '__mro__', '__itemsize__', '__isabstractmethod__',
               '__basicsize__', '__base__'}


def reset_module(module, inner_modules_also=True):
    """
    This function is a stronger form of importlib's `reload` function. What it does, is that aside from reloading a
    module, it goes to the old instance of the module, and sets all the (not read-only) attributes, functions and classes
    to be the reloaded-module's
    :param module: The module to reload (module reference, not the name)
    :param inner_modules_also: Whether to treat ths module as a package as well, and reload all the modules within it.
    """

    new_module = importlib.reload(module)

    reset_items = set()

    # For the case when the module is actually a package
    if inner_modules_also:
        submods = {submod for _, submod in inspect.getmembers(module)
                   if (type(submod).__name__ == 'module') and (submod.__package__.startswith(module.__name__))}
        for submod in submods:
            reset_module(submod, True)

    _reset_item_recursively(module, new_module, module.__name__, reset_items)


def _reset_item_recursively(item, new_item, module_name, reset_items=None):
    if reset_items is None:
        reset_items = set()

    attr_names = set(dir(item)) - _readonly_attrs

    for sitem_name in attr_names:

        sitem = getattr(item, sitem_name)
        new_sitem = getattr(new_item, sitem_name)

        try:
            # Set the item
            setattr(item, sitem_name, new_sitem)

            try:
                # Will work for classes and functions defined in that module.
                mod_name = sitem.__module__
            except AttributeError:
                mod_name = None

            # If this item was defined within this module, deep-reset
            if (mod_name is None) or (mod_name != module_name) or (id(sitem) in reset_items) \
                    or isinstance(sitem, EnumMeta):  # Deal with enums
                continue

            reset_items.add(id(sitem))
            _reset_item_recursively(sitem, new_sitem, module_name, reset_items)
        except Exception as ex:
            raise Exception(sitem_name) from ex

Note: Use with care! Using these on non-peripheral modules (modules that define externally-used classes, for example) might lead to internal problems in Python (such as pickling/un-pickling issues).

Disable double-tap "zoom" option in browser on touch devices

You should set the css property touch-action to none as described in this other answer https://stackoverflow.com/a/42288386/1128216

.disable-doubletap-to-zoom {
    touch-action: none;
}

jQuery UI dialog positioning

To put it right on top of control, you can use this code:

    $("#dialog-edit").dialog({
...    
        position: { 
            my: 'top',
            at: 'top',
            of: $('#myControl')
        },

...
    });

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

How can I order a List<string>?

ListaServizi = ListaServizi.OrderBy(q => q).ToList();

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

How to synchronize or lock upon variables in Java?

For this functionality you are better off not using a lock at all. Try an AtomicReference.

public class Sample {
    private final AtomicReference<String> msg = new AtomicReference<String>();

    public void setMsg(String x) {
        msg.set(x);
    }

    public String getMsg() {
        return msg.getAndSet(null);
    }
}

No locks required and the code is simpler IMHO. In any case, it uses a standard construct which does what you want.

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Iterating over every property of an object in javascript using Prototype?

You should iterate over the keys and get the values using square brackets.

See: How do I enumerate the properties of a javascript object?

EDIT: Obviously, this makes the question a duplicate.

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

How to write an ArrayList of Strings into a text file?

I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset()); will not do this,throwing exception if the parent directories don't exist.

FileUtils.writeLines(new File("output.txt"), encoding, list);

Check if input value is empty and display an alert

Check empty input with removing space(if user enter space) from input using trim

$(document).ready(function(){     
       $('#button').click(function(){
            if($.trim($('#fname').val()) == '')
           {
               $('#fname').css("border-color", "red");
               alert("Empty"); 
           }
     });
});

Best cross-browser method to capture CTRL+S with JQuery?

You could use a shortcut library to handle the browser specific stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});

How to download file in swift?

Downloading a file in Swift 5 with progress reporting, encapsulated into a copy-paste friendly protocol-accessed class:

protocol FileDownloadingDelegate: class {
    func updateDownloadProgressWith(progress: Float)
    func downloadFinished(localFilePath: URL)
    func downloadFailed(withError error: Error)
}

class FilesDownloader: NSObject, URLSessionDownloadDelegate {
    private weak var delegate: FileDownloadingDelegate?

    func download(from url: URL, delegate: FileDownloadingDelegate) {
        self.delegate = delegate
        let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString) // use this identifier to resume download after app restart
        let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
        let task = session.downloadTask(with: url)
        task.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        DispatchQueue.main.async { self.delegate?.downloadFinished(localFilePath: location) }
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        DispatchQueue.main.async { self.delegate?.updateDownloadProgressWith(progress: Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)) }
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        guard let theError = error else { assertionFailure("something weird happened here"); return }
        DispatchQueue.main.async { self.delegate?.downloadFailed(withError: theError) }
    }

}

How to use it:

class MyViewController: UIViewController {

    private lazy var downloader = FilesDownloader()

    func downloadFile(from url: URL) {
        downloader.download(from: url, delegate: self)
    }

}

extension MyViewController: FileDownloadingDelegate {
    func updateDownloadProgressWith(progress: Float) {
        // self.downloadProgressView.setProgress(progress, animated: true)
    }

    func downloadFinished(tempFilePath: URL) {
        print("downloaded to \(tempFilePath)")
        // resave the file into your desired place using 
        // let dataFromURL = NSData(contentsOf: location)
        // dataFromURL?.write(to: yourDesiredFileUrl, atomically: true)
    }

    func downloadFailed(withError error: Error) {
        // handle the error
    }
}

CSS background-image-opacity?

#id {
  position: relative;
  opacity: 0.99;
}

#id::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: url('image.png');
  opacity: 0.3;
}

Hack with opacity 0.99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.

Demo.

JQuery get data from JSON array

try this

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

How much RAM is SQL Server actually using?

You should explore SQL Server\Memory Manager performance counters.

Perform curl request in javascript?

You can use JavaScripts Fetch API (available in your browser) to make network requests.

If using node, you will need to install the node-fetch package.

const url = "https://api.wit.ai/message?v=20140826&q=";

const options = {
  headers: {
    Authorization: "Bearer 6Q************"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

Sublime Text 3, convert spaces to tabs

if you have Mac just use help option (usually the last option on Mac's menu bar) then type: "tab indentation" and choose a tab indentation width

but generally, you can follow this path: view -> indentation

SQL Server: Extract Table Meta-Data (description, fields and their data types)

If it is OK to use .NET code I'd suggest using SMO: http://msdn.microsoft.com/en-us/library/ms162169.aspx, In your particular case it would be the Table class http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.table.aspx This would be a more portable solution than using version specific system views and tables.

If this is something you are going to use on a regular basis - you might want to write a simple console application, perhaps with a runtime T4 code generator http://msdn.microsoft.com/en-us/library/ee844259.aspx

If it's just a one-off task - you could use my LiveDoco's( http://www.livedoco.com ) export to XML feature with an optional XSLT transform or I'm sure there are free tools out there that can do this. This one looks okay: http://sqldbdoc.codeplex.com/ - supports XML via XSLT, but I'm not sure if you can run it for a selection of tables though (With LiveDoco you can).

jQuery Determine if a matched class has a given id

You could also check if the id element is used by doing so:

if(typeof $(.div).attr('id') == undefined){
   //element has no id
} else {
   //element has id selector
}

I use this method for global dataTables and specific ordered dataTables

How are software license keys generated?

There are also DRM behaviors that incorporate multiple steps to the process. One of the most well known examples is one of Adobe's methods for verifying an installation of their Creative Suite. The traditional CD Key method discussed here is used, then Adobe's support line is called. The CD key is given to the Adobe representative and they give back an activation number to be used by the user.

However, despite being broken up into steps, this falls prey to the same methods of cracking used for the normal process. The process used to create an activation key that is checked against the original CD key was quickly discovered, and generators that incorporate both of the keys were made.

However, this method still exists as a way for users with no internet connection to verify the product. Going forward, it's easy to see how these methods would be eliminated as internet access becomes ubiquitous.

UIView Hide/Show with animation

isHidden is an immediate value and you cannot affect an animation on it, instead of this you can use Alpha for hide your view

UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
        view.alpha = 0
    })

And for showing:

UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations: {
      view.alpha = 1
})

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

What does "javascript:void(0)" mean?

Web Developers use javascript:void(0) because it is the easiest way to prevent the default behavior of a tag. void(*anything*) returns undefined and it is a falsy value. and returning a falsy value is like return false in onclick event of a tag that prevents its default behavior.

So I think javascript:void(0) is the simplest way to prevent the default behavior of a tag.

How to pop an alert message box using PHP?

Create function for alert

<?php
alert("Hello World");

function alert($msg) {
    echo "<script type='text/javascript'>alert('$msg');</script>";
}
?>

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

Installing Google Protocol Buffers on mac

brew install --devel protobuf

If it tells you "protobuf-2.6.1 already installed": 1. brew uninstall --devel protobuf 2. brew link libtool 3. brew install --devel protobuf

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

How do I get PHP errors to display?

     error_reporting(1);
     ini_set('display_errors', '1');
     ini_set('display_startup_errors', '1');
     error_reporting(E_ALL);

Put this at the top of your page.

How do I select a MySQL database through CLI?

While invoking the mysql CLI, you can specify the database name through the -D option. From mysql --help:

-D, --database=name Database to use.

I use this command:

mysql -h <db_host> -u <user> -D <db_name> -p

What difference is there between WebClient and HTTPWebRequest classes in .NET?

I know its too longtime to reply but just as an information purpose for future readers:

WebRequest

System.Object
    System.MarshalByRefObject
        System.Net.WebRequest

The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest.

You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream.

There are also FileWebRequest and FtpWebRequest classes that inherit from WebRequest. Normally, you would use WebRequest to, well, make a request and convert the return to either HttpWebRequest, FileWebRequest or FtpWebRequest, depend on your request. Below is an example:

Example:

var _request = (HttpWebRequest)WebRequest.Create("http://stackverflow.com");
var _response = (HttpWebResponse)_request.GetResponse();

WebClient

System.Object
        System.MarshalByRefObject
            System.ComponentModel.Component
                System.Net.WebClient

WebClient provides common operations to sending and receiving data from a resource identified by a URI. Simply, it’s a higher-level abstraction of HttpWebRequest. This ‘common operations’ is what differentiate WebClient from HttpWebRequest, as also shown in the sample below:

Example:

var _client = new WebClient();
var _stackContent = _client.DownloadString("http://stackverflow.com");

There are also DownloadData and DownloadFile operations under WebClient instance. These common operations also simplify code of what we would normally do with HttpWebRequest. Using HttpWebRequest, we have to get the response of our request, instantiate StreamReader to read the response and finally, convert the result to whatever type we expect. With WebClient, we just simply call DownloadData, DownloadFile or DownloadString.

However, keep in mind that WebClient.DownloadString doesn’t consider the encoding of the resource you requesting. So, you would probably end up receiving weird characters if you don’t specify and encoding.

NOTE: Basically "WebClient takes few lines of code as compared to Webrequest"

HTTP POST with Json on Body - Flutter/Dart

I think many people have problems with Post 'Content-type': 'application / json' The problem here is parse data Map <String, dynamic> to json:

Hope the code below can help someone

Model:

class ConversationReq {
  String name = '';
  String description = '';
  String privacy = '';
  String type = '';
  String status = '';

  String role;
  List<String> members;
  String conversationType = '';

  ConversationReq({this.type, this.name, this.status, this.description, this.privacy, this.conversationType, this.role, this.members});

  Map<String, dynamic> toJson() {

    final Map<String, dynamic> data = new Map<String, dynamic>();

    data['name'] = this.name;
    data['description'] = this.description;
    data['privacy'] = this.privacy;
    data['type'] = this.type;

    data['conversations'] = [
      {
        "members": members,
        "conversationType": conversationType,
      }
    ];

    return data;
  }
}

Request:

createNewConversation(ConversationReq param) async {
    HeaderRequestAuth headerAuth = await getAuthHeader();
    var headerRequest = headerAuth.toJson();
/*
{
            'Content-type': 'application/json',
            'x-credential-session-token': xSectionToken,
            'x-user-org-uuid': xOrg,
          }
*/

    var bodyValue = param.toJson();

    var bodydata = json.encode(bodyValue);// important
    print(bodydata);

    final response = await http.post(env.BASE_API_URL + "xxx", headers: headerRequest, body: bodydata);

    print(json.decode(response.body));
    if (response.statusCode == 200) {
      // TODO
    } else {
      // If that response was not OK, throw an error.
      throw Exception('Failed to load ConversationRepo');
    }
  }

Create PostgreSQL ROLE (user) if it doesn't exist

Bash alternative (for Bash scripting):

psql -h localhost -U postgres -tc \
"SELECT 1 FROM pg_user WHERE usename = 'my_user'" \
| grep -q 1 \
|| psql -h localhost -U postgres \
-c "CREATE ROLE my_user LOGIN PASSWORD 'my_password';"

(isn't the answer for the question! it is only for those who may be useful)

Loading custom functions in PowerShell

I kept using this all this time

Import-module .\build_functions.ps1 -Force

TypeError: Cannot read property "0" from undefined

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

How to select specific columns in laravel eloquent

You can also use find() like this:

ModelName::find($id, ['name', 'surname']);

The $id variable can be an array in case you need to retrieve multiple instances of the model.

ASP.NET MVC Conditional validation

I'm using MVC 5 but you could try something like this:

public DateTime JobStart { get; set; }

[AssertThat("StartDate >= JobStart", ErrorMessage = "Time Manager may not begin before job start date")]
[DisplayName("Start Date")]
[Required]
public DateTime? StartDate { get; set; }

In your case you would say something like "IsSenior == true". Then you just need to check the validation on your post action.

How to update ruby on linux (ubuntu)?

There's really no reason to remove ruby1-8, unless someone else knows better. Execute the commands below to install 1.9 and then link ruby to point to the new version.

sudo apt-get install ruby1-9 rubygems1-9
sudo ln -sf /usr/bin/ruby1-9 /usr/bin/ruby

while-else-loop

Java does not have this control structure.
It should be noted though, that other languages do.
Python for example, has the while-else construct.

In Java's case, you can mimic this behaviour as you have already shown:

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your HTML you have set a "base" tag:

<base href="http://www.cyclistinsuranceaustralia.com.au/">
  1. Delete that line from your HTML if you don't need it. This should make the fonts work when viewed from http://cyclistinsuranceaustralia.com.au.
  2. You'll probably need to redirect http://www.cyclistinsuranceaustralia.com.au to http://cyclistinsuranceaustralia.com.au

When to use a linked list over an array/array list?

Hmm, Arraylist can be used in cases like follows I guess:

  1. you are not sure how many elements will be present
  2. but you need to access all the elements randomly through indexing

For eg, you need to import and access all elements in a contact list (the size of which is unknown to you)

Is it possible to use if...else... statement in React render function?

The shorthand for an if else structure works as expected in JSX

this.props.hasImage ? <MyImage /> : <SomeotherElement>

You can find other options on this blogpost of DevNacho, but it's more common to do it with the shorthand. If you need to have a bigger if clause you should write a function that returns or component A or component B.

for example:

this.setState({overlayHovered: true});

renderComponentByState({overlayHovered}){
    if(overlayHovered) {
        return <overlayHoveredComponent />
    }else{
        return <overlayNotHoveredComponent />
    }
}

You can destructure your overlayHovered from this.state if you give it as parameter. Then execute that function in your render() method:

renderComponentByState(this.state)

Order a MySQL table by two columns

ORDER BY article_rating, article_time DESC

will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 4, 2009    3.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

but consider:

? primary sort                         secondary sort ?
1.  50 | This article rocks          | Feb 2, 2009    3.
1.  50 | This article rocks, too     | Feb 4, 2009    4.
2.  35 | This article is pretty good | Feb 1, 2009    2.
3.  5  | This Article isn't so hot   | Jan 25, 2009   1.

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

Expired certificate was the cause of our "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated".

keytool -list -v -keystore filetruststore.ts

    Enter keystore password:
    Keystore type: JKS
    Keystore provider: SUN
    Your keystore contains 1 entry
    Alias name: somealias
    Creation date: Jul 26, 2012
    Entry type: PrivateKeyEntry
    Certificate chain length: 1
    Certificate[1]:
    Owner: CN=Unknown, OU=SomeOU, O="Some Company, Inc.", L=SomeCity, ST=GA, C=US
    Issuer: CN=Unknown, OU=SomeOU, O=Some Company, Inc.", L=SomeCity, ST=GA, C=US
    Serial number: 5011a47b
    Valid from: Thu Jul 26 16:11:39 EDT 2012 until: Wed Oct 24 16:11:39 EDT 2012

List<Map<String, String>> vs List<? extends Map<String, String>>

What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:

Covariance

If you have a class Automobile, then Car and Truck are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.

I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:

List<Car> cars;
List<Automobile> automobiles = cars;
// You'd expect this to work because Car is-a Automobile, but
// throws inconvertible types compile error.

The reason of the error is, however, correct: List<Car> does not inherit from List<Automobile> and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:

List<Car> cars;
List<? extends Automobile> automobiles = cars;   // no error

Contravariance

The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:

class AutoColorComparer implements Comparator<Automobile>
    public int compare(Automobile a, Automobile b) {
        // Return comparison of colors
    }

This can be used with Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

// Which you can call like this, without errors:
List<Car> cars = getListFromSomewhere();
Collections.sort(cars, new AutoColorComparer());

You could even call it with a comparer that compares objects and use it with any type.

When to use contra or co-variance?

A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you get something, use covariance and when you put something, use contravariance. This is best explained in an answer to Stack Overflow question How would contravariance be used in Java generics?.

So what is it then with List<? extends Map<String, String>>

You use extends, so the rules for covariance applies. Here you have a list of maps and each item you store in the list must be a Map<string, string> or derive from it. The statement List<Map<String, String>> cannot derive from Map, but must be a Map.

Hence, the following will work, because TreeMap inherits from Map:

List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(new TreeMap<String, String>());

but this will not:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new TreeMap<String, String>());

and this will not work either, because it does not satisfy the covariance constraint:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new ArrayList<String>());   // This is NOT allowed, List does not implement Map

What else?

This is probably obvious, but you may have already noted that using the extends keyword only applies to that parameter and not to the rest. I.e., the following will not compile:

List<? extends Map<String, String>> mapList = new List<? extends Map<String, String>>();
mapList.add(new TreeMap<String, Element>())  // This is NOT allowed

Suppose you want to allow any type in the map, with a key as string, you can use extend on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:

List<? extends Map<String, ? extends Node>> listOfMapsOfNodes = new...;

// Now you can do:
listOfMapsOfNodes.add(new TreeMap<Sting, Element>());
listOfMapsOfNodes.add(new TreeMap<Sting, CDATASection>());

Can one do a for each loop in java in reverse order?

You can use the Collections class to reverse the list then loop.

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

Java function for arrays like PHP's join()?

Starting from Java8 it is possible to use String.join().

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String.

For example:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String:

Hello, World, !

Upgrade python without breaking yum

ln -s /usr/local/bin/python2.7 /usr/bin/python

GridView - Show headers on empty data source

<asp:GridView ID="gvEmployee" runat="server"    
                 AutoGenerateColumns="False" ShowHeaderWhenEmpty=”True”>  
                    <Columns>  
                        <asp:BoundField DataField="Id" HeaderText="Id" />  
                        <asp:BoundField DataField="Name" HeaderText="Name" />  
                        <asp:BoundField DataField="Designation" HeaderText="Designation" />  
                        <asp:BoundField DataField="Salary" HeaderText="Salary"  />  
                    </Columns>  
                    <EmptyDataTemplate>No Record Available</EmptyDataTemplate>  
                </asp:GridView>  


in CS Page

gvEmployee.DataSource = dt;  
gvEmployee.DataBind();  

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

Waiting for another flutter command to release the startup lock

On Mac remove hidden file: <FLUTTER_HOME>/bin/cache/.upgrade_lock

Accessing a property in a parent Component

Since the parent-child interaction is not an easy task to do. But by having a reference for the parent component in the child component it would be much easier to interact. In my method, you need to first pass a reference of the parent component by calling the function of the child component. Here is the for this method.

The Code For Child Component.

    import { Component, Input,ElementRef,Renderer2 } from '@angular/core';

    import { ParentComponent } from './parent.component';

    @Component({
      selector: 'qb-child',
      template: `<div class="child"><button (click)="parentClickFun()">Show text Of Parent Element</button><button (click)="childClickFun()">Show text Of Child Element</button><ng-content></ng-content></div>`,
      styleUrls: ['./app.component.css']
    })
    export class ChildComponent  {
      constructor(private el: ElementRef,private rend: Renderer2){

      };

      qbParent:ParentComponent; 
      getParent(parentEl):void{
        this.qbParent=parentEl;
        console.log(this.el.nativeElement.innerText);
      }
      @Input() name: string;
      childClickFun():void{
        console.log("Properties of Child Component is Accessed");
      }

      parentClickFun():void{
        this.qbParent.callFun();
      }
    }

This is Code for parent Component

import { Component, Input , AfterViewInit,ContentChild,ElementRef,Renderer2} from '@angular/core';

import { ChildComponent } from './child.component';

@Component({
  selector: 'qb-parent',
  template: `<div class="parent"><ng-content></ng-content></div>`,
  styleUrls: ['./app.component.css']
})
export class ParentComponent implements AfterViewInit {
  constructor(private el: ElementRef,private rend: Renderer2){

  };
  @Input() name: string;
  @ContentChild(ChildComponent,{read:ChildComponent,static:true}) qbChild:ChildComponent;

  ngAfterViewInit():void{
    this.qbChild.getParent(this);
  }

  callFun():void{
    console.log("Properties of Parent Component is Accessed");
  }

}

The Html Code

<qb-parent>
  This is Parent
  <qb-child>
    This is Child
  </qb-child>
</qb-parent>

Here we pass the parent component by calling a function of the child component. The link below is an example of this method. Click here!

How can I determine the URL that a local Git repository was originally cloned from?

Short answer:

$ git remote show -n origin

or, an alternative for pure quick scripts:

$ git config --get remote.origin.url

Some info:

  1. $ git remote -v will print all remotes (not what you want). You want origin right?
  2. $ git remote show origin much better, shows only origin but takes too long (tested on git version 1.8.1.msysgit.1).

I ended up with: $ git remote show -n origin, which seems to be fastest. With -n it will not fetch remote heads (AKA branches). You don't need that type of info, right?

http://www.kernel.org/pub//software/scm/git/docs/git-remote.html

You can apply | grep -i fetch to all three versions to show only the fetch URL.

If you require pure speed, then use:

$ git config --get remote.origin.url

Thanks to @Jefromi for pointing that out.

Using lodash to compare jagged arrays (items existence without order)

Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays

It's an old question, but I was having issues with the speed of using .sort() or sortBy(), so I used this instead:

function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
  return (
    array1.length === array2.length &&
    array1.every((str) => array2.includes(str)) &&
    array2.every((str) => array1.includes(str))
  )
}

It was intended to fail fast, and for my purposes works fine.