Programs & Examples On #Filter

A program or routine that blocks access to data that meet a particular criterion. An example would be a "Web filter" that screens out adult websites. Do NOT use this tag for Java servlet filters. Use [servlet-filters] instead.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I set up a simple 3-column range on Sheet1 with Country, City, and Language in columns A, B, and C. The following code autofilters the range and then pastes only one of the columns of autofiltered data to another sheet. You should be able to modify this for your purposes:

Sub CopyPartOfFilteredRange()
    Dim src As Worksheet
    Dim tgt As Worksheet
    Dim filterRange As Range
    Dim copyRange As Range
    Dim lastRow As Long

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set tgt = ThisWorkbook.Sheets("Sheet2")

    ' turn off any autofilters that are already set
    src.AutoFilterMode = False

    ' find the last row with data in column A
    lastRow = src.Range("A" & src.Rows.Count).End(xlUp).Row

    ' the range that we are auto-filtering (all columns)
    Set filterRange = src.Range("A1:C" & lastRow)

    ' the range we want to copy (only columns we want to copy)
    ' in this case we are copying country from column A
    ' we set the range to start in row 2 to prevent copying the header
    Set copyRange = src.Range("A2:A" & lastRow)

    ' filter range based on column B
    filterRange.AutoFilter field:=2, Criteria1:="Rio de Janeiro"

    ' copy the visible cells to our target range
    ' note that you can easily find the last populated row on this sheet
    ' if you don't want to over-write your previous results
    copyRange.SpecialCells(xlCellTypeVisible).Copy tgt.Range("A1")

End Sub

Note that by using the syntax above to copy and paste, nothing is selected or activated (which you should always avoid in Excel VBA) and the clipboard is not used. As a result, Application.CutCopyMode = False is not necessary.

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Using "-Filter" with a variable

Or

-like '*'+$nameregex+'*'

if you would like to use wildcards.

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

How do I filter date range in DataTables?

Here is DataTable with Single DatePicker as "from" Date Filter

LiveDemo

Here is DataTable with Two DatePickers for DateRange (To and From) Filter

LiveDemo

Capitalize the first letter of string in AngularJs

For the AngularJS from meanjs.org, I place the custom filters in modules/core/client/app/init.js

I needed a custom filter to capitalize each word in a sentence, here is how I do so:

angular.module(ApplicationConfiguration.applicationModuleName).filter('capitalize', function() {
return function(str) {
    return str.split(" ").map(function(input){return (!!input) ? input.charAt(0).toUpperCase() + input.substr(1).toLowerCase() :         ''}).join(" ");

}
});

The credit of the map function goes to @Naveen raj

XSS filtering function in PHP

htmlspecialchars() is perfectly adequate for filtering user input that is displayed in html forms.

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

How can I filter a date of a DateTimeField in Django?

Such lookups are implemented in django.views.generic.date_based as follows:

{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
                            datetime.datetime.combine(date, datetime.time.max))} 

Because it is quite verbose there are plans to improve the syntax using __date operator. Check "#9596 Comparing a DateTimeField to a date is too hard" for more details.

Why does foo = filter(...) return a <filter object>, not a list?

filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:

In [47]: def greetings(x):
   ....:     return x == "hello"
   ....:

In [48]: filter(greetings, ["hello", "goodbye"])
Out[48]: ['hello']

Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"])) to get this same result.

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

Java 8 Streams: multiple filters vs. complex condition

This test shows that your second option can perform significantly better. Findings first, then the code:

one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}

now the code:

enum Gender {
    FEMALE,
    MALE
}

static class User {
    Gender gender;
    int age;

    public User(Gender gender, int age){
        this.gender = gender;
        this.age = age;
    }

    public Gender getGender() {
        return gender;
    }

    public void setGender(Gender gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

static long test1(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test2(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(u -> u.getGender() == Gender.FEMALE)
            .filter(u -> u.getAge() % 2 == 0)
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

static long test3(List<User> users){
    long time1 = System.currentTimeMillis();
    users.stream()
            .filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
            .allMatch(u -> true);                   // least overhead terminal function I can think of
    long time2 = System.currentTimeMillis();
    return time2 - time1;
}

public static void main(String... args) {
    int size = 10000000;
    List<User> users =
    IntStream.range(0,size)
            .mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
            .collect(Collectors.toCollection(()->new ArrayList<>(size)));
    repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
    repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
    repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);
}

private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
    System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
            .mapToLong(i -> test.applyAsLong(users))
            .summaryStatistics());
}

how to customize `show processlist` in mysql?

If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here

http://www.dbasquare.com/2012/03/28/how-to-work-with-a-long-process-list-in-mysql/

Isn't it exactly what you need?

array filter in python?

How about

set(A).difference(subset_of_A)

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

Filter rows which contain a certain string

Solution

It is possible to use str_detect of the stringr package included in the tidyverse package. str_detect returns True or False as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr package.

library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1     ? purrr   0.2.4
# ? tibble  1.4.2     ? dplyr   0.7.4
# ? tidyr   0.7.2     ? stringr 1.2.0
# ? readr   1.1.1     ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag()    masks stats::lag()

mtcars$type <- rownames(mtcars)
mtcars %>%
  filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl  disp  hp drat    wt  qsec vs am gear carb           type
# 1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
# 2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
# 3 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1 Toyota Corolla
# 4 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1  Toyota Corona

The good things about Stringr

We should use rather stringr::str_detect() than base::grepl(). This is because there are the following reasons.

  • The functions provided by the stringr package start with the prefix str_, which makes the code easier to read.
  • The first argument of the functions of stringr package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)
object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"

Benchmark

The results of the benchmark test are as follows. For large dataframe, str_detect is faster.

library(rbenchmark)
library(tidyverse)

# The data. Data expo 09. ASA Statistics Computing and Graphics 
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728      29

benchmark(
  "str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
  "grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
  replications = 10,
  columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2      grepl           10  16.480    1.513    16.195    0.248
# 1 str_detect           10  10.891    1.000     9.594    1.281

How to filter an array from all elements of another array

You can write a generic filterByIndex() function and make use of type inference in TS to save the hassle with the callback function:

let's say you have your array [1,2,3,4] that you want to filter() with the indices specified in the [2,4] array.

var filtered = [1,2,3,4,].filter(byIndex(element => element, [2,4]))

the byIndex function expects the element function and an array and looks like this:

byIndex = (getter: (e:number) => number, arr: number[]) => (x: number) => {
    var i = getter(x);
    return arr.indexOf(i); 
}

result is then

filtered = [1,3]

how do you filter pandas dataframes by multiple columns

You can create your own filter function using query in pandas. Here you have filtering of df results by all the kwargs parameters. Dont' forgot to add some validators(kwargs filtering) to get filter function for your own df.

def filter(df, **kwargs):
    query_list = []
    for key in kwargs.keys():
        query_list.append(f'{key}=="{kwargs[key]}"')
    query = ' & '.join(query_list)
    return df.query(query)

How to specify "does not contain" in dplyr filter

Note that %in% returns a logical vector of TRUE and FALSE. To negate it, you can use ! in front of the logical statement:

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
 !where_case_travelled_1 %in% 
   c('Outside Canada','Outside province/territory of residence but within Canada'))

Regarding your original approach with -c(...), - is a unary operator that "performs arithmetic on numeric or complex vectors (or objects which can be coerced to them)" (from help("-")). Since you are dealing with a character vector that cannot be coerced to numeric or complex, you cannot use -.

iterating and filtering two lists using java 8

See below, would welcome anyones feedback on the below code.

not common between two arrays:

List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());

Common between two arrays:

List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());

How can I group data with an Angular filter?

You can use groupBy of angular.filter module.
so you can do something like this:

JS:

$scope.players = [
  {name: 'Gene', team: 'alpha'},
  {name: 'George', team: 'beta'},
  {name: 'Steve', team: 'gamma'},
  {name: 'Paula', team: 'beta'},
  {name: 'Scruath', team: 'gamma'}
];

HTML:

<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  Group name: {{ key }}
  <li ng-repeat="player in value">
    player: {{ player.name }} 
  </li>
</ul>

RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath

UPDATE: jsbin Remember the basic requirements to use angular.filter, specifically note you must add it to your module's dependencies:

(1) You can install angular-filter using 4 different methods:

  1. clone & build this repository
  2. via Bower: by running $ bower install angular-filter from your terminal
  3. via npm: by running $ npm install angular-filter from your terminal
  4. via cdnjs http://www.cdnjs.com/libraries/angular-filter

(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.

(3) Add 'angular.filter' to your main module's list of dependencies.

Java8: sum values from specific field of the objects in a list

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();

What is the recommended way to make a numeric TextField in JavaFX?

I don't like exceptions thus I used the matches function from String-Class

text.textProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, 
        String newValue) {
        if (newValue.matches("\\d*")) {
            int value = Integer.parseInt(newValue);
        } else {
            text.setText(oldValue);
        }
    }
});

Filtering DataGridView without changing datasource

I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.

(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);

javascript filter array multiple conditions

Can also be done this way:

    this.users = this.users.filter((item) => {
                return (item.name.toString().toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.address.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.age.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
                item.email.toLowerCase().indexOf(val.toLowerCase()) > -1);
            })

Limit the length of a string with AngularJS

< div >{{modal.title | limitTo:20}}...< / div>

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

How to filter files when using scp to copy dir recursively?

Since you can scp you should be ok to ssh,
either script the following or login and execute...

# After reaching the server of interest
cd /usr/some/unknown/number/of/sub/folders
tar cfj pack.tar.bz2 $(find . -type f -name *.class)

return back (logout) to local server and scp,

# from the local machine
cd /usr/project/backup/some/unknown/number/of/sub/folders
scp you@server:/usr/some/unknown/number/of/sub/folders/pack.tar.bz2 .
tar xfj pack.tar.bz2

If you find the $(find ...) is too long for your tar change to,

find . -type f -name *.class | xargs tar cfj pack.tar.bz2

Finally, since you are keeping it in /usr/project/backup/,
why bother extraction? Just keep the tar.bz2, with maybe a date+time stamp.

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

Using File.listFiles with FileNameExtensionFilter

Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter

Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.

Filter object properties by key in ES6

The cleanest way you can find is with Lodash#pick

const _ = require('lodash');

const allowed = ['item1', 'item3'];

const obj = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}

const filteredObj = _.pick(obj, allowed)

Remove rows with all or some NAs (missing values) in data.frame

My guess is that this could be more elegantly solved in this way:

  m <- matrix(1:25, ncol = 5)
  m[c(1, 6, 13, 25)] <- NA
  df <- data.frame(m)
  library(dplyr) 
  df %>%
  filter_all(any_vars(is.na(.)))
  #>   X1 X2 X3 X4 X5
  #> 1 NA NA 11 16 21
  #> 2  3  8 NA 18 23
  #> 3  5 10 15 20 NA

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

File input 'accept' attribute - is it useful?

It is supported by Chrome. It's not supposed to be used for validation, but for type hinting the OS. If you have an accept="image/jpeg" attribute in a file upload the OS can only show files of the suggested type.

How to filter a data frame

Another method utilizing the dplyr package:

library(dplyr)
df <- mtcars %>%
        filter(mpg > 25)

Without the chain (%>%) operator:

library(dplyr)
df <- filter(mtcars, mpg > 25)

How to filter a dictionary according to an arbitrary condition function?

dict((k, v) for (k, v) in points.iteritems() if v[0] < 5 and v[1] < 5)

Datetime in where clause

Use a convert function to get all entries for a particular day.

Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'

See CAST and CONVERT for more info

List comprehension vs. lambda + filter

My take

def filter_list(list, key, value, limit=None):
    return [i for i in list if i[key] == value][:limit]

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

I don't know of any out-of-the-box way to achieve this. As you say, this is not how SharePoint lists are intended used. It might work to create a custom site column displaying the path to the document, as this might be used in a filter. Have never tried it, though.

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

How to filter keys of an object with lodash?

Native ES2019 one-liner

_x000D_
_x000D_
const data = {
  aaa: 111,
  abb: 222,
  bbb: 333
};

const filteredByKey = Object.fromEntries(Object.entries(data).filter(([key, value]) => key.startsWith("a")))

console.log(filteredByKey);
_x000D_
_x000D_
_x000D_

Hive: Filtering Data between Specified Dates when Date is a String

Try this:

select * from your_table
where date >= '2020-10-01'  

remove None value from a list without removing the 0 value

A list comprehension is likely the cleanest way:

>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

There is also a functional programming approach but it is more involved:

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]

Filtering array of objects with lodash based on property value

_x000D_
_x000D_
let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
let list = _.filter(myArr, item => item.name === "john");
_x000D_
_x000D_
_x000D_

Jquery how to find an Object by attribute in an Array

Javascript has a function just for that: Array.prototype.find. As example

function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 44].find(isBigEnough); // 130

It not difficult to extends the callback to a function. However this is not compatible with IE (and partially with Edge). For a full list look at the Browser Compatibility

How to use filter, map, and reduce in Python 3

Here are the examples of Filter, map and reduce functions.

numbers = [10,11,12,22,34,43,54,34,67,87,88,98,99,87,44,66]

//Filter

oddNumbers = list(filter(lambda x: x%2 != 0, numbers))

print(oddNumbers)

//Map

multiplyOf2 = list(map(lambda x: x*2, numbers))

print(multiplyOf2)

//Reduce

The reduce function, since it is not commonly used, was removed from the built-in functions in Python 3. It is still available in the functools module, so you can do:

from functools import reduce

sumOfNumbers = reduce(lambda x,y: x+y, numbers)

print(sumOfNumbers)

How to apply a low-pass or high-pass filter to an array in Matlab?

Look at the filter function.

If you just need a 1-pole low-pass filter, it's

xfilt = filter(a, [1 a-1], x);

where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.

Here's the corresponding high-pass filter:

xfilt = filter([1-a a-1],[1 a-1], x);

If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

How can I remove non-ASCII characters but leave periods and spaces using Python?

You can filter all characters from the string that are not printable using string.printable, like this:

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'

string.printable on my machine contains:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c

EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:

''.join(filter(lambda x: x in printable, s))

How I can filter a Datatable?

For anybody who work in VB.NET (just in case)

Dim dv As DataView = yourDatatable.DefaultView

dv.RowFilter ="query" ' ex: "parentid = 0"

What are the best PHP input sanitizing functions?

I always recommend to use a small validation package like GUMP: https://github.com/Wixel/GUMP

Build all you basic functions arround a library like this and is is nearly impossible to forget sanitation. "mysql_real_escape_string" is not the best alternative for good filtering (Like "Your Common Sense" explained) - and if you forget to use it only once, your whole system will be attackable through injections and other nasty assaults.

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

How to create Gmail filter searching for text only at start of subject line?

Regex is not on the list of search features, and it was on (more or less, as Better message search functionality (i.e. Wildcard and partial word search)) the list of pre-canned feature requests, so the answer is "you cannot do this via the Gmail web UI" :-(

There are no current Labs features which offer this. SIEVE filters would be another way to do this, that too was not supported, there seems to no longer be any definitive statement on SIEVE support in the Gmail help.

Updated for link rot The pre-canned list of feature requests was, er canned, the original is on archive.org dated 2012, now you just get redirected to a dumbed down page telling you how to give feedback. Lack of SIEVE support was covered in answer 78761 Does Gmail support all IMAP features?, since some time in 2015 that answer silently redirects to the answer about IMAP client configuration, archive.org has a copy dated 2014.

With the current search facility brackets of any form () {} [] are used for grouping, they have no observable effect if there's just one term within. Using (aaa|bbb) and [aaa|bbb] are equivalent and will both find words aaa or bbb. Most other punctuation characters, including \, are treated as a space or a word-separator, + - : and " do have special meaning though, see the help.

As of 2016, only the form "{term1 term2}" is documented for this, and is equivalent to the search "term1 OR term2".

You can do regex searches on your mailbox (within limits) programmatically via Google docs: http://www.labnol.org/internet/advanced-gmail-search/21623/ has source showing how it can be done (copy the document, then Tools > Script Editor to get the complete source).

You could also do this via IMAP as described here: Python IMAP search for partial subject and script something to move messages to different folder. The IMAP SEARCH verb only supports substrings, not regex (Gmail search is further limited to complete words, not substrings), further processing of the matches to apply a regex would be needed.

For completeness, one last workaround is: Gmail supports plus addressing, if you can change the destination address to [email protected] it will still be sent to your mailbox where you can filter by recipient address. Make sure to filter using the full email address to:[email protected]. This is of course more or less the same thing as setting up a dedicated Gmail address for this purpose :-)

IE 8: background-size fix

I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:

background: no-repeat center center fixed\0/; /* IE8 HACK */

This has solved the frozen links problem for me.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

How to put a delay on AngularJS instant search?

Why does everyone wants to use watch? You could also use a function:

var tempArticleSearchTerm;
$scope.lookupArticle = function (val) {
    tempArticleSearchTerm = val;

    $timeout(function () {
        if (val == tempArticleSearchTerm) {
            //function you want to execute after 250ms, if the value as changed

        }
    }, 250);
}; 

List View Filter Android

In case anyone are still interested in this subject, I find that the best approach for filtering lists is to create a generic Filter class and use it with some base reflection/generics techniques contained in the Java old school SDK package. Here's what I did:

public class GenericListFilter<T> extends Filter {

    /**
     * Copycat constructor
     * @param list  the original list to be used
     */
    public GenericListFilter (List<T> list, String reflectMethodName, ArrayAdapter<T> adapter) {
        super ();

        mInternalList = new ArrayList<>(list);
        mAdapterUsed  = adapter;

        try {
            ParameterizedType stringListType = (ParameterizedType)
                    getClass().getField("mInternalList").getGenericType();
            mCompairMethod =
                    stringListType.getActualTypeArguments()[0].getClass().getMethod(reflectMethodName);
        }
        catch (Exception ex) {
            Log.w("GenericListFilter", ex.getMessage(), ex);

            try {
                if (mInternalList.size() > 0) {
                    T type = mInternalList.get(0);
                    mCompairMethod = type.getClass().getMethod(reflectMethodName);
                }
            }
            catch (Exception e) {
                Log.e("GenericListFilter", e.getMessage(), e);
            }

        }
    }

    /**
     * Let's filter the data with the given constraint
     * @param constraint
     * @return
     */
    @Override protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        List<T> filteredContents = new ArrayList<>();

        if ( constraint.length() > 0 ) {
            try {
                for (T obj : mInternalList) {
                    String result = (String) mCompairMethod.invoke(obj);
                    if (result.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        filteredContents.add(obj);
                    }
                }
            }
            catch (Exception ex) {
                Log.e("GenericListFilter", ex.getMessage(), ex);
            }
        }
        else {
            filteredContents.addAll(mInternalList);
        }

        results.values = filteredContents;
        results.count  = filteredContents.size();
        return results;
    }

    /**
     * Publish the filtering adapter list
     * @param constraint
     * @param results
     */
    @Override protected void publishResults(CharSequence constraint, FilterResults results) {
        mAdapterUsed.clear();
        mAdapterUsed.addAll((List<T>) results.values);

        if ( results.count == 0 ) {
            mAdapterUsed.notifyDataSetInvalidated();
        }
        else {
            mAdapterUsed.notifyDataSetChanged();
        }
    }

    // class properties
    private ArrayAdapter<T> mAdapterUsed;
    private List<T> mInternalList;
    private Method  mCompairMethod;
}

And afterwards, the only thing you need to do is to create the filter as a member class (possibly within the View's "onCreate") passing your adapter reference, your list, and the method to be called for filtering:

this.mFilter = new GenericFilter<MyObjectBean> (list, "getName", adapter);

The only thing missing now, is to override the "getFilter" method in the adapter class:

@Override public Filter getFilter () {
     return MyViewClass.this.mFilter;
}

All done! You should successfully filter your list - Of course, you should also implement your filter algorithm the best way that describes your need, the code bellow is just an example.. Hope it helped, take care.

What is the best way to filter a Java Collection?

With the ForEach DSL you may write

import static ch.akuhn.util.query.Query.select;
import static ch.akuhn.util.query.Query.$result;
import ch.akuhn.util.query.Select;

Collection<String> collection = ...

for (Select<String> each : select(collection)) {
    each.yield = each.value.length() > 3;
}

Collection<String> result = $result();

Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.

All iteration styles supported by the ForEach DSL are

  • AllSatisfy
  • AnySatisfy
  • Collect
  • Counnt
  • CutPieces
  • Detect
  • GroupedBy
  • IndexOf
  • InjectInto
  • Reject
  • Select

For more details, please refer to https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach

How to get parameters from the URL with JSP

request.getParameter("accountID") is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.

Disable nginx cache for JavaScript files

I have the following nginx virtual host (static content) for local development work to disable all browser caching:

server {
    listen 8080;
    server_name localhost;

    location / {
        root /your/site/public;
        index index.html;

        # kill cache
        add_header Last-Modified $date_gmt;
        add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
        if_modified_since off;
        expires off;
        etag off;
    }
}

No cache headers sent:

$ curl -I http://localhost:8080
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Mon, 24 Jul 2017 16:19:30 GMT
Content-Type: text/html
Content-Length: 2076
Connection: keep-alive
Last-Modified: Monday, 24-Jul-2017 16:19:30 GMT
Cache-Control: no-store
Accept-Ranges: bytes

Last-Modified is always current time.

How to split a comma-separated value to columns

Try this (change instances of ' ' to ',' or whatever delimiter you want to use)

CREATE FUNCTION dbo.Wordparser
(
  @multiwordstring VARCHAR(255),
  @wordnumber      NUMERIC
)
returns VARCHAR(255)
AS
  BEGIN
      DECLARE @remainingstring VARCHAR(255)
      SET @remainingstring=@multiwordstring

      DECLARE @numberofwords NUMERIC
      SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)

      DECLARE @word VARCHAR(50)
      DECLARE @parsedwords TABLE
      (
         line NUMERIC IDENTITY(1, 1),
         word VARCHAR(255)
      )

      WHILE @numberofwords > 1
        BEGIN
            SET @word=LEFT(@remainingstring, CHARINDEX(' ', @remainingstring) - 1)

            INSERT INTO @parsedwords(word)
            SELECT @word

            SET @remainingstring= REPLACE(@remainingstring, Concat(@word, ' '), '')
            SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)

            IF @numberofwords = 1
              BREAK

            ELSE
              CONTINUE
        END

      IF @numberofwords = 1
        SELECT @word = @remainingstring
      INSERT INTO @parsedwords(word)
      SELECT @word

      RETURN
        (SELECT word
         FROM   @parsedwords
         WHERE  line = @wordnumber)

  END

Example usage:

SELECT dbo.Wordparser(COLUMN, 1),
       dbo.Wordparser(COLUMN, 2),
       dbo.Wordparser(COLUMN, 3)
FROM   TABLE

Serializing list to JSON

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

Why extend the Android Application class?

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities - sometimes everywhere within the application. In this case, the Application object will help you.

For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

After this,you can get the username and password in any of the activities like this:

MyApplication mApplication = (MyApplication)getApplicationContext();
String username = mApplication.getUsername();
String password = mApplication.getPassword();

And finally, do remember to use the Application object as a singleton object:

 public class MyApplication extends Application {
    private static MyApplication singleton;

    public MyApplication getInstance(){
        return singleton;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }
}

For more information, please Click Application Class

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

You've the following possibilities to solve issue with CERTIFICATE_VERIFY_FAILED:

  • Use HTTP instead of HTTPS (e.g. --index-url=http://pypi.python.org/simple/).
  • Use --cert <trusted.pem> or CA_BUNDLE variable to specify alternative CA bundle.

    E.g. you can go to failing URL from web-browser and import root certificate into your system.

  • Run python -c "import ssl; print(ssl.get_default_verify_paths())" to check the current one (validate if exists).

  • OpenSSL has a pair of environments (SSL_CERT_DIR, SSL_CERT_FILE) which can be used to specify different certificate databasePEP-476.
  • Use --trusted-host <hostname> to mark the host as trusted.
  • In Python use verify=False for requests.get (see: SSL Cert Verification).
  • Use --proxy <proxy> to avoid certificate checks.

Read more at: TLS/SSL wrapper for socket objects - Verifying certificates.

What is the difference between procedural programming and functional programming?

Procedural programming divides sequences of statements and conditional constructs into separate blocks called procedures that are parameterized over arguments that are (non-functional) values.

Functional programming is the same except that functions are first-class values, so they can be passed as arguments to other functions and returned as results from function calls.

Note that functional programming is a generalization of procedural programming in this interpretation. However, a minority interpret "functional programming" to mean side-effect-free which is quite different but irrelevant for all major functional languages except Haskell.

Do HTTP POST methods send data as a QueryString?

The best way to visualize this is to use a packet analyzer like Wireshark and follow the TCP stream. HTTP simply uses TCP to send a stream of data starting with a few lines of HTTP headers. Often this data is easy to read because it consists of HTML, CSS, or XML, but it can be any type of data that gets transfered over the internet (Executables, Images, Video, etc).

For a GET request, your computer requests a specific URL and the web server usually responds with a 200 status code and the the content of the webpage is sent directly after the HTTP response headers. This content is the same content you would see if you viewed the source of the webpage in your browser. The query string you mentioned is just part of the URL and gets included in the HTTP GET request header that your computer sends to the web server. Below is an example of an HTTP GET request to http://accel91.citrix.com:8000/OA_HTML/OALogout.jsp?menu=Y, followed by a 302 redirect response from the server. Some of the HTTP Headers are wrapped due to the size of the viewing window (these really only take one line each), and the 302 redirect includes a simple HTML webpage with a link to the redirected webpage (Most browsers will automatically redirect any 302 response to the URL listed in the Location header instead of displaying the HTML response):

HTTP GET with 302 redirect

For a POST request, you may still have a query string, but this is uncommon and does not have anything to do with the data that you are POSTing. Instead, the data is included directly after the HTTP headers that your browser sends to the server, similar to the 200 response that the web server uses to respond to a GET request. In the case of POSTing a simple web form this data is encoded using the same URL encoding that a query string uses, but if you are using a SOAP web service it could also be encoded using a multi-part MIME format and XML data.

For example here is what an HTTP POST to an XML based SOAP web service located at http://192.168.24.23:8090/msh looks like in Wireshark Follow TCP Stream:

HTTP POST TCP Stream

How do you implement a class in C?

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <uchar.h>

/**
 * Define Shape class
 */
typedef struct Shape Shape;
struct Shape {
    /**
     * Variables header...
     */
    double width, height;

    /**
     * Functions header...
     */
    double (*area)(Shape *shape);
};

/**
 * Functions
 */
double calc(Shape *shape) {
        return shape->width * shape->height;
}

/**
 * Constructor
 */
Shape _Shape() {
    Shape s;

    s.width = 1;
    s.height = 1;

    s.area = calc;

    return s;
}

/********************************************/

int main() {
    Shape s1 = _Shape();
    s1.width = 5.35;
    s1.height = 12.5462;

    printf("Hello World\n\n");

    printf("User.width = %f\n", s1.width);
    printf("User.height = %f\n", s1.height);
    printf("User.area = %f\n\n", s1.area(&s1));

    printf("Made with \xe2\x99\xa5 \n");

    return 0;
};

What does %~dp0 mean, and how does it work?

(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)

Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/

The %~dp0 Variable

The %~dp0 (that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.

The variables %0-%9 refer to the command line parameters of the batch file. %1-%9 refer to command line arguments after the batch file name. %0 refers to the batch file itself.

If you follow the percent character (%) with a tilde character (~), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. The d modifier expands to the drive letter and the p modifier expands to the path of the parameter.

Example: Let’s say you have a directory on C: called bat_files, and in that directory is a file called example.bat. In this case, %~dp0 (combining the d and p modifiers) will expand to C:\bat_files\.

Check out this Microsoft article for a full explanation.

Also, check out this forum thread.

And a more clear reference from here:

  • %CmdCmdLine% will return the entire command line as passed to CMD.EXE

  • %* will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)

  • %~dn will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)

  • %~pn will return the directory of %n if %n is a valid path or file name (no UNC)

  • %~nn will return the file name only of %n if %n is a valid file name

  • %~xn will return the file extension only of %n if %n is a valid file name

  • %~fn will return the fully qualified path of %n if %n is a valid file name or directory

ADD 1

Just found some good reference for the mysterious ~ tilde operator.

The %~ string is called percent tilde operator. You can find it in situations like: %~0.

The :~ string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%.

ADD 2 - 1:12 PM 7/6/2018

%1-%9 refer to the command line args. If they are not valid path values, %~dp1 - %~dp9 will all expand to the same value as %~dp0. But if they are valid path values, they will expand to their own driver/path value.

For example: (batch.bat)

@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on

Run 1:

D:\Workbench>batch arg1 arg2

~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\

Run 2:

D:\Workbench>batch c:\123\a.exe e:\abc\b.exe

~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\

Express.js - app.listen vs server.listen

Just for punctuality purpose and extend a bit Tim answer.
From official documentation:

The app returned by express() is in fact a JavaScript Function, DESIGNED TO BE PASSED to Node’s HTTP servers as a callback to handle requests.

This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

All of these are kinds of indices.

primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

Getting a timestamp for today at midnight?

_x000D_
_x000D_
function getTodaysTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
  return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
  return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
  const currentMonth = currentDay.getMonth() + 1;_x000D_
  let daysInMonth = 0;_x000D_
  if (currentMonth === 2) daysInMonth = 28;_x000D_
  else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
  else daysInMonth = 30;_x000D_
  return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
_x000D_
_x000D_

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

http://jsfiddle.net/Fy8vD/3041/

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
     left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
}
.gps_ring:before {
    content:"";
    display:block;
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    left:-8px;
    top:-8px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
}
.gps_ring:after {
    content:"";
    display:block;
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    left:-18px;
    top:-18px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

Stop mouse event propagation

This worked for me:

mycomponent.component.ts:

action(event): void {
  event.stopPropagation();
}

mycomponent.component.html:

<button mat-icon-button (click)="action($event);false">Click me !<button/>

Bootstrap 3 modal responsive

Old post. I ended up setting media queries and using max-width: YYpx; and width:auto; for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md screen), the modal will scale down to 740px (excluding padding for the .modal-body, if applied)

<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-body"></div>
        </div>
    </div>
</div>

Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss file that _bootstrap.scss imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss.

It is also important to note that the original bootstrap styles for .modal-dialog is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;, hence why I overrode it w/ width: auto;.

@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
    .modal-dialog {
        max-width: 600px;
        width: auto;
    }
}

@media (min-width: $screen-md-min) { // this is the 992px breakpoint
    .modal-dialog { 
        max-width: 800px;
    }
}

Example below of modal being responsive with an image.

enter image description here

How to create a thread?

Update The currently suggested way to start a Task is simply using Task.Run()

Task.Run(() => foo());

Note that this method is described as the best way to start a task see here

Previous answer

I like the Task Factory from System.Threading.Tasks. You can do something like this:

Task.Factory.StartNew(() => 
{
    // Whatever code you want in your thread
});

Note that the task factory gives you additional convenience options like ContinueWith:

Task.Factory.StartNew(() => {}).ContinueWith((result) => 
{
    // Whatever code should be executed after the newly started thread.
});

Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.

How to link to a <div> on another page?

Take a look at anchor tags. You can create an anchor with

<div id="anchor-name">Heading Text</div>

and refer to it later with

<a href="http://server/page.html#anchor-name">Link text</a>

Regex: ignore case sensitivity

Depends on implementation but I would use

(?i)G[a-b].

VARIATIONS:

(?i) case-insensitive mode ON    
(?-i) case-insensitive mode OFF

Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?im) in the middle of the regex then the modifier only applies to the part of the regex to the right of the modifier. With these flavors, you can turn off modes by preceding them with a minus sign (?-i).

Description is from the page: https://www.regular-expressions.info/modifiers.html

How to use custom font in a project written in Android Studio

Hello here we have a better way to apply fonts on EditTexts and TextViews on android at once and apply it in whole project.

First of All you need to make fonts folder. Here are Steps.

1: Go to the (project folder) Then app>src>main

2: Create folders named 'assets/fonts' into the main folder.

3: Put your fonts into the fonts folder. Here I Have 'MavenPro-Regular.ttf'

Here are the Steps for applying custom fonts on EditText and using this approach you can apply fonts on every input.

1 : Create a Class MyEditText (your preferred name ...)

2 : which extends EditText

3 : Apply your font

Here is code Example;

public class MyEditText extends EditText {

    public MyEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyEditText(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MavenPro-Regular.ttf");
            setTypeface(tf);
        }
    }

}

And in Here is the code how to use it.

MyEditText editText = (MyEditText) findViewById(R.id.editText);

editText.setText("Hello");

Or in Your xml File

   <MyEditText
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textColor="#fff"
    android:textSize="16dp"
    android:id="@+id/editText"
    />

How do I do a not equal in Django queryset filtering?

You should use filter and exclude like this

results = Model.objects.exclude(a=true).filter(x=5)

java.net.SocketException: Software caused connection abort: recv failed

This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling shutdownInput and shutdownOutput to clear up the session.

How to terminate a python subprocess launched with shell=True

Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.

Here's the code:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

Virtual network interface in Mac OS X

In regards to @bmasterswizzle's BRILLIANT answer - more specifically - to @DanRamos' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...

#!/bin/zsh

[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

I am NOT quite sure I understand the alteration to the prompt at the end, or...

dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null

but WHATEVER. it works. link light: green?. loves it.

enter image description here

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

A simple example, where a change on a dropdown list triggers an ajax form-submit to reload a datagrid:

<div id="pnlSearch">

    <% using (Ajax.BeginForm("UserSearch", "Home", new AjaxOptions { UpdateTargetId = "pnlSearchResults" }, new { id="UserSearchForm" }))
    { %>

        UserType: <%: Html.DropDownList("FilterUserType", Model.UserTypes, "--", new { onchange = "$('#UserSearchForm').trigger('submit');" })%>

    <% } %>

</div>

The trigger('onsubmit') is the key thing: it calls the onsubmit function that MVC has grafted onto the form.

NB. The UserSearchResults controller returns a PartialView that renders a table using the supplied Model

<div id="pnlSearchResults">
    <% Html.RenderPartial("UserSearchResults", Model); %>
</div>

Difference between x86, x32, and x64 architectures?

As the 64bit version is an x86 architecture and was accordingly first called x86-64, that would be the most appropriate name, IMO. Also, x32 is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).

Not Able To Debug App In Android Studio

In my case, i forgot minifyEnabled=true and shrinkResources=true in my debug buildType. I change these values to false, it's worked again!

enter image description here

How to remove old Docker containers

Since Docker 1.13.x you can use Docker container prune:

docker container prune

This will remove all stopped containers and should work on all platforms the same way.

There is also a Docker system prune:

docker system prune

which will clean up all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes, in one command.


For older Docker versions, you can string Docker commands together with other Unix commands to get what you need. Here is an example on how to clean up old containers that are weeks old:

$ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm

To give credit, where it is due, this example is from https://twitter.com/jpetazzo/status/347431091415703552.

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

How to remove symbols from a string with Python?

One way, using regular expressions:

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup   20 99  That s ridiculous   '
  • \w will match alphanumeric characters and underscores

  • [^\w] will match anything that's not alphanumeric or underscore

Invariant Violation: _registerComponent(...): Target container is not a DOM element

When you got:

Error: Uncaught Error: Target container is not a DOM element.

You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function(event) {
  ReactDOM.render(<App />, document.getElementById('root'));
})

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

Remove duplicate rows in MySQL

-- Here is what I used, and it works:
create table temp_table like my_table;
-- t_id is my unique column
insert into temp_table (id) select id from my_table GROUP by t_id;
delete from my_table where id not in (select id from temp_table);
drop table temp_table;

Matplotlib discrete colorbar

I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.

Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.

import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)

which produces the image below. The n in the call to Set1 specifies the first n colors of that colormap, and the last n in the call to from_list specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:

cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)

scatterplot with disrete colors

IIS w3svc error

As for me - I just restarted the computer.

'"SDL.h" no such file or directory found' when compiling

Having a similar case and I couldn't use StackAttacks solution as he's referring to SDL2 which is for the legacy code I'm using too new.

Fortunately our friends from askUbuntu had something similar:

Download SDL

tar xvf SDL-1.2.tar.gz
cd SDL-1.2
./configure
make
sudo make install

How to vertically center <div> inside the parent element with CSS?

I found this site useful: http://www.vanseodesign.com/css/vertical-centering/ This worked for me:

HTML

<div id="parent">
    <div id="child">Content here</div>
</div>

CSS

#parent {
    padding: 5% 0;
}

#child {
    padding: 10% 0;
}

IE prompts to open or save json result from server

I faced this while using jQuery FileUpload plugin.

Then I took a look in their documentation, most exactly in the Content-Type Negotiation section and followed their suggestion for Ruby/Rails.

render(json: <some-data>, content_type: request.format)

Which fixed the issue for me.

Quick Explanation: for old IE/Opera versions, this plugin will use an iframe with text/plain or text/html content-type, so if you force the response to json, browser will try download it. Using the same content-type as in the request will make it work for any browser.

Flask Value error view function did not return a response

The following does not return a response:

You must return anything like return afunction() or return 'a string'.

This can solve the issue

How to add a title to a html select tag

<select name="city">
   <option value ="0">What is your city</option>
   <option value ="1">Sydney</option>
   <option value ="2">Melbourne</option>
   <option value ="3">Cromwell</option>
   <option value ="4">Queenstown</option>
</select>

You can use the unique id for the value instead

How to make Visual Studio copy a DLL file to the output directory?

The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.

I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line

now I added these two lines to copy the output dll into the two folders:

xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug

How to submit http form using C#

You can use the HttpWebRequest class to do so.

Example here:

using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

The program can't start because libgcc_s_dw2-1.dll is missing

Code::Blocks: add '-static' in settings->compiler->Linker settings->Other linker options.

Spring Boot @Value Properties

I had the same issue get value for my property in my service class. I resolved it by using @ConfigurationProperties instead of @Value.

  1. create a class like this:
    import org.springframework.boot.context.properties.ConfigurationProperties;

    @ConfigurationProperties(prefix = "file")
    public class FileProperties {
        private String directory;

        public String getDirectory() {
            return directory;
        }

        public void setDirectory(String dir) {
            this.directory = dir;
        }
    }

  1. add the following to your BootApplication class:
    @EnableConfigurationProperties({
        FileProperties.class
    })
  1. Inject FileProperties to your PrintProperty class, then you can get hold of the property through the getter method.

What is the path for the startup folder in windows 2008 server

You can easily reach them by using the Run window and entering:

shell:startup

and

shell:common startup

Source.

Is there a way I can retrieve sa password in sql server 2005

Wait!

There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password


How to use the tool to retrieve the password

To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer

"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user

name for which you want to retrieve password.Copy the password field (Hashed Code) and

paste here (in Hashed code Field) and click on start button to retrieve

I checked the tool on SQLServer 2000 and it's working fine.

java.util.NoSuchElementException: No line found

You're calling nextLine() and it's throwing an exception when there's no line, exactly as the javadoc describes. It will never return null

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html

How can I fix "Design editor is unavailable until a successful build" error?

just click file in your android studio then click Sync Project with Gradle Files..

if it won't work, click Build click Clean Project.

it always work for me

HTML / CSS Popup div on text click

For the sake of completeness, what you are trying to create is a "modal window".

Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.

I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

how to set cursor style to pointer for links without hrefs

This is how change the cursor from an arrow to a hand when you hover over a given object (myObject).

myObject.style.cursor = 'pointer';

Angular IE Caching issue for $http

I get it resolved appending datetime as an random number:

$http.get("/your_url?rnd="+new Date().getTime()).success(function(data, status, headers, config) {
    console.log('your get response is new!!!');
});

Calling a Function defined inside another function in Javascript

Again, not a direct answer to the question, but was led here by a web search. Ended up exposing the inner function without using return, etc. by simply assigning it to a global variable.

var fname;

function outer() {
    function inner() {
        console.log("hi");
    }
    fname = inner;
}

Now just

fname();

How to call javascript function on page load in asp.net

Place this line before the closing script tag,writing from memory:

window.onload  = GetTimeZoneOffset;

i think the question is how to call the javascript function on pageload

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;

Or TABLE for an unbounded array:

...
   type array_t is table of varchar2(10);
...

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
begin
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;
end;

The first index is 1 not 0.

How do I REALLY reset the Visual Studio window layout?

How about running the following from command line,

Devenv.exe /ResetSettings

You could also save those settings in to a file, like so,

Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"

The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.

MSDN link

Center-align a HTML table

Try this -

<table align="center" style="margin: 0px auto;"></table>

Align a div to center

One of my websites involves a div whose size is variable and you won't know it ahead of time. it is an outer div with 2 nested divs, the outer div is the same width as the first nested div, which is the content, and the second nested div right below the content is the caption, which must be centered. Because the width is not known, I use jQuery to adjust accordingly.

so my html is this

<div id='outer-container'>
<div id='inner-container'></div>
<div id='captions'></div>
</div>

and then I center the captions in jQuery like this

captionWidth=$("#captions").css("width");
outerWidth=$("#outer-container").css("width");
marginIndent=(outerWidth-captionWidth)/2;
$("#captions").css("margin","0px "+marginIndent+"px");

Converting Integer to String with comma for thousands

can't you use a

System.out.printf("%n%,d",int name);

The comma in the printf should add the commas into the %d inter.

Not positive about it, but works for me.

Update multiple rows using select statement

If you have ids in both tables, the following works:

update table2
    set value = (select value from table1 where table1.id = table2.id)

Perhaps a better approach is a join:

update table2
    set value = table1.value
    from table1
    where table1.id = table2.id

Note that this syntax works in SQL Server but may be different in other databases.

post checkbox value

There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Single check box

HTML code:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

PHP Code:

<?php

if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}    

?>

Check box group

<form action="checkbox-form.php" method="post">
    Which buildings do you want access to?<br />
    <input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
    <input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
    <input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
    <input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
    <input type="checkbox" name="formDoor[]" value="E" />Elliot House

    <input type="submit" name="formSubmit" value="Submit" />
 /form>

<?php
  $aDoor = $_POST['formDoor'];
  if(empty($aDoor)) 
  {
    echo("You didn't select any buildings.");
  } 
  else
  {
    $N = count($aDoor);

    echo("You selected $N door(s): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor[$i] . " ");
    }
  }
?>

Get ID from URL with jQuery

You could just use window.location.hash to grab the id.

var id = window.location.hash;

I don't think you will need that much code to achieve this.

What does $(function() {} ); do?

Some Theory

$ is the name of a function like any other name you give to a function. Anyone can create a function in JavaScript and name it $ as shown below:

$ = function() { 
        alert('I am in the $ function');
    }

JQuery is a very famous JavaScript library and they have decided to put their entire framework inside a function named jQuery. To make it easier for people to use the framework and reduce typing the whole word jQuery every single time they want to call the function, they have also created an alias for it. That alias is $. Therefore $ is the name of a function. Within the jQuery source code, you can see this yourself:

window.jQuery = window.$ = jQuery;

Answer To Your Question

So what is $(function() { });?

Now that you know that $ is the name of the function, if you are using the jQuery library, then you are calling the function named $ and passing the argument function() {} into it. The jQuery library will call the function at the appropriate time. When is the appropriate time? According to jQuery documentation, the appropriate time is once all the DOM elements of the page are ready to be used.

The other way to accomplish this is like this:

$(document).ready(function() { });

As you can see this is more verbose so people prefer $(function() { })

So the reason why some functions cannot be called, as you have noticed, is because those functions do not exist yet. In other words the DOM has not loaded yet. But if you put them inside the function you pass to $ as an argument, the DOM is loaded by then. And thus the function has been created and ready to be used.

Another way to interpret $(function() { }) is like this:

Hey $ or jQuery, can you please call this function I am passing as an argument once the DOM has loaded?

How to display Base64 images in HTML?

The + character occurring in a data URI should be encoded as %2B. This is like encoding any other string in a URI. For example, argument separators (? and &) must be encoded when a URI with an argument is sent as part of another URI.

How to insert blank lines in PDF?

directly use

paragraph.add("\n");

to add an empty line.

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

Read whole ASCII file into C++ std::string

Try one of these two methods:

string get_file_string(){
    std::ifstream ifs("path_to_file");
    return string((std::istreambuf_iterator<char>(ifs)),
                  (std::istreambuf_iterator<char>()));
}

string get_file_string2(){
    ifstream inFile;
    inFile.open("path_to_file");//open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();//read the file
    return strStream.str();//str holds the content of the file
}

What exactly does Perl's "bless" do?

In general, bless associates an object with a class.

package MyClass;
my $object = { };
bless $object, "MyClass";

Now when you invoke a method on $object, Perl know which package to search for the method.

If the second argument is omitted, as in your example, the current package/class is used.

For the sake of clarity, your example might be written as follows:

sub new { 
  my $class = shift; 
  my $self = { }; 
  bless $self, $class; 
} 

EDIT: See kixx's good answer for a little more detail.

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

How to check the input is an integer or not in Java?

You can try this way

 String input = "";
 try {
   int x = Integer.parseInt(input); 
   // You can use this method to convert String to int, But if input 
   //is not an int  value then this will throws NumberFormatException. 
   System.out.println("Valid input");
 }catch(NumberFormatException e) {
   System.out.println("input is not an int value"); 
   // Here catch NumberFormatException
   // So input is not a int.
 } 

Fixed size div?

As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:

.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }

<div class="container">
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
</div>

Latex - Change margins of only a few pages

Look up \enlargethispage in some LaTeX reference.

Foreach loop, determine which is the last iteration of the loop

Another way, which I didn't see posted, is to use a Queue. It's analogous to a way to implement a SkipLast() method without iterating more than necessary. This way will also allow you to do this on any number of last items.

public static void ForEachAndKnowIfLast<T>(
    this IEnumerable<T> source,
    Action<T, bool> a,
    int numLastItems = 1)
{
    int bufferMax = numLastItems + 1;
    var buffer = new Queue<T>(bufferMax);
    foreach (T x in source)
    {
        buffer.Enqueue(x);
        if (buffer.Count < bufferMax)
            continue; //Until the buffer is full, just add to it.
        a(buffer.Dequeue(), false);
    }
    foreach (T item in buffer)
        a(item, true);
}

To call this you'd do the following:

Model.Results.ForEachAndKnowIfLast(
    (result, isLast) =>
    {
        //your logic goes here, using isLast to do things differently for last item(s).
    });

Get full path of a file with FileUpload Control

Path.GetFullPath(fileUpload.PostedFile.FileName);

Sorry this 'll get your program file directory + your file name.

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

How to set size for local image using knitr for markdown?

The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:

Resizing local images

As of knitr 1.12, there is the function include_graphics. From ?include_graphics (emphasis mine):

The major advantage of using this function is that it is portable in the sense that it works for all document formats that knitr supports, so you do not need to think if you have to use, for example, LaTeX or Markdown syntax, to embed an external image. Chunk options related to graphics output that work for normal R plots also work for these images, such as out.width and out.height.

Example:

```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```

Advantages:

  • Over agastudy's answer: No need for external libraries or for re-rastering the image.
  • Over Shruti Kapoor's answer: No need to manually write HTML. Besides, the image is included in the self-contained version of the file.

Including generated images

To compose the path to a plot that is generated in a chunk (but not included), the chunk options opts_current$get("fig.path") (path to figure directory) as well as opts_current$get("label") (label of current chunk) may be useful. The following example uses fig.path to include the second of two images which were generated (but not displayed) in the first chunk:

```{r generate_figures, fig.show = "hide"}
library(knitr)
plot(1:10, col = "green")
plot(1:10, col = "red")
```

```{r}
include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path")))
```

The general pattern of figure paths is [fig.path]/[chunklabel]-[i].[ext], where chunklabel is the label of the chunk where the plot has been generated, i is the plot index (within this chunk) and ext is the file extension (by default png in RMarkdown documents).

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.)

Which exception should I raise on bad/illegal argument combinations in Python?

I've mostly just seen the builtin ValueError used in this situation.

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

How do I configure HikariCP in my Spring Boot app in my application.properties files?

According to the documentation it is changed,

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html

Example :

spring:
    datasource:
        url: 'jdbc:mysql://localhost/db?useSSL=false'
        username: root
        password: pass
        driver: com.mysql.jdbc.Driver
        hikari:
            minIdle: 10
            idle-timeout: 10000
            maximumPoolSize: 30

These are the following configuration changes we can do on hikari, please add/update according to your need.

autoCommit
connectionTimeout
idleTimeout
maxLifetime
connectionTestQuery
connectionInitSql
validationTimeout
maximumPoolSize
poolName
allowPoolSuspension
readOnly
transactionIsolation
leakDetectionThreshold

jQuery: Setting select list 'selected' based on text, failing strangely

When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

var text1 = 'Monkey';
$("#mySelect1").val(text1);

var text2 = 'Mushroom pie';
$("#mySelect2").val(text2);

You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

var text1 = 'Monkey';
$("#mySelect1 option").filter(function() {
    return this.text == text1; 
}).attr('selected', true);

var text2 = 'Mushroom pie';
$("#mySelect2 option").filter(function() {
    return this.text == text2; 
}).attr('selected', true);?

You can test that version here.

Auto-center map with multiple markers in Google Maps API v3

I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:

//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;

map.setCenter(new google.maps.LatLng(
  ((lat_max + lat_min) / 2.0),
  ((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
  //bottom left
  new google.maps.LatLng(lat_min, lng_min),
  //top right
  new google.maps.LatLng(lat_max, lng_max)
));

MySQL Event Scheduler on a specific time everyday

This might be too late for your work, but here is how I did it. I want something run everyday at 1AM - I believe this is similar to what you are doing. Here is how I did it:

CREATE EVENT event_name
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    # Your awesome query

How do I find out my MySQL URL, host, port and username?

If you use phpMyAdmin, click on Home, then Variables on the top menu. Look for the port setting on the page. The value it is set to is the port your MySQL server is running on.

App installation failed due to application-identifier entitlement

Steps

  1. With your device connected, and Xcode open, select Window->Devices
  2. Now select the app and download the container using setting icon
  3. Delete the app
  4. Install app again using Xcode
  5. Stop from Xcode
  6. Go to Window->Device and select the app and replace the container that is backup from previous app

Can a variable number of arguments be passed to a function?

Adding to the other excellent posts.

Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

def manyArgs1(args):
  print args.a, args.b #note args.c is not used here

def manyArgs2(args):
  print args.c #note args.b and .c are not used here

class Args: pass

args = Args()
args.a = 1
args.b = 2
args.c = 3

manyArgs1(args) #outputs 1 2
manyArgs2(args) #outputs 3

Then you can do things like

myfuns = [manyArgs1, manyArgs2]
for fun in myfuns:
  fun(args)

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

Parsing JSON array into java.util.List with Gson

Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:

List<String> servers = Streams.stream(jsonArray.iterator())
                              .map(je -> je.getAsString())
                              .collect(Collectors.toList());

Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.

Find p-value (significance) in scikit-learn LinearRegression

p_value is among f statistics. if you want to get the value, simply use this few lines of code:

import statsmodels.api as sm
from scipy import stats

diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
print(est.fit().f_pvalue)

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

Read input numbers separated by spaces

You'll want to:

  • Read in an entire line from the console
  • Tokenize the line, splitting along spaces.
  • Place those split pieces into an array or list
  • Step through that array/list, performing your prime/perfect/etc tests.

What has your class covered along these lines so far?

How to check version of python modules?

The previous answers did not solve my problem, but this code did:

import sys 
for name, module in sorted(sys.modules.items()): 
  if hasattr(module, '__version__'): 
    print name, module.__version__ 

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

I added a new environment variable ANDROID_HOME and pointed it to the SDK (C:\Program Files (x86)\Android\android-studio\sdk) that is inside the installation directory of Android Studio. (Environment variables are a part of windows; you access them through the advanced computer properties...google it for more info)

T-SQL datetime rounded to nearest minute and nearest hours with using functions

I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:

CAST(YourValueHere as smalldatetime);

For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.

What is the main difference between Inheritance and Polymorphism?

Polymorphism: Suppose you work for a company that sells pens. So you make a very nice class called "Pen" that handles everything that you need to know about a pen. You write all sorts of classes for billing, shipping, creating invoices, all using the Pen class. A day boss comes and says, "Great news! The company is growing and we are selling Books & CD's now!" Not great news because now you have to change every class that uses Pen to also use Book & CD. But what if you had originally created an interface called "SellableProduct", and Pen implemented this interface. Then you could have written all your shipping, invoicing, etc classes to use that interface instead of Pen. Now all you would have to do is create a new class called Book & CompactDisc which implements the SellableProduct interface. Because of polymorphism, all of the other classes could continue to work without change! Make Sense?

So, it means using Inheritance which is one of the way to achieve polymorphism.

Polymorhism can be possible in a class / interface but Inheritance always between 2 OR more classes / interfaces. Inheritance always conform "is-a" relationship whereas it is not always with Polymorphism (which can conform both "is-a" / "has-a" relationship.

How do you create a Swift Date object?

According to Apple documentation

Example :

var myObject = NSDate()
let futureDate = myObject.dateByAddingTimeInterval(10)
let timeSinceNow = myObject.timeIntervalSinceNow

How to show current time in JavaScript in the format HH:MM:SS?

_x000D_
_x000D_
function checkTime(i) {_x000D_
  if (i < 10) {_x000D_
    i = "0" + i;_x000D_
  }_x000D_
  return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
  var today = new Date();_x000D_
  var h = today.getHours();_x000D_
  var m = today.getMinutes();_x000D_
  var s = today.getSeconds();_x000D_
  // add a zero in front of numbers<10_x000D_
  m = checkTime(m);_x000D_
  s = checkTime(s);_x000D_
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
  t = setTimeout(function() {_x000D_
    startTime()_x000D_
  }, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
_x000D_
_x000D_

DEMO using javaScript only

Update

Updated Demo

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    startTime();
})();

Bad Request - Invalid Hostname IIS7

Don't forget to bind to the IPv6 address as well! I was trying to add a site on 127.0.0.1 using localhost and got the bad request/invalid hostname error. When I pinged localhost it resolved to ::1 since IPv6 was enabled so I just had to add the additional binding to fix the issue.

IIS Site Bindings

Can the Unix list command 'ls' output numerical chmod permissions?

You can use the following command

stat -c "%a %n" *

Also you can use any filename or directoryname instead of * to get a specific result.

On Mac, you can use

stat -f '%A %N' *

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Add Expires headers

In ASP.NET there is similar object, you can use Caching Portions in WebFormsUserControls in order to cache objects of a page for a period of time and save server resources. This is also known as fragment caching.
If you include this code to top of your user control, a version of the control stored in the output cache for 150 seconds. You can create your own control that would contain expire header for a specific resource you want.

<%@ OutputCache Duration="150" VaryByParam="None" %>

This article explain it completely: Caching Portions of an ASP.NET Page

A potentially dangerous Request.Path value was detected from the client (*)

If you're using .NET 4.0 you should be able to allow these urls via the web.config

<system.web>
    <httpRuntime 
            requestPathInvalidCharacters="&lt;,&gt;,%,&amp;,:,\,?" />
</system.web>

Note, I've just removed the asterisk (*), the original default string is:

<httpRuntime 
          requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,:,\,?" />

See this question for more details.

What Regex would capture everything from ' mark to the end of a line?

When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.

To capture everything until end of that line I typed the following:

'.*?\n

This would only capture everything from ' until end of that line.

kubectl apply vs kubectl create?

Just to give a more straight forward answer, from my understanding:

apply - makes incremental changes to an existing object
create - creates a whole new object (previously non-existing / deleted)


Taking this from a DigitalOcean article which was linked by Kubernetes website:

We use apply instead of create here so that in the future we can incrementally apply changes to the Ingress Controller objects instead of completely overwriting them.

What is the difference between DBMS and RDBMS?

DBMS is the software program that is used to manage all the database that are stored on the network or system hard disk. whereas RDBMS is the database system in which the relationship among different tables are maintained.

What is the best collation to use for MySQL with PHP?

Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.

Example from the documentation for charset unicode:

utf8_general_ci also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should use utf8_general_ci because it is faster. Otherwise, use utf8_unicode_ci because it is more accurate.

So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci should suffice, for other languages, like Swedish, special collations have been created.

Stop absolutely positioned div from overlapping text

Short answer: There's no way to do it using CSS only.

Long(er) answer: Why? Because when you do position: absolute;, that takes your element out of the document's regular flow, so there's no way for the text to have any positional-relationship with it, unfortunately.

One of the possible alternatives is to float: right; your div, but if that doesn't achieve what you want, you'll have to use JavaScript/jQuery, or just come up with a better layout.

Append text to file from command line without using io redirection

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

Get path to execution directory of Windows Forms application

Both of the examples are in VB.NET.

Debug path:

TextBox1.Text = My.Application.Info.DirectoryPath

EXE path:

TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)

vbscript output to console

This was found on Dragon-IT Scripts and Code Repository.

You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

Subscript out of bounds - general definition and solution?

This came from standford's sna free tutorial and it states that ...

# Reachability can only be computed on one vertex at a time. To # get graph-wide statistics, change the value of "vertex" # manually or write a for loop. (Remember that, unlike R objects, # igraph objects are numbered from 0.)

ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at

this_node_reach <- subcomponent(g, (i - 1), mode = m)

but for the alter calculation, there is a typo here

alter = this_node_reach[j] + 1

delete +1 and it will work alright

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

Shuffle DataFrame rows

What is also useful, if you use it for Machine_learning and want to seperate always the same data, you could use:

df.sample(n=len(df), random_state=42)

this makes sure, that you keep your random choice always replicatable

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How to Lock/Unlock screen programmatically?

Edit:

As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.

Original Answer was:

You need to get Admin permission and you can lock phone screen

please check below simple tutorial to achive this one

Lock Phone Screen Programmtically

also here is the code example..

LockScreenActivity.java

public class LockScreenActivity extends Activity implements OnClickListener {  
 private Button lock;  
 private Button disable;  
 private Button enable;  
 static final int RESULT_ENABLE = 1;  

     DevicePolicyManager deviceManger;  
     ActivityManager activityManager;  
     ComponentName compName;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        deviceManger = (DevicePolicyManager)getSystemService(  
          Context.DEVICE_POLICY_SERVICE);  
        activityManager = (ActivityManager)getSystemService(  
          Context.ACTIVITY_SERVICE);  
        compName = new ComponentName(this, MyAdmin.class);  

        setContentView(R.layout.main);  

        lock =(Button)findViewById(R.id.lock);  
        lock.setOnClickListener(this);  

        disable = (Button)findViewById(R.id.btnDisable);  
        enable =(Button)findViewById(R.id.btnEnable);  
        disable.setOnClickListener(this);  
        enable.setOnClickListener(this);  
    }  

 @Override  
 public void onClick(View v) {  

  if(v == lock){  
    boolean active = deviceManger.isAdminActive(compName);  
             if (active) {  
                 deviceManger.lockNow();  
             }  
  }  

  if(v == enable){  
   Intent intent = new Intent(DevicePolicyManager  
     .ACTION_ADD_DEVICE_ADMIN);  
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,  
                    compName);  
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  
                    "Additional text explaining why this needs to be added.");  
            startActivityForResult(intent, RESULT_ENABLE);  
  }  

  if(v == disable){  
     deviceManger.removeActiveAdmin(compName);  
              updateButtonStates();  
  }    
 }  

 private void updateButtonStates() {  

        boolean active = deviceManger.isAdminActive(compName);  
        if (active) {  
            enable.setEnabled(false);  
            disable.setEnabled(true);  

        } else {  
            enable.setEnabled(true);  
            disable.setEnabled(false);  
        }      
 }  

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
         switch (requestCode) {  
             case RESULT_ENABLE:  
                 if (resultCode == Activity.RESULT_OK) {  
                     Log.i("DeviceAdminSample", "Admin enabled!");  
                 } else {  
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");  
                 }  
                 return;  
         }  
         super.onActivityResult(requestCode, resultCode, data);  
     }  
}

MyAdmin.java

public class MyAdmin extends DeviceAdminReceiver{  


    static SharedPreferences getSamplePreferences(Context context) {  
        return context.getSharedPreferences(  
          DeviceAdminReceiver.class.getName(), 0);  
    }  

    static String PREF_PASSWORD_QUALITY = "password_quality";  
    static String PREF_PASSWORD_LENGTH = "password_length";  
    static String PREF_MAX_FAILED_PW = "max_failed_pw";  

    void showToast(Context context, CharSequence msg) {  
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();  
    }  

    @Override  
    public void onEnabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: enabled");  
    }  

    @Override  
    public CharSequence onDisableRequested(Context context, Intent intent) {  
        return "This is an optional message to warn the user about disabling.";  
    }  

    @Override  
    public void onDisabled(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: disabled");  
    }  

    @Override  
    public void onPasswordChanged(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw changed");  
    }  

    @Override  
    public void onPasswordFailed(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw failed");  
    }  

    @Override  
    public void onPasswordSucceeded(Context context, Intent intent) {  
        showToast(context, "Sample Device Admin: pw succeeded");  
    }  

}

Convert string to boolean in C#

You must use some of the C # conversion systems:

string to boolean: True to true

string str = "True";
bool mybool = System.Convert.ToBoolean(str);

boolean to string: true to True

bool mybool = true;
string str = System.Convert.ToString(mybool);

//or

string str = mybool.ToString();

bool.Parse expects one parameter which in this case is str, even .

Convert.ToBoolean expects one parameter.

bool.TryParse expects two parameters, one entry (str) and one out (result).

If TryParse is true, then the conversion was correct, otherwise an error occurred

string str = "True";
bool MyBool = bool.Parse(str);

//Or

string str = "True";
if(bool.TryParse(str, out bool result))
{
   //Correct conversion
}
else
{
     //Incorrect, an error has occurred
}

How to download Javadoc to read offline?

Links to access the JDK documentation

By the way, a history of Java SE versions.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I work for a large corporation and encountered this same error, but needed a different work around. My issue was related to proxy settings. I had my proxy set up so I needed to set my no_proxy to whitelist AWS before I was able to get everything to work. You can set it in your bash script as well if you don't want to muddy up your Python code with os settings.

Python:

import os
os.environ["NO_PROXY"] = "s3.amazonaws.com"

Bash:

export no_proxy = "s3.amazonaws.com"

Edit: The above assume a US East S3 region. For other regions: use s3.[region].amazonaws.com where region is something like us-east-1 or us-west-2

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

How to convert integer to string in C?

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);

String formatting: % vs. .format vs. string literal

Python 3.6.7 comparative:

#!/usr/bin/env python
import timeit

def time_it(fn):
    """
    Measure time of execution of a function
    """
    def wrapper(*args, **kwargs):
        t0 = timeit.default_timer()
        fn(*args, **kwargs)
        t1 = timeit.default_timer()
        print("{0:.10f} seconds".format(t1 - t0))
    return wrapper


@time_it
def new_new_format(s):
    print("new_new_format:", f"{s[0]} {s[1]} {s[2]} {s[3]} {s[4]}")


@time_it
def new_format(s):
    print("new_format:", "{0} {1} {2} {3} {4}".format(*s))


@time_it
def old_format(s):
    print("old_format:", "%s %s %s %s %s" % s)


def main():
    samples = (("uno", "dos", "tres", "cuatro", "cinco"), (1,2,3,4,5), (1.1, 2.1, 3.1, 4.1, 5.1), ("uno", 2, 3.14, "cuatro", 5.5),) 
    for s in samples:
        new_new_format(s)
        new_format(s)
        old_format(s)
        print("-----")


if __name__ == '__main__':
    main()

Output:

new_new_format: uno dos tres cuatro cinco
0.0000170280 seconds
new_format: uno dos tres cuatro cinco
0.0000046750 seconds
old_format: uno dos tres cuatro cinco
0.0000034820 seconds
-----
new_new_format: 1 2 3 4 5
0.0000043980 seconds
new_format: 1 2 3 4 5
0.0000062590 seconds
old_format: 1 2 3 4 5
0.0000041730 seconds
-----
new_new_format: 1.1 2.1 3.1 4.1 5.1
0.0000092650 seconds
new_format: 1.1 2.1 3.1 4.1 5.1
0.0000055340 seconds
old_format: 1.1 2.1 3.1 4.1 5.1
0.0000052130 seconds
-----
new_new_format: uno 2 3.14 cuatro 5.5
0.0000053380 seconds
new_format: uno 2 3.14 cuatro 5.5
0.0000047570 seconds
old_format: uno 2 3.14 cuatro 5.5
0.0000045320 seconds
-----

trace a particular IP and port

you can use tcpdump on the server to check if the client even reaches the server.

  tcpdump -i any tcp port 9100

also make sure your firewall is not blocking incoming connections.

EDIT: you can also write the dump into a file and view it with wireshark on your client if you don't want to read it on the console.

2nd Edit: you can check if you can reach the port via

 nc ip 9100 -z -v

from your local PC.

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

I find that the "solution" of just increasing the timeouts obscures what's really going on here, which is either

  1. Your code and/or network calls are way too slow (should be sub 100 ms for a good user experience)
  2. The assertions (tests) are failing and something is swallowing the errors before Mocha is able to act on them.

You usually encounter #2 when Mocha doesn't receive assertion errors from a callback. This is caused by some other code swallowing the exception further up the stack. The right way of dealing with this is to fix the code and not swallow the error.

When external code swallows your errors

In case it's a library function that you are unable to modify, you need to catch the assertion error and pass it onto Mocha yourself. You do this by wrapping your assertion callback in a try/catch block and pass any exceptions to the done handler.

it('should not fail', function (done) { // Pass reference here!

  i_swallow_errors(function (err, result) {
    try { // boilerplate to be able to get the assert failures
      assert.ok(true);
      assert.equal(result, 'bar');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This boilerplate can of course be extracted into some utility function to make the test a little more pleasing to the eye:

it('should not fail', function (done) { // Pass reference here!
    i_swallow_errors(handleError(done, function (err, result) {
        assert.equal(result, 'bar');
    }));
});

// reusable boilerplate to be able to get the assert failures
function handleError(done, fn) {
    try { 
        fn();
        done();
    } catch (error) {
        done(error);
    }
}

Speeding up network tests

Other than that I suggest you pick up the advice on starting to use test stubs for network calls to make tests pass without having to rely on a functioning network. Using Mocha, Chai and Sinon the tests might look something like this

describe('api tests normally involving network calls', function() {

    beforeEach: function () {
        this.xhr = sinon.useFakeXMLHttpRequest();
        var requests = this.requests = [];

        this.xhr.onCreate = function (xhr) {
            requests.push(xhr);
        };
    },

    afterEach: function () {
        this.xhr.restore();
    }


    it("should fetch comments from server", function () {
        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        assertEquals(1, this.requests.length);

        this.requests[0].respond(200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]');
        expect(callback.calledWith([{ id: 12, comment: "Hey there" }])).to.be.true;
    });

});

See Sinon's nise docs for more info.

How do I change the font size of a UILabel in Swift?

You can use an extension.

import UIKit

extension UILabel {

    func sizeFont(_ size: CGFloat) {
        self.font = self.font.withSize(size)
    }
}

To use it:

self.myLabel.fontSize(100)

Is there a foreach loop in Go?

You can in fact use range without referencing it's return values by using for range against your type:

arr := make([]uint8, 5)
i,j := 0,0
for range arr {
    fmt.Println("Array Loop",i)
    i++
}

for range "bytes" {
    fmt.Println("String Loop",j)
    j++
}

https://play.golang.org/p/XHrHLbJMEd

Total number of items defined in an enum

The question is:

How can I get the number of items defined in an enum?

The number of "items" could really mean two completely different things. Consider the following example.

enum MyEnum
{
    A = 1,
    B = 2,
    C = 1,
    D = 3,
    E = 2
}

What is the number of "items" defined in MyEnum?

Is the number of items 5? (A, B, C, D, E)

Or is it 3? (1, 2, 3)

The number of names defined in MyEnum (5) can be computed as follows.

var namesCount = Enum.GetNames(typeof(MyEnum)).Length;

The number of values defined in MyEnum (3) can be computed as follows.

var valuesCount = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Distinct().Count();

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

My Routes are Returning a 404, How can I Fix Them?

I think you have deleted default .htaccess file inside the laravel public folder. upload the file it should fix your problem.

How to run or debug php on Visual Studio Code (VSCode)

If you are using Ubuntu 16.04 and php7 you can install xdebug with below command:

sudo apt-get install php-xdebug

You can find the full configuration process here.

If you are using windows, you can download xdebug from xdebug.org.

And start debugging in VS-code with php-debug extension.

how to configure php-debug for xdebug

Differences between fork and exec

They are use together to create a new child process. First, calling fork creates a copy of the current process (the child process). Then, exec is called from within the child process to "replace" the copy of the parent process with the new process.

The process goes something like this:

child = fork();  //Fork returns a PID for the parent process, or 0 for the child, or -1 for Fail

if (child < 0) {
    std::cout << "Failed to fork GUI process...Exiting" << std::endl;
    exit (-1);
} else if (child == 0) {       // This is the Child Process
    // Call one of the "exec" functions to create the child process
    execvp (argv[0], const_cast<char**>(argv));
} else {                       // This is the Parent Process
    //Continue executing parent process
}

How to distinguish mouse "click" and "drag"

For a public action on an OSM map (position a marker on click) the question was: 1) how to determine the duration of mouse down->up (you can't imagine creating a new marker for each click) and 2) did the mouse move during down->up (i.e user is dragging the map).

const map = document.getElementById('map');

map.addEventListener("mousedown", position); 
map.addEventListener("mouseup", calculate);

let posX, posY, endX, endY, t1, t2, action;

function position(e) {

  posX = e.clientX;
  posY = e.clientY;
  t1 = Date.now();

}

function calculate(e) {

  endX = e.clientX;
  endY = e.clientY;
  t2 = (Date.now()-t1)/1000;
  action = 'inactive';

  if( t2 > 0.5 && t2 < 1.5) { // Fixing duration of mouse down->up

      if( Math.abs( posX-endX ) < 5 && Math.abs( posY-endY ) < 5 ) { // 5px error on mouse pos while clicking
         action = 'active';
         // --------> Do something
      }
  }
  console.log('Down = '+posX + ', ' + posY+'\nUp = '+endX + ', ' + endY+ '\nAction = '+ action);    

}

What is the correct XPath for choosing attributes that contain "foo"?

Have you tried something like:

//a[contains(@prop, "Foo")]

I've never used the contains function before but suspect that it should work as advertised...

SQL changing a value to upper or lower case

SQL SERVER 2005:

print upper('hello');
print lower('HELLO');

Select mySQL based only on month and year

to get the month and year values from the date column

select year(Date) as "year", month(Date) as "month" from Projects

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

How to terminate process from Python using pid?

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid)
p.terminate()  #or p.kill()

If you don't want to install a new library, you can use the os module:

import os
import signal

os.kill(pid, signal.SIGTERM) #or signal.SIGKILL 

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'StripCore.py']:
        print('Process found. Terminating it.')
        process.terminate()
        break
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.
$killall python
$python test_strip.py 
Process not found: starting it.
$python test_strip.py 
Process found. Terminating it.
$python test_strip.py 
Process not found: starting it.

Note: In previous psutil versions cmdline was an attribute instead of a method.

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>

You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.

instead of mvn clean package or mvn package you can try only package its work fine for me

OnclientClick and OnClick is not working at the same time?

OnClientClick seems to be very picky when used with OnClick.

I tried unsuccessfully with the following use cases:

OnClientClick="return ValidateSearch();" 
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"

But they did not work. The following worked:

<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1" 
  OnClick="keywordSearch_Click" 
  OnClientClick="if (!ValidateSearch()) { return false;};" />

Is <img> element block level or inline level?

It's true, they are both - or more precisely, they are "inline block" elements. This means that they flow inline like text, but also have a width and height like block elements.

In CSS, you can set an element to display: inline-block to make it replicate the behaviour of images*.

Images and objects are also known as "replaced" elements, since they do not have content per se, the element is essentially replaced by binary data.

* Note that browsers technically use display: inline (as seen in the developer tools) but they are giving special treatment to images. They still follow all traits of inline-block.

How do I create a message box with "Yes", "No" choices and a DialogResult?

dynamic MsgResult = this.ShowMessageBox("Do you want to cancel all pending changes ?", "Cancel Changes", MessageBoxOption.YesNo);

if (MsgResult == System.Windows.MessageBoxResult.Yes)
{
    enter code here
}
else 
{
    enter code here
}

Check more detail from here

Change CSS properties on click

Firstly, using on* attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:

<div id="foo">hello world!</div>
<img src="zoom.png" id="image" />
$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

A more efficient method is to put those styles into a class, and then add that class onclick, like this:

_x000D_
_x000D_
$('#image').click(function() {
  $('#foo').addClass('myClass');
});
_x000D_
.myClass {
  background-color: red;
  color: white;
  font-size: 44px;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
_x000D_
_x000D_

Here's a plain Javascript implementation of the above for those who require it:

_x000D_
_x000D_
document.querySelector('#image').addEventListener('click', () => {
  document.querySelector('#foo').classList.add('myClass');
}); 
_x000D_
.myClass {
  background-color: red;
  color: white;
  font-size: 44px;
}
_x000D_
<div id="foo">hello world!</div>
<img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
_x000D_
_x000D_
_x000D_

How do I link to Google Maps with a particular longitude and latitude?

It´s out of the scope of the question, but I think it might be also interesting to know how to link to a route. The query would look like this:

https://www.google.es/maps/dir/'52.51758801683297,13.397978515625027'/'52.49083837044266,13.369826049804715'

Is it possible to write data to file using only JavaScript?

const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();

Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file

How to compare two List<String> to each other?

I discovered that SequenceEqual is not the most efficient way to compare two lists of strings (initially from http://www.dotnetperls.com/sequenceequal).

I wanted to test this myself so I created two methods:

    /// <summary>
    /// Compares two string lists using LINQ's SequenceEqual.
    /// </summary>
    public bool CompareLists1(List<string> list1, List<string> list2)
    {
        return list1.SequenceEqual(list2);
    }

    /// <summary>
    /// Compares two string lists using a loop.
    /// </summary>
    public bool CompareLists2(List<string> list1, List<string> list2)
    {
        if (list1.Count != list2.Count)
            return false;

        for (int i = 0; i < list1.Count; i++)
        {
            if (list1[i] != list2[i])
                return false;
        }

        return true;
    }

The second method is a bit of code I encountered and wondered if it could be refactored to be "easier to read." (And also wondered if LINQ optimization would be faster.)

As it turns out, with two lists containing 32k strings, over 100 executions:

  • Method 1 took an average of 6761.8 ticks
  • Method 2 took an average of 3268.4 ticks

I usually prefer LINQ for brevity, performance, and code readability; but in this case I think a loop-based method is preferred.

Edit:

I recompiled using optimized code, and ran the test for 1000 iterations. The results still favor the loop (even more so):

  • Method 1 took an average of 4227.2 ticks
  • Method 2 took an average of 1831.9 ticks

Tested using Visual Studio 2010, C# .NET 4 Client Profile on a Core i7-920

Get user info via Google API

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

How do I invert BooleanToVisibilityConverter?

A simple one way version which can be used like this:

Visibility="{Binding IsHidden, Converter={x:Static Ui:Converters.BooleanToVisibility}, ConverterParameter=true}

can be implemented like this:

public class BooleanToVisibilityConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var invert = false;

    if (parameter != null)
    {
      invert = Boolean.Parse(parameter.ToString());
    }

    var booleanValue = (bool) value;

    return ((booleanValue && !invert) || (!booleanValue && invert)) 
      ? Visibility.Visible : Visibility.Collapsed;
  }

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

Working with $scope.$emit and $scope.$on

How can I send my $scope object from one controller to another using .$emit and .$on methods?

You can send any object you want within the hierarchy of your app, including $scope.

Here is a quick idea about how broadcast and emit work.

Notice the nodes below; all nested within node 3. You use broadcast and emit when you have this scenario.

Note: The number of each node in this example is arbitrary; it could easily be the number one; the number two; or even the number 1,348. Each number is just an identifier for this example. The point of this example is to show nesting of Angular controllers/directives.

                 3
           ------------
           |          |
         -----     ------
         1   |     2    |
      ---   ---   ---  ---
      | |   | |   | |  | |

Check out this tree. How do you answer the following questions?

Note: There are other ways to answer these questions, but here we'll discuss broadcast and emit. Also, when reading below text assume each number has it's own file (directive, controller) e.x. one.js, two.js, three.js.

How does node 1 speak to node 3?

In file one.js

scope.$emit('messageOne', someValue(s));

In file three.js - the uppermost node to all children nodes needed to communicate.

scope.$on('messageOne', someValue(s));

How does node 2 speak to node 3?

In file two.js

scope.$emit('messageTwo', someValue(s));

In file three.js - the uppermost node to all children nodes needed to communicate.

scope.$on('messageTwo', someValue(s));

How does node 3 speak to node 1 and/or node 2?

In file three.js - the uppermost node to all children nodes needed to communicate.

scope.$broadcast('messageThree', someValue(s));

In file one.js && two.js whichever file you want to catch the message or both.

scope.$on('messageThree', someValue(s));

How does node 2 speak to node 1?

In file two.js

scope.$emit('messageTwo', someValue(s));

In file three.js - the uppermost node to all children nodes needed to communicate.

scope.$on('messageTwo', function( event, data ){
  scope.$broadcast( 'messageTwo', data );
});

In file one.js

scope.$on('messageTwo', someValue(s));

HOWEVER

When you have all these nested child nodes trying to communicate like this, you will quickly see many $on's, $broadcast's, and $emit's.

Here is what I like to do.

In the uppermost PARENT NODE ( 3 in this case... ), which may be your parent controller...

So, in file three.js

scope.$on('pushChangesToAllNodes', function( event, message ){
  scope.$broadcast( message.name, message.data );
});

Now in any of the child nodes you only need to $emit the message or catch it using $on.

NOTE: It is normally quite easy to cross talk in one nested path without using $emit, $broadcast, or $on, which means most use cases are for when you are trying to get node 1 to communicate with node 2 or vice versa.

How does node 2 speak to node 1?

In file two.js

scope.$emit('pushChangesToAllNodes', sendNewChanges());

function sendNewChanges(){ // for some event.
  return { name: 'talkToOne', data: [1,2,3] };
}

In file three.js - the uppermost node to all children nodes needed to communicate.

We already handled this one remember?

In file one.js

scope.$on('talkToOne', function( event, arrayOfNumbers ){
  arrayOfNumbers.forEach(function(number){
    console.log(number);
  });
});

You will still need to use $on with each specific value you want to catch, but now you can create whatever you like in any of the nodes without having to worry about how to get the message across the parent node gap as we catch and broadcast the generic pushChangesToAllNodes.

Hope this helps...

How to add the text "ON" and "OFF" to toggle button

Have a look on this example

_x000D_
_x000D_
.switch {
        width: 50px;
        height: 17px;
        position: relative;
        display: inline-block;
    }

        .switch input {
            display: none;
        }

        .switch .slider {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
            cursor: pointer;
            background-color: #e7ecf1;
            border-radius: 30px !important;
            border: 0;
            padding: 0;
            display: block;
            margin: 12px 10px;
            min-height: 11px;
        }

            .switch .slider:before {
                position: absolute;
                background-color: #aaa;
                height: 15px;
                width: 15px;
                content: "";
                left: 0px;
                bottom: -2px;
                border-radius: 50%;
                transition: ease-in-out .5s;
            }

            .switch .slider:after {
                content: "";
                color: white;
                display: block;
                position: absolute;
                transform: translate(-50%,-50%);
                top: 50%;
                left: 70%;
                transition: all .5s;
                font-size: 10px;
                font-family: Verdana,sans-serif;
            }

        .switch input:checked + .slider:after {
            transition: all .5s;
            left: 30%;
            content: "";
        }

        .switch input:checked + .slider {
            background-color: #d3d6d9;
        }

            .switch input:checked + .slider:before {
                transform: translateX(15px);
                background-color: #26a2ac;
            }
_x000D_
<label class="switch">
                                        <input type="checkbox" />
                                        <div class="slider"></div>
                                    </label>
_x000D_
_x000D_
_x000D_

Fatal error: Maximum execution time of 300 seconds exceeded

In my case, when I faced that error in Phpmyadmin, I tried MySQL-Front and import my DB successfully.

Note: You can still use the provided solutions under this question to solve your problem in Phpmyadmin.

SQLAlchemy equivalent to SQL "LIKE" statement

Each column has like() method, which can be used in query.filter(). Given a search string, add a % character on either side to search as a substring in both directions.

tag = request.form["tag"]
search = "%{}%".format(tag)
posts = Post.query.filter(Post.tags.like(search)).all()

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

It's a kludge, but assuming there's a minimum length for SEARCHSTRING, for example 2 characters, substring the SEARCHSTRING parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu") and SEARCHSTRING2 ("ll"). Concatenate them back together when executing the query to the database.

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

This is not the real problem, if you want to see why this is happening then please go to error log file of IIS.

in case of visual studio kindly navigate to:

C:\Users\User\Documents\IISExpress\TraceLogFiles\[your project name]\.

arrange file here in datewise descending and then open very first file.

it will look like:

enter image description here

now scroll down to bottom to see the GENERAL_RESPONSE_ENTITY_BUFFER it is the actual problem. now solve it the above problem will solve automatically.

enter image description here

Can you use a trailing comma in a JSON object?

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:

s.append("[");
for (i = 0; i < 5; ++i) {
  if (i) s.append(","); // add the comma only if this isn't the first entry
  s.appendF("\"%d\"", i);
}
s.append("]");

That extra one line of code in your for loop is hardly expensive...

Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).

Doesn't work well with an array unfortunately.

How do I print the key-value pairs of a dictionary in python

The dictionary:

d={'key1':'value1','key2':'value2','key3':'value3'}

Another one line solution:

print(*d.items(), sep='\n')

Output:

('key1', 'value1')
('key2', 'value2')
('key3', 'value3')

(but, since no one has suggested something like this before, I suspect it is not good practice)

PHP: get the value of TEXTBOX then pass it to a VARIABLE

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}

React / JSX Dynamic Component Name

Across all options with component maps I haven't found the simplest way to define the map using ES6 short syntax:

import React from 'react'
import { PhotoStory, VideoStory } from './stories'

const components = {
    PhotoStory,
    VideoStory,
}

function Story(props) {
    //given that props.story contains 'PhotoStory' or 'VideoStory'
    const SpecificStory = components[props.story]
    return <SpecificStory/>
}

Subtracting time.Duration from time in Go

You can negate a time.Duration:

then := now.Add(- dur)

You can even compare a time.Duration against 0:

if dur > 0 {
    dur = - dur
}

then := now.Add(dur)

You can see a working example at http://play.golang.org/p/ml7svlL4eW

Text blinking jQuery

this code is work for me

   $(document).ready(function () {
        setInterval(function(){
            $(".blink").fadeOut(function () {
                $(this).fadeIn();
            });
        } ,100)
    });

Place input box at the center of div

You can just use either of the following approaches:

_x000D_
_x000D_
.center-block {
  margin: auto;
  display: block;
}
_x000D_
<div>
  <input class="center-block">
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.parent {
  display: grid;
  place-items: center;
}
_x000D_
<div class="parent">
  <input>
</div>
_x000D_
_x000D_
_x000D_

how to toggle attr() in jquery

$(".list-toggle").click(function() {
    $(this).hasAttr('colspan') ? 
        $(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});

How to use Visual Studio Code as Default Editor for Git

Good news! At the time of writing, this feature has already been implemented in the 0.10.12-insiders release and carried out through 0.10.14-insiders. Hence we are going to have it in the upcoming version 1.0 Release of VS Code.

Implementation Ref: Implement -w/--wait command line arg

How do Python functions handle the types of the parameters that you pass in?

Many languages have variables, which are of a specific type and have a value. Python does not have variables; it has objects, and you use names to refer to these objects.

In other languages, when you say:

a = 1

then a (typically integer) variable changes its contents to the value 1.

In Python,

a = 1

means “use the name a to refer to the object 1”. You can do the following in an interactive Python session:

>>> type(1)
<type 'int'>

The function type is called with the object 1; since every object knows its type, it's easy for type to find out said type and return it.

Likewise, whenever you define a function

def funcname(param1, param2):

the function receives two objects, and names them param1 and param2, regardless of their types. If you want to make sure the objects received are of a specific type, code your function as if they are of the needed type(s) and catch the exceptions that are thrown if they aren't. The exceptions thrown are typically TypeError (you used an invalid operation) and AttributeError (you tried to access an inexistent member (methods are members too) ).

Bring element to front using CSS

Add z-index:-1 and position:relative to .content

_x000D_
_x000D_
#header {_x000D_
    background: url(http://placehold.it/420x160) center top no-repeat;_x000D_
}_x000D_
#header-inner {_x000D_
    background: url(http://placekitten.com/150/200) right top no-repeat;_x000D_
}_x000D_
.logo-class {_x000D_
    height: 128px;_x000D_
}_x000D_
.content {_x000D_
    margin-left: auto;_x000D_
    margin-right: auto;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
    z-index: -1;_x000D_
    position:relative;_x000D_
}_x000D_
.td-main {_x000D_
    text-align: center;_x000D_
    padding: 80px 10px 80px 10px;_x000D_
    border: 1px solid #A02422;_x000D_
    background: #ABABAB;_x000D_
}
_x000D_
<body>_x000D_
    <div id="header">_x000D_
        <div id="header-inner">_x000D_
            <table class="content">_x000D_
                <col width="400px" />_x000D_
                <tr>_x000D_
                    <td>_x000D_
                        <table class="content">_x000D_
                            <col width="400px" />_x000D_
                            <tr>_x000D_
                                <td>_x000D_
                                    <div class="logo-class"></div>_x000D_
                                </td>_x000D_
                            </tr>_x000D_
                            <tr>_x000D_
                                <td id="menu"></td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                        <table class="content">_x000D_
                            <col width="120px" />_x000D_
                            <col width="160px" />_x000D_
                            <col width="120px" />_x000D_
                            <tr>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                                <td class="td-main">text</td>_x000D_
                            </tr>_x000D_
                        </table>_x000D_
                    </td>_x000D_
                </tr>_x000D_
            </table>_x000D_
        </div>_x000D_
        <!-- header-inner -->_x000D_
    </div>_x000D_
    <!-- header -->_x000D_
</body>
_x000D_
_x000D_
_x000D_

Integer value in TextView

TextView tv = new TextView(this);
tv.setText("" + 4);

How to update Ruby to 1.9.x on Mac?

This command actually works

\curl -L https://get.rvm.io | bash -s stable --ruby

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

Update: I should have probably started with this as your projects are SNAPSHOTs. It is part of the SNAPSHOT semantics that Maven will check for updates on each build. Being a SNAPSHOT means that it is volatile and subject to change so updates should be checked for. However it's worth pointing out that the Maven super POM configures central to have snapshots disabled, so Maven shouldn't ever check for updates for SNAPSHOTs on central unless you've overridden that in your own pom/settings.


You can configure Maven to use a mirror for the central repository, this will redirect all requests that would normally go to central to your internal repository.

In your settings.xml you would add something like this to set your internal repository as as mirror for central:

<mirrors>
  <mirror>
    <id>ibiblio.org</id>
    <name>ibiblio Mirror of http://repo1.maven.org/maven2/</name>
    <url>http://path/to/my/repository</url>
    <mirrorOf>central</mirrorOf>
  </mirror>
</mirrors>

If you are using a repository manager like Nexus for your internal repository. You can set up a proxy repository for proxy central, so any requests that would normally go to Central are instead sent to your proxy repository (or a repository group containing the proxy), and subsequent requests are cached in the internal repository manager. You can even set the proxy cache timeout to -1, so it will never request for contents from central that are already on the proxy repository.


A more basic solution if you are only working with local repositories is to set the updatePolicy for the central repository to "never", this means Maven will only ever check for artifacts that aren't already in the local repository. This can then be overridden at the command line when needed by using the -U switch to force Maven to check for updates.

You would configure the repository (in your pom or a profile in the settings.xml) as follows:

<repository>
  <id>central</id>
  <url>http://repo1.maven.org/maven2</url>
  <updatePolicy>never</updatePolicy>
</repository>

CSS: Set a background color which is 50% of the width of the window

I have used :after and it is working in all major browsers. please check the link. just need to careful for the z-index as after is having position absolute.

<div class="splitBg">
    <div style="max-width:960px; margin:0 auto; padding:0 15px; box-sizing:border-box;">
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
        </div>
        <div style="float:left; width:50%; position:relative; z-index:10;">
            Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, 
        </div>
        <div style="clear:both;"></div>
    </div>
</div>`
css

    .splitBg{
        background-color:#666;
        position:relative;
        overflow:hidden;
        }
    .splitBg:after{
        width:50%;
        position:absolute;
        right:0;
        top:0;
        content:"";
        display:block;
        height:100%;
        background-color:#06F;
        z-index:1;
        }

fiddle link

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

The target principal name is incorrect. Cannot generate SSPI context

I had the same problem for SQL Server 2014 and all I had to do was to run the application as an administrador.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

But, sometimes, even with user-select and touch-callout turned off, cursor: pointer; may cause this effect, so, just set cursor: default; and it'll work.

How to catch exception output from Python subprocess.check_output()?

As mentioned by @Sebastian the default solution should aim to use run(): https://docs.python.org/3/library/subprocess.html#subprocess.run

Here a convenient implementation (feel free to change the log class with print statements or what ever other logging functionality you are using):

import subprocess

def _run_command(command):
    log.debug("Command: {}".format(command))
    result = subprocess.run(command, shell=True, capture_output=True)
    if result.stderr:
        raise subprocess.CalledProcessError(
                returncode = result.returncode,
                cmd = result.args,
                stderr = result.stderr
                )
    if result.stdout:
        log.debug("Command Result: {}".format(result.stdout.decode('utf-8')))
    return result

And sample usage (code is unrelated, but I think it serves as example of how readable and easy to work with errors it is with this simple implementation):

try:
    # Unlock PIN Card
    _run_command(
        "sudo qmicli --device=/dev/cdc-wdm0 -p --uim-verify-pin=PIN1,{}"
        .format(pin)
    )

except subprocess.CalledProcessError as error:
    if "couldn't verify PIN" in error.stderr.decode("utf-8"):
        log.error(
                "SIM card could not be unlocked. "
                "Either the PIN is wrong or the card is not properly connected. "
                "Resetting module..."
                )
        _reset_4g_hat()
        return

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

Move UIView up when the keyboard appears in iOS

It can be done easily & automatically if that textfield is in a table's cell (even when the table.scrollable = NO).

NOTE that: the position and size of the table must be reasonable. e.g:

  • if the y position of table is 100 counted from the view's bottom, then the 300 height keyboard will overlap the whole table.
  • if table's height = 10, and the textfield in it must be scrolled up 100 when keyboard appears in order to be visible, then that textfield will be out of the table's bound.

Using jQuery how to get click coordinates on the target element

see here enter link description here

html

<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>

css

#myPosition{
  background-color:red;
  height:200px;
  width:200px;
}

jquery

$(document).ready(function(){
    $("#myPosition").click(function(e){
       var elm = $(this);
       var xPos = e.pageX - elm.offset().left;
       var yPos = e.pageY - elm.offset().top;
       alert("X position: " + xPos + ", Y position: " + yPos);
    });
});

Create zip file and ignore directory structure

Using -j won't work along with the -r option.
So the work-around for it can be this:

cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;

Or in-line version

cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -

you can direct the output to /dev/null if you don't want the cd - output to appear on screen

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How to set a string's color

Console

See the Wikipedia page on ANSI escapes for the full collection of sequences, including the colors.

But for one simple example (Printing in red) in Java (as you tagged this as Java) do:

System.out.println("\u001B31;1mhello world!");

The 3 indicates change color, the first 1 indicates red (green would be 2) and the second 1 indicates do it in "bright" mode.

GUI

However, if you want to print to a GUI the easiest way is to use html:

JEditorPane pane = new new JEditorPane();
pane.setText("<html><font color=\"red\">hello world!</font></html>");

For more details on this sort of thing, see the Swing Tutorial. It is also possible by using styles in a JTextPane. Here is a helpful example of code to do this easily with a JTextPane (added from helpful comment).

JTextArea is a single coloured Text component, as described here. It can only display in one color. You can set the color for the whole JTextArea like this:

JTextArea area = new JTextArea("hello world");
area.setForeground(Color.red)

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 
});

Using jQuery bind() and specififying your desired eventTypes .

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

https://stackoverflow.com/a/1320708/969984

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

MySQL - Make an existing Field Unique

If you also want to name the constraint, use this:

ALTER TABLE myTable
  ADD CONSTRAINT constraintName 
    UNIQUE (columnName);

What is the right way to check for a null string in Objective-C?

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;

}

Refer the picture below:

enter image description here

Reset local repository branch to be just like remote repository HEAD

Have you forgotten to create a feature-branch and have committed directly on master by mistake?

You can create the feature branch now and set master back without affecting the worktree (local filesystem) to avoid triggering builds, tests and trouble with file-locks:

git checkout -b feature-branch
git branch -f master origin/master

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

You can write your own listener. It's same as HelmiB's answer but looks more natural:

Create listener interface:

public interface myAsyncTaskCompletedListener {
    void onMyAsynTaskCompleted(int responseCode, String result);
}

Then write your asynchronous task:

public class myAsyncTask extends AsyncTask<String, Void, String> {

    private myAsyncTaskCompletedListener listener;
    private int responseCode = 0;

    public myAsyncTask() {
    }

    public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
        this.listener = listener;
        this.responseCode = responseCode;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @Override
    protected String doInBackground(String... params) {
        String result;
        String param = (params.length == 0) ? null : params[0];
        if (param != null) {
            // Do some background jobs, like httprequest...
            return result;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String finalResult) {
        super.onPostExecute(finalResult);
        if (!isCancelled()) {
            if (listener != null) {
                listener.onMyAsynTaskCompleted(responseCode, finalResult);
            }
        }
    }
}

Finally implement listener in activity:

public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {

    @Override
    public void onMyAsynTaskCompleted(int responseCode, String result) {

        switch (responseCode) {
            case TASK_CODE_ONE: 
                // Do something for CODE_ONE
                break;
            case TASK_CODE_TWO:
                // Do something for CODE_TWO
                break;
            default: 
                // Show some error code
        }        
    }

And this is how you can call asyncTask:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Some other codes...
        new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
        // And some another codes...
}

self referential struct definition?

All previous answers are great , i just thought to give an insight on why a structure can't contain an instance of its own type (not a reference).

its very important to note that structures are 'value' types i.e they contain the actual value, so when you declare a structure the compiler has to decide how much memory to allocate to an instance of it, so it goes through all its members and adds up their memory to figure out the over all memory of the struct, but if the compiler found an instance of the same struct inside then this is a paradox (i.e in order to know how much memory struct A takes you have to decide how much memory struct A takes !).

But reference types are different, if a struct 'A' contains a 'reference' to an instance of its own type, although we don't know yet how much memory is allocated to it, we know how much memory is allocated to a memory address (i.e the reference).

HTH

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

I got the same error when I changed the Compile SDK version from API:21 to API:16. The problem was, appcompat version. If you need to use an older version of android API, so you have to change this appcompat version also. In my case (for API:16), I had to use appcompat-v7:19.+.

So I replace dependencies in build.gradle as follows,

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'
}

And make sure you have older versions of appcompat versions on your SDK enter image description here

HTML: how to force links to open in a new tab, not new window

Simply using "target=_blank" will respect the user/browser preference of whether to use a tab or a new window, which in most cases is "doing the right thing".

If you specify the dimensions of the new window, some browsers will use this as an indicator that a certain size is needed, in which case a new window will always be used. Stack overflow code example Stack Overflow

select count(*) from table of mysql in php

If you only need the value:

$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);

How do I expire a PHP session after 30 minutes?

Store a timestamp in the session


<?php    
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];

require ('db_connection.php');

// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));

if( mysql_num_rows( $result ) > 0)
{
    $array = mysql_fetch_assoc($result);    

    session_start();
    $_SESSION['user_id'] = $user;
    $_SESSION['login_time'] = time();
    header("Location:loggedin.php");            
}
else
{
    header("Location:login.php");
}
?>

Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)

<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
    header("Location:login.php");
}
else
{
    // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
    //$_SESSION['login_time'] = time();
    echo ( "this session is ". $_SESSION['user_id'] );
    //show rest of the page and all other content
}
?>

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

One more sample

declare @objectId int,  @objectName varchar(500), @schemaName varchar(500), @type nvarchar(30), @parentObjId int, @parentObjName nvarchar(500)
declare cur cursor 
for 

select obj.object_id, s.name as schema_name, obj.name, obj.type, parent_object_id
from sys.schemas s
    inner join sys.sysusers u
        on u.uid = s.principal_id
        JOIN
        sys.objects obj on obj.schema_id = s.schema_id
WHERE s.name = 'schema_name' and (type = 'p' or obj.type = 'v' or obj.type = 'u' or obj.type = 'f' or obj.type = 'fn')

order by obj.type

open cur
fetch next from cur into @objectId, @schemaName, @objectName,  @type, @parentObjId
while @@fetch_status = 0
begin
    if @type = 'p'
    begin
        exec('drop procedure ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'fn'
    begin
        exec('drop FUNCTION ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'f'
    begin
        set @parentObjName = (SELECT name from sys.objects WHERE object_id = @parentObjId)
        exec('ALTER TABLE ['+@schemaName +'].[' + @parentObjName + ']' + 'DROP CONSTRAINT ' +  @objectName)
    end

    if @type = 'u'
    begin
        exec('drop table ['+@schemaName +'].[' + @objectName + ']')
    end

    if @type = 'v'
    begin
        exec('drop view ['+@schemaName +'].[' + @objectName + ']')
    end
    fetch next from cur into  @objectId, @schemaName, @objectName,  @type, @parentObjId
end
close cur
deallocate cur