Programs & Examples On #Fouc

A flash of unstyled content (FOUC) is an instance where a web page appears briefly with the browser's default styles prior to loading an external CSS stylesheet.

Get filename from input [type='file'] using jQuery

You can access to the properties you want passing an argument to your callback function (like evt), and then accessing the files with it (evt.target.files[0].name) :

$("document").ready(function(){
  $("main").append('<input type="file" name="photo" id="upload-photo"/>');
  $('#upload-photo').on('change',function(evt) {
    alert(evt.target.files[0].name);
  });
});

Pandas every nth row

I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it.

groups = data.groupby(['group_key'])
selection = groups['index_col'].apply(lambda x: x % 3 == 0)
subset = data[selection]

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

Is there any way to call a function periodically in JavaScript?

Since you want the function to be executed periodically, use setInterval

Using two CSS classes on one element

Another option is to use Descendant selectors

HTML:

<div class="social">
<p class="first">burrito</p>
<p class="last">chimichanga</p>
</div>

Reference first one in CSS: .social .first { color: blue; }

Reference last one in CSS: .social .last { color: green; }

Jsfiddle: https://jsfiddle.net/covbtpaq/153/

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

How add spaces between Slick carousel item

Yup, I have found the solution for dis issue.

  • Create one slider box with extra width from both side( Which we can use to add item space from both sides ).
  • Create Inner Item Content with proper width & margin from both sides( This should be your actual wrapper size )
  • Done

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

HTML5 - mp4 video does not play in IE9

use both format it works fine in all browser:

<video width="640" height="360" controls>
    <!-- MP4 must be first for iPad! -->
    <source src="unbelievable.mp4" type="video/mp4" /><!-- Safari / iOS video    -->
    <source src="movie.ogg" type="video/ogg" /><!-- Firefox / Opera / Chrome10 -->
</video>

Assigning strings to arrays of characters

When initializing an array, C allows you to fill it with values. So

char s[100] = "abcd";

is basically the same as

int s[3] = { 1, 2, 3 };

but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

s = "abcd" 

is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.

If you want to copy the string simple use strcpy.

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

Remove end of line characters from Java string

Did you try

string.trim(); 

This is meant to trim all leading and leaning while spaces in the string. Hope this helps.

Edit: (I was not explicit enough)

So, when you string.split(), you will have a string[] - for each of the strings in the array, do a string.trim() and then append it.

String[] tokens = yourString.split(" ");
StringBuffer buff = new StringBuffer();
for (String token : tokens)
{
  buff.append(token.trim());
}

Use stringBuffer/Builder instead of appending in the same string.

Should I use past or present tense in git commit messages?

Who are you writing the message for? And is that reader typically reading the message pre- or post- ownership the commit themselves?

I think good answers here have been given from both perspectives, I’d perhaps just fall short of suggesting there is a best answer for every project. The split vote might suggest as much.

i.e. to summarise:

  • Is the message predominantly for other people, typically reading at some point before they have assumed the change: A proposal of what taking the change will do to their existing code.

  • Is the message predominantly as a journal/record to yourself (or to your team), but typically reading from the perspective of having assumed the change and searching back to discover what happened.

Perhaps this will lead the motivation for your team/project, either way.

Move to another EditText when Soft Keyboard Next is clicked on Android

Simple way :

  • Auto move cursor to next edittext
  • If edittext is last input -> hidden keyboard

Add this to edittext field in .xml file

android:inputType="textCapWords"

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

How to unescape a Java string literal in Java?

Java 13 added a method which does this: String#translateEscapes.

It was a preview feature in Java 13 and 14, but was promoted to a full feature in Java 15.

C++ Best way to get integer division and remainder

You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.

Eloquent ->first() if ->exists()

Try it this way in a simple manner it will work

$userset = User::where('name',$data['name'])->first();
if(!$userset) echo "no user found";

Laravel 5.4 Specific Table Migration

If you want to create one and specific table. You can use this code. It works for laravel(5.x) versions.

php artisan migrate:refresh --path=/database/migrations/fileName.php

Parse error: Syntax error, unexpected end of file in my PHP code

I developed a plugin and installed it on a Wordpress site running on Nginx and it was fine. I only had this error when I switched to Apache, turned out the web server was not accepting the <?, so I just replaced the <? tags to <?php then it worked.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

Strip spaces/tabs/newlines - python

How about a one-liner using a list comprehension within join?

>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb                 ccc
ddd

>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd

How to list all properties of a PowerShell object

You can also use:

Get-WmiObject -Class "Win32_computersystem" | Select *

This will show the same result as Format-List * used in the other answers here.

How to parse data in JSON format?

Can use either json or ast python modules:

Using json :
=============

import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")

Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2




Using ast:
==========

import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")

Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2

Run certain code every n seconds

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

Sending GET request with Authentication headers using restTemplate

These days something like the following will suffice:

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:

print "Hello, World!"

The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:

print("Hello, World!")

“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.

In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:

>>> print("Hello, World!")
Hello, World!

In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: invalid syntax

As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.

In Python 2:

>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6

In Python 3:

>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6

Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:

>>> print "Hello!"
  File "<stdin>", line 1
    print "Hello!"
                 ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?

Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).

The TypeError raised for the right shift operator has also been customised:

>>> print >> sys.stderr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?

Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.

Failed to decode downloaded font

for me it was a problem with lfs files that were not downloaded

git lfs fetch --all

fixed the problem.

see https://github.com/git-lfs/git-lfs/issues/325

Android Push Notifications: Icon not displaying in notification, white square shown instead

I really suggest following Google's Design Guidelines:

which says "Notification icons must be entirely white."

Spring not autowiring in unit tests with JUnit

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

What is this Javascript "require"?

I noticed that whilst the other answers explained what require is and that it is used to load modules in Node they did not give a full reply on how to load node modules when working in the Browser.

It is quite simple to do. Install your module using npm as you describe, and the module itself will be located in a folder usually called node_modules.

Now the simplest way to load it into your app is to reference it from your html with a script tag which points at this directory. i.e if your node_modules directory is in the root of the project at the same level as your index.html you would write this in your index.html:

<script src="node_modules/ng"></script>

That whole script will now be loaded into the page - so you can access its variables and methods directly.

There are other approaches which are more widely used in larger projects, such as a module loader like require.js. Of the two, I have not used Require myself, but I think it is considered by many people the way to go.

Spring Boot - Handle to Hibernate SessionFactory

You can accomplish this with:

SessionFactory sessionFactory = 
    entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

package net.andreaskluth.hibernatesample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeService {

  private SessionFactory hibernateFactory;

  @Autowired
  public SomeService(EntityManagerFactory factory) {
    if(factory.unwrap(SessionFactory.class) == null){
      throw new NullPointerException("factory is not a hibernate factory");
    }
    this.hibernateFactory = factory.unwrap(SessionFactory.class);
  }

}

REST API - why use PUT DELETE POST GET?

In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.

border-radius not working

Try add !important to your css. Its working for me.

.panel {
  float: right;
  width: 120px;
  height: auto;
  background: #fff;
  border-radius: 7px!important;
}

Change text from "Submit" on input tag

The value attribute is used to determine the rendered label of a submit input.

<input type="submit" class="like" value="Like" />

Note that if the control is successful (this one won't be as it has no name) this will also be the submitted value for it.

To have a different submitted value and label you need to use a button element, in which the textNode inside the element determines the label. You can include other elements (including <img> here).

<button type="submit" class="like" name="foo" value="bar">Like</button>

Note that support for <button> is dodgy in older versions of Internet Explorer.

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

What is the --save option for npm install?

npm install --save or npm install --save-dev why we choose 1 options between this two while installing package in our project.

things is clear from the above answers that npm install --save will add entry in the dependency field in pacakage.json file and other one in dev-dependency.

So question arises why we need entry of our installing module in pacakge.json file because whenever we check-in code in git or giving our code to some one we always give it or check it without node-modules because it is very large in size and also available at common place so to avoid this we do that.

so then how other person will get all the modules that is specifically or needed for that project so answers is from the package.json file that have the entry of all the required packages for running or developing that project.

so after getting the code we simply need to run the npm install command it will read the package.json file and install the necessary required packages.

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

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

    return 0;
} 

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

Convert pyQt UI to python

I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:

python uic.py input.ui -o output.py -x

Difference between Pig and Hive? Why have both?

Read the difference between PIG and HIVE in this link.

http://www.aptibook.com/Articles/Pig-and-hive-advantages-disadvantages-features

All the aspects are given. If you are in the confusion which to choose then you must see that web page.

Requested registry access is not allowed

app.manifest should be like this:

<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
   <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
      <security>
         <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
            <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
         </requestedPrivileges>
      </security>
   </trustInfo>
</asmv1:assembly>

How to suppress Update Links warning?

UPDATE:

After all the details summarized and discussed, I spent 2 fair hours in checking the options, and this update is to dot all is.

Preparations

First of all, I performed a clean Office 2010 x86 install on Clean Win7 SP1 Ultimate x64 virtual machine powered by VMWare (this is usual routine for my everyday testing tasks, so I have many of them deployed).

Then, I changed only the following Excel options (i.e. all the other are left as is after installation):

  • Advanced > General > Ask to update automatic links checked:

Ask to update automatic links

  • Trust Center > Trust Center Settings... > External Content > Enable All... (although that one that relates to Data Connections is most likely not important for the case):

External Content

Preconditions

I prepared and placed to C:\ a workbook exactly as per @Siddharth Rout suggestions in his updated answer (shared for your convenience): https://www.dropbox.com/s/mv88vyc27eljqaq/Book1withLinkToBook2.xlsx Linked book was then deleted so that link in the shared book is unavailable (for sure).

Manual Opening

The above shared file shows on opening (having the above listed Excel options) 2 warnings - in the order of appearance:

WARNING #1

This workbook contains links to other data sources

After click on Update I expectedly got another:

WARNING #2

This workbook contains one or more links that cannot be updated

So, I suppose my testing environment is now pretty much similar to OP's) So far so good, we finally go to

VBA Opening

Now I'll try all possible options step by step to make the picture clear. I'll share only relevant lines of code for simplicity (complete sample file with code will be shared in the end).

1. Simple Application.Workbooks.Open

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"

No surprise - this produces BOTH warnings, as for manual opening above.

2. Application.DisplayAlerts = False

Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True

This code ends up with WARNING #1, and either option clicked (Update / Don't Update) produces NO further warnings, i.e. Application.DisplayAlerts = False suppresses WARNING #2.

3. Application.AskToUpdateLinks = False

Application.AskToUpdateLinks = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.AskToUpdateLinks = True

Opposite to DisplayAlerts, this code ends up with WARNING #2 only, i.e. Application.AskToUpdateLinks = False suppresses WARNING #1.

4. Double False

Application.AskToUpdateLinks = False
Application.DisplayAlerts = False
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx"
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True

Apparently, this code ends up with suppressing BOTH WARNINGS.

5. UpdateLinks:=False

Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=False

Finally, this 1-line solution (originally proposed by @brettdj) works the same way as Double False: NO WARNINGS are shown!

Conclusions

Except a good testing practice and very important solved case (I may face such issues everyday while sending my workbooks to 3rd party, and now I'm prepared), 2 more things learned:

  1. Excel options DO matter, regardless of version - especially when we come to VBA solutions.
  2. Every trouble has short and elegant solution - together with not obvious and complicated one. Just one more proof for that!)

Thanks very much to everyone who contributed to the solution, and especially OP who raised the question. Hope my investigations and thoroughly described testing steps were helpful not only for me)

Sample file with the above code samples is shared (many lines are commented deliberately): https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

Original answer (tested for Excel 2007 with certain options):

This code works fine for me - it loops through ALL Excel files specified using wildcards in the InputFolder:

Sub WorkbookOpening2007()

Dim InputFolder As String
Dim LoopFileNameExt As String

InputFolder = "D:\DOCUMENTS\" 'Trailing "\" is required!

LoopFileNameExt = Dir(InputFolder & "*.xls?")
Do While LoopFileNameExt <> ""

Application.DisplayAlerts = False
Application.Workbooks.Open (InputFolder & LoopFileNameExt)
Application.DisplayAlerts = True

LoopFileNameExt = Dir
Loop

End Sub

I tried it with books with unavailable external links - no warnings.

Sample file: https://www.dropbox.com/s/9bwu6pn8fcogby7/NoWarningsOpen.xlsm

How to run a SQL query on an Excel table?

Might I suggest giving QueryStorm a try - it's a plugin for Excel that makes it quite convenient to use SQL in Excel.

Also, it's freemium. If you don't care about autocomplete, error squigglies etc, you can use it for free. Just download and install, and you have SQL support in Excel.

Disclaimer: I'm the author.

how to delete a specific row in codeigniter?

a simple way:

in view(pass the id value):

<td><?php echo anchor('textarea/delete_row?id='.$row->id, 'DELETE', 'id="$row->id"'); ?></td>

in controller(receive the id):

$id = $this->input->get('id');
$this->load->model('mod1');
$this->mod1->row_delete($id);

in model(get the passed args):

function row_delete($id){}

Actually, you should use the ajax to POST the id value to controller and delete the row, not the GET.

What are .a and .so files?

.a files are usually libraries which get statically linked (or more accurately archives), and
.so are dynamically linked libraries.

To do a port you will need the source code that was compiled to make them, or equivalent files on your AIX machine.

AngularJS $http-post - convert binary to excel file and download

Just noticed you can't use it because of IE8/9 but I'll push submit anyway... maybe someone finds it useful

This can actually be done through the browser, using blob. Notice the responseType and the code in the success promise.

$http({
    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    headers: {
       'Content-type': 'application/json'
    },
    responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
    var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}).error(function (data, status, headers, config) {
    //upload failed
});

There are some problems with it though like:

  1. It doesn't support IE 8 and 9:
  2. It opens a pop up window to open the objectUrl which people might have blocked
  3. Generates weird filenames

It did work!

blob The server side code in PHP I tested this with looks like this. I'm sure you can set similar headers in Java:

$file = "file.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));

Edit 20.04.2016

Browsers are making it harder to save data this way. One good option is to use filesaver.js. It provides a cross browser implementation for saveAs, and it should replace some of the code in the success promise above.

Typescript: React event types

for update: event: React.ChangeEvent for submit: event: React.FormEvent for click: event: React.MouseEvent

Determining the path that a yum package installed to

yum uses RPM, so the following command will list the contents of the installed package:

$ rpm -ql package-name

How to set a variable to current date and date-1 in linux?

simple:

today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"

Reading specific columns from a text file in python

You have a space delimited file, so use the module designed for reading delimited values files, csv.

import csv

with open('path/to/file.txt') as inf:
    reader = csv.reader(inf, delimiter=" ")
    second_col = list(zip(*reader))[1]
    # In Python2, you can omit the `list(...)` cast

The zip(*iterable) pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...

>>> testdata = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]

>>> for line in testdata:
...     print(line)

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

...but need columns, you can pass each row to the zip function

>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])

>>> for line in testdata_columns:
...     print(line)

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

how do I use an enum value on a switch statement in C++

The user's input will always be given to you in the form of a string of characters... if you want to convert the user's input from a string to an integer, you'll need to supply the code to do that. If the user types in a number (e.g. "1"), you can pass the string to atoi() to get the integer corresponding to the string. If the user types in an english string (e.g. "EASY") then you'll need to check for that string (e.g. with strcmp()) and assign the appropriate integer value to your variable based on which check matches. Once you have an integer value that was derived from the user's input string, you can pass it into the switch() statement as usual.

How do I iterate through table rows and cells in JavaScript?

If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), then this is the way to go.

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     //iterate through cells
     //cells would be accessed using the "cell" variable assigned in the for loop
}

Could not load NIB in bundle

Working on Xcode 4.6.3 and localizing my NIB files I also run into this issue.

For me nothing else helped besides changing "Document Versioning" in File Inspector to Deployment 5.0 instead of 6.1.

How to change the CHARACTER SET (and COLLATION) throughout a database?

Adding to what David Whittaker posted, I have created a query that generates the complete table and columns alter statement that will convert each table. It may be a good idea to run

SET SESSION group_concat_max_len = 100000;

first to make sure your group concat doesn't go over the very small limit as seen here.

     SELECT a.table_name, concat('ALTER TABLE ', a.table_schema, '.', a.table_name, ' DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci, ',
        group_concat(distinct(concat(' MODIFY ',  column_name, ' ', column_type, ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ', if (is_nullable = 'NO', ' NOT', ''), ' NULL ',
        if (COLUMN_DEFAULT is not null, CONCAT(' DEFAULT \'', COLUMN_DEFAULT, '\''), ''), if (EXTRA != '', CONCAT(' ', EXTRA), '')))), ';') as alter_statement
    FROM information_schema.columns a
    INNER JOIN INFORMATION_SCHEMA.TABLES b ON a.TABLE_CATALOG = b.TABLE_CATALOG
        AND a.TABLE_SCHEMA = b.TABLE_SCHEMA
        AND a.TABLE_NAME = b.TABLE_NAME
        AND b.table_type != 'view'
    WHERE a.table_schema = ? and (collation_name = 'latin1_swedish_ci' or collation_name = 'utf8mb4_general_ci')
    GROUP BY table_name;

A difference here between the previous answer is it was using utf8 instead of ut8mb4 and using t1.data_type with t1.CHARACTER_MAXIMUM_LENGTH didn't work for enums. Also, my query excludes views since those will have to altered separately.

I simply used a Perl script to return all these alters as an array and iterated over them, fixed the columns that were too long (generally they were varchar(256) when the data generally only had 20 characters in them so that was an easy fix).

I found some data was corrupted when altering from latin1 -> utf8mb4. It appeared to be utf8 encoded latin1 characters in columns would get goofed in the conversion. I simply held data from the columns I knew was going to be an issue in memory from before and after the alter and compared them and generated update statements to fix the data.

What are the main performance differences between varchar and nvarchar SQL Server data types?

Since your application is small, there is essentially no appreciable cost increase to using nvarchar over varchar, and you save yourself potential headaches down the road if you have a need to store unicode data.

Move / Copy File Operations in Java

Try to use org.apache.commons.io.FileUtils (General file manipulation utilities). Facilities are provided in the following methods:

(1) FileUtils.moveDirectory(File srcDir, File destDir) => Moves a directory.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.

It's simple, easy and fast.

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

What is Bit Masking?

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]

What are .NET Assemblies?

MSDN has a good explanation:

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

What does += mean in Python?

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

Sometimes you can just do 'Window -> Reset Window Layout', and that'll work :)

Can I open a dropdownlist using jQuery

I've come across the same problem and I have a solution. A function called ExpandSelect() that emulates mouse clicking on "select" element, it does so by creating an another <select> element that is absolutely posioned and have multiple options visible at once by setting the size attribute. Tested in all major browsers: Chrome, Opera, Firefox, Internet Explorer. Explanation of how it works, along with the code here:

Edit (link was broken).

I've created a project at Google Code, go for the code there:

http://code.google.com/p/expandselect/

Screenshots

There is a little difference in GUI when emulating click, but it does not really matter, see it for yourself:

When mouse clicking:

MouseClicking
(source: googlecode.com)

When emulating click:

EmulatingClicking
(source: googlecode.com)

More screenshots on project's website, link above.

Android Studio was unable to find a valid Jvm (Related to MAC OS)

For those who were having trouble creating a script that launched on startup, as an alternative you can add this .plist to your LaunchAgents folder. This may be a more appropriate way of adding environment variables to the system since Yosemite decided to do away with launchd.conf. This should also work across user accounts due to the nature of the LaunchAgents folder, but I haven't tested that.

To do this, create a .plist file with the following name and path:

/Library/LaunchAgents/setenv.STUDIO_JDK.plist

and the contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
            <string>setenv.STUDIO_JDK</string>
        <key>ProgramArguments</key>
            <array>
                <string>sh</string>
                <string>-c</string>
                <string>
                    launchctl setenv STUDIO_JDK /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk
                </string>
            </array>
        <key>RunAtLoad</key>
            <true/>
        <key>ServiceIPC</key>
            <false/>
        <key>LaunchOnlyOnce</key>
            <true/>
        <key>KeepAlive</key>
            <false/>
    </dict>
</plist>

Then change file properties by running the following commands in Terminal:

sudo chmod 644 /Library/LaunchAgents/setenv.STUDIO_JDK.plist

sudo chown root /Library/LaunchAgents/setenv.STUDIO_JDK.plist

sudo chgrp wheel /Library/LaunchAgents/setenv.STUDIO_JDK.plist

Notes:

1) You may need to change 'jdk1.8.0_25.jdk' to match the version that you have on your computer.

2) I tried to use "jdk1.8.*.jdk" to try and account for varying Java * versions, but when I opened Android Studio I got the no JVM error even though if you run "echo $STUDIO_JDK" it returns the correct path. Perhaps someone has some insight as to how to fix that issue.

Converting a character code to char (VB.NET)

You could use the Chr(int) function

How to use operator '-replace' in PowerShell to replace strings of texts with special characters and replace successfully

If you've got V3, you can take advantage of auto-enumeration, the -Raw switch in Get-Content, and some of the new line contiunation syntax to simply it to this, using the string .replace() method instead of the -replace operator:

(Get-ChildItem "[FILEPATH]" -recurse).FullName |
  Foreach-Object {
   (Get-Content $_ -Raw).
     Replace('abt7d9epp4','w2svuzf54f').
     Replace('AccountName=adtestnego','AccountName=zadtestnego').
     Replace('AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA==') |
   Set-Content $_
  }

Using the .replace() method uses literal strings for the replaced text argument (not regex), so you don't need to worry about escaping regex metacharacters in the text-to-replace argument.

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I don't think that replacing "Require all denied" with "Require all granted" in this directive:

<Directory>

    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

as suggested by Jan Czarny and seonded by user3801675 is the most secure way of solving this problem.

According to the Apache configuration files, that line denies access to the entirety of your server's filesystem. Replacing it might indeed allow access to your virtual host folders but at the price of allowing access to your entire computer as well!

Gev Balyan's approach seems to be the most secure approach here. It was the answer to the "access denied problems" plaguing me after setting up my new Apache server this morning.

How to resize html canvas element?

This worked for me just now:

<canvas id="c" height="100" width="100" style="border:1px solid red"></canvas>
<script>
var c = document.getElementById('c');
alert(c.height + ' ' + c.width);
c.height = 200;
c.width = 200;
alert(c.height + ' ' + c.width);
</script>

How to query as GROUP BY in django?

You can also use the regroup template tag to group by attributes. From the docs:

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

...

{% regroup cities by country as country_list %}

<ul>
    {% for country in country_list %}
        <li>{{ country.grouper }}
            <ul>
            {% for city in country.list %}
                <li>{{ city.name }}: {{ city.population }}</li>
            {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

Looks like this:

  • India
    • Mumbai: 19,000,000
    • Calcutta: 15,000,000
  • USA
    • New York: 20,000,000
    • Chicago: 7,000,000
  • Japan
    • Tokyo: 33,000,000

It also works on QuerySets I believe.

source: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup

edit: note the regroup tag does not work as you would expect it to if your list of dictionaries is not key-sorted. It works iteratively. So sort your list (or query set) by the key of the grouper before passing it to the regroup tag.

How do I get DOUBLE_MAX?

Using double to store large integers is dubious; the largest integer that can be stored reliably in double is much smaller than DBL_MAX. You should use long long, and if that's not enough, you need your own arbitrary-precision code or an existing library.

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Stuck at ".android/repositories.cfg could not be loaded."

Windows 10 Solution:

For me this issue was due to downloading and creating an AVD using Android Studio and then trying to use that virtual device with the Ionic command line. I resolved this by deleting all existing emulators and creating a new one from the command line.

(the avdmanager file typically lives in C:\Users\\Android\sdk\tools\bin)

List existing emulators: avdmanager list avd

Delete an existing emulator: avdmanager delete avd -n emulator_name

Add system image: sdkmanager "system-images;android-24;default;x86_64"

Create new emulator: sdkmanager "system-images;android-27;google_apis_playstore;x86"

Replace non-ASCII characters with a single space

What about this one?

def replace_trash(unicode_string):
     for i in range(0, len(unicode_string)):
         try:
             unicode_string[i].encode("ascii")
         except:
              #means it's non-ASCII
              unicode_string=unicode_string[i].replace(" ") #replacing it with a single space
     return unicode_string

Remove all newlines from inside a string

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

How can I convert byte size into a human-readable format in Java?


private static final String[] Q = new String[]{"", "K", "M", "G", "T", "P", "E"};

public String getAsString(long bytes)
{
    for (int i = 6; i > 0; i--)
    {
        double step = Math.pow(1024, i);
        if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]);
    }
    return Long.toString(bytes);
}

Chrome says "Resource interpreted as script but transferred with MIME type text/plain.", what gives?

If you're generating your javascript with a php file, add this as the beginning of your file:

<?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>

how to remove the dotted line around the clicked a element in html

In my case it was a button, and apparently, with buttons, this is only a problem in Firefox. Solution found here:

button::-moz-focus-inner {
  border: 0;
}

Xcode project not showing list of simulators

I had the same issue, generated from an imported project, the project had 10.3 as deployment target and I only had 10.0 installed, changing the deployment target to 10.0 solved my issues.

How to check if a file exists in a folder?

This helped me:

bool fileExists = (System.IO.File.Exists(filePath) ? true : false);

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

Links not going back a directory?

There are two type of paths: absolute and relative. This is basically the same for files in your hard disc and directories in a URL.

Absolute paths start with a leading slash. They always point to the same location, no matter where you use them:

  • /pages/en/faqs/faq-page1.html

Relative paths are the rest (all that do not start with slash). The location they point to depends on where you are using them

  • index.html is:
    • /pages/en/faqs/index.html if called from /pages/en/faqs/faq-page1.html
    • /pages/index.html if called from /pages/example.html
    • etc.

There are also two special directory names: . and ..:

  • . means "current directory"
  • .. means "parent directory"

You can use them to build relative paths:

  • ../index.html is /pages/en/index.html if called from /pages/en/faqs/faq-page1.html
  • ../../index.html is /pages/index.html if called from /pages/en/faqs/faq-page1.html

Once you're familiar with the terms, it's easy to understand what it's failing and how to fix it. You have two options:

  • Use absolute paths
  • Fix your relative paths

Create stacked barplot where each stack is scaled to sum to 100%

You just need to divide each element by the sum of the values in its column.

Doing this should suffice:

data.perc <- apply(data, 2, function(x){x/sum(x)})

Note that the second parameter tells apply to apply the provided function to columns (using 1 you would apply it to rows). The anonymous function, then, gets passed each data column, one at a time.

Remove .php extension with .htaccess

If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo

This is all you need:

create file .htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

How do I get the offset().top value of an element without using jQuery?

For Angular 2+ to get the offset of the current element (this.el.nativeElement is equvalent of $(this) in jquery):

export class MyComponent implements  OnInit {

constructor(private el: ElementRef) {}

    ngOnInit() {
      //This is the important line you can use in your function in the code
      //-------------------------------------------------------------------------- 
        let offset = this.el.nativeElement.getBoundingClientRect().top;
      //--------------------------------------------------------------------------    

        console.log(offset);
    }

}

Difference between .keystore file and .jks file

You are confused on this.

A keystore is a container of certificates, private keys etc.

There are specifications of what should be the format of this keystore and the predominant is the #PKCS12

JKS is Java's keystore implementation. There is also BKS etc.

These are all keystore types.

So to answer your question:

difference between .keystore files and .jks files

There is none. JKS are keystore files. There is difference though between keystore types. E.g. JKS vs #PKCS12

Creating virtual directories in IIS express

A new option is Jexus Manager for IIS Express,

https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/

It is just the management tool you know how to use.

php how to go one level up on dirname(__FILE__)

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

TypeScript for ... of with index / key?

.forEach already has this ability:

const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
});

But if you want the abilities of for...of, then you can map the array to the index and value:

for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
}

That's a little long, so it may help to put it in a reusable function:

function toEntries<T>(a: T[]) {
    return a.map((value, index) => [index, value] as const);
}

for (const [index, value] of toEntries(someArray)) {
    // ..etc..
}

Iterable Version

This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration compiler option.

function* toEntries<T>(values: T[] | IterableIterator<T>) {
    let index = 0;
    for (const value of values) {
        yield [index, value] as const;
        index++;
    }
}

Array.prototype.entries() - ES6+

If you are able to target ES6+ environments then you can use the .entries() method as outlined in Arnavion's answer.

How to easily consume a web service from PHP

This article explains how you can use PHP SoapClient to call a api web service.

Can git undo a checkout of unstaged files

I normally have all of my work in a dropbox folder. This ensures me that I would have the current folder available outside my local machine and Github. I think it's my other step to guarantee a "version control" other than git. You can follow this in order to revert your file to previous versions of your dropbox files

Hope this helps.

Java regex email

String emailRegex = "[a-zA-Z0-9_.]+@[a-zA-Z0-9]+.[a-zA-Z]{2,3}[.] {0,1}[a-zA-Z]+";
Pattern.matches(emailRegex,"You_Input_Mail_Id");

This is the regex to match valid email addresses.

php static function

Simply, static functions function independently of the class where they belong.

$this means, this is an object of this class. It does not apply to static functions.

class test {
    public function sayHi($hi = "Hi") {
        $this->hi = $hi;
        return $this->hi;
    }
}
class test1 {
    public static function sayHi($hi) {
        $hi = "Hi";
        return $hi;
    }
}

//  Test
$mytest = new test();
print $mytest->sayHi('hello');  // returns 'hello'
print test1::sayHi('hello');    //  returns 'Hi'

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/

// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");

File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);

// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");

The result is damning:

Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.

As Eddie explains above, you can enable better protocols manually:

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; 

I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?

How to update a claim in ASP.NET Identity?

To remove claim details from database we can use below code. Also, we need to sign in again to update the cookie values

 // create a new identity 
            var identity = new ClaimsIdentity(User.Identity);

            // Remove the existing claim value of current user from database
            if(identity.FindFirst("NameOfUser")!=null)
                await UserManager.RemoveClaimAsync(applicationUser.Id, identity.FindFirst("NameOfUser"));

            // Update customized claim 
            await UserManager.AddClaimAsync(applicationUser.Id, new Claim("NameOfUser", applicationUser.Name));

            // the claim has been updates, We need to change the cookie value for getting the updated claim
            AuthenticationManager.SignOut(identity.AuthenticationType);
            await SignInManager.SignInAsync(Userprofile, isPersistent: false, rememberBrowser: false);

            return RedirectToAction("Index", "Home");

ImportError: No module named enum

Depending on your rights, you need sudo at beginning.

How can I repeat a character in Bash?

In bash 3.0 or higher

for i in {1..100};do echo -n =;done

Check that an email address is valid on iOS

Good cocoa function:

-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
   BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
   NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
   NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
   NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
   NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
   return [emailTest evaluateWithObject:checkString];
}

Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/

And because categories are just better, you could also add an interface:

@interface NSString (emailValidation) 
  - (BOOL)isValidEmail;
@end

Implement

@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
  BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
  NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
  NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
  NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  return [emailTest evaluateWithObject:self];
}
@end

And then utilize:

if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }

res.sendFile absolute path

res.sendFile( __dirname + "/public/" + "index1.html" );

where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.

What is the difference between npm install and npm run build?

  • npm install installs the depedendencies in your package.json config.
  • npm run build runs the script "build" and created a script which runs your application - let's say server.js
  • npm start runs the "start" script which will then be "node server.js"

It's difficult to tell exactly what the issue was but basically if you look at your scripts configuration, I would guess that "build" uses some kind of build tool to create your application while "start" assumes the build has been done but then fails if the file is not there.

You are probably using bower or grunt - I seem to remember that a typical grunt application will have defined those scripts as well as a "clean" script to delete the last build.

Build tools tend to create a file in a bin/, dist/, or build/ folder which the start script then calls - e.g. "node build/server.js". When your npm start fails, it is probably because you called npm clean or similar to delete the latest build so your application file is not present causing npm start to fail.

npm build's source code - to touch on the discussion in this question - is in github for you to have a look at if you like. If you run npm build directly and you have a "build" script defined, it will exit with an error asking you to call your build script as npm run-script build so it's not the same as npm run script.

I'm not quite sure what npm build does, but it seems to be related to postinstall and packaging scripts in dependencies. I assume that this might be making sure that any CLI build scripts's or native libraries required by dependencies are built for the specific environment after downloading the package. This will be why link and install call this script.

php date validation

I think it will help somebody.

function isValidDate($thedate) {
    $data = [
        'separators' => array("/", "-", "."),
        'date_array' => '',
        'day_index' => '',
        'year' => '',
        'month' => '',
        'day' => '',
        'status' => false
    ];

    // loop through to break down the date
    foreach ($data['separators'] as $separator) {
        $data['date_array'] = explode($separator, $thedate);
        if (count($data['date_array']) == 3) {
            $data['status'] = true;
            break;
        }
    }

    // err, if more than 4 character or not int
    if ($data['status']) {
        foreach ($data['date_array'] as $value) {
            if (strlen($value) > 4 || !is_numeric($value)) {
                $data['status'] = false;
                break;
            }
        }
    }

    // get the year
    if ($data['status']) {
        if (strlen($data['date_array'][0]) == 4) {
            $data['year'] = $data['date_array'][0];
            $data['day_index'] = 2;
        }elseif (strlen($data['date_array'][2]) == 4) {
            $data['year'] = $data['date_array'][2];
            $data['day_index'] = 0;
        }else {
            $data['status'] = false;
        }
    }

    // get the month
    if ($data['status']) {
        if (strlen($data['date_array'][1]) == 2) {
            $data['month'] = $data['date_array'][1];
        }else {
            $data['status'] = false;
        }
    }

    // get the day
    if ($data['status']) {
        if (strlen($data['date_array'][$data['day_index']]) == 2) {
            $data['day'] = $data['date_array'][$data['day_index']];
        }else {
            $data['status'] = false;
        }
    }

    // finally validate date
    if ($data['status']) {
        return checkdate($data['month'] , $data['day'], $data['year']);
    }

    return false;
}

Get selected option from select element

Here is a shorter version that should also work:

 $('#ddlCodes').change(function() {
      $('#txtEntry2').text(this.val());
    });

adding child nodes in treeview

Example of adding child nodes:

private void AddExampleNodes()
        {
            TreeNode node;

            node = treeView1.Nodes.Add("Master node");
            node.Nodes.Add("Child node");
            node.Nodes.Add("Child node 2");

            node = treeView1.Nodes.Add("Master node 2");
            node.Nodes.Add("mychild");
            node.Nodes.Add("mychild");
        }

Can you force Visual Studio to always run as an Administrator in Windows 8?

I found a simple way to do this on EightForums (Option 8), create a string value under HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers. Set the name to the path to the program and the value to ~RUNASDMIN. Next time you open the program it will open as an administrator

[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
    "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\devenv.exe"="~RUNASADMIN"

How to add line breaks to an HTML textarea?

Maybe someone find this useful:

I had problem with line breaks which were passed from server variable to javascript variable, and then javascript was writing them to textarea (using knockout.js value bindings).

the solution was double escaping new lines:

orginal.Replace("\r\n", "\\r\\n")

on the server side, because with just single escape chars javascript was not parsing.

How to use a keypress event in AngularJS?

here's my directive:

mainApp.directive('number', function () {
    return {
        link: function (scope, el, attr) {
            el.bind("keydown keypress", function (event) {
                //ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
                if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
                    event.preventDefault();
                }
            });
        }
    };
});

usage:

<input number />

java.net.SocketTimeoutException: Read timed out under Tomcat

I had the same problem while trying to read the data from the request body. In my case which occurs randomly only to the mobile-based client devices. So I have increased the connectionUploadTimeout to 1min as suggested by this link

Input jQuery get old value before onchange and get value after on change

Just put the initial value into a data attribute when you create the textbox, eg

HTML

<input id="my-textbox" type="text" data-initial-value="6" value="6" /> 

JQuery

$("#my-textbox").change(function () {
 var oldValue = $(this).attr("data-initial-value");
 var newValue = $(this).val();
});

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Add a new column to existing table in a migration

laravel 5.6 and above

in case you want to add new column as a FOREIGN KEY to an existing table.

Create a new migration by executing this command : make:migration

Example :

php artisan make:migration add_store_id_to_users_table --table=users

In database/migrations folder you have new migration file, something like :

2018_08_08_093431_add_store_id_to_users_table.php (see the comments)

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddStoreIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Create new column
            // You probably want to make the new column nullable
            $table->integer('store_id')->unsigned()->nullable()->after('password');

            // 2. Create foreign key constraints
            $table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {

            // 1. Drop foreign key constraints
            $table->dropForeign(['store_id']);

            // 2. Drop the column
            $table->dropColumn('store_id');
        });
    }
}

After that run the command :

php artisan migrate

In case you want to undo the last migration for any reason, run this command :

php artisan migrate:rollback

You can find more information about migrations in the docs

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

"Eliminate render-blocking CSS in above-the-fold content"

Please have a look on the following page https://varvy.com/pagespeed/render-blocking-css.html . This helped me to get rid of "Render Blocking CSS". I used the following code in order to remove "Render Blocking CSS". Now in google page speed insight I am not getting issue related with render blocking css.

<!-- loadCSS -->
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/cssrelpreload.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/loadCSS.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/onloadCSS.js"></script>
<script>
      /*!
      loadCSS: load a CSS file asynchronously.
      */
      function loadCSS(href){
        var ss = window.document.createElement('link'),
            ref = window.document.getElementsByTagName('head')[0];

        ss.rel = 'stylesheet';
        ss.href = href;

        // temporarily, set media to something non-matching to ensure it'll
        // fetch without blocking render
        ss.media = 'only x';

        ref.parentNode.insertBefore(ss, ref);

        setTimeout( function(){
          // set media back to `all` so that the stylesheet applies once it loads
          ss.media = 'all';
        },0);
      }
      loadCSS('styles.css');
    </script>
    <noscript>
      <!-- Let's not assume anything -->
      <link rel="stylesheet" href="styles.css">
    </noscript>

How do I change the ID of a HTML element with JavaScript?

You can modify the id without having to use getElementById

Example:

<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>

You can see it here: http://jsbin.com/elikaj/1/

Tested with Mozilla Firefox 22 and Google Chrome 60.0

Html code as IFRAME source rather than a URL

iframe srcdoc: This attribute contains HTML content, which will override src attribute. If a browser does not support the srcdoc attribute, it will fall back to the URL in the src attribute.

Let's understand it with an example

<iframe 
    name="my_iframe" 
    srcdoc="<h1 style='text-align:center; color:#9600fa'>Welcome to iframes</h1>"
    src="https://www.birthdaycalculatorbydate.com/"
    width="500px"
    height="200px"
></iframe>

Original content is taken from iframes.

How to develop Android app completely using python?

You could try BeeWare - as described on their website:

Write your apps in Python and release them on iOS, Android, Windows, MacOS, Linux, Web, and tvOS using rich, native user interfaces. One codebase. Multiple apps.

Gives you want you want now to write Android Apps in Python, plus has the advantage that you won't need to learn yet another framework in future if you end up also wanting to do something on one of the other listed platforms.

Here's the Tutorial for Android Apps.

Filter Excel pivot table using VBA

I think i am understanding your question. This filters things that are in the column labels or the row labels. The last 2 sections of the code is what you want but im pasting everything so that you can see exactly how It runs start to finish with everything thats defined etc. I definitely took some of this code from other sites fyi.

Near the end of the code, the "WardClinic_Category" is a column of my data and in the column label of the pivot table. Same for the IVUDDCIndicator (its a column in my data but in the row label of the pivot table).

Hope this helps others...i found it very difficult to find code that did this the "proper way" rather than using code similar to the macro recorder.

Sub CreatingPivotTableNewData()


'Creating pivot table
Dim PvtTbl As PivotTable
Dim wsData As Worksheet
Dim rngData As Range
Dim PvtTblCache As PivotCache
Dim wsPvtTbl As Worksheet
Dim pvtFld As PivotField

'determine the worksheet which contains the source data
Set wsData = Worksheets("Raw_Data")

'determine the worksheet where the new PivotTable will be created
Set wsPvtTbl = Worksheets("3N3E")

'delete all existing Pivot Tables in the worksheet
'in the TableRange1 property, page fields are excluded; to select the entire PivotTable report, including the page fields, use the TableRange2 property.
For Each PvtTbl In wsPvtTbl.PivotTables
If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
PvtTbl.TableRange2.Clear
End If
Next PvtTbl


'A Pivot Cache represents the memory cache for a PivotTable report. Each Pivot Table report has one cache only. Create a new PivotTable cache, and then create a new PivotTable report based on the cache.

'set source data range:
Worksheets("Raw_Data").Activate
Set rngData = wsData.Range(Range("A1"), Range("H1").End(xlDown))


'Creates Pivot Cache and PivotTable:
Worksheets("Raw_Data").Activate
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData.Address, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("A1"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1")

'Default value of ManualUpdate property is False so a PivotTable report is recalculated automatically on each change.
'Turn this off (turn to true) to speed up code.
PvtTbl.ManualUpdate = True


'Adds row and columns for pivot table
PvtTbl.AddFields RowFields:="VerifyHr", ColumnFields:=Array("WardClinic_Category", "IVUDDCIndicator")

'Add item to the Report Filter
PvtTbl.PivotFields("DayOfWeek").Orientation = xlPageField


'set data field - specifically change orientation to a data field and set its function property:
With PvtTbl.PivotFields("TotalVerified")
.Orientation = xlDataField
.Function = xlAverage
.NumberFormat = "0.0"
.Position = 1
End With

'Removes details in the pivot table for each item
Worksheets("3N3E").PivotTables("PivotTable1").PivotFields("WardClinic_Category").ShowDetail = False

'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("WardClinic_Category").PivotItems
    Select Case PivotItem.Name
        Case "3N3E"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem


'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("IVUDDCIndicator").PivotItems
    Select Case PivotItem.Name
        Case "UD", "IV"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem

'turn on automatic update / calculation in the Pivot Table
PvtTbl.ManualUpdate = False


End Sub

How to get UTC+0 date in Java 8?

tl;dr

Instant.now()

java.time

The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

Instant

An Instant represents a moment on the timeline in UTC with a resolution of up to nanoseconds.

Instant instant = Instant.now();

The toString method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.

String output = instant.toString();  

2016-06-27T19:15:25.864Z

The Instant class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.

OffsetDateTime

But Instant has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant to OffsetDateTime. Specify an offset-from-UTC. In java.time that means a ZoneOffset object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

2016-06-27T19:15:25.864Z

Or skip the Instant class.

OffsetDateTime.now( ZoneOffset.UTC )

Now with an OffsetDateTime object in hand, you can use DateTimeFormatter to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter.

ZonedDateTime

When you want to display wall-clock time for some particular time zone, apply a ZoneId to get a ZonedDateTime.

In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00. So note how the time-of-day is four hours earlier in the output, 15 instead of 19 hours. Instant and the ZonedDateTime both represent the very same simultaneous moment, just viewed through two different lenses.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

2016-06-27T15:15:25.864-04:00[America/Montreal]

Converting

While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant ) and java.util.Date::toInstant.

java.util.Date utilDate = java.util.Date.from( instant );

And going the other direction.

Instant instant= utilDate.toInstant();

Similarly, look for new methods added to GregorianCalendar (subclass of Calendar) to convert to and from java.time.ZonedDateTime.

Table of types of date-time classes in modern java.time versus legacy.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

How can I use numpy.correlate to do autocorrelation?

I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:

def autocorrelate(x, period):

    # x is a deep indicator array 
    # period of sample and slices of comparison

    # oldest data (period of input array) may be nan; remove it
    x = x[-np.count_nonzero(~np.isnan(x)):]
    # subtract mean to normalize indicator
    x -= np.mean(x)
    # isolate the recent sample to be autocorrelated
    sample = x[-period:]
    # create slices of indicator data
    correls = []
    for n in range((len(x)-1), period, -1):
        alpha = period + n
        slices = (x[-alpha:])[:period]
        # compare each slice to the recent sample
        correls.append(ta.CORREL(slices, sample, period)[-1])
    # fill in zeros for sample overlap period of recent correlations    
    for n in range(period,0,-1):
        correls.append(0)
    # oldest data (autocorrelation period) will be nan; remove it
    correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])      

    return correls

# CORRELATION OF BEST FIT
# the highest value correlation    
max_value = np.max(correls)
# index of the best correlation
max_index = np.argmax(correls)

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

How to leave a message for a github.com user

Github said on April 3rd 2012 :

Today we're removing two features. They've been gathering dust for a while and it's time to throw them out : Fork Queue & Private Messaging

Source

how to create a Java Date object of midnight today and midnight tomorrow?

As of JodaTime 2.3, the toDateMidnight() is deprecated.

From Upgrade from 2.2 to 2.3

    Deprecations since 2.2
    ----------------------
    - DateMidnight [#41]
     This class is flawed in concept
     The time of midnight occasionally does not occur in some time-zones
     This is a result of a daylight savings time from 00:00 to 01:00
     DateMidnight is essentially a DateTime with a time locked to midnight
     Such a concept is more generally a poor one to use, given LocalDate
     Replace DateMidnight with LocalDate
     Or replace it with DateTime, perhaps using the withTimeAtStartOfDay() method

Here is a sample code without toDateMidnight() method.

Code

DateTime todayAtMidnight = new DateTime().withTimeAtStartOfDay();
System.out.println(todayAtMidnight.toString("yyyy-MM-dd HH:mm:ss"));

Output (may be different depending on your local time zone)

2013-09-28 00:00:00

Java Web Service client basic authentication

If you are using a JAX-WS implementation for your client, such as Metro Web Services, the following code shows how to pass username and password in the HTTP headers:

 MyService port = new MyService();
 MyServiceWS service = port.getMyServicePort();

 Map<String, List<String>> credentials = new HashMap<String,List<String>>();

 credentials.put("username", Collections.singletonList("username"));
 credentials.put("password", Collections.singletonList("password"));

 ((BindingProvider)service).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, credentials);

Then subsequent calls to the service will be authenticated. Beware that the password is only encoded using Base64, so I encourage you to use other additional mechanism like client certificates to increase security.

How to set root password to null

It's not a good idea to edit mysql database directly.

I prefer the following steps:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY ''; 
mysql> flush privileges;

Android WebView Cookie Problem

My working code

public View onCreateView(...){
    mWebView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

        ...
        ...
        ...

    CookieSyncManager.createInstance(mWebView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    //cookieManager.removeSessionCookie(); // remove
    cookieManager.removeAllCookie(); //remove
    // Recommended "hack" with a delay between the removal and the installation of "Cookies"
    SystemClock.sleep(1000);

    cookieManager.setCookie("https://my.app.site.com/", "cookiename=" + value + "; path=/registration" + "; secure"); // ;
    CookieSyncManager.getInstance().sync();

    mWebView.loadUrl(sp.getString("url", "") + end_url);

    return view;
}

To debug the query, "cookieManager.setCookie (....);" I recommend you to look through the contents of the database webviewCookiesChromium.db (stored in "/data/data/my.app.webview/database") There You can see the correct settings.

Disabling "cookieManager.removeSessionCookie();" and/or "cookieManager.removeAllCookie();"

//cookieManager.removeSessionCookie();
// and/or
//cookieManager.removeAllCookie();"

Compare the set value with those that are set by the browser. Adjust the request for the installation of the cookies before until "flags" browser is not installed will fit with what You decide. I found that a query can be "flags":

// You may want to add the secure flag for https:
+ "; secure"
// In case you wish to convert session cookies to have an expiration:
+ "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// These flags I found in the database:
+ "; path=/registration"
+ "; domain=my.app.site.com"

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

None of the suggestions above worked for me so I created a new file with a slightly different name and copied the contents of the offending file into the new file, renamed the offending file and renamed the new file with the offending file's name. Worked like a charm. Problem solved.

Using member variable in lambda capture list inside a member function

Summary of the alternatives:

capture this:

auto lambda = [this](){};

use a local reference to the member:

auto& tmp = grid;
auto lambda = [ tmp](){}; // capture grid by (a single) copy
auto lambda = [&tmp](){}; // capture grid by ref

C++14:

auto lambda = [ grid = grid](){}; // capture grid by copy
auto lambda = [&grid = grid](){}; // capture grid by ref

example: https://godbolt.org/g/dEKVGD

Character reading from file in Python

Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.

You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.

>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"

Alternatively you can use the iconv command line utility to clean up your file:

$ xxd foo
0000000: e280 980a                                ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a                                     '.

Getting return value from stored procedure in C#

retval.Direction = ParameterDirection.Output;

ParameterDirection.ReturnValue should be used for the "return value" of the procedure, not output parameters. It gets the value returned by the SQL RETURN statement (with the parameter named @RETURN_VALUE).

Instead of RETURN @b you should SET @b = something

By the way, return value parameter is always int, not string.

Symfony2 Setting a default choice field selection

The form should map the species->id value automatically to the selected entity select field. For example if your have a Breed entity that has a OnetoOne relationship with a Species entity in a join table called 'breed_species':

class Breed{

    private $species;

    /**
    * @ORM\OneToOne(targetEntity="BreedSpecies", mappedBy="breed")
    */
    private $breedSpecies;

    public function getSpecies(){
       return $breedSpecies->getSpecies();
    }

    private function getBreedSpecies(){
       return $this->$breedSpecies;
    }
}

The field 'species' in the form class should pick up the species->id value from the 'species' attribute object in the Breed class passed to the form.

Alternatively, you can explicitly set the value by explicitly passing the species entity into the form using SetData():

    $breedForm = $this->createForm( new BreedForm(), $breed );
    $species   = $breed->getBreedSpecies()->getSpecies();

    $breedForm->get('species')->setData( $species );

    return $this->render( 'AcmeBundle:Computer:edit.html.twig'
                        , array( 'breed'     => $breed
                               , 'breedForm' => $breedForm->createView()
            )
    );

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

What is the best JavaScript code to create an img element

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Access restriction: Is not accessible due to restriction on required library ..\jre\lib\rt.jar

In Eclipse:
Project -> properties -> java Build Path -> libraries

Remove existing JRE System Library, then Add Library -> JRE System library -> next -> ok

Error will be removed.

Sending POST data without form

have a look at the php documentation for theese functions you can send post reqeust using them.

fsockopen()
fputs()

or simply use a class like Zend_Http_Client which is also based on socket-conenctions.

also found a neat example using google...

How to set session attribute in java?

Java file : Jclass.java

package Jclasspackage

public class Jclass {

    public String uname ;
    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }

    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }

    public Jclass() {
        this.uname = null;
    }

    public static void main(String[] args) {

    }
}

JSP file: sample.jsp

    <%@ page language="java"
    import="java.util.*,java.io.*"
    pageEncoding="ISO-8859-1"%>

<jsp:directive.page import="Jclasspackage.Jclass.java" />   
<% Jclass jc = new Jclass();
String username = (String)request.getAttribute("un")
jc.setUname(username);
%>

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

In this way you can access the username in the java file using "this.username" in the class

How to handle AccessViolationException

Add the following in the config file, and it will be caught in try catch block. Word of caution... try to avoid this situation, as this means some kind of violation is happening.

<configuration>
   <runtime>
      <legacyCorruptedStateExceptionsPolicy enabled="true" />
   </runtime>
</configuration>

Repeat table headers in print mode

Flying Saucer xhtmlrenderer repeats the THEAD on every page of PDF output, if you add the following to your CSS:

        table {
            -fs-table-paginate: paginate;
        }

(It works at least since the R8 release.)

Add regression line equation and R^2 on graph

Here is one solution

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA

lm_eqn <- function(df){
    m <- lm(y ~ x, df);
    eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
         list(a = format(unname(coef(m)[1]), digits = 2),
              b = format(unname(coef(m)[2]), digits = 2),
             r2 = format(summary(m)$r.squared, digits = 3)))
    as.character(as.expression(eq));
}

p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)

EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups

Output

How and when to use ‘async’ and ‘await’

On a higher level:

1) Async keyword enables the await and that's all it does. Async keyword does not run the method in a separate thread. The beginning f async method runs synchronously until it hits await on a time-consuming task.

2) You can await on a method that returns Task or Task of type T. You cannot await on async void method.

3) The moment main thread encounters await on time-consuming task or when the actual work is started, the main thread returns to the caller of the current method.

4) If the main thread sees await on a task that is still executing, it doesn't wait for it and returns to the caller of the current method. In this way, the application remains responsive.

5) Await on processing task, will now execute on a separate thread from the thread pool.

6) When this await task is completed, all the code below it will be executed by the separate thread

Below is the sample code. Execute it and check the thread id

using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncAwaitDemo
{
    class Program
    {
        public static async void AsynchronousOperation()
        {
            Console.WriteLine("Inside AsynchronousOperation Before AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            //Task<int> _task = AsyncMethod();
            int count = await AsyncMethod();

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod Before Await, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            //int count = await _task;

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await Before DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            DependentMethod(count);

            Console.WriteLine("Inside AsynchronousOperation After AsyncMethod After Await After DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
        }

        public static async Task<int> AsyncMethod()
        {
            Console.WriteLine("Inside AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
            int count = 0;

            await Task.Run(() =>
            {
                Console.WriteLine("Executing a long running task which takes 10 seconds to complete, Thread Id: " + Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(20000);
                count = 10;
            });

            Console.WriteLine("Completed AsyncMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            return count;
        }       

        public static void DependentMethod(int count)
        {
            Console.WriteLine("Inside DependentMethod, Thread Id: " + Thread.CurrentThread.ManagedThreadId + ". Total count is " + count);
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Started Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            AsynchronousOperation();

            Console.WriteLine("Completed Main method, Thread Id: " + Thread.CurrentThread.ManagedThreadId);

            Console.ReadKey();
        }

    }
}

How to save a new sheet in an existing excel file, using Pandas?

For creating a new file

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
with pd.ExcelWriter('sample.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='x1')

For appending to the file, use the argument mode='a' in pd.ExcelWriter.

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer:  
    df2.to_excel(writer, sheet_name='x2')

Default is mode ='w'. See documentation.

The action or event has been blocked by Disabled Mode

No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.

Dimitri

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

JavaScript function to add X months to a date

I wrote this alternative solution which works fine to me. It is useful when you wish calculate the end of a contract. For example, start=2016-01-15, months=6, end=2016-7-14 (i.e. last day - 1):

<script>
function daysInMonth(year, month)
{
    return new Date(year, month + 1, 0).getDate();
}

function addMonths(date, months)
{
    var target_month = date.getMonth() + months;
    var year = date.getFullYear() + parseInt(target_month / 12);
    var month = target_month % 12;
    var day = date.getDate();
    var last_day = daysInMonth(year, month);
    if (day > last_day)
    {
        day = last_day;
    }
    var new_date = new Date(year, month, day);
    return new_date;
}

var endDate = addMonths(startDate, months);
</script>

Examples:

addMonths(new Date("2016-01-01"), 1); // 2016-01-31
addMonths(new Date("2016-01-01"), 2); // 2016-02-29 (2016 is a leap year)
addMonths(new Date("2016-01-01"), 13); // 2017-01-31
addMonths(new Date("2016-01-01"), 14); // 2017-02-28

How can I convert uppercase letters to lowercase in Notepad++

You could also, higlight the text you want to change, then navigate to - 'Edit' > 'Convert Case to' choose UPPERCASE or lowercase (as required).

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

Naming Conventions: What to name a boolean variable?

A simple semantic name would be last. This would allow code always positive code like:

if (item.last)
    ...

do {
   ...
} until (item.last);

Is there a way to check for both `null` and `undefined`?

careful if you're using local storage, you can end up with the string undefined rather than the value undefined:

localStorage.setItem('mykey',JSON.stringify(undefined));
localStorage.getItem('mykey') === "undefined"
true

People may find this useful: https://github.com/angular/components/blob/master/src/cdk/coercion/boolean-property.spec.ts

/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

/** Coerces a data-bound value (typically a string) to a boolean. */
export function coerceBooleanProperty(value: any): boolean {
  return value != null && `${value}` !== 'false';
}

import {coerceBooleanProperty} from './boolean-property';

describe('coerceBooleanProperty', () => {

  it('should coerce undefined to false', () => {
    expect(coerceBooleanProperty(undefined)).toBe(false);
  });

  it('should coerce null to false', () => {
    expect(coerceBooleanProperty(null)).toBe(false);
  });

  it('should coerce the empty string to true', () => {
    expect(coerceBooleanProperty('')).toBe(true);
  });

  it('should coerce zero to true', () => {
    expect(coerceBooleanProperty(0)).toBe(true);
  });

  it('should coerce the string "false" to false', () => {
    expect(coerceBooleanProperty('false')).toBe(false);
  });

  it('should coerce the boolean false to false', () => {
    expect(coerceBooleanProperty(false)).toBe(false);
  });

  it('should coerce the boolean true to true', () => {
    expect(coerceBooleanProperty(true)).toBe(true);
  });

  it('should coerce the string "true" to true', () => {
    expect(coerceBooleanProperty('true')).toBe(true);
  });

  it('should coerce an arbitrary string to true', () => {
    expect(coerceBooleanProperty('pink')).toBe(true);
  });

  it('should coerce an object to true', () => {
    expect(coerceBooleanProperty({})).toBe(true);
  });

  it('should coerce an array to true', () => {
    expect(coerceBooleanProperty([])).toBe(true);
  });
});

How do I access the $scope variable in browser's console using AngularJS?

Pick an element in the HTML panel of the developer tools and type this in the console:

angular.element($0).scope()

In WebKit and Firefox, $0 is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console.

You can also target the scope by element ID, like so:

angular.element(document.getElementById('yourElementId')).scope()

Addons/Extensions

There are some very useful Chrome extensions that you might want to check out:

  • Batarang. This has been around for a while.

  • ng-inspector. This is the newest one, and as the name suggests, it allows you to inspect your application's scopes.

Playing with jsFiddle

When working with jsfiddle you can open the fiddle in show mode by adding /show at the end of the URL. When running like this you have access to the angular global. You can try it here:

http://jsfiddle.net/jaimem/Yatbt/show

jQuery Lite

If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with

angular.element('[ng-controller=ctrl]').scope()

Of a button

 angular.element('button:eq(1)').scope()

... and so on.

You might actually want to use a global function to make it easier:

window.SC = function(selector){
    return angular.element(selector).scope();
};

Now you could do this

SC('button:eq(10)')
SC('button:eq(10)').row   // -> value of scope.row

Check here: http://jsfiddle.net/jaimem/DvRaR/1/show/

Finding a branch point with Git?

Sometimes it is effectively impossible (with some exceptions of where you might be lucky to have additional data) and the solutions here wont work.

Git doesn't preserve ref history (which includes branches). It only stores the current position for each branch (the head). This means you can lose some branch history in git over time. Whenever you branch for example, it's immediately lost which branch was the original one. All a branch does is:

git checkout branch1    # refs/branch1 -> commit1
git checkout -b branch2 # branch2 -> commit1

You might assume that the first commited to is the branch. This tends to be the case but it's not always so. There's nothing stopping you from commiting to either branch first after the above operation. Additionally, git timestamps aren't guaranteed to be reliable. It's not until you commit to both that they truly become branches structurally.

While in diagrams we tend to number commits conceptually, git has no real stable concept of sequence when the commit tree branches. In this case you can assume the numbers (indicating order) are determined by timestamp (it might be fun to see how a git UI handles things when you set all the timestamps to the same).

This is what a human expect conceptually:

After branch:
       C1 (B1)
      /
    -
      \
       C1 (B2)
After first commit:
       C1 (B1)
      /
    - 
      \
       C1 - C2 (B2)

This is what you actually get:

After branch:
    - C1 (B1) (B2)
After first commit (human):
    - C1 (B1)
        \
         C2 (B2)
After first commit (real):
    - C1 (B1) - C2 (B2)

You would assume B1 to be the original branch but it could infact simply be a dead branch (someone did checkout -b but never committed to it). It's not until you commit to both that you get a legitimate branch structure within git:

Either:
      / - C2 (B1)
    -- C1
      \ - C3 (B2)
Or:
      / - C3 (B1)
    -- C1
      \ - C2 (B2)

You always know that C1 came before C2 and C3 but you never reliably know if C2 came before C3 or C3 came before C2 (because you can set the time on your workstation to anything for example). B1 and B2 is also misleading as you can't know which branch came first. You can make a very good and usually accurate guess at it in many cases. It is a bit like a race track. All things generally being equal with the cars then you can assume that a car that comes in a lap behind started a lap behind. We also have conventions that are very reliable, for example master will nearly always represent the longest lived branches although sadly I have seen cases where even this is not the case.

The example given here is a history preserving example:

Human:
    - X - A - B - C - D - F (B1)
           \     / \     /
            G - H ----- I - J (B2)
Real:
            B ----- C - D - F (B1)
           /       / \     /
    - X - A       /   \   /
           \     /     \ /
            G - H ----- I - J (B2)

Real here is also misleading because we as humans read it left to right, root to leaf (ref). Git does not do that. Where we do (A->B) in our heads git does (A<-B or B->A). It reads it from ref to root. Refs can be anywhere but tend to be leafs, at least for active branches. A ref points to a commit and commits only contain a like to their parent/s, not to their children. When a commit is a merge commit it will have more than one parent. The first parent is always the original commit that was merged into. The other parents are always commits that were merged into the original commit.

Paths:
    F->(D->(C->(B->(A->X)),(H->(G->(A->X))))),(I->(H->(G->(A->X))),(C->(B->(A->X)),(H->(G->(A->X)))))
    J->(I->(H->(G->(A->X))),(C->(B->(A->X)),(H->(G->(A->X)))))

This is not a very efficient representation, rather an expression of all the paths git can take from each ref (B1 and B2).

Git's internal storage looks more like this (not that A as a parent appears twice):

    F->D,I | D->C | C->B,H | B->A | A->X | J->I | I->H,C | H->G | G->A

If you dump a raw git commit you'll see zero or more parent fields. If there are zero, it means no parent and the commit is a root (you can actually have multiple roots). If there's one, it means there was no merge and it's not a root commit. If there is more than one it means that the commit is the result of a merge and all of the parents after the first are merge commits.

Paths simplified:
    F->(D->C),I | J->I | I->H,C | C->(B->A),H | H->(G->A) | A->X
Paths first parents only:
    F->(D->(C->(B->(A->X)))) | F->D->C->B->A->X
    J->(I->(H->(G->(A->X))) | J->I->H->G->A->X
Or:
    F->D->C | J->I | I->H | C->B->A | H->G->A | A->X
Paths first parents only simplified:
    F->D->C->B->A | J->I->->G->A | A->X
Topological:
    - X - A - B - C - D - F (B1)
           \
            G - H - I - J (B2)

When both hit A their chain will be the same, before that their chain will be entirely different. The first commit another two commits have in common is the common ancestor and from whence they diverged. there might be some confusion here between the terms commit, branch and ref. You can in fact merge a commit. This is what merge really does. A ref simply points to a commit and a branch is nothing more than a ref in the folder .git/refs/heads, the folder location is what determines that a ref is a branch rather than something else such as a tag.

Where you lose history is that merge will do one of two things depending on circumstances.

Consider:

      / - B (B1)
    - A
      \ - C (B2)

In this case a merge in either direction will create a new commit with the first parent as the commit pointed to by the current checked out branch and the second parent as the commit at the tip of the branch you merged into your current branch. It has to create a new commit as both branches have changes since their common ancestor that must be combined.

      / - B - D (B1)
    - A      /
      \ --- C (B2)

At this point D (B1) now has both sets of changes from both branches (itself and B2). However the second branch doesn't have the changes from B1. If you merge the changes from B1 into B2 so that they are syncronised then you might expect something that looks like this (you can force git merge to do it like this however with --no-ff):

Expected:
      / - B - D (B1)
    - A      / \
      \ --- C - E (B2)
Reality:
      / - B - D (B1) (B2)
    - A      /
      \ --- C

You will get that even if B1 has additional commits. As long as there aren't changes in B2 that B1 doesn't have, the two branches will be merged. It does a fast forward which is like a rebase (rebases also eat or linearise history), except unlike a rebase as only one branch has a change set it doesn't have to apply a changeset from one branch on top of that from another.

From:
      / - B - D - E (B1)
    - A      /
      \ --- C (B2)
To:
      / - B - D - E (B1) (B2)
    - A      /
      \ --- C

If you cease work on B1 then things are largely fine for preserving history in the long run. Only B1 (which might be master) will advance typically so the location of B2 in B2's history successfully represents the point that it was merged into B1. This is what git expects you to do, to branch B from A, then you can merge A into B as much as you like as changes accumulate, however when merging B back into A, it's not expected that you will work on B and further. If you carry on working on your branch after fast forward merging it back into the branch you were working on then your erasing B's previous history each time. You're really creating a new branch each time after fast forward commit to source then commit to branch. You end up with when you fast forward commit is lots of branches/merges that you can see in the history and structure but without the ability to determine what the name of that branch was or if what looks like two separate branches is really the same branch.

         0   1   2   3   4 (B1)
        /-\ /-\ /-\ /-\ /
    ----   -   -   -   -
        \-/ \-/ \-/ \-/ \
         5   6   7   8   9 (B2)

1 to 3 and 5 to 8 are structural branches that show up if you follow the history for either 4 or 9. There's no way in git to know which of this unnamed and unreferenced structural branches belong to with of the named and references branches as the end of the structure. You might assume from this drawing that 0 to 4 belongs to B1 and 4 to 9 belongs to B2 but apart from 4 and 9 was can't know which branch belongs to which branch, I've simply drawn it in a way that gives the illusion of that. 0 might belong to B2 and 5 might belong to B1. There are 16 different possibilies in this case of which named branch each of the structural branches could belong to. This is assuming that none of these structural branches came from a deleted branch or as a result of merging a branch into itself when pulling from master (the same branch name on two repos is infact two branches, a separate repository is like branching all branches).

There are a number of git strategies that work around this. You can force git merge to never fast forward and always create a merge branch. A horrible way to preserve branch history is with tags and/or branches (tags are really recommended) according to some convention of your choosing. I realy wouldn't recommend a dummy empty commit in the branch you're merging into. A very common convention is to not merge into an integration branch until you want to genuinely close your branch. This is a practice that people should attempt to adhere to as otherwise you're working around the point of having branches. However in the real world the ideal is not always practical meaning doing the right thing is not viable for every situation. If what you're doing on a branch is isolated that can work but otherwise you might be in a situation where when multiple developers are working one something they need to share their changes quickly (ideally you might really want to be working on one branch but not all situations suit that either and generally two people working on a branch is something you want to avoid).

Oracle query to fetch column names

You can try this:

describe 'Table Name'

It will return all column names and data types

Share cookie between subdomain and domain

In both cases yes it can, and this is the default behaviour for both IE and Edge.

The other answers add valuable insight but chiefly describe the behaviour in Chrome. it's important to note that the behaviour is completely different in IE. CMBuckley's very helpful test script demonstrates that in (say) Chrome, the cookies are not shared between root and subdomains when no domain is specified. However the same test in IE shows that they are shared. This IE case is closer to the take-home description in CMBuckley's www-or-not-www link. I know this to be the case because we have a system that used different servicestack cookies on both the root and subdomain. It all worked fine until someone accessed it in IE and the two systems fought over whose session cookie would win until we blew up the cache.

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

Programmatically navigate using react router V4

I think that @rgommezz covers most of the cases minus one that I think it's quite important.

// history is already a dependency or React Router, but if don't have it then try npm install save-dev history

import createHistory from "history/createBrowserHistory"

// in your function then call add the below 
const history = createHistory();
// Use push, replace, and go to navigate around.
history.push("/home");

This allows me to write a simple service with actions/calls that I can call to do the navigation from any component I want without doing a lot HoC on my components...

It is not clear why nobody has provided this solution before. I hope it helps, and if you see any issue with it please let me know.

Playing Sound In Hidden Tag

I have been trying to attach an audio which should autoplay and will be hidden. It's very simple. Just a few lines of HTML and CSS. Check this out!! Here is the piece of code I used within the body.

<div id="player">
    <audio controls autoplay hidden>
     <source src="file.mp3" type="audio/mpeg">
                unsupported !! 
    </audio>
</div>

Angular2: custom pipe could not be found

If you are declaring your pipe in another module, make sure to add it to that module Declarations and Exports array, then import that module in whatever module is consuming that pipe.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Errors: Data path ".builders['app-shell']" should have required property 'class'

I had this issue, this is how i have solved it. The problem mostly is that your Angular version is not supporting your Node.js version for the build. So the best solution is to upgrade your Node.js to the most current stable one.

For a clean upgrade of Node.js, i advise using n. if you are using Mac.

npm install -g n
npm cache clean -f
sudo n stable
npm update -g

and now check that you are updated:

node -v
npm -v

For more details, check this link: here

Confirm postback OnClientClick button ASP.NET

try this : OnClientClick="return confirm('Are you sure ?');" Also set : CausesValidation="False"

How do you round a float to 2 decimal places in JRuby?

Try this:

module Util
module MyUtil



    def self.redondear_up(suma,cantidad, decimales=0)

        unless suma.present?
            return nil
        end


        if suma>0
            resultado= (suma.to_f/cantidad)
            return resultado.round(decimales)
        end


        return nil


    end

end 
end 

How to remove .html from URL?

RewriteRule /(.+)(\.html)$ /$1 [R=301,L] 

Try this :) don't know if it works.

Find multiple files and rename them in Linux

For renaming recursively I use the following commands:

find -iname \*.* | rename -v "s/ /-/g"

TypeError: 'float' object is not callable

You have forgotten a * between -3.7 and (prof[x]).

Thus:

for x in range(len(prof)):
    PB = 2.25 * (1 - math.pow(math.e, (-3.7 * (prof[x])/2.25))) * (math.e, (0/2.25)))

Also, there seems to be missing an ( as I count 6 times ( and 7 times ), and I think (math.e, (0/2.25)) is missing a function call (probably math.pow, but thats just a wild guess).

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

What does double question mark (??) operator mean in PHP

$myVar = $someVar ?? 42;

Is equivalent to :

$myVar = isset($someVar) ? $someVar : 42;

For constants, the behaviour is the same when using a constant that already exists :

define("FOO", "bar");
define("BAR", null);

$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";

echo $MyVar . PHP_EOL;  // bar
echo $MyVar2 . PHP_EOL; // 42

However, for constants that don't exist, this is different :

$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL;       // IDONTEXIST

Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)

Php will convert the non-existing constant to a string.

You can use constant("ConstantName") that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @ to ignore the warning message :

$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42

Pandas DataFrame concat vs append

I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat and append. I updated the code snippet and the results after the comment by ssk08 - thanks alot!

The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.

+--------+---------------------------------+---------------------------------+
|        | ignore_index=False              | ignore_index=True               |
+--------+---------------------------------+---------------------------------+
| size   | append | concat | append/concat | append | concat | append/concat |
+--------+--------+--------+---------------+--------+--------+---------------+
| small  | 0.4635 | 0.4891 | 94.77 %       | 0.4056 | 0.3314 | 122.39 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| medium | 0.5532 | 0.6617 | 83.60 %       | 0.3605 | 0.3521 | 102.37 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| large  | 0.9558 | 0.9442 | 101.22 %      | 0.6670 | 0.6749 | 98.84 %       |
+--------+--------+--------+---------------+--------+--------+---------------+

Using ignore_index=False append is slightly faster, with ignore_index=True concat is slightly faster.

tl;dr No significant difference between concat and append.

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

ImportError: No module named psycopg2

I faced the same issue and resolved it with following commands:

sudo apt-get install libpq-dev
pip install psycopg2

How can I correctly format currency using jquery?

I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.

$(".currencyMask").change(function () {
            if (!$.isNumeric($(this).val()))
                $(this).val('0').trigger('change');

            $(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
        });

Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" /> and it will format it perfectly in any browser.

Concatenate multiple files but include filename as section headers

This is how I normally handle formatting like that:

for i in *; do echo "$i"; echo ; cat "$i"; echo ; done ;

I generally pipe the cat into a grep for specific information.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Command to delete all pods in all kubernetes namespaces

I tried commands from listed answers here but pods were stuck in terminating state.
I found below command to delete all pods from particular namespace if stuck in terminating state or you are not able to delete it then you can delete pods forcefully.

kubectl delete pods --all --grace-period=0 --force --namespace namespace

Hope it might be useful to someone.

Spring Security exclude url patterns in security annotation configurartion

Found the solution in Spring security examples posted in Github.

WebSecurityConfigurerAdapter has a overloaded configure message that takes WebSecurity as argument which accepts ant matchers on requests to be ignored.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authFailure");
}

See Spring Security Samples for more details

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

Calendar date to yyyy-MM-dd format in java

public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, date);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);
}

Send message to specific client with socket.io and node.js

Well you have to grab the client for that (surprise), you can either go the simple way:

var io = io.listen(server);
io.clients[sessionID].send()

Which may break, I doubt it, but it's always a possibility that io.clients might get changed, so use the above with caution

Or you keep track of the clients yourself, therefore you add them to your own clients object in the connection listener and remove them in the disconnect listener.

I would use the latter one, since depending on your application you might want to have more state on the clients anyway, so something like clients[id] = {conn: clientConnect, data: {...}} might do the job.

SQL query to select distinct row with minimum value

This is another way of doing the same thing, which would allow you to do interesting things like select the top 5 winning games, etc.

 SELECT *
 FROM
 (
     SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Point) as RowNum, *
     FROM Table
 ) X 
 WHERE RowNum = 1

You can now correctly get the actual row that was identified as the one with the lowest score and you can modify the ordering function to use multiple criteria, such as "Show me the earliest game which had the smallest score", etc.

Make sure that the controller has a parameterless public constructor error

If you are using UnityConfig.cs to resister your type's mappings like below.

public static void RegisterTypes(IUnityContainer container)
    {
     container.RegisterType<IProductRepository, ProductRepository>();
    }

You have to let the know **webApiConfig.cs** about Container

config.DependencyResolver = new Unity.AspNet.WebApi.UnityDependencyResolver(UnityConfig.Container);

How do I trim leading/trailing whitespace in a standard way?

I didn't like most of these answers because they did one or more of the following...

  1. Returned a different pointer inside the original pointer's string (kind of a pain to juggle two different pointers to the same thing).
  2. Made gratuitous use of things like strlen() that pre-iterate the entire string.
  3. Used non-portable OS-specific lib functions.
  4. Backscanned.
  5. Used comparison to ' ' instead of isspace() so that TAB / CR / LF are preserved.
  6. Wasted memory with large static buffers.
  7. Wasted cycles with high-cost functions like sscanf/sprintf.

Here is my version:

void fnStrTrimInPlace(char *szWrite) {

    const char *szWriteOrig = szWrite;
    char       *szLastSpace = szWrite, *szRead = szWrite;
    int        bNotSpace;

    // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST
    while( *szRead != '\0' ) {

        bNotSpace = !isspace((unsigned char)(*szRead));

        if( (szWrite != szWriteOrig) || bNotSpace ) {

            *szWrite = *szRead;
            szWrite++;

            // TRACK POINTER TO LAST NON-SPACE
            if( bNotSpace )
                szLastSpace = szWrite;
        }

        szRead++;
    }

    // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)
    *szLastSpace = '\0';
}

How do I monitor the computer's CPU, memory, and disk usage in Java?

Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime

To get the percentage of CPU used, all you need is some simple maths:

MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();

OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);

long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();

// Call an expensive task, or sleep if you are monitoring a remote process

long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();

long percent;
if (nanoAfter > nanoBefore)
 percent = ((cpuAfter-cpuBefore)*100L)/
   (nanoAfter-nanoBefore);
else percent = 0;

System.out.println("Cpu usage: "+percent+"%");

Note: You must import com.sun.management.OperatingSystemMXBean and not java.lang.management.OperatingSystemMXBean.

ActivityCompat.requestPermissions not showing dialog box

Replace:

ActivityCompat.requestPermissions(this, new String[]{"Manifest.permission.READ_PHONE_STATE"}, 225);

with:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 225);

The actual string for that permission is not "Manifest.permission.READ_PHONE_STATE". Use the symbol Manifest.permission.READ_PHONE_STATE.

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

ES6 Class Multiple inheritance

The solution below (class cloning by copying the instance fields and prototype properties) works for me. I am using normal JS (i.e. not Typescript), with JsDoc annotations and VSCode for compile-time type checking.

The solution interface is very simple:

class DerivedBase extends cloneClass(Derived, Base) {}

//To add another superclass:
//class Der1Der2Base extends cloneClass(Derived2, DerivedBase)

let o = new DerivedBase()  

The classes involved can be created just like normal ES6 classes.

However the following needs to be done:

  • Use isInstanceOf() instead of the builtin operator instanceof.
  • Instead of using 'super' to call non-constructor members of the base class, use the function super2() instead.
  • Don't write any code in the constructors, instead write it in a class method called 'init()' that is in turn called by the constructor. See the example below.
/* Paste the entire following text into the browser's dev console */
/* Tested on latest version of Chrome, Microsoft Edge and FireFox (Win OS)*/
/* Works with JSDoc in VSCode */
/* Not tested on minified/obfuscated code */

//#region library

const log = console.log

/**
 * abbreviation for Object.getPrototypeOf()
 * @param {any} o
 */
function proto(o) { return Object.getPrototypeOf(o) }

/** @param {function} fn */
function callIfNonNull(fn) { if (fn != null) { return fn() } }

/**
 * @param {boolean} b
 * @param {()=>string} [msgFn]
 */
function assert(b, msgFn) {
    if (b) { return }
    throw new Error('assert failed: ' + ((msgFn == null) ? '' : msgFn()))
}

/** @param {any} o */
function asAny(o) { return o }

/**
 * Use this function instead of super.<functionName>
 * @param {any} obj
 * @param {string} attr the name of the function/getter/setter
 * @param {any} cls the class for the current method
 * @param {any[]} args arguments to the function/getter/setter
 */
function super2(obj, attr, cls, ...args) {
    let nms = clsNms(obj)
    assert(nms[0] == nms[1])
    const objCls = proto(obj)
    const superObj = proto(ancestorNamed(objCls, cls.name))
    assert(superObj != obj)
    const attrDscr = getOwnOrBasePropDscr(superObj, attr)
    if (attrDscr == null) { return null }
    let attrVal = attrDscr['value']
    const attrGet = attrDscr['get']
    const attrSet = attrDscr['set']
    if (attrVal == null) {
        if (attrGet != null) {
            if (attrSet != null) {
                assert([0, 1].includes(args.length))
                attrVal = ((args.length == 0) ? attrGet : attrSet)
            } else {
                assert(args.length == 0,
                    () => 'attr=' + attr + ', args=' + args)
                attrVal = attrGet
            }
        } else if (attrSet != null) {
            assert(args.length == 1)
            attrVal = attrSet
        } else {
            assert(false)//no get or set or value!!!!
        }
        assert(typeof attrVal == 'function')
    }
    if (typeof attrVal != 'function') { return attrVal }
    const boundFn = attrVal.bind(obj)
    return boundFn(...args)
}

/**
 * Use this function to call own prop instead of overriden prop
 * @param {any} obj
 * @param {string} attr the name of the function/getter/setter
 * @param {any} cls the class for the current method
 * @param {any[]} args arguments to the function/getter/setter
 */
function ownProp(obj, attr, cls, ...args) {
    let protoObj = ancestorNamed(proto(obj), cls.name)
    const attrDscr = Object.getOwnPropertyDescriptor(protoObj, attr)
    if (attrDscr == null) {
        log(`ownProp(): own property '${attr}' does not exist...`)
        return null
    }
    let attrVal = attrDscr['value']
    const attrGet = attrDscr['get']
    const attrSet = attrDscr['set']
    if (attrVal == null) {
        if (attrGet != null) {
            if (attrSet != null) {
                assert([0, 1].includes(args.length))
                attrVal = ((args.length == 0) ? attrGet : attrSet)
            } else {
                assert(args.length == 0,
                    () => 'attr=' + attr + ', args=' + args)
                attrVal = attrGet
            }
        } else if (attrSet != null) {
            assert(args.length == 1)
            attrVal = attrSet
        } else {
            assert(false)//no get or set or value!!!!
        }
        assert(typeof attrVal == 'function')
    }
    if (typeof attrVal != 'function') {
        log(`ownProp(): own property '${attr}' not a fn...`)
        return attrVal
    }
    const boundFn = attrVal.bind(obj)
    return boundFn(...args)
}

/**
 * @param {any} obj
 * @param {string} nm
 */
function getOwnOrBasePropDscr(obj, nm) {
    let rv = Object.getOwnPropertyDescriptor(obj, nm)
    if (rv != null) { return rv }
    let protObj = proto(obj)
    if (protObj == null) { return null }
    return getOwnOrBasePropDscr(protObj, nm)
}

/**
 * @param {any} obj
 * @param {string} nm
 */
function ancestorNamed(obj, nm) {
    const ancs = ancestors(obj)
    for (const e of ancs) {
        if ((e.name || e.constructor.name) == nm) { return e }
    }
}

/**
 * @template typeOfDerivedCls
 * @template typeOfBaseCls
 * @param {typeOfDerivedCls} derivedCls
 * @param {typeOfBaseCls} baseCls
 * @returns {typeOfDerivedCls & typeOfBaseCls}
 */
function cloneClass(derivedCls, baseCls) {
    const derClsNm = derivedCls['name'], baseClsNm = baseCls['name']
    const gbl = globalThis

    //prevent unwanted cloning and circular inheritance:
    if (isInstanceOf(baseCls, asAny(derivedCls))) { return asAny(baseCls) }
    if (isInstanceOf(derivedCls, asAny(baseCls))) { return asAny(derivedCls) }

    //Object does not derive from anything; it is the other way round:
    if (derClsNm == 'Object') { return cloneClass(baseCls, derivedCls) }

    //use cached cloned classes if available
    if (gbl.clonedClasses == null) { gbl.clonedClasses = {} }
    const k = derClsNm + '_' + baseClsNm, kVal = gbl.clonedClasses[k]
    if (kVal != null) { return kVal }

    //clone the base class of the derived class (cloning occurs only if needed)
    let derBase = cloneClass(proto(derivedCls), baseCls)

    //clone the derived class

    const Clone = class Clone extends derBase {

        /**  @param {any[]} args */
        constructor(...args) {
            super(...args)
            ownProp(this, 'init', Clone, ...args)
        }
    }

    //clone the properties of the derived class
    Object.getOwnPropertyNames(derivedCls['prototype'])
        .filter(prop => prop != 'constructor')
        .forEach(prop => {
            const valToSet =
                Object.getOwnPropertyDescriptor(derivedCls['prototype'], prop)
            if (typeof valToSet == 'undefined') { return }
            Object.defineProperty(Clone.prototype, prop, valToSet)
        })

    //set the name of the cloned class to the same name as its source class:
    Object.defineProperty(Clone, 'name', { value: derClsNm, writable: true })

    //cache the cloned class created
    gbl.clonedClasses[k] = Clone
    log('Created a cloned class with id ' + k + '...')
    return asAny(Clone)
}

/**
 * don't use instanceof throughout your application, use this fn instead
 * @param {any} obj
 * @param {Function} cls
 */
function isInstanceOf(obj, cls) {
    if (obj instanceof cls) { return true }
    return clsNms(obj).includes(cls.name)
}

/** @param {any} obj */
function clsNms(obj) {
    return ancestors(obj).map(/** @param {any} e */ e =>
        e.name || e.constructor.name)
}

/**
 * From: https://gist.github.com/ceving/2fa45caa47858ff7c639147542d71f9f
 * Returns the list of ancestor classes.
 *
 * Example:
 *   ancestors(HTMLElement).map(e => e.name || e.constructor.name)
 *   => ["HTMLElement", "Element", "Node", "EventTarget", "Function", "Object"]
 * @param {any} anyclass
 */
function ancestors(anyclass) {
    if (anyclass == null) { return [] }
    return [anyclass, ...(ancestors(proto(anyclass)))]
}

//#endregion library

//#region testData
class Base extends Object {

    /** @param {any[]} args */
    constructor(...args) {//preferably accept any input
        super(...args)
        ownProp(this, 'init', Base, ...args)
    }

    /** @param {any[]} _args */
    init(..._args) {
        log('Executing init() of class Base...')
        //TODO: add code here to get the args as a named dictionary

        //OR, follow a practice of parameterless constructors and
        //initial-value-getting methods for class field intialization

        /** example data field of the base class */
        this.baseClsFld = 'baseClsFldVal'
    }

    m1() { log('Executed base class method m1') }

    b1() { log('Executed base class method b1') }

    get baseProp() { return 'basePropVal' }
}

class Derived extends Object {//extend Object to allow use of 'super'

    /** @param {any[]} args */
    constructor(...args) {//convention: accept any input
        super(...args)
        ownProp(this, 'init', Derived, ...args)
    }

    /** @param {any[]} _args */
    init(..._args) {
        log('Executing init() of class Derived...')
        this.derClsFld = 'derclsFldVal'
    }

    m1() {
        const log = /** @param {any[]} args */(...args) =>
            console.log('Derived::m1(): ', ...args)
        log(`super['m1']: `, super['m1'])
        super2(this, 'm1', Derived)

        log(`super['baseProp']`, super['baseProp'])

        log(`super2(this, 'baseProp', Derived)`,
            super2(this, 'baseProp', Derived))

        log(`super2(this, 'nonExistentBaseProp', Derived)`,
            super2(this, 'nonExistentBaseProp', Derived))
    }

    m2() {
        log('Executed derived class method 2')
    }
}

class DerivedBase extends cloneClass(Derived, Base) {

    /** @param {any[]} args */
    constructor(...args) {
        super(...args)
        ownProp(this, 'init', DerivedBase, ...args)
    }

    /** @param {any[]} _args */
    init(..._args) {
        log('Executing init() of class DerivedBase...')
    }
}

log('Before defining o (object of DerivedBase)...')
let o = new DerivedBase()
log('After defining o (object of DerivedBase)...')

class Derived2 extends Base {

    /** @param {any} args */
    constructor(...args) {
        //convention/best practice: use passthrough constructors for the classes
        //you write
        super(...args)
        ownProp(this, 'init', Derived2, ...args)
    }

    /**
     * @param {any[]} _args
     */
    init(..._args) {
        log('Executing init() of class Derived2...')
    }

    derived2func() { log('Executed Derived2::derived2func()') }
}

class Der1Der2Base extends cloneClass(Derived2, DerivedBase) {

    /** @param {any} args */
    constructor(...args) {
        //convention/best practice: use passthrough constructors for the classes
        //you write
        super(...args)
        ownProp(this, 'init', Der1Der2Base, ...args)
    }

    /** @param {any[]} _args */
    init(..._args) {
        log('Executing original ctor of class Der1Der2Base...')
    }

}

log('Before defining o2...')
const o2 = new Der1Der2Base()
log('After defining o2...')

class NotInInheritanceChain { }
//#endregion testData

log('Testing fields...')
log('o.derClsFld:', o.derClsFld)
log('o.baseClsFld:', o.baseClsFld)
//o.f3  JSDoc gives error in VSCode

log('Test method calls')
o.b1()
o.m1()
o.m2()
//o.m3() //JSDoc gives error in VSCode
log('Test object o2')
o2.b1()
o2.m1()
o2.derived2func()

//don't use instanceof throughout your application, use this fn instead
log('isInstanceOf(o,DerivedBase)', isInstanceOf(o, DerivedBase))
log('isInstanceOf(o,Derived)', isInstanceOf(o, Derived))
log('isInstanceOf(o,Base)', isInstanceOf(o, Base))

log('isInstanceOf(o,NotInInheritanceChain)',
    isInstanceOf(o, NotInInheritanceChain))

A note of caution: the JSDoc intersection operator & may not always work. In that case some other solution may need to be used. For example, a separate interface class may need to be defined that will 'manually' combine the 2 classes. This interface class can extend from one of the classes and the other class's interface can be automatically implemented using VsCode quick fix option.

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

Xcode 4 - build output directory

From the Xcode menu on top, click preferences, select the locations tab, look at the build location option.

You have 2 options:

  1. Place build products in derived data location (recommended)
  2. Place build products in locations specified by targets

Update: On xcode 4.6.2 you need to click the advanced button on the right side below the derived data text field. Build Location select legacy.

Finding sum of elements in Swift array

Swift 3.0

i had the same problem, i found on the documentation Apple this solution.

let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10

But, in my case i had a list of object, then i needed transform my value of my list:

let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })

this work for me.

How to remove the Flutter debug banner?

There is also another way for removing the "debug" banner from the flutter app. Now after new release there is no "debugShowCheckedModeBanner: false," code line in main .dart file. So I think these methods are effective:

  1. If you are using VS Code, then install "Dart DevTools" from extensions. After installation, you can easily find "Dart DevTools" text icon at the bottom of the VS Code. When you click on that text icon, a link will be open in google chrome. From that link page, you can easily remove the banner by just tapping on the banner icon as shown in this screenshot.

NOTE:-- Dart DevTools is a dart language debugger extension in VS Code

  1. If Dart DevTools is already installed in your VS Code, then you can directly open the google chrome and open this URL = "127.0.0.1: ZZZZZ/?hide=debugger&port=XXXXX"

NOTE:-- In this link replace "XXXXX" by 5 digit port-id (on which your flutter app is running) which will vary whenever you use "flutter run" command and replace "ZZZZZ" by your global(unchangeable) 5 digit debugger-id

NOTE:-- these dart dev tools are only for "Google Chrome Browser"

Typescript import/as vs import/require?

These are mostly equivalent, but import * has some restrictions that import ... = require doesn't.

import * as creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or newable - it only has properties. If you're trying to import a function or class, you should use

import express = require('express');

or (depending on your module loader)

import express from 'express';

Attempting to use import * as express and then invoking express() is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.

How to change the order of DataFrame columns?

Most of the answers did not generalize enough and pandas reindex_axis method is a little tedious, hence I offer a simple function to move an arbitrary number of columns to any position using a dictionary where key = column name and value = position to move to. If your dataframe is large pass True to 'big_data' then the function will return the ordered columns list. And you could use this list to slice your data.

def order_column(df, columns, big_data = False):

    """Re-Orders dataFrame column(s)
       Parameters : 
       df      -- dataframe
       columns -- a dictionary:
                  key   = current column position/index or column name
                  value = position to move it to  
       big_data -- boolean 
                  True = returns only the ordered columns as a list
                          the user user can then slice the data using this
                          ordered column
                  False = default - return a copy of the dataframe
    """
    ordered_col = df.columns.tolist()

    for key, value in columns.items():

        ordered_col.remove(key)
        ordered_col.insert(value, key)

    if big_data:

        return ordered_col

    return df[ordered_col]

# e.g.
df = pd.DataFrame({'chicken wings': np.random.rand(10, 1).flatten(), 'taco': np.random.rand(10,1).flatten(),
                          'coffee': np.random.rand(10, 1).flatten()})
df['mean'] = df.mean(1)

df = order_column(df, {'mean': 0, 'coffee':1 })

>>>

output

col = order_column(df, {'mean': 0, 'coffee':1 }, True)

col
>>>
['mean', 'coffee', 'chicken wings', 'taco']

# you could grab it by doing this

df = df[col]

Matching a Forward Slash with a regex

I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.

The regular expression

/\\(.*)\//g

does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)

/\b/\\(.*)\/\b/g

does not work either. I think the second / terminates the regular expression in spite of the escape character.

What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.