Programs & Examples On #Divide and conquer

Divide-and-conquer is a top-down technique for designing algorithms that consists of dividing the problem into smaller subproblems hoping that the solutions of the subproblems are easier to find and then composing the partial solutions into the solution of the original problem.

Difference between Divide and Conquer Algo and Dynamic Programming

The other difference between divide and conquer and dynamic programming could be:

Divide and conquer:

  1. Does more work on the sub-problems and hence has more time consumption.
  2. In divide and conquer the sub-problems are independent of each other.

Dynamic programming:

  1. Solves the sub-problems only once and then stores it in the table.
  2. In dynamic programming the sub-problem are not independent.

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

How do I make an auto increment integer field in Django?

What I needed: A document number with a fixed number of integers that would also act like an AutoField.

My searches took me all over incl. this page.

Finally I did something like this:

I created a table with a DocuNumber field as an IntegerField with foll. attributes:

  • max_length=6
  • primary_key=True
  • unique=True
  • default=100000

The max_length value anything as required (and thus the corresponding default= value).

A warning is issued while creating the said model, which I could ignore.

Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.

Afterwards changed the model key field as:

  • Changed the field type as: AutoField
  • Got rid of the max_length And defaultattributes
  • Retained the primary_key = True attribute

The next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.

So far so good.

Send form data using ajax

as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:

First Solution

function submitForm(form){
    var url = form.attr("action");
    var formData = {};
    $(form).find("input[name]").each(function (index, node) {
        formData[node.name] = node.value;
    });
    $.post(url, formData).done(function (data) {
        alert(data);
    });
}

Second Solution: in this solution you can create an array of input values:

function submitForm(form){
    var url = form.attr("action");
    var formData = $(form).serializeArray();
    $.post(url, formData).done(function (data) {
        alert(data);
    });
}

How to add an element to the beginning of an OrderedDict?

If you know you will want a 'c' key, but do not know the value, insert 'c' with a dummy value when you create the dict.

d1 = OrderedDict([('c', None), ('a', '1'), ('b', '2')])

and change the value later.

d1['c'] = 3

How can I run MongoDB as a Windows service?

Plz try the steps in Mongo DB: 3.6 & Windows 10

  1. mongod --remove
  2. mongod --dbpath=C:/data/db --port 27017 --logpath C:/data/log/log.txt --service
  3. mongod --dbpath=C:/data/db --port 27017 --logpath C:/data/log/log.txt --install
  4. net start MongoDB

Sorting HashMap by values

package com.naveen.hashmap;

import java.util.*;
import java.util.Map.Entry;

public class SortBasedonValues {

    /**
     * @param args
     */
    public static void main(String[] args) {

        HashMap<String, Integer> hm = new HashMap<String, Integer>();
        hm.put("Naveen", 2);
        hm.put("Santosh", 3);
        hm.put("Ravi", 4);
        hm.put("Pramod", 1);
        Set<Entry<String, Integer>> set = hm.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                set);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        for (Entry<String, Integer> entry : list) {
            System.out.println(entry.getValue());

        }

    }
}

How to save data in an android app

use this methods to use sharedPreferences very easily.

private val sharedPreferences = context.getSharedPreferences("myPreferences", Context.MODE_PRIVATE)

fun put(key: String, value: String) = sharedPreferences.edit().putString(key, value).apply()

fun put(key: String, value: Int) = sharedPreferences.edit().putInt(key, value).apply()

fun put(key: String, value: Float) = sharedPreferences.edit().putFloat(key, value).apply()

fun put(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply()

fun put(key: String, value: Long) = sharedPreferences.edit().putLong(key, value).apply()

fun getString(key: String, defaultValue: String? = null): String? = sharedPreferences.getString(key, defaultValue)

fun getInt(key: String, defaultValue: Int = -1): Int = sharedPreferences.getInt(key, defaultValue)

fun getFloat(key: String, defaultValue: Float = -1F): Float = sharedPreferences.getFloat(key, defaultValue)

fun getBoolean(key: String, defaultValue: Boolean = false): Boolean = sharedPreferences.getBoolean(key, defaultValue)

fun getLong(key: String, defaultValue: Long = -1L): Long = sharedPreferences.getLong(key, defaultValue)

fun clearAll() = sharedPreferences.edit().clear().apply()

put them in a class and get context in its constructor.

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

What programming language does facebook use?

Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.

How do I loop through a date range?

Well, you'll need to loop over them one way or the other. I prefer defining a method like this:

public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
    for(var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
        yield return day;
}

Then you can use it like this:

foreach (DateTime day in EachDay(StartDate, EndDate))
    // print it or whatever

In this manner you could hit every other day, every third day, only weekdays, etc. For example, to return every third day starting with the "start" date, you could just call AddDays(3) in the loop instead of AddDays(1).

Can I check if Bootstrap Modal Shown / Hidden?

Use hasClass('in'). It will return true if modal is in OPEN state.

E.g:

if($('.modal').hasClass('in')){
   //Do something here
}

How to set time to 24 hour format in Calendar

Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23) 
            k Hour in day (1-24) 
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }        
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

First Or Create

An update:

As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

See documentation

Get the list of stored procedures created and / or modified on a particular date?

SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC

SELECT name, create_date, modify_date 
FROM sys.objects
WHERE type = 'P'

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

Merge two rows in SQL

There are a few ways depending on some data rules that you have not included, but here is one way using what you gave.

SELECT
    t1.Field1,
    t2.Field2
FROM Table1 t1
    LEFT JOIN Table1 t2 ON t1.FK = t2.FK AND t2.Field1 IS NULL

Another way:

SELECT
    t1.Field1,
    (SELECT Field2 FROM Table2 t2 WHERE t2.FK = t1.FK AND Field1 IS NULL) AS Field2
FROM Table1 t1

What is the &#xA; character?

It is the equivalent to \n -> LF (Line Feed).

Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine.

How can I start pagenumbers, where the first section occurs in LaTex?

I use

\pagenumbering{roman}

for everything in the frontmatter and then switch over to

\pagenumbering{arabic}

for the actual content. With pdftex, the page numbers come out right in the PDF file.

How to append rows to an R data frame

My solution is almost the same as the original answer but it doesn't worked for me.

So, I gave names for the columns and it works:

painel <- rbind(painel, data.frame("col1" = xtweets$created_at,
                                   "col2" = xtweets$text))

What is the difference between H.264 video and MPEG-4 video?

They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"

jQuery Show-Hide DIV based on Checkbox Value

`Display

$('#cbxShowHide').click(function(){ this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show });`

.htaccess deny from all

Deny from all 

is an .htaccess command(the actual content of that file you are trying to view). Not a denial of being able to edit the file. Just reopen the .htaccess file in the text viewer of choice and make the alterations as you so desire, save it, then reupload it to your folder of choice.

Though I think inadvertently you are blocking even yourself from viewing said application once uploaded.

I would do something like:

order deny,allow
deny from all
allow from 127.0.0.1

which will deny everyone but the IP in the allow from line, which you would change the IP to match your IP which you can obtain from http://www.whatismyip.com/ or similar site.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

PreparedStatement IN clause alternatives?

I came across a number of limitations related to prepared statement:

  1. The prepared statements are cached only inside the same session (Postgres), so it will really work only with connection pooling
  2. A lot of different prepared statements as proposed by @BalusC may cause the cache to overfill and previously cached statements will be dropped
  3. The query has to be optimized and use indices. Sounds obvious, however e.g. the ANY(ARRAY...) statement proposed by @Boris in one of the top answers cannot use indices and query will be slow despite caching
  4. The prepared statement caches the query plan as well and the actual values of any parameters specified in the statement are unavailable.

Among the proposed solutions I would choose the one that doesn't decrease the query performance and makes the less number of queries. This will be the #4 (batching few queries) from the @Don link or specifying NULL values for unneeded '?' marks as proposed by @Vladimir Dyuzhev

How to check if an element is visible with WebDriver

public boolean isElementFound( String text) {
        try{
            WebElement webElement = appiumDriver.findElement(By.xpath(text));
            System.out.println("isElementFound : true :"+text + "true");
        }catch(NoSuchElementException e){
            System.out.println("isElementFound : false :"+text);
            return false;
        }
        return true;
    }

    text is the xpath which you would be passing when calling the function.
the return value will be true if the element is present else false if element is not pressent

Get the first element of an array

No one has suggested using the ArrayIterator class:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'

gets around the by reference stipulation of the OP.

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

How can I test a PDF document if it is PDF/A compliant?

pdf validation with OPEN validator:

DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/

JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/

Python 3 turn range to a list

The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range() function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range() function to produce a list and pass into a function.

Therefore, in this case, Python3 is less convenient as compared to Python2 because:

  • In Python2, we have xrange() and range();
  • In Python3, we have range() and list(range())

Nonetheless, you can still use list expansion in this way:

[*range(N)]

Equivalent of Math.Min & Math.Max for Dates?

There's no built in method to do that. You can use the expression:

(date1 > date2 ? date1 : date2)

to find the maximum of the two.

You can write a generic method to calculate Min or Max for any type (provided that Comparer<T>.Default is set appropriately):

public static T Max<T>(T first, T second) {
    if (Comparer<T>.Default.Compare(first, second) > 0)
        return first;
    return second;
}

You can use LINQ too:

new[]{date1, date2, date3}.Max()

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

What __init__ and self do in Python?

Had trouble undestanding this myself. Even after reading the answers here.

To properly understand the __init__ method you need to understand self.

The self Parameter

The arguments accepted by the __init__ method are :

def __init__(self, arg1, arg2):

But we only actually pass it two arguments :

instance = OurClass('arg1', 'arg2')

Where has the extra argument come from ?

When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.

In order to access object attributes from within the __init__ method we need a reference to the object.

Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.

This means in the __init__ method we can do :

self.arg1 = arg1
self.arg2 = arg2

Here we are setting attributes on the object. You can verify this by doing the following :

instance = OurClass('arg1', 'arg2')
print instance.arg1
arg1

values like this are known as object attributes. Here the __init__ method sets the arg1 and arg2 attributes of the instance.

source: http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

Exim 4 requires that AUTH command only be sent after the client issued EHLO - attempts to authenticate without EHLO would be rejected. Some mailservers require that EHLO be issued twice. PHPMailer apparently fails to do so. If PHPMailer does not allow you to force EHLO initiation, you really should switch to SwiftMailer 4.

Bash Shell Script - Check for a flag and grab its value

You should read this getopts tutorial.

Example with -a switch that requires an argument :

#!/bin/bash

while getopts ":a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

Like greybot said(getopt != getopts) :

The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

How do I set a variable to the output of a command in Bash?

$(sudo run command)

If you're going to use an apostrophe, you need `, not '. This character is called "backticks" (or "grave accent"):

#!/bin/bash

VAR1="$1"
VAR2="$2"

MOREF=`sudo run command against "$VAR1" | grep name | cut -c7-`

echo "$MOREF"

How do I set the maximum line length in PyCharm?

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Pycharm 4 Settings Screenshot

AngularJS passing data to $http.get request

Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:

CONTROLLER:

public class AngularController : Controller
{
    public JsonResult GetFullName(string name, string surname)
    {
        System.Diagnostics.Debugger.Break();
        return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
    }
}

VIEW:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);

    myApp.controller('controller', function ($scope, $http) {

        $scope.GetFullName = function (employee) {

            //The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue

            $http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
            success(function (data, status, headers, config) {
                alert('Your full name is - ' + data.fullName);
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });

        }
    });

</script>

<div ng-app="app" ng-controller="controller">

    <input type="text" ng-model="name" />
    <input type="text" ng-model="surname" />
    <input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

How to copy static files to build directory with Webpack?

The way I load static images and fonts:

module: {
    rules: [
      ....

      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        /* Exclude fonts while working with images, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/fonts'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
        /* Exclude images while working with fonts, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/images'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/'
          },
        }
    ]
}

Don't forget to install file-loader to have that working.

Get all mysql selected rows into an array

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Avoid line break between html elements

CSS for that td: white-space: nowrap; should solve it.

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

[Updated to adapt to modern pandas, which has isnull as a method of DataFrames..]

You can use isnull and any to build a boolean Series and use that to index into your frame:

>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False
>>> df.isnull().any(axis=1)
0    False
1     True
2     True
3    False
4    False
dtype: bool
>>> df[df.isnull().any(axis=1)]
   0   1   2
1  0 NaN   0
2  0   0 NaN

[For older pandas:]

You could use the function isnull instead of the method:

In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])

In [57]: df
Out[57]: 
   0   1   2
0  0   1   2
1  0 NaN   0
2  0   0 NaN
3  0   1   2
4  0   1   2

In [58]: pd.isnull(df)
Out[58]: 
       0      1      2
0  False  False  False
1  False   True  False
2  False  False   True
3  False  False  False
4  False  False  False

In [59]: pd.isnull(df).any(axis=1)
Out[59]: 
0    False
1     True
2     True
3    False
4    False

leading to the rather compact:

In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]: 
   0   1   2
1  0 NaN   0
2  0   0 NaN

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

I don't think your problem is with the BouncyCastle keystore; I think the problem is with a broken javax.net.ssl package in Android. The BouncyCastle keystore is a supreme annoyance because Android changed a default Java behavior without documenting it anywhere -- and removed the default provider -- but it does work.

Note that for SSL authentication you may require 2 keystores. The "TrustManager" keystore, which contains the CA certs, and the "KeyManager" keystore, which contains your client-site public/private keys. (The documentation is somewhat vague on what needs to be in the KeyManager keystore.) In theory, you shouldn't need the TrustManager keystore if all of your certficates are signed by "well-known" Certifcate Authorities, e.g., Verisign, Thawte, and so on. Let me know how that works for you. Your server will also require the CA for whatever was used to sign your client.

I could not create an SSL connection using javax.net.ssl at all. I disabled the client SSL authentication on the server side, and I still could not create the connection. Since my end goal was an HTTPS GET, I punted and tried using the Apache HTTP Client that's bundled with Android. That sort-of worked. I could make the HTTPS conection, but I still could not use SSL auth. If I enabled the client SSL authentication on my server, the connection would fail. I haven't checked the Apache HTTP Client code, but I suspect they are using their own SSL implementation, and don't use javax.net.ssl.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I just recently had this error. What fixed it for me was to close a chrome window that was running the inspector. I have it pop out its own window whenever I inspect a web page. Did not need to disable or change anything on visual studio.

How to mock static methods in c# using MOQ framework?

Moq cannot mock a static member of a class.

When designing code for testability it's important to avoid static members (and singletons). A design pattern that can help you refactoring your code for testability is Dependency Injection.

This means changing this:

public class Foo
{
    public Foo()
    {
        Bar = new Bar();
    }
}

to

public Foo(IBar bar)
{
    Bar = bar;
}

This allows you to use a mock from your unit tests. In production you use a Dependency Injection tool like Ninject or Unity wich can wire everything together.

I wrote a blog about this some time ago. It explains which patterns an be used for better testable code. Maybe it can help you: Unit Testing, hell or heaven?

Another solution could be to use the Microsoft Fakes Framework. This is not a replacement for writing good designed testable code but it can help you out. The Fakes framework allows you to mock static members and replace them at runtime with your own custom behavior.

Delete sql rows where IDs do not have a match from another table

Using LEFT JOIN/IS NULL:

DELETE b FROM BLOB b 
  LEFT JOIN FILES f ON f.id = b.fileid 
      WHERE f.id IS NULL

Using NOT EXISTS:

DELETE FROM BLOB 
 WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)

Using NOT IN:

DELETE FROM BLOB
 WHERE fileid NOT IN (SELECT f.id 
                        FROM FILES f)

Warning

Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.

error: pathspec 'test-branch' did not match any file(s) known to git

My friend, you need to create those corresponding branches locally first, in order to check-out to those other two branches, using this line of code

git branch test-branch  

and

git branch change-the-title

then only you will be able to do git checkout to those branches

Also after creating each branch, take latest changes of those particular branches by using git pull origin branch_name as shown in below code

git branch test-branch
git checkout test-branch
git pull origin test-branch

and for other branch named change-the-title run following code =>

git branch change-the-title
git checkout change-the-title
git pull origin change-the-title

Happy programming :)

The result of a query cannot be enumerated more than once

if you getting this type of error so I suggest you used to stored proc data as usual list then binding the other controls because I also get this error so I solved it like this ex:-

repeater.DataSource = data.SPBinsReport().Tolist();
repeater.DataBind();

try like this

How to Correctly handle Weak Self in Swift Blocks with Arguments

EDIT: Reference to an updated solution by LightMan

See LightMan's solution. Until now I was using:

input.action = { [weak self] value in
    guard let this = self else { return }
    this.someCall(value) // 'this' isn't nil
}

Or:

input.action = { [weak self] value in
    self?.someCall(value) // call is done if self isn't nil
}

Usually you don't need to specify the parameter type if it's inferred.

You can omit the parameter altogether if there is none or if you refer to it as $0 in the closure:

input.action = { [weak self] in
    self?.someCall($0) // call is done if self isn't nil
}

Just for completeness; if you're passing the closure to a function and the parameter is not @escaping, you don't need a weak self:

[1,2,3,4,5].forEach { self.someCall($0) }

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Please check your listenning ports with :

netstat -nat |grep :3306

If it show

 tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN 

Thats is ok for your remote connection.

But in this case i think you have

tcp        0     192.168.1.3:3306            0.0.0.0:*               LISTEN 

Thats is ok for your remote connection. You should also check your firewall (iptables if you centos/redhat)

services iptables stop

for testing or use :

iptables -A input -p tcp -i eth0 --dport 3306 -m state NEW,ESTABLISHED -j ACCEPT
iptables -A output -p tcp -i eth0 --sport 3306 -m state NEW,ESTABLISHED -j ACCEPT

And another thing to check your grant permission for remote connection :

GRANT ALL ON *.* TO remoteUser@'remoteIpadress' IDENTIFIED BY 'my_password';

Rendering an array.map() in React

Gosha Arinich is right, you should return your <li> element. But, nevertheless, you should get nasty red warning in the browser console in this case

Each child in an array or iterator should have a unique "key" prop.

so, you need to add "key" to your list:

this.state.data.map(function(item, i){
  console.log('test');
  return <li key={i}>Test</li>
})

or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:

this.state.data.map((item,i) => <li key={i}>Test</li>)

IMPORTANT UPDATE:

The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id if id already there, or just generate unique ids for it.

how to pass value from one php page to another using session

Use something like this:

page1.php

<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>

Any other PHP page:

<?php
session_start();
echo $_SESSION['myValue'];
?>

A few notes to keep in mind though: You need to call session_start() BEFORE any output, HTML, echos - even whitespace.

You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.

The setting of the variable itself can be done in one of a number of ways:

$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];

And if you want to check if the variable is set before getting a potential error, use something like this:

if(!empty($_SESSION['myValue'])
{
    echo $_SESSION['myValue'];
}
else
{
    echo "Session not set yet.";
}

Making a Simple Ajax call to controller in asp.net mvc

It's for your UPDATE question.

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

UPDATE:

[HttpGet]
public ActionResult FirstAjax()
{
    Some Code--Some Code---Some Code
    return View();
}

[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
    Some Code--Some Code---Some Code
    return View();
}

And please refer this link for further reference of how a method becomes an action. Very good reference though.

How to change maven logging level to display only warning and errors?

Changing the info to error in simplelogging.properties file will help in achieving your requirement.

Just change the value of the below line

org.slf4j.simpleLogger.defaultLogLevel=info 

to

org.slf4j.simpleLogger.defaultLogLevel=error

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

How do I embed PHP code in JavaScript?

If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:

page.php (this will work)

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>;
    alert(i);
}

page.js (this won't work)

function jst()
{
    var i = 0;
    i = <?php echo 35; ?>
    alert(i);
}

How to find specified name and its value in JSON-string from Java?

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

display HTML page after loading complete

Hide the body initially, and then show it with jQuery after it has loaded.

body {
    display: none;
}

$(function () {
    $('body').show();
}); // end ready

Also, it would be best to have $('body').show(); as the last line in your last and main .js file.

Any way of using frames in HTML5?

I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.

Single TextView with multiple colored text

yes, if you format the String with html's font-color property then pass it to the method Html.fromHtml(your text here)

String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));

How to Validate on Max File Size in Laravel?

Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.

I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up

My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:

in resources/lang/en/validaton.php:

'uploaded' => 'The :attribute failed to upload.',

And this is the message displayed when the file is larger than the limit set by PHP.

I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.

However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.

So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.

Here is what works if the file to smaller than the PHP file size limit:

In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:

This is how I set a custom error message and maximum file size:

I have an input field <input type="file" name="upload">. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
  ...
  ...
  public function rules() {
    return [
      'upload' => 'required|file|max:8192',
    ];
  }
  public function messages()
  {
    return [            
      'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
      'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
    ];
  }
}

Ubuntu: OpenJDK 8 - Unable to locate package

sudo apt-get update
sudo apt-get  install openjdk-8-jdk

this should work

How do I pull from a Git repository through an HTTP proxy?

Setup proxy to git

command

git config --global http.proxy http://user:password@domain:port

example

git config --global http.proxy http://clairton:[email protected]:8080

How to represent empty char in Java Character class

You can do something like this:

mystring.replace(""+ch, "");

How to convert current date into string in java?

For time as YYYY-MM-dd

String time = new DateTime( yourData ).toString("yyyy-MM-dd");

And the Library of DateTime is:

import org.joda.time.DateTime;

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

SQL Server: how to select records with specific date from datetime column

SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';

This will select all the data between the 2 dates

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;        

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var searcher = new ManagementObjectSearcher
                ("SELECT * FROM WIN32_SerialPort"))
            {
                string[] portnames = SerialPort.GetPortNames();
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
                var tList = (from n in portnames
                            join p in ports on n equals p["DeviceID"].ToString()
                            select n + " - " + p["Caption"]).ToList();

                tList.ForEach(Console.WriteLine);
            }

            // pause program execution to review results...
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}

More info here: http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx

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

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

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

See the documentation

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

There are 3 ways to allow cross domain origin (excluding jsonp):

1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.

 <?php header("Access-Control-Allow-Origin: http://example.com"); ?>

2) Modify the server configuration file (apache.conf) and add this line. Note that "*" represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true

3) To allow multiple domains on Apache web servers add the following to your config file

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension

5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:

open -a Google\ Chrome --args --disable-web-security --user-data-dir

How to know what the 'errno' means?

Instead of running perror on any error code you get, you can retrieve a complete listing of errno values on your system with the following one-liner:

cpp -dM /usr/include/errno.h | grep 'define E' | sort -n -k 3

Javascript + Regex = Nothing to repeat error?

For Google travelers: this stupidly unhelpful error message is also presented when you make a type and double up the + regex operator:

Okay:

\w+

Not okay:

\w++

Android Spinner: Get the selected item change event

You can implement AdapterView.OnItemSelectedListener class in your Activity.

And then use the below line within onCreate()

Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

Then override these two methods:

public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    selection.setText(items[position]);
}

public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
}

How to frame two for loops in list comprehension python

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

isset in jQuery?

function isset(element) {
    return element.length > 0;
}

http://jsfiddle.net/8KYxe/1/


Or, as a jQuery extension:

$.fn.exists = function() { return this.length > 0; };

// later ...
if ( $("#id").exists() ) {
  // do something
}

react native get TextInput value

_x000D_
_x000D_
export default class App extends Component {_x000D_
  state = { username: '', password: '' }_x000D_
_x000D_
  onChangeText = (key, val) => {_x000D_
    this.setState({ [key]: val})_x000D_
  }_x000D_
  _x000D_
  render() { _x000D_
    return (_x000D_
      <View style={styles.container}>_x000D_
          <Text>Login Form</Text>_x000D_
          <TextInput_x000D_
            placeholder='Username'_x000D_
            onChangeText={val => this.onChangeText('username', val)}_x000D_
            style={styles.input}_x000D_
          />_x000D_
          <TextInput_x000D_
            placeholder='Password'_x000D_
            onChangeText={val => this.onChangeText('password', val)}_x000D_
            style={styles.input}_x000D_
            secureTextEntry={true}_x000D_
          />      _x000D_
      </View>_x000D_
    );_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Hope this will solve your problem

How to change href attribute using JavaScript after opening the link in a new window?

Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Use the .scrollHeight property of the DOM node: $('#your_div')[0].scrollHeight

Docker: Copying files from Docker container to host

Create a data directory on the host system (outside the container) and mount this to a directory visible from inside the container. This places the files in a known location on the host system, and makes it easy for tools and applications on the host system to access the files

docker run -d -v /path/to/Local_host_dir:/path/to/docker_dir docker_image:tag

What's the best mock framework for Java?

The best solution to mocking is to have the machine do all the work with automated specification-based testing. For Java, see ScalaCheck and the Reductio framework included in the Functional Java library. With automated specification-based testing frameworks, you supply a specification of the method under test (a property about it that should be true) and the framework generates tests as well as mock objects, automatically.

For example, the following property tests the Math.sqrt method to see if the square root of any positive number n squared is equal to n.

val propSqrt = forAll { (n: Int) => (n >= 0) ==> scala.Math.sqrt(n*n) == n }

When you call propSqrt.check(), ScalaCheck generates hundreds of integers and checks your property for each, also automatically making sure that the edge cases are covered well.

Even though ScalaCheck is written in Scala, and requires the Scala Compiler, it's easy to test Java code with it. The Reductio framework in Functional Java is a pure Java implementation of the same concepts.

AngularJS view not updating on model change

Just use $interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

how to install python distutils

If the system Python is borked (i.e. the OS packages split distutils in a python-devel package) and you can’t ask a sysadmin to install the missing piece, then you’ll have to install your own Python. It requires some header files and a compiler toolchain. If you can’t have those, try compiling a Python on an identical computer and just copying it.

Check for special characters in string

Your regexp use ^ and $ so it tries to match the entire string. And if you want only a boolean as the result, use test instead of match.

var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;

if(format.test(string)){
  return true;
} else {
  return false;
}

Change icon-bar (?) color in bootstrap

Dude I know totally how you feel, but don't forget about inline styling. It is almost the super saiyan of the CSS specificity

So it should look something like this for you,

<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>

Merge two objects with ES6

You can use Object.assign() to merge them into a new object:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

_x000D_
_x000D_
const response = {_x000D_
  lat: -51.3303,_x000D_
  lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
  id: 'qwenhee-9763ae-lenfya',_x000D_
  address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
_x000D_
_x000D_

How to set xampp open localhost:8080 instead of just localhost

The port that the Admin button references is configurable. In the XAMPP install folder there is a xampp-control.ini file. Changing the Apache entry under [ServicePorts] will affect the url the Admin button opens.

[ServicePorts]
Apache=8080

Failed to start mongod.service: Unit mongod.service not found

It worked for me on ubuntu 20.04: In my case, mongod.service file was locked so it was giving me the same error. To resolve the issue:- Step 1: Use following command to check if the mongod.service is present there

cd /usr/bin/systemd/system
ls

Step 2: If the file is present there then Run the following command to unlock the file mongod.service

sudo chmod 777 /usr/bin/systemd/system/mongod.service -R

Step 3: Now run the following commands:

sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

How to vertically align label and input in Bootstrap 3?

This works perfectly for me in Bootstrap 4.

<div class="form-row align-items-center">
   <div class="col-md-2">
     <label for="FirstName" style="margin-bottom:0rem !important;">First Name</label>
 </div>
 <div class="col-md-10">
    <input type="text" id="FirstName" name="FirstName" class="form-control" val=""/>
  /div>
</div>

What is difference between functional and imperative programming languages?

• Imperative Languages:

  • Efficient execution

  • Complex semantics

  • Complex syntax

  • Concurrency is programmer designed

  • Complex testing, has no referential transparency, has side effects

  • Has state

• Functional Languages:

  • Simple semantics

  • Simple syntax

  • Less efficient execution

  • Programs can automatically be made concurrent

  • Simple testing, has referential transparency, has no side effects

  • Has no state

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.

How to get a tab character?

Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

"&nbsp;&nbsp;&nbsp;&nbsp;" 

This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

How is the AND/OR operator represented as in Regular Expressions?

use
if in vim:

:s/{\|}/"/g

will replace { and } on " so {lol} becomes "lol"

Storing integer values as constants in Enum manner in java

if you want to be able to convert integer back to corresponding enum with selected value see Constants.forValue(...) in below auto generated code but if not the answer of BlairHippo is best way to do it.

public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);

    public static final int SIZE = java.lang.Integer.SIZE;

    private int intValue;
    private static java.util.HashMap<Integer, Constants> mappings;
    private static java.util.HashMap<Integer, Constants> getMappings()
    {
        if (mappings == null)
        {
            synchronized (Constants.class)
            {
                if (mappings == null)
                {
                    mappings = new java.util.HashMap<Integer, Constants>();
                }
            }
        }
        return mappings;
    }

    private Constants(int value)
    {
        intValue = value;
        getMappings().put(value, this);
    }

    public int getValue()
    {
        return intValue;
    }

    public static Constants forValue(int value)
    {
        return getMappings().get(value);
    }
}

Get latest from Git branch

Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.

Assuming the original branch is named master, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master updates into your local master:

 git fetch origin
 git checkout master
 git merge origin/master

To switch to your branch, just do

 git checkout branch1

How to convert time milliseconds to hours, min, sec format in JavaScript?

I needed time only up to one day, 24h, this was my take:

_x000D_
_x000D_
const milliseconds = 5680000;_x000D_
_x000D_
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);_x000D_
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);_x000D_
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);_x000D_
_x000D_
const time = `${hours}:${minutes}:${seconds}`_x000D_
console.log(time);
_x000D_
_x000D_
_x000D_

you could get days this way as well if needed.

How to install a specific version of a ruby gem?

Use the --version parameter (shortcut -v):

$ gem install rails -v 0.14.1

You can also use version comparators like >= or ~>

$ gem install rails -v '~> 0.14.0'

Or with newer versions of gem even:

$ gem install rails:0.14.4 rubyzip:'< 1'
…
Successfully installed rails-0.14.4
Successfully installed rubyzip-0.9.9

TypeLoadException says 'no implementation', but it is implemented

NOTE - If this answer doesn't help you, please take the time to scroll down through the other answers that people have added since.

Short answer

This can happen if you add a method to an interface in one assembly, and then to an implementing class in another assembly, but you rebuild the implementing assembly without referencing the new version of the interface assembly.

In this case, DummyItem implements an interface from another assembly. The SetShort method was recently added to both the interface and the DummyItem - but the assembly containing DummyItem was rebuilt referencing the previous version of the interface assembly. So the SetShort method is effectively there, but without the magic sauce linking it to the equivalent method in the interface.

Long answer

If you want to try reproducing this, try the following:

  1. Create a class library project: InterfaceDef, add just one class, and build:

    public interface IInterface
    {
        string GetString(string key);
        //short GetShort(string key);
    }
    
  2. Create a second class library project: Implementation (with separate solution), copy InterfaceDef.dll into project directory and add as file reference, add just one class, and build:

    public class ImplementingClass : IInterface
    {
        #region IInterface Members
        public string GetString(string key)
        {
            return "hello world";
        }
    
        //public short GetShort(string key)
        //{
        //    return 1;
        //}
        #endregion
    }
    
  3. Create a third, console project: ClientCode, copy the two dlls into the project directory, add file references, and add the following code into the Main method:

     IInterface test = new ImplementingClass();
     string s = test.GetString("dummykey");
     Console.WriteLine(s);
     Console.ReadKey();
    
  4. Run the code once, the console says "hello world"

  5. Uncomment the code in the two dll projects and rebuild - copy the two dlls back into the ClientCode project, rebuild and try running again. TypeLoadException occurs when trying to instantiate the ImplementingClass.

"Submit is not a function" error in JavaScript

Use getElementById:

document.getElementById ('frmProduct').submit ()

How to find SQL Server running port?

In our enterprise I don't have access to MSSQL Server, so I can'r access the system tables.

What works for me is:

  1. capture the network traffic Wireshark (run as Administrator, select Network Interface),while opening connection to server.
  2. Find the ip address with ping
  3. filter with ip.dst == x.x.x.x

The port is shown in the column info in the format src.port -> dst.port

Modelling an elevator using Object-Oriented Analysis and Design

I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.

A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:

  1. Representation of the central controller (assuming there is one).

  2. Representations of elevators

  3. Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.

  4. Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).

  5. Representation of a human and cargo (may be important for factoring in maximal loads)

  6. Representation of the building (in some cases, as certain floors may be blocked at times, etc.)

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

WSDL/SOAP Test With soapui

A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.

The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

How to add time to DateTime in SQL

Try this

SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '03:30:00')

How can I return pivot table output in MySQL?

For MySQL you can directly put conditions in SUM() function and it will be evaluated as Boolean 0 or 1 and thus you can have your count based on your criteria without using IF/CASE statements

SELECT
    company_name,  
    SUM(action = 'EMAIL')AS Email,
    SUM(action = 'PRINT' AND pagecount = 1)AS Print1Pages,
    SUM(action = 'PRINT' AND pagecount = 2)AS Print2Pages,
    SUM(action = 'PRINT' AND pagecount = 3)AS Print3Pages
FROM t
GROUP BY company_name

DEMO

What is Hash and Range Primary Key?

As the whole thing is mixing up let's look at it function and code to simulate what it means consicely

The only way to get a row is via primary key

getRow(pk: PrimaryKey): Row

Primary key data structure can be this:

// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)

// and in thids case
getRow(somePartitionKey): Row

However you can decide your primary key is partition key + sort key in this case:

// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)

getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]

So the bottom line:

  1. Decided that your primary key is partition key only? get single row by partition key.

  2. Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)

In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key

Building blocks are:

  1. Table
  2. Item
  3. KV Attribute.

Think of Item as a row and of KV Attribute as cells in that row.

  1. You can get an item (a row) by primary key.
  2. You can get multiple items (multiple rows) by specifying (HashKey, RangeKeyQuery)

You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).

More visually as its complex, the way I see it:

+----------------------------------------------------------------------------------+
|Table                                                                             |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...|                       |  |
||+-----------+ +-----------+ +-----------+ +-----------+                       |  |
|+------------------------------------------------------------------------------+  |
|+------------------------------------------------------------------------------+  |
||Item                                                                          |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|||primaryKey | |kv attr    | |kv attr ...| |kv attr ...| |kv attr ...|         |  |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+         |  |
|+------------------------------------------------------------------------------+  |
|                                                                                  |
+----------------------------------------------------------------------------------+

+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey                                                  |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range     |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey                               |
|                                                      +--------------------------+|
|                                 +---------------+    |getByPK => getBy(1        ||
|                 +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
|              +->|Composite  |-+ +---------------+    |of rangeKeys)             ||
|              |  +-----------+                        +--------------------------+|
|+-----------+ |                                                                   |
||PrimaryKey |-+                                                                   |
|+-----------+ |                                       +--------------------------+|
|              |  +-----------+   +---------------+    |getByPK => get by specific||
|              +->|HashType   |-->|get one item   |--->|hashKey                   ||
|                 +-----------+   +---------------+    |                          ||
|                                                      +--------------------------+|
+----------------------------------------------------------------------------------+

So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.

If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.

Note: I did not refer to secondary indexes.

FlutterError: Unable to load asset

This is issue has almost driven me nut in the past. To buttress what others have said, after making sure that all the indentations on the yaml file has been corrected and the problem persist, run a 'flutter clean' command at the terminal in Android studio. As at flutter 1.9, this should fix the issue.

How to load Spring Application Context

package com.dataload;

    public class insertCSV 
    {
        public static void main(String args[])
        {
            ApplicationContext context =
        new ClassPathXmlApplicationContext("applicationcontext.xml");


            // retrieve configured instance
            JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
            Job job = context.getBean("job", Job.class);
            JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
        }
    }

Deserializing JSON array into strongly typed .NET object

Json.NET - Documentation

http://james.newtonking.com/json/help/index.html?topic=html/SelectToken.htm

Interpretation for the author

var o = JObject.Parse(response);
var a = o.SelectToken("data").Select(jt => jt.ToObject<TheUser>()).ToList();

Use sudo with password as parameter

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi

How do I return a string from a regex match in python?

imgtag.group(0) or imgtag.group(). This returns the entire match as a string. You are not capturing anything else either.

http://docs.python.org/release/2.5.2/lib/match-objects.html

Is there a Pattern Matching Utility like GREP in Windows?

TL;DR: ripgrep

Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.

It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)

Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.

If you have Scoop, you can install it with scoop install ripgrep. Else head over to the installation section of the doc.

Tree data structure in C#

delegate void TreeVisitor<T>(T nodeData);

class NTree<T>
{
    private T data;
    private LinkedList<NTree<T>> children;

    public NTree(T data)
    {
         this.data = data;
        children = new LinkedList<NTree<T>>();
    }

    public void AddChild(T data)
    {
        children.AddFirst(new NTree<T>(data));
    }

    public NTree<T> GetChild(int i)
    {
        foreach (NTree<T> n in children)
            if (--i == 0)
                return n;
        return null;
    }

    public void Traverse(NTree<T> node, TreeVisitor<T> visitor)
    {
        visitor(node.data);
        foreach (NTree<T> kid in node.children)
            Traverse(kid, visitor);
    }
}

Simple recursive implementation... < 40 lines of code... You just need to keep a reference to the root of the tree outside of the class, or wrap it in another class, maybe rename to TreeNode??

Check if a variable is between two numbers with Java

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    if (i >= minValueInclusive && i <= maxValueInclusive)
        return true;
    else
        return false;
}

https://alvinalexander.com/java/java-method-integer-is-between-a-range

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I run into the same problem with linker complaining about the main executable missing. This happened during our solution port to the new Visual Studio 2013. The solution is a varied mix of managed and un-managed projects/code. The problem (and fix) ended up being a missing app.config file in the solution folder. Took a day to figure this one out :(, as output log was not very helpful.

Specify multiple attribute selectors in CSS

Concatenate the attribute selectors:

input[name="Sex"][value="M"]

Why is "throws Exception" necessary when calling a function?

package javaexception;


public class JavaException {
   void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

void show2() throws Exception  // Why throws is necessary here ?
{
    show();
}

void show3() throws Exception  // Why throws is necessary here ?
{
    show2();
}
public static void main(String[] args) {

   JavaException a = new JavaException();

   try{
   a.show3();
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
}

Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

How to delete an array element based on key?

You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()).
If so, just use unset():

unset($arr[1]);

How to find if an array contains a string

I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!

You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.

There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6

jQuery ajax success callback function definition

The "new" way of doing this since jQuery 1.5 (Jan 2011) is to use deferred objects instead of passing a success callback. You should return the result of $.ajax and then use the .done, .fail etc methods to add the callbacks outside of the $.ajax call.

function getData() {
    return $.ajax({
        url : 'example.com',
        type: 'GET'
    });
}

function handleData(data /* , textStatus, jqXHR */ ) {
    alert(data);
    //do some stuff
}

getData().done(handleData);

This decouples the callback handling from the AJAX handling, allows you to add multiple callbacks, failure callbacks, etc, all without ever needing to modify the original getData() function. Separating the AJAX functionality from the set of actions to be completed afterwards is a good thing!.

Deferreds also allow for much easier synchronisation of multiple asynchronous events, which you can't easily do just with success:

For example, I could add multiple callbacks, an error handler, and wait for a timer to elapse before continuing:

// a trivial timer, just for demo purposes -
// it resolves itself after 5 seconds
var timer = $.Deferred();
setTimeout(timer.resolve, 5000);

// add a done handler _and_ an `error:` handler, even though `getData`
// didn't directly expose that functionality
var ajax = getData().done(handleData).fail(error);

$.when(timer, ajax).done(function() {
    // this won't be called until *both* the AJAX and the 5s timer have finished
});

ajax.done(function(data) {
    // you can add additional callbacks too, even if the AJAX call
    // already finished
});

Other parts of jQuery use deferred objects too - you can synchronise jQuery animations with other async operations very easily with them.

"CSV file does not exist" for a filename with embedded quotes

I am using a Mac. I had the same problem wherein .csv file was in the same folder where the python script was placed, however, Spyder still was unable to locate the file. I changed the file name from capital letters to all small letters and it worked.

importing go files in same folder

./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)

in this case:
main.go import "./a"

It can call the function in the a.go and b.go,that with first letter caps on.

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

jQuery find element by data attribute value

You can also use .filter()

$('.slide-link').filter('[data-slide="0"]').addClass('active');

How to check if a number is between two values?

Here is the shortest method possible:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

Parametrized:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

You can divide both sides by 2 if you don't understand how the first one works;)

Replace preg_replace() e modifier with preg_replace_callback

You shouldn't use flag e (or eval in general).

You can also use T-Regx library

pattern('(^|_)([a-z])')->replace($word)->by()->group(2)->callback('strtoupper');

How can I make a .NET Windows Forms application that only runs in the System Tray?

"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.

And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:

private void MainForm_Shown(object sender, EventArgs e)
{
    WindowState = FormWindowState.Minimized;
    Hide();
} 

Can't use Swift classes inside Objective-C

When you add new Swift files to the project, please, make sure that you add them to correct targets. Please, make sure that every swift file you're going to use inherits NSObject class and annotated with @ObjCMembers Change to YES inside the build settings under the option ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES. Change to YES inside the build settings under the option DEFINES_MODULE.

jQuery if statement, syntax

It depends on what you mean by stop. If it's in a function that can return void then:

if(a && b) {
    // do something
}else{
    // "stop"
    return;
}

WCF error: The caller was not authenticated by the service

This can be caused if the client is in a different domain than the server.

I encountered this when testing one of my applications from my PC(client) to my (cloud) testing server and the simplest solution i could think of was setting up a vpn.

Bash foreach loop

Something like this would do:

xargs cat <filenames.txt

The xargs program reads its standard input, and for each line of input runs the cat program with the input lines as argument(s).

If you really want to do this in a loop, you can:

for fn in `cat filenames.txt`; do
    echo "the next file is $fn"
    cat $fn
done

height: calc(100%) not working correctly in CSS

You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.

Following CSS works:

html,body {
    background: blue;
    height:100%;
    padding:0;
    margin:0;
}
header {
    background: red;
    height: 20px;
    width:100%
}
h1 {
    font-size:1.2em;
    margin:0;
    padding:0;
    height: 30px;
    font-weight: bold;
    background:yellow
}
#theCalcDiv {
    background:green;
    height: -moz-calc(100% - (20px + 30px));
    height: -webkit-calc(100% - (20px + 30px));
    height: calc(100% - (20px + 30px));
    display:block
}

I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.

Here's an updated fiddle

http://jsfiddle.net/UF3mb/10/

Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

Disable keyboard on EditText

Add below properties to the Edittext controller in the layout file

<Edittext
   android:focusableInTouchMode="true"
   android:cursorVisible="false"
   android:focusable="false"  />

I have been using this solution for while and it works fine for me.

How to compare two tags with git?

For a side-by-side visual representation, I use git difftool with openDiff set to the default viewer.

Example usage:

git difftool tags/<FIRST TAG> tags/<SECOND TAG>

If you are only interested in a specific file, you can use:

git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>

As a side-note, the tags/<TAG>s can be replaced with <BRANCH>es if you are interested in diffing branches.

Why is setState in reactjs Async instead of Sync?

Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md

// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3

Solution
this.setState((prevState, props) => ({
  count: prevState.count + props.increment
}));

or pass callback this.setState ({.....},callback)

https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

I think you want to return a REFCURSOR:

create function test_cursor 
            return sys_refcursor
            is
                    c_result sys_refcursor;
            begin
                    open c_result for
                    select * from dual;
                    return c_result;
            end;

Update: If you need to call this from SQL, use a table function like @Tony Andrews suggested.

How to remove the underline for anchors(links)?

The css is

text-decoration: none;

and

text-decoration: underline;

Spring Boot and multiple external configuration files

I ran into a lot of issues when trying to figure this out. Here is my setup,

Dev Env : Windows 10, Java : 1.8.0_25, Spring Boot : 2.0.3.RELEASE, Spring : 5.0.7.RELEASE

What I found is spring is sticking with the concept "Sensible defaults for configuration". What this translates in to is, you have to have all your property files as part of your war file. Once in there, you can then override them using the "--spring.config.additional-location" command line property to point to external property files. But this will NOT WORK if the property files are not part of the original war file.

Demo code: https://github.com/gselvara/spring-boot-property-demo/tree/master

Better way to cast object to int

Convert.ToInt32(myobject);

This will handle the case where myobject is null and return 0, instead of throwing an exception.

Show DataFrame as table in iPython Notebook

You'll need to use the HTML() or display() functions from IPython's display module:

from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))

Note that if you just print df1.to_html() you'll get the raw, unrendered HTML.

You can also import from IPython.core.display with the same effect

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

How to convert string to integer in PowerShell

Use:

$filelist = @(11, 1, 2)
$filelist | sort @{expression={$_[0]}} | 
  % {$newName = [string]([int]$($_[0]) + 1)}
  New-Item $newName -ItemType Directory

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

Image vs zImage vs uImage

What is the difference between them?

Image: the generic Linux kernel binary image file.

zImage: a compressed version of the Linux kernel image that is self-extracting.

uImage: an image file that has a U-Boot wrapper (installed by the mkimage utility) that includes the OS type and loader information.
A very common practice (e.g. the typical Linux kernel Makefile) is to use a zImage file. Since a zImage file is self-extracting (i.e. needs no external decompressors), the wrapper would indicate that this kernel is "not compressed" even though it actually is.


Note that the author/maintainer of U-Boot considers the (widespread) use of using a zImage inside a uImage questionable:

Actually it's pretty stupid to use a zImage inside an uImage. It is much better to use normal (uncompressed) kernel image, compress it using just gzip, and use this as poayload for mkimage. This way U-Boot does the uncompresiong instead of including yet another uncompressor with each kernel image.

(quoted from https://lists.yoctoproject.org/pipermail/yocto/2013-October/016778.html)


Which type of kernel image do I have to use?

You could choose whatever you want to program for.
For economy of storage, you should probably chose a compressed image over the uncompressed one.
Beware that executing the kernel (presumably the Linux kernel) involves more than just loading the kernel image into memory. Depending on the architecture (e.g. ARM) and the Linux kernel version (e.g. with or without DTB), there are registers and memory buffers that may have to be prepared for the kernel. In one instance there was also hardware initialization that U-Boot performed that had to be replicated.

ADDENDUM

I know that u-boot needs a kernel in uImage format.

That is accurate for all versions of U-Boot which only have the bootm command.
But more recent versions of U-Boot could also have the bootz command that can boot a zImage.

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

Open new popup window without address bars in firefox & IE

Check the mozilla documentation on window.open. The window features ("directory=...,...,height=350") etc. arguments should be a string:

window.open('/pageaddress.html','winname',"directories=0,titlebar=0,toolbar=0,location=0,status=0,menubar=0,scrollbars=no,resizable=no,width=400,height=350");

Try if that works in your browsers. Note that some of the features might be overridden by user preferences, such as "location" (see doc.)

Combine two (or more) PDF's

I combined the two above, because I needed to merge 3 pdfbytes and return a byte

internal static byte[] mergePdfs(byte[] pdf1, byte[] pdf2,byte[] pdf3)
        {
            MemoryStream outStream = new MemoryStream();
            using (Document document = new Document())
            using (PdfCopy copy = new PdfCopy(document, outStream))
            {
                document.Open();
                copy.AddDocument(new PdfReader(pdf1));
                copy.AddDocument(new PdfReader(pdf2));
                copy.AddDocument(new PdfReader(pdf3));
            }
            return outStream.ToArray();
        } 

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

How to rename a single column in a data.frame?

Let df be the dataframe you have with col names myDays and temp. If you want to rename "myDays" to "Date",

library(plyr)
rename(df,c("myDays" = "Date"))

or with pipe, you can

dfNew      <- df %>% 
  plyr::rename(c("myDays" = "Date"))

PHP unable to load php_curl.dll extension

In PHP 5.6.x version You should do the following:

Move to Windows\system32 folder DLLs from php folder:

libssh2.dll, ssleay32.dll, libeay32.dll and php_curl.dll from php ext folder

Move to Apache24\bin folder from php folder:

libssh2.dll

Also, don't forget to uncomment extension=php_curl.dll in php.ini

CSS for the "down arrow" on a <select> element?

There's a cool CSS-only solution to styling dropdowns here: http://bavotasan.com/2011/style-select-box-using-only-css/

Basically, wrap the select in a container div, style the select to be 18px wider than the container with a transparent background, give overflow:hidden to the container (to chop off the browser-generated arrow), and add your background image with stylized arrow to the container.

Doesn't work in IE7 (or 6), but seriously, I say if you're using IE7 you deserve a less-pretty dropdown experience.

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

ImageMagick security policy 'PDF' blocking conversion

Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:

sudo apt install img2pdf

Convert one or more images to pdf:

img2pdf img.jpg -o output.pdf

It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.

How to create multiple class objects with a loop in python?

you can use list to define it.

objs = list()
for i in range(10):
    objs.append(MyClass())

What is the current directory in a batch file?

It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2 and you do cd c:\dir3, then run the batch, the current directory will be c:\dir3.

Better way to represent array in java properties file

Use YAML files for properties, this supports properties as an array.

Quick glance about YAML:

A superset of JSON, it can do everything JSON can + more

  1. Simple to read
  2. Long properties into multiline values
  3. Supports comments
  4. Properties as Array
  5. YAML Validation

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

Using curl POST with variables defined in bash script functions

Here's what actually worked for me, after guidance from answers here:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'

How do you clear a stringstream variable?

my 2 cents:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

Fast way to get the min/max values among properties of object

You could try:

const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5

Get querystring from URL using jQuery

We do it this way...

String.prototype.getValueByKey = function (k) {
    var p = new RegExp('\\b' + k + '\\b', 'gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p) + k.length + 1).substr(0, this.substr(this.search(p) + k.length + 1).search(/(&|;|$)/))) : "";
};

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

PHP Redirect with POST data

There is a simple hack, use $_SESSION and create an array of the posted values, and once you go to the File_C.php you can use it then do you process after that destroy it.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

You can also set these values programatically in the class library, this will avoid unnecessary movement of the config files across the library. The example code for simple BasciHttpBinding is -

BasicHttpBinding basicHttpbinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
basicHttpbinding.Name = "BasicHttpBinding_YourName";
basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
basicHttpbinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

EndpointAddress endpointAddress = new EndpointAddress("http://<Your machine>/Service1/Service1.svc");
Service1Client proxyClient = new Service1Client(basicHttpbinding,endpointAddress);

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

iOS - UIImageView - how to handle UIImage image orientation

Swift 3.0 version of Tommy's answer

let imageToDisplay = UIImage.init(cgImage: originalImage.cgImage!, scale: originalImage.scale, orientation: UIImageOrientation.up)

How to send string from one activity to another?

You can send data from one actvity to another with an Intent

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

Then all you have to do is call setText on your TextView and use that string.

Markdown and image alignment

<div style="float:left;margin:0 10px 10px 0" markdown="1">
    ![book](/images/book01.jpg)
</div>

The attribute markdown possibility inside Markdown.

Get current date/time in seconds

Using new Date().getTime() / 1000 is an incomplete solution for obtaining the seconds, because it produces timestamps with floating-point units.

const timestamp = new Date() / 1000; // 1405792936.933
// Technically, .933 would be milliseconds. 

A better solution would be:

// Rounds the value
const timestamp = Math.round(new Date() / 1000); // 1405792937

// - OR -

// Floors the value
const timestamp = new Date() / 1000 | 0; // 1405792936

Values without floats are also safer for conditional statements, as the float may produce unwanted results. The granularity you obtain with a float may be more than needed.

if (1405792936.993 < 1405792937) // true

Uncaught ReferenceError: angular is not defined - AngularJS not working

Just to complement m59's correct answer, here is a working jsfiddle:

<body ng-app='myApp'>
    <div>
        <button my-directive>Click Me!</button>
    </div>
     <h1>{{2+3}}</h1>

</body>

How to install package from github repo in Yarn

You can add any Git repository (or tarball) as a dependency to yarn by specifying the remote URL (either HTTPS or SSH):

yarn add <git remote url> installs a package from a remote git repository.
yarn add <git remote url>#<branch/commit/tag> installs a package from a remote git repository at specific git branch, git commit or git tag.
yarn add https://my-project.org/package.tgz installs a package from a remote gzipped tarball.

Here are some examples:

yarn add https://github.com/fancyapps/fancybox [remote url]
yarn add ssh://github.com/fancyapps/fancybox#3.0  [branch]
yarn add https://github.com/fancyapps/fancybox#5cda5b529ce3fb6c167a55d42ee5a316e921d95f [commit]

(Note: Fancybox v2.6.1 isn't available in the Git version.)

To support both npm and yarn, you can use the git+url syntax:

git+https://github.com/owner/package.git#commithashortagorbranch
git+ssh://github.com/owner/package.git#commithashortagorbranch

MySQL maximum memory usage

If you are looking for optimizing your docker mysql container then the below command may help. I was able to run mysql docker container from a default 480mb to mere 100 mbs

docker run -d -p 3306:3306 -e MYSQL_DATABASE=test -e MYSQL_ROOT_PASSWORD=tooor -e MYSQL_USER=test -e MYSQL_PASSWORD=test -v /mysql:/var/lib/mysql --name mysqldb mysql --table_definition_cache=100 --performance_schema=0 --default-authentication-plugin=mysql_native_password

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

How can I stage and commit all files, including newly added files, using a single command?

Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:

1. Create an alias:

git config --global alias.coa "!git add -A && git commit -m"

2. Add all files & commit with a message:

git coa "A bunch of horrible changes"

NOTE: coa is short for commit all and can be replaced with anything your heart desires

How do I select an element in jQuery by using a variable for the ID?

The shortest way would be:

$("#" + row_id)

Limiting the search to the body doesn't have any benefit.

Also, you should consider renaming your ids to something more meaningful (and HTML compliant as per Paolo's answer), especially if you have another set of data that needs to be named as well.

Is it possible to run one logrotate check manually?

Issue the following command,the way to run specified logrotate:

logrotate -vf /etc/logrotate.d/custom

Options:

-v :show the process

-f :forcing run

custom :user-defined log setting

eg: mongodb-log

# mongodb-log rotate

/data/var/log/mongodb/mongod.log {
    daily
    dateext
    rotate 30
    copytruncate
    missingok
}

Remove duplicates from an array of objects in JavaScript

_x000D_
_x000D_
let myData = [{place:"here",name:"stuff"}, _x000D_
 {place:"there",name:"morestuff"},_x000D_
 {place:"there",name:"morestuff"}];_x000D_
_x000D_
_x000D_
let q = [...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];_x000D_
_x000D_
console.log(q)
_x000D_
_x000D_
_x000D_

One-liner using ES6 and new Map().

// assign things.thing to myData
let myData = things.thing;

[...new Map(myData.map(obj => [JSON.stringify(obj), obj])).values()];

Details:-

  1. Doing .map() on the data list and converting each individual object into a [key, value] pair array(length =2), the first element(key) would be the stringified version of the object and second(value) would be an object itself.
  2. Adding above created array list to new Map() would have the key as stringified object and any same key addition would result in overriding the already existing key.
  3. Using .values() would give MapIterator with all values in a Map (obj in our case)
  4. Finally, spread ... operator to give new Array with values from the above step.

How should I set the default proxy to use default credentials?

Is need in some systems set null the Proxy proprerty:

Net.WebRequest.DefaultWebProxy.Credentials = System.Net.CredentialCache.DefaultCredentials Dim request As WebRequest = WebRequest.Create(sRemoteFileURL) request.Proxy = Nothing

It's a bug.

Android - Start service on boot

Just to make searching easier, as mentioned in comments, this is not possible since 3.1 https://stackoverflow.com/a/19856367/6505257

Reliable way for a Bash script to get the full path to itself

The simplest way that I have found to get a full canonical path in Bash is to use cd and pwd:

ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"

Using ${BASH_SOURCE[0]} instead of $0 produces the same behavior regardless of whether the script is invoked as <name> or source <name>.

How do I parse an ISO 8601-formatted date?

A simple option from one of the comments: replace 'Z' with '+00:00' - and use Python 3.7+'s fromisoformat:

from datetime import datetime

s = "2008-09-03T20:56:35.450686Z"

datetime.fromisoformat(s.replace('Z', '+00:00'))
# datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=datetime.timezone.utc)

Although strptime can parse the 'Z' character to UTC, fromisoformat is faster by ~ x40 (see also: A faster strptime):

%timeit datetime.fromisoformat(s.replace('Z', '+00:00'))
346 ns ± 22.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
14.2 µs ± 452 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit dateutil.parser.parse(s)
80.1 µs ± 3.32 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

(Python 3.8.7 x64 on Windows 10)

How can I check if a string contains ANY letters from the alphabet?

Regex should be a fast approach:

re.search('[a-zA-Z]', the_string)

async await return Task

async methods are different than normal methods. Whatever you return from async methods are wrapped in a Task.

If you return no value(void) it will be wrapped in Task, If you return int it will be wrapped in Task<int> and so on.

If your async method needs to return int you'd mark the return type of the method as Task<int> and you'll return plain int not the Task<int>. Compiler will convert the int to Task<int> for you.

private async Task<int> MethodName()
{
    await SomethingAsync();
    return 42;//Note we return int not Task<int> and that compiles
}

Sameway, When you return Task<object> your method's return type should be Task<Task<object>>

public async Task<Task<object>> MethodName()
{
     return Task.FromResult<object>(null);//This will compile
}

Since your method is returning Task, it shouldn't return any value. Otherwise it won't compile.

public async Task MethodName()
{
     return;//This should work but return is redundant and also method is useless.
}

Keep in mind that async method without an await statement is not async.

HTTP status code for update and delete?

For a PUT request: HTTP 200 or HTTP 204 should imply "resource updated successfully".

For a DELETE request: HTTP 200 or HTTP 204 should imply "resource deleted successfully". HTTP 202 can also be returned which would imply that the instruction was accepted by the server and the "resource was marked for deletion".

PUT

If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

DELETE

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

Source: W3.org: HTTP/1.1 Method Definitions

HTTP 200 OK: Standard response for successful HTTP requests. The actual response will depend on the request method used.

HTTP 204 No Content: The server successfully processed the request, but is not returning any content

Source: List of HTTP status codes: 2xx Success