Programs & Examples On #Drupal feeds

This tag is for questions about the Feeds module.

Necessary to add link tag for favicon.ico?

The bottom line is not all browsers will actually look for your favicon.ico file. Some browsers allow users to choose whether or not it should automatically look. Therefore, in order to ensure that it will always appear and get looked at, you do have to define it.

Updates were rejected because the tip of your current branch is behind its remote counterpart

To make sure your local branch FixForBug is not ahead of the remote branch FixForBug pull and merge the changes before pushing.

git pull origin FixForBug
git push origin FixForBug

NullPointerException in Java with no StackTrace

Here is an explanation : Hotspot caused exceptions to lose their stack traces in production – and the fix

I've tested it on Mac OS X

  • java version "1.6.0_26"
  • Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
  • Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)

    Object string = "abcd";
    int i = 0;
    while (i < 12289) {
        i++;
        try {
            Integer a = (Integer) string;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

For this specific fragment of code, 12288 iterations (+frequency?) seems to be the limit where JVM has decided to use preallocated exception...

How to remove trailing whitespaces with sed?

For those who look for efficiency (many files to process, or huge files), using the + repetition operator instead of * makes the command more than twice faster.

With GNU sed:

sed -Ei 's/[ \t]+$//' "$1"
sed -i 's/[ \t]\+$//' "$1"   # The same without extended regex

I also quickly benchmarked something else: using [ \t] instead of [[:space:]] also significantly speeds up the process (GNU sed v4.4):

sed -Ei 's/[ \t]+$//' "$1"

real    0m0,335s
user    0m0,133s
sys 0m0,193s

sed -Ei 's/[[:space:]]+$//' "$1"

real    0m0,838s
user    0m0,630s
sys 0m0,207s

sed -Ei 's/[ \t]*$//' "$1"

real    0m0,882s
user    0m0,657s
sys 0m0,227s

sed -Ei 's/[[:space:]]*$//' "$1"

real    0m1,711s
user    0m1,423s
sys 0m0,283s

Send Mail to multiple Recipients in java

Try this way:

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
String address = "[email protected],[email protected]";
InternetAddress[] iAdressArray = InternetAddress.parse(address);
message.setRecipients(Message.RecipientType.CC, iAdressArray);

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

Use SQL Server's date styles to pre-format your date values.

SELECT
    CONVERT(varchar(2), GETDATE(), 101) AS monthLeadingZero  -- Date Style 101 = mm/dd/yyyy
    ,CONVERT(varchar(2), GETDATE(), 103) AS dayLeadingZero   -- Date Style 103 = dd/mm/yyyy

Sorting using Comparator- Descending order (User defined classes)

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

How to create a file in Ruby

The directory doesn't exist. Make sure it exists as open won't create those dirs for you.

I ran into this myself a while back.

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

onclick or inline script isn't working in extension

As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.

HTML file

<!doctype html>
    <html>
        <head>
            <title>
                Getting Started Extension's Popup
            </title>
            <script src="popup.js"></script>
        </head>
        <body>
            <div id="text-holder">ha</div><br />
            <a class="clickableBtn">
                  hyhy
            </a>
        </body>
    </html>
<!doctype html>

popup.js

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        var clickedEle = document.activeElement.id ;
        var ele = document.getElementById(clickedEle);
        alert(ele.text);
    }
}

Or if you are having a Jquery file included then

window.onclick = function(event) {
    var target = event.target ;
    if(target.matches('.clickableBtn')) {
        alert($(target).text());
    }
}

How to find the path of Flutter SDK

How to create FLUTTER project in android studio in fedora:-

I have installed following:- 1 Android studio 2 Then do following:-

Start Android Studio. Open plugin preferences (Preferences > Plugins on macOS, File > Settings > Plugins on Windows & Linux). Select Marketplace, select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Restart when prompted.

4:- Now create project by clicking new flutter project and do following:- * Choose Flutter Application from the list of configurations * Fill the name and other things * For flutter sdk click and install flutter sdk and specify the location of downloading and after downloading completion, choose that sdk path, this will load your FLutter sdk.

Rest do steps as per your need to create project

Inverse dictionary lookup in Python

Your list comprehension goes through all the dict's items finding all the matches, then just returns the first key. This generator expression will only iterate as far as necessary to return the first value:

key = next(key for key, value in dd.items() if value == 'value')

where dd is the dict. Will raise StopIteration if no match is found, so you might want to catch that and return a more appropriate exception like ValueError or KeyError.

AngularJS custom filter function

You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

Like you found, filter accepts predicate function which accepts item by item from the array. So, you just have to create an predicate function based on the given criteria.

In this example, criteriaMatch is a function which returns a predicate function which matches the given criteria.

template:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

scope:

$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return item.name === criteria.name;
  };
};

URL.Action() including route values

outgoing url in mvc generated based on the current routing schema.

because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.

to solve this problem you should use UrlParameter.Optional:

 <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>

String comparison technique used by Python

Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).

To reply to the comment

What? How else can ordering be defined other than left-to-right?

by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

Remove plot axis values

you can also put labels inside plot:

plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)

you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.

Define static method in source-file with declaration in header-file in C++

You don't need to have static in function definition

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

For what is worth if anyone should read again this topic(like me) the correct answer would be in DateTimeFormatter definition, e.g.:

private static DateTimeFormatter DATE_FORMAT =  
            new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy[ [HH][:mm][:ss][.SSS]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .toFormatter(); 

One should set the optional fields if they will appear. And the rest of code should be exactly the same.

How to use QueryPerformanceCounter?

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"\n";
    return 0;
}

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

to

PCFreq = double(li.QuadPart);

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

But really it's about convenience since it returns a double.

How to check if IEnumerable is null or empty?

I built this off of the answer by @Matt Greer

He answered the OP's question perfectly.

I wanted something like this while maintaining the original capabilities of Any while also checking for null. I'm posting this in case anyone else needs something similar.

Specifically I wanted to still be able to pass in a predicate.

public static class Utilities
{
    /// <summary>
    /// Determines whether a sequence has a value and contains any elements.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable"/> to check for emptiness.</param>
    /// <returns>true if the source sequence is not null and contains any elements; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source)
    {
        return source?.Any() == true;
    }

    /// <summary>
    /// Determines whether a sequence has a value and any element of a sequence satisfies a condition.
    /// </summary>
    /// <typeparam name="TSource">The type of the elements of source.</typeparam>
    /// <param name="source">An <see cref="System.Collections.Generic.IEnumerable"/> whose elements to apply the predicate to.</param>
    /// <param name="predicate">A function to test each element for a condition.</param>
    /// <returns>true if the source sequence is not null and any elements in the source sequence pass the test in the specified predicate; otherwise, false.</returns>
    public static bool AnyNotNull<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    {
        return source?.Any(predicate) == true;
    }
}

The naming of the extension method could probably be better.

Get current URL path in PHP

You want $_SERVER['REQUEST_URI']. From the docs:

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

How to overlay images

All we want is parent above child. This is how you do it.

You put img into span, set z-index & position for both elements, and extra display for span. Add hover to span so you can test it and you got it!

HTML:

<span><img src="/images/"></span>

CSS

span img {
    position:relative;
    z-index:-1;
}
span {
    position:relative;
    z-index:initial;
    display:inline-block;
}
span:hover {
    background-color:#000;
}

Java: recommended solution for deep cloning/copying an instance

Since version 2.07 Kryo supports shallow/deep cloning:

Kryo kryo = new Kryo();
SomeClass someObject = ...
SomeClass copy1 = kryo.copy(someObject);
SomeClass copy2 = kryo.copyShallow(someObject);

Kryo is fast, at the and of their page you may find a list of companies which use it in production.

How do I pass multiple parameters into a function in PowerShell?

If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;

Code:

function FunctionName()
{
    Write-Host $args
}

That would print out all arguments. For example:

FunctionName a b c 1 2 3

Output

a b c 1 2 3

I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.

Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);

Code:

Function traceroute
{
    Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}

Proper way to restrict text input values (e.g. only numbers)

A few of the answers did not work for me so I took the best bits from some of the answers (thanks guys) and created an Angular 5 Directive that should do the job (and more) for you. It maybe not perfect but it offers flexibility.

import { Directive, HostListener, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
selector: '[appInputMask]'
})
export class InputMaskDirective {
@Input('appInputMask') inputType: string;

showMsg = false;
pattern: RegExp;

private regexMap = { // add your own
integer: /^[0-9 ]*$/g,
float: /^[+-]?([0-9]*[.])?[0-9]+$/g,
words: /([A-z]*\\s)*/g,
point25: /^\-?[0-9]*(?:\\.25|\\.50|\\.75|)$/g,
badBoys: /^[^{}*+£$%\\^-_]+$/g
};

constructor(public el: ElementRef, public renderer: Renderer2) { };

@HostListener('keypress', ['$event']) onInput(e) {
this.pattern = this.regexMap[this.inputType]
const inputChar = e.key;
this.pattern.lastIndex = 0; // dont know why but had to add this

if (this.pattern.test(inputChar)) {
   // success
  this.renderer.setStyle(this.el.nativeElement, 'color', 'green'); 
  this.badBoyAlert('black');
} else {

  this.badBoyAlert('black');
   //do something her to indicate invalid character
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  e.preventDefault();

}

  }
  badBoyAlert(color: string) {
    setTimeout(() => {
      this.showMsg = true;
      this.renderer.setStyle(this.el.nativeElement, 'color', color);
    }, 2000)
  }

  }

HTML <input class="form-control" appInputMask="badBoys">

How to pass event as argument to an inline event handler in JavaScript?

to pass the event object:

<p id="p" onclick="doSomething(event)">

to get the clicked child element (should be used with event parameter:

function doSomething(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    console.log(target);
}

to pass the element itself (DOMElement):

<p id="p" onclick="doThing(this)">

see live example on jsFiddle.

You can specify the name of the event as above, but alternatively your handler can access the event parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.

Creating a zero-filled pandas data frame

If you already have a dataframe, this is the fastest way:

In [1]: columns = ["col{}".format(i) for i in range(10)]
In [2]: orig_df = pd.DataFrame(np.ones((10, 10)), columns=columns)
In [3]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
10000 loops, best of 3: 60.2 µs per loop

Compare to:

In [4]: %timeit d = pd.DataFrame(0, index = np.arange(10), columns=columns)
10000 loops, best of 3: 110 µs per loop

In [5]: temp = np.zeros((10, 10))
In [6]: %timeit d = pd.DataFrame(temp, columns=columns)
10000 loops, best of 3: 95.7 µs per loop

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

Prevent div from moving while resizing the page

1 - remove the margin from your BODY CSS.

2 - wrap all of your html in a wrapper <div id="wrapper"> ... all your body content </div>

3 - Define the CSS for the wrapper:

This will hold everything together, centered on the page.

#wrapper {
    margin-left:auto;
    margin-right:auto;
    width:960px;
}

How to read/write arbitrary bits in C/C++

"How do I for example read a 3 bit integer value starting at the second bit?"

int number = // whatever;
uint8_t val; // uint8_t is the smallest data type capable of holding 3 bits
val = (number & (1 << 2 | 1 << 3 | 1 << 4)) >> 2;

(I assumed that "second bit" is bit #2, i. e. the third bit really.)

Query to get all rows from previous month

Alternatively to hobodave's answer

SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

You could achieve the same with EXTRACT, using YEAR_MONTH as unit, thus you wouldn't need the AND, like so:

SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM date_created) = EXTRACT(YEAR_MONTH FROM CURDATE() - INTERVAL
1 MONTH)

How to capitalize the first letter of text in a TextView in an Android Application

for Kotlin, just call

textview.text = string.capitalize()

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.

As the before-mentioned attachments can and very often are of text/plain or text/html part, this non-bullet-proof sample skips those by checking the content-disposition header:

b = email.message_from_string(a)
body = ""

if b.is_multipart():
    for part in b.walk():
        ctype = part.get_content_type()
        cdispo = str(part.get('Content-Disposition'))

        # skip any text/plain (txt) attachments
        if ctype == 'text/plain' and 'attachment' not in cdispo:
            body = part.get_payload(decode=True)  # decode
            break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
    body = b.get_payload(decode=True)

BTW, walk() iterates marvelously on mime parts, and get_payload(decode=True) does the dirty work on decoding base64 etc. for you.

Some background - as I implied, the wonderful world of MIME emails presents a lot of pitfalls of "wrongly" finding the message body. In the simplest case it's in the sole "text/plain" part and get_payload() is very tempting, but we don't live in a simple world - it's often surrounded in multipart/alternative, related, mixed etc. content. Wikipedia describes it tightly - MIME, but considering all these cases below are valid - and common - one has to consider safety nets all around:

Very common - pretty much what you get in normal editor (Gmail,Outlook) sending formatted text with an attachment:

multipart/mixed
 |
 +- multipart/related
 |   |
 |   +- multipart/alternative
 |   |   |
 |   |   +- text/plain
 |   |   +- text/html
 |   |      
 |   +- image/png
 |
 +-- application/msexcel

Relatively simple - just alternative representation:

multipart/alternative
 |
 +- text/plain
 +- text/html

For good or bad, this structure is also valid:

multipart/alternative
 |
 +- text/plain
 +- multipart/related
      |
      +- text/html
      +- image/jpeg

Hope this helps a bit.

P.S. My point is don't approach email lightly - it bites when you least expect it :)

Align div with fixed position on the right side

make a parent div, in css make it float:right then make the child div's position fixed this will make the div stay in its position at all times and on the right

Copy all the lines to clipboard

:%y a Yanks all the content into vim's buffer, Pressing p in command mode will paste the yanked content after the line that your cursor is currently standing at.

Add object to ArrayList at specified index

This is a possible solution:

list.add(list.size(), new Object());

Local Storage vs Cookies

In the context of JWTs, Stormpath have written a fairly helpful article outlining possible ways to store them, and the (dis-)advantages pertaining to each method.

It also has a short overview of XSS and CSRF attacks, and how you can combat them.

I've attached some short snippets of the article below, in case their article is taken offline/their site goes down.

Local Storage

Problems:

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS in a nutshell is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts alert('You are Hacked'); into a form to see if it is run by the browser and can be viewed by other users.

Prevention:

To prevent XSS, the common response is to escape and encode all untrusted data. But this is far from the full story. In 2015, modern web apps use JavaScript hosted on CDNs or outside infrastructure. Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.

What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

As a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.

Cookies

Problems:

Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS. This is one of the main reasons that cookies have been leveraged in the past to store tokens or session data. Modern developers are hesitant to use cookies because they traditionally required state to be stored on the server, thus breaking RESTful best practices. Cookies as a storage mechanism do not require state to be stored on the server if you are storing a JWT in the cookie. This is because the JWT encapsulates everything the server needs to serve the request.

However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF). A CSRF attack is a type of attack that occurs when a malicious web site, email, or blog causes a user’s web browser to perform an unwanted action on a trusted site on which the user is currently authenticated. This is an exploit of how the browser handles cookies. A cookie can only be sent to the domains in which it is allowed. By default, this is the domain that originally set the cookie. The cookie will be sent for a request regardless of whether you are on galaxies.com or hahagonnahackyou.com.

Prevention:

Modern browsers support the SameSite flag, in addition to HttpOnly and Secure. The purpose of this flag is to prevent the cookie from being transmitted in cross-site requests, preventing many kinds of CSRF attack.

For browsers that do not support SameSite, CSRF can be prevented by using synchronized token patterns. This sounds complicated, but all modern web frameworks have support for this.

For example, AngularJS has a solution to validate that the cookie is accessible by only your domain. Straight from AngularJS docs:

When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain. You can make this CSRF protection stateless by including a xsrfToken JWT claim:

{
  "iss": "http://galaxies.com",
  "exp": 1300819380,
  "scopes": ["explorer", "solar-harvester", "seller"],
  "sub": "[email protected]",
  "xsrfToken": "d9b9714c-7ac0-42e0-8696-2dae95dbc33e"
}

Leveraging your web app framework’s CSRF protection makes cookies rock solid for storing a JWT. CSRF can also be partially prevented by checking the HTTP Referer and Origin header from your API. CSRF attacks will have Referer and Origin headers that are unrelated to your application.

The full article can be found here: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/

They also have a helpful article on how to best design and implement JWTs, with regards to the structure of the token itself: https://stormpath.com/blog/jwt-the-right-way/

JQuery/Javascript: check if var exists

It is impossible to determine whether a variable has been declared or not other than using try..catch to cause an error if it hasn't been declared. Test like:

if (typeof varName == 'undefined') 

do not tell you if varName is a variable in scope, only that testing with typeof returned undefined. e.g.

var foo;
typeof foo == 'undefined'; // true
typeof bar == 'undefined'; // true

In the above, you can't tell that foo was declared but bar wasn't. You can test for global variables using in:

var global = this;
...
'bar' in global;  // false

But the global object is the only variable object* you can access, you can't access the variable object of any other execution context.

The solution is to always declare variables in an appropriate context.

  • The global object isn't really a variable object, it just has properties that match global variables and provide access to them so it just appears to be one.

CSS: fixed position on x-axis but not y?

I realize this thread is mighty old but it helped me come up with a solution for my project.

In my case I had a header that I wanted to never be less than 1000px wide, header always on top, with content that could go unlimited right.

header{position:fixed; min-width:1024px;}
<header data-min-width="1024"></header>

    $(window).on('scroll resize', function () {
        var header = $('header');
        if ($(this).width() < header.data('min-width')) {
            header.css('left', -$(this).scrollLeft());
        } else {
            header.css('left', '');
        }
    });

This also should handle when your browser is less than your headers min-width

Best way to log POST data in Apache?

You can install mod_security and put in /etc/modsecurity/modsecurity.conf:

SecRuleEngine On
SecAuditEngine On
SecAuditLog /var/log/apache2/modsec_audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIJDFHZ

Why do I get "MismatchSenderId" from GCM server side?

Check google-services.json file in app folder of your Android project. Generate a new one from Firebase console if you are unsure. I got this error in two cases.

  1. I used a test Firebase project with test application (that contained right google-services.json file). Then I tried to send push notification to another application and got this error ('"error": "MismatchSenderId"'). I understood that the second application was bound to another Firebase project with different google-services.json. Because server keys are different, the request should be rewritten.

  2. I changed google-services.json in the application, because I wanted to replace test Firebase project with an actual. I generated right google-services.json file, changed request, but kept receiving this error. On the next day it fixed itself. I suspect Firebase doesn't update synchronously.

To get a server key for the request, open https://console.firebase.google.com and select an appropriate project.

enter image description here

Then paste it in the request.

enter image description here

How to get JSON objects value if its name contains dots?

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]

this should do the trick

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Set up git to pull and push all branches

If you are pushing from one remote origin to another, you can use this:

git push newremote refs/remotes/oldremote/*:refs/heads/*

This worked for me. Reffer to this: https://www.metaltoad.com/blog/git-push-all-branches-new-remote

PHP: maximum execution time when importing .SQL data file

The following might help you:

ini_set('max_execution_time', 100000);

And in your mysql - max_allowed_packet=100M in some cases where queries are too long sql also produce and error "MySQL server has gone away";

Change the values to whatever you need.

Remove the last three characters from a string

Probably not exactly what you're looking for since you say it's "dynamic data" but given your example string, this also works:

? "abcdxxx".TrimEnd('x');
"abc"

Create a Bitmap/Drawable from file path

you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.

declare a HashMap somewhere in your class:

private static HashMap<String, Integer> images = null;

//Then initialize it in your constructor:

public myClass() {
  if (images == null) {
    images = new HashMap<String, Integer>();
    images.put("Human1Arm", R.drawable.human_one_arm);
    // for all your images - don't worry, this is really fast and will only happen once
  }
}

Now for access -

String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

For the people finding this post in 2019, this error could also occur because the Python version 3.7 does not have support for TensorFlow (see https://www.tensorflow.org/install/pip). So, check the Python version:

python --version

In case it is larger than 3.6, it should be downgraded to 3.6. For Anaconda:

conda install python=3.6

Then, install TensorFlow.

pip install tensorflow

Btw, I did not have the GPU version, so there were no CUDA related issues in my case.

How to get a microtime in Node.js?

process.hrtime() not give current ts.

This should work.

 const loadNs       = process.hrtime(),
        loadMs       = new Date().getTime(),
        diffNs       = process.hrtime(loadNs),
        microSeconds = (loadMs * 1e6) + (diffNs[0] * 1e9) + diffNs[1]

  console.log(microSeconds / 1e3)

How to get tf.exe (TFS command line client)?

In Visual Studio 2017 & 2019, it can be found here :

-Replace {YEAR} by the appropriate year ("2017", "2019").

-Replace {EDITION} by the appropriate edition name ("Enterprise", "Professional", or "Community")

C:\Program Files (x86)\Microsoft Visual Studio\{YEAR}\{EDITION}\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\tf.exe

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

It may have been because I am still new to VS and definitely new to C, but the only thing that allowed me to build was adding

#pragma warning(disable:4996)

At the top of my file, this suppressed the C4996 error I was getting with sprintf

A bit annoying but perfect for my tiny bit of code and by far the easiest.

I read about it here: https://msdn.microsoft.com/en-us/library/2c8f766e.aspx

How can I get a channel ID from YouTube?

At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

How to handle calendar TimeZones using Java?

It looks like your TimeStamp is being set to the timezone of the originating system.

This is deprecated, but it should work:

cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());

The non-deprecated way is to use

Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)

but that would need to be done on the client side, since that system knows what timezone it is in.

How to "comment-out" (add comment) in a batch/cmd?

You can use :: or rem for comments.

When commenting, use :: as it's 3 times faster. An example is shown here

Only if comments are in if, use rem, as the colons could make errors, because they are a label.

SyntaxError: missing ) after argument list

SyntaxError: missing ) after argument list.

the issue also may occur if you pass string directly without a single or double quote.

$('#contentData').append("<div class='media'><div class='media-body'><a class='btn' href='" + type + "'  onclick=\"(canLaunch(' + v.LibraryItemName +  '))\">View &raquo;</a></div></div>").

so always keep the habit to pass in a quote like

 onclick=\"(canLaunch(\'' + v.LibraryItemName  + '\'))"\

Passing arguments forward to another javascript function

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

_x000D_
_x000D_
function a(...args){_x000D_
  b(...args);_x000D_
  b(6, ...args, 8) // You can even add more elements_x000D_
}_x000D_
function b(){_x000D_
  console.log(arguments)_x000D_
}_x000D_
_x000D_
a(1, 2, 3)
_x000D_
_x000D_
_x000D_

Note This snippet returns a syntax error if your browser still uses ES5.

Editor's note: Since the snippet uses console.log(), you must open your browser's JS console to see the result - there will be no in-page result.

It will display this result:

Image of Spread operator arguments example

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

How to initialize a vector in C++

With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:

std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };

Or even:

std::vector<int> v(2);
v = { 34,23 };

On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:

int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);

Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:

template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }

And then you can do this without having to repeat the size all over:

int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));

Find Oracle JDBC driver in Maven repository

For whatever reason, I could not get any of the above solutions to work. (Still can't.)

What I did instead was to include the jar in my project (blech) and then create a "system" dependency for it that indicates the path to the jar. It's probably not the RIGHT way to do it, but it does work. And it eliminates the need for the other developers on the team (or the guy setting up the build server) to put the jar in their local repositories.

UPDATE: This solution works for me when I run Hibernate Tools. It does NOT appear to work for building the WAR file, however. It doesn't include the ojdbc6.jar file in the target WAR file.

1) Create a directory called "lib" in the root of your project.

2) Copy the ojdbc6.jar file there (whatever the jar is called.)

3) Create a dependency that looks something like this:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc</artifactId>
    <version>14</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/ojdbc6.jar</systemPath> <!-- must match file name -->
</dependency>

Ugly, but works for me.

To include the files in the war file add the following to your pom

<build>
    <finalName>MyAppName</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${basedir}/src/main/java</directory>
                        <targetPath>WEB-INF/classes</targetPath>
                        <includes>
                            <include>**/*.properties</include>
                            <include>**/*.xml</include>
                            <include>**/*.css</include>
                            <include>**/*.html</include>
                        </includes>
                    </resource>
                    <resource>
                        <directory>${basedir}/lib</directory>
                        <targetPath>WEB-INF/lib</targetPath>
                        <includes>
                            <include>**/*.jar</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>

        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Match all elements having class name starting with a specific string

The following should do the trick:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

Edit: Added wildcard (*) as suggested by David

Centering controls within a form in .NET (Winforms)?

myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

Break out of a While...Wend loop

A While/Wend loop can only be exited prematurely with a GOTO or by exiting from an outer block (Exit sub/function or another exitable loop)

Change to a Do loop instead:

Do While True
    count = count + 1

    If count = 10 Then
        Exit Do
    End If
Loop

Or for looping a set number of times:

for count = 1 to 10
   msgbox count
next

(Exit For can be used above to exit prematurely)

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

Auto Generate Database Diagram MySQL

On a Mac, SQLEditor will do what you want.

Pretty-print a Map in Java

Arrays.toString(map.entrySet().toArray())

Identify if a string is a number

All the Answers are Useful. But while searching for a solution where the Numeric value is 12 digits or more (in my case), then while debugging, I found the following solution useful :

double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);

Th result variable will give you true or false.

How to get the directory of the currently running file?

Use package osext

It's providing function ExecutableFolder() that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
    "log"
)

func main() {
    folderPath, err := osext.ExecutableFolder()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(folderPath)
}

Property 'value' does not exist on type EventTarget in TypeScript

The way I do it is the following (better than type assertion imho):

onFieldUpdate(event: { target: HTMLInputElement }) {
  this.$emit('onFieldUpdate', event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

This is a Vue.js version but the concept applies to all frameworks. Obviously you can go more specific and instead of using a general HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

Convert iterator to pointer?

If you can, a better choice may be to change the function to take either an iterator to an element or a brand new vector (if it does not modify).

While you can do this sort of things with arrays since you know how they are stored, it's probably a bad idea to do the same with vectors. &foo[1] does not have the type vector<int>*.

Also, while the STL implementation is available online, it's usually risky to try and rely on the internal structure of an abstraction.

How to get All input of POST in Laravel

It should be at least this:

public function login(Request $loginCredentials){
     $data = $loginCredentials->all();
     return $data['username'];
}

How to delete files older than X hours

-mmin is for minutes.

Try looking at the man page.

man find

for more types.

React Native Responsive Font Size

import { Dimensions } from 'react-native';

const { width, fontScale } = Dimensions.get("window");

const styles = StyleSheet.create({
    fontSize: idleFontSize / fontScale,
});

fontScale get scale as per your device.

How do I get data from a table?

in this code data is a two dimensional array of table data

let oTable = document.getElementById('datatable-id');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))

Example on ToggleButton

You should follow the Google guide;

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // The toggle is enabled
        } else {
            // The toggle is disabled
        }
    }
});

You can check the documentation here

Get size of a View in React Native

Here is the code to get the Dimensions of the complete view of the device.

var windowSize = Dimensions.get("window");

Use it like this:

width=windowSize.width,heigth=windowSize.width/0.565

How do I format a date in Jinja2?

There is a jinja2 extension you can use just need pip install (https://github.com/hackebrot/jinja2-time)

How do I create an Android Spinner as a popup?

In xml there is option

android:spinnerMode="dialog"

use this for Dialog mode

Is there a way to programmatically minimize a window

in c#.net

this.WindowState = FormWindowState.Minimized

Java: Calculating the angle between two points in degrees

you could add the following:

public float getAngle(Point target) {
    float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));

    if(angle < 0){
        angle += 360;
    }

    return angle;
}

by the way, why do you want to not use a double here?

Python Git Module experiences?

The git interaction library part of StGit is actually pretty good. However, it isn't broken out as a separate package but if there is sufficient interest, I'm sure that can be fixed.

It has very nice abstractions for representing commits, trees etc, and for creating new commits and trees.

Swift apply .uppercaseString to only the first letter of a string

Capitalize the first character in the string

extension String {
    var capitalizeFirst: String {
        if self.characters.count == 0 {
            return self

        return String(self[self.startIndex]).capitalized + String(self.characters.dropFirst())
    }
}

What does enctype='multipart/form-data' mean?

When you make a POST request, you have to encode the data that forms the body of the request in some way.

HTML forms provide three methods of encoding.

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data
  • text/plain

Work was being done on adding application/json, but that has been abandoned.

(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)

The specifics of the formats don't matter to most developers. The important points are:

  • Never use text/plain.

When you are writing client-side code:

  • use multipart/form-data when your form includes any <input type="file"> elements
  • otherwise you can use multipart/form-data or application/x-www-form-urlencoded but application/x-www-form-urlencoded will be more efficient

When you are writing server-side code:

  • Use a prewritten form handling library

Most (such as Perl's CGI->param or the one exposed by PHP's $_POST superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.

Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).


If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.

application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.

multipart/form-data is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.

text/plain is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).

What are the benefits to marking a field as `readonly` in C#?

The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.

Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).

Why doesn't height: 100% work to expand divs to the screen height?

Alternatively, if you use position: absolute then height: 100% will work just fine.

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

Android Material Design Button Styles

I tried a lot of answer & third party libs, but none was keeping the border and raised effect on pre-lollipop while having the ripple effect on lollipop without drawback. Here is my final solution combining several answers (border/raised are not well rendered on gifs due to grayscale color depth) :

Lollipop

enter image description here

Pre-lollipop

enter image description here

build.gradle

compile 'com.android.support:cardview-v7:23.1.1'

layout.xml

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    card_view:cardElevation="2dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardMaxElevation="8dp"
    android:layout_margin="6dp"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="0dp"
        android:background="@drawable/btn_bg"
        android:text="My button"/>
</android.support.v7.widget.CardView>

drawable-v21/btn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
    <item android:drawable="?attr/colorPrimary"/>
</ripple>

drawable/btn_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/colorPrimaryDark" android:state_pressed="true"/>
    <item android:drawable="@color/colorPrimaryDark" android:state_focused="true"/>
    <item android:drawable="@color/colorPrimary"/>
</selector>

Activity's onCreate

    final CardView cardView = (CardView) findViewById(R.id.card);
    final Button button = (Button) findViewById(R.id.button);
    button.setOnTouchListener(new View.OnTouchListener() {
        ObjectAnimator o1 = ObjectAnimator.ofFloat(cardView, "cardElevation", 2, 8)
                .setDuration
                        (80);
        ObjectAnimator o2 = ObjectAnimator.ofFloat(cardView, "cardElevation", 8, 2)
                .setDuration
                        (80);

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    o1.start();
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    o2.start();
                    break;
            }
            return false;
        }
    });

Does "git fetch --tags" include "git fetch"?

Note: this answer is only valid for git v1.8 and older.

Most of this has been said in the other answers and comments, but here's a concise explanation:

  • git fetch fetches all branch heads (or all specified by the remote.fetch config option), all commits necessary for them, and all tags which are reachable from these branches. In most cases, all tags are reachable in this way.
  • git fetch --tags fetches all tags, all commits necessary for them. It will not update branch heads, even if they are reachable from the tags which were fetched.

Summary: If you really want to be totally up to date, using only fetch, you must do both.

It's also not "twice as slow" unless you mean in terms of typing on the command-line, in which case aliases solve your problem. There is essentially no overhead in making the two requests, since they are asking for different information.

How to terminate script execution when debugging in Google Chrome?

If you have a rogue loop, pause the code in Google Chrome debugger (the small "||" button while in Sources tab).

Switch back to Chrome itself, open "Task Manager" (Shift+ESC), select your tab, click the "End Process" button.

You will get the Aww Snap message and then you can reload (F5).

As others have noted, reloading the page at the point of pausing is the same as restarting the rogue loop and can cause nasty lockups if the debugger also then locks (in some cases leading to restarting chrome or even the PC). The debugger needs a "Stop" button. Nb: The accepted answer is out of date in that some aspects of it are now apparently wrong. If you vote me down, pls explain :).

remove all variables except functions

Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.

list.objects <- function(env = .GlobalEnv) 
{
    if(!is.environment(env)){
        env <- deparse(substitute(env))
        stop(sprintf('"%s" must be an environment', env))
    }
    obj.type <- function(x) class(get(x, envir = env))
    foo <- sapply(ls(envir = env), obj.type)
    object.name <- names(foo)
    names(foo) <- seq(length(foo))
    dd <- data.frame(CLASS = foo, OBJECT = object.name, 
                     stringsAsFactors = FALSE)
    dd[order(dd$CLASS),]
}

> x <- 1:5
> d <- data.frame(x)
> list.objects()
#        CLASS       OBJECT
# 1 data.frame            d
# 2   function list.objects
# 3    integer            x 
> list.objects(env = x)
# Error in list.objects(env = x) : "x" must be an environment

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

PHP 5.4 Call-time pass-by-reference - Easy fix available?

You should be denoting the call by reference in the function definition, not the actual call. Since PHP started showing the deprecation errors in version 5.3, I would say it would be a good idea to rewrite the code.

From the documentation:

There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);.

For example, instead of using:

// Wrong way!
myFunc(&$arg);               # Deprecated pass-by-reference argument
function myFunc($arg) { }

Use:

// Right way!
myFunc($var);                # pass-by-value argument
function myFunc(&$arg) { }

Javascript to open popup window and disable parent window

The key term is modal-dialog.

As such there is no built in modal-dialog offered.

But you can use many others available e.g. this

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

What is a None value?

None is a singleton object (meaning there is only one None), used in many places in the language and library to represent the absence of some other value.


For example:
if d is a dictionary, d.get(k) will return d[k] if it exists, but None if d has no key k.

Read this info from a great blog: http://python-history.blogspot.in/

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

How to specify the current directory as path in VBA?

I thought I had misunderstood but I was right. In this scenario, it will be ActiveWorkbook.Path

But the main issue was not here. The problem was with these 2 lines of code

strFile = Dir(strPath & "*.csv")

Which should have written as

strFile = Dir(strPath & "\*.csv")

and

With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _

Which should have written as

With .QueryTables.Add(Connection:="TEXT;" & strPath & "\" & strFile, _

Instagram API - How can I retrieve the list of people a user is following on Instagram

You can use the following Instagram API Endpoint to get a list of people a user is following.

https://api.instagram.com/v1/users/{user-id}/follows?access_token=ACCESS-TOKEN

Here's the complete documentation for that endpoint. GET /users/user-id/follows

And here's a sample response from executing that endpoint. enter image description here

Since this endpoint required a user-id (and not user-name), depending on how you've written your API client, you might have to make a call to the /users/search endpoint with a username, and then get the user-id from the response and pass it on to the above /users/user-id/follows endpoint to get the list of followers.

IANAL, but considering it's documented in their API, and looking at the terms of use, I don't see how this wouldn't be legal to do.

How to pass parameters to ThreadStart method in Thread?

In Additional

    Thread thread = new Thread(delegate() { download(i); });
    thread.Start();

How to calculate distance from Wifi router using Signal Strength?

Distance (km) = 10^((Free Space Path Loss – 92.45 – 20log10(f))/20)

pip: no module named _internal

This command works for me.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py --force-reinstall --user

The controller for path was not found or does not implement IController

I've found it.

When a page, that is located inside an area, wants to access a controller that is located outside of this area (such as a shared layout page or a certain page inside a different area), the area of this controller needs to be added. Since the common controller is not in a specific area but part of the main project, you have to leave area empty:

@Html.Action("MenuItems", "Common", new {area="" }) 

The above needs to be added to all of the actions and actionlinks since the layout page is shared throughout the various areas.

It's exactly the same problem as here: ASP.NET MVC Areas with shared layout

Edit: To be clear, this is marked as the answer because it was the answer for my problem. The above answers might solve the causes that trigger the same error.

What is and how to fix System.TypeInitializationException error?

I had this problem. As stated it is probably a static declaration issue. In my case it was because I had a static within a DEBUG clause. That is (in c#)

#if DEBUG
    public static bool DOTHISISINDEBUGONLY = false;
#endif

Everything worked fine until I complied a Release version of the code and after that I got this error - even on old release versions of the code. Once I took the variable out of the DEBUG clause everything returned to normal.

Converting a UNIX Timestamp to Formatted Date String

You can do like as.....

$originalDate = "1585876500";

echo $newDate = date("Y-m-d h:i:sa", date($originalDate));

Using async/await with a forEach loop

As other answers have mentioned, you're probably wanting it to be executed in sequence rather in parallel. Ie. run for first file, wait until it's done, then once it's done run for second file. That's not what will happen.

I think it's important to address why this doesn't happen.

Think about how forEach works. I can't find the source, but I presume it works something like this:

const forEach = (arr, cb) => {
  for (let i = 0; i < arr.length; i++) {
    cb(arr[i]);
  }
};

Now think about what happens when you do something like this:

forEach(files, async logFile(file) {
  const contents = await fs.readFile(file, 'utf8');
  console.log(contents);
});

Inside forEach's for loop we're calling cb(arr[i]), which ends up being logFile(file). The logFile function has an await inside it, so maybe the for loop will wait for this await before proceeding to i++?

No, it won't. Confusingly, that's not how await works. From the docs:

An await splits execution flow, allowing the caller of the async function to resume execution. After the await defers the continuation of the async function, execution of subsequent statements ensues. If this await is the last expression executed by its function execution continues by returning to the function's caller a pending Promise for completion of the await's function and resuming execution of that caller.

So if you have the following, the numbers won't be logged before "b":

const delay = (ms) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
};

const logNumbers = async () => {
  console.log(1);
  await delay(2000);
  console.log(2);
  await delay(2000);
  console.log(3);
};

const main = () => {
  console.log("a");
  logNumbers();
  console.log("b");
};

main();

Circling back to forEach, forEach is like main and logFile is like logNumbers. main won't stop just because logNumbers does some awaiting, and forEach won't stop just because logFile does some awaiting.

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

How to center an image horizontally and align it to the bottom of the container?

wouldn't

margin-left:auto;
margin-right:auto;

added to the .image_block a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block the container Div

text-align:center;

position:relative; could be a problem too.

php random x digit number

This is another simple solution to generate random number of N digits:

$number_of_digits = 10;
echo substr(number_format(time() * mt_rand(),0,'',''),0,$number_of_digits);

Check it here: http://codepad.org/pyVvNiof

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

How can I print using JQuery

Hey If you want to print selected area or div ,Try This.

<style type="text/css">
@media print
{
body * { visibility: hidden; }
.div2 * { visibility: visible; }
.div2 { position: absolute; top: 40px; left: 30px; }
}
</style>

Hope it helps you

ClassNotFoundException com.mysql.jdbc.Driver

see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

Had trouble importing standard java libraries such as java.beans.*

Fixed it on my Redhat 7 system by pointing it to the correct JRE path.

File->ProjectStructure->SDKs->1.8 Changed 'JDK home path:' to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0161-2.b14.el7.x86_64 instead of /usr/lib/jvm/java-1.8.0-openjdk-1.8.0161-2.b14.el7_4.x86_64

The former path to jdk(with the _4 difference in path) hardly had anything in it. It was missing many java libraries.

How to stretch div height to fill parent div - CSS

Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This is working code

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            { 
                    DropDownList1.DataTextField = "user_name";
                    DropDownList1.DataValueField = "user_id";
                    DropDownList1.DataSource = getData();// get the data into the list you can set it
                    DropDownList1.DataBind();

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));
            }
        }

Ruby class instance variable vs. class variable

Source

Availability to instance methods

  • Class instance variables are available only to class methods and not to instance methods.
  • Class variables are available to both instance methods and class methods.

Inheritability

  • Class instance variables are lost in the inheritance chain.
  • Class variables are not.
class Vars

  @class_ins_var = "class instance variable value"  #class instance variable
  @@class_var = "class variable value" #class  variable

  def self.class_method
    puts @class_ins_var
    puts @@class_var
  end

  def instance_method
    puts @class_ins_var
    puts @@class_var
  end
end

Vars.class_method

puts "see the difference"

obj = Vars.new

obj.instance_method

class VarsChild < Vars


end

VarsChild.class_method

How to extract a value from a string using regex and a shell?

Using ripgrep's replace option, it is possible to change the output to a capture group:

rg --only-matching --replace '$1' '(\d+) rofl'
  • --only-matching or -o outputs only the part that matches instead of the whole line.
  • --replace '$1' or -r replaces the output by the first capture group.

How to convert hex to rgb using Java?

you can do it simply as below:

 public static int[] getRGB(final String rgb)
{
    final int[] ret = new int[3];
    for (int i = 0; i < 3; i++)
    {
        ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
    }
    return ret;
}

For Example

getRGB("444444") = 68,68,68   
getRGB("FFFFFF") = 255,255,255

Convert date to UTC using moment.js

This worked for me. Others might find it useful.

// date = 2020-08-31T00:00:00Z I'm located in Denmark (timezone is +2 hours)

moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z

How to use onBlur event on Angular2?

This is the proposed answer on the Github repo:

// example without validators
const c = new FormControl('', { updateOn: 'blur' });

// example with validators
const c= new FormControl('', {
   validators: Validators.required,
   updateOn: 'blur'
});

Github : feat(forms): add updateOn blur option to FormControls

Can I loop through a table variable in T-SQL?

look like this demo:

DECLARE @vTable TABLE (IdRow int not null primary key identity(1,1),ValueRow int);

-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (SELECT MAX(IdRow) FROM @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (Select ValueRow FROM @vTable WHERE IdRow = @cnt);

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

Version without idRow, using ROW_NUMBER

    DECLARE @vTable TABLE (ValueRow int);
-------Initialize---------
insert into @vTable select 345;
insert into @vTable select 795;
insert into @vTable select 565;
---------------------------

DECLARE @cnt int = 1;
DECLARE @max int = (select count(*) from @vTable);

WHILE @cnt <= @max
BEGIN
    DECLARE @tempValueRow int = (
        select ValueRow 
        from (select ValueRow
            , ROW_NUMBER() OVER(ORDER BY (select 1)) as RowId 
            from @vTable
        ) T1 
    where t1.RowId = @cnt
    );

    ---work demo----
    print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
    print '@cnt:' + convert(varchar(10),@cnt);
    print'';
    --------------

    set @cnt = @cnt+1;
END

Vertically align text to top within a UILabel

Refering to the extension solution:

for(int i=1; i< newLinesToPad; i++) 
    self.text = [self.text stringByAppendingString:@"\n"];

should be replaced by

for(int i=0; i<newLinesToPad; i++)
    self.text = [self.text stringByAppendingString:@"\n "];

Additional space is needed in every added newline, because iPhone UILabels' trailing carriage returns seems to be ignored :(

Similarly, alignBottom should be updated too with a @" \n@%" in place of "\n@%" (for cycle initialization must be replaced by "for(int i=0..." too).

The following extension works for me:

// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end

// -- file: UILabel+VerticalAlign.m
@implementation UILabel (VerticalAlign)
- (void)alignTop {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
        self.text = [self.text stringByAppendingString:@"\n "];
}

- (void)alignBottom {
    CGSize fontSize = [self.text sizeWithFont:self.font];
    double finalHeight = fontSize.height * self.numberOfLines;
    double finalWidth = self.frame.size.width;    //expected width of label
    CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
    int newLinesToPad = (finalHeight  - theStringSize.height) / fontSize.height;
    for(int i=0; i<newLinesToPad; i++)
        self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
@end

Then call [yourLabel alignTop]; or [yourLabel alignBottom]; after each yourLabel text assignment.

How do I get the path to the current script with Node.js?

This command returns the current directory:

var currentPath = process.cwd();

For example, to use the path to read the file:

var fs = require('fs');
fs.readFile(process.cwd() + "\\text.txt", function(err, data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});

What is the function of the push / pop instructions used on registers in x86 assembly?

Almost all CPUs use stack. The program stack is LIFO technique with hardware supported manage.

Stack is amount of program (RAM) memory normally allocated at the top of CPU memory heap and grow (at PUSH instruction the stack pointer is decreased) in opposite direction. A standard term for inserting into stack is PUSH and for remove from stack is POP.

Stack is managed via stack intended CPU register, also called stack pointer, so when CPU perform POP or PUSH the stack pointer will load/store a register or constant into stack memory and the stack pointer will be automatic decreased xor increased according number of words pushed or poped into (from) stack.

Via assembler instructions we can store to stack:

  1. CPU registers and also constants.
  2. Return addresses for functions or procedures
  3. Functions/procedures in/out variables
  4. Functions/procedures local variables.

Create a date time with month and day only, no year

There is no such thing like a DateTime without a year!

From what I gather your design is a bit strange:

I would recommend storing a "start" (DateTime including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.

After the event occurs you calculate the next and store that etc.

How to SHUTDOWN Tomcat in Ubuntu?

If you installed tomcat manually, run the shutdown.sh(/.../tomcat/bin) from the terminal to shut it down easily.

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

How to read numbers from file in Python?

is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4)

with open('in.txt') as f:
  rows,cols=np.fromfile(f, dtype=int, count=2, sep=" ")
  data = np.fromfile(f, dtype=int, count=cols*rows, sep=" ").reshape((rows,cols))

another way: is working with both python2(e.g. Python 2.7.10) and python3(e.g. Python 3.6.4), as well for complex matrices see the example below (only change int to complex)

with open('in.txt') as f:
   data = []
   cols,rows=list(map(int, f.readline().split()))
   for i in range(0, rows):
      data.append(list(map(int, f.readline().split()[:cols])))
print (data)

I updated the code, this method is working for any number of matrices and any kind of matrices(int,complex,float) in the initial in.txt file.

This program yields matrix multiplication as an application. Is working with python2, in order to work with python3 make the following changes

print to print()

and

print "%7g" %a[i,j],    to     print ("%7g" %a[i,j],end="")

the script:

import numpy as np

def printMatrix(a):
   print ("Matrix["+("%d" %a.shape[0])+"]["+("%d" %a.shape[1])+"]")
   rows = a.shape[0]
   cols = a.shape[1]
   for i in range(0,rows):
      for j in range(0,cols):
         print "%7g" %a[i,j],
      print
   print      

def readMatrixFile(FileName):
   rows,cols=np.fromfile(FileName, dtype=int, count=2, sep=" ")
   a = np.fromfile(FileName, dtype=float, count=rows*cols, sep=" ").reshape((rows,cols))
   return a

def readMatrixFileComplex(FileName):
   data = []
   rows,cols=list(map(int, FileName.readline().split()))
   for i in range(0, rows):
      data.append(list(map(complex, FileName.readline().split()[:cols])))
   a = np.array(data)
   return a

f = open('in.txt')
a=readMatrixFile(f)
printMatrix(a)
b=readMatrixFile(f)
printMatrix(b)
a1=readMatrixFile(f)
printMatrix(a1)
b1=readMatrixFile(f)
printMatrix(b1)
f.close()

print ("matrix multiplication")
c = np.dot(a,b)
printMatrix(c)
c1 = np.dot(a1,b1)
printMatrix(c1)

with open('complex_in.txt') as fid:
  a2=readMatrixFileComplex(fid)
  print(a2)
  b2=readMatrixFileComplex(fid)
  print(b2)

print ("complex matrix multiplication")
c2 = np.dot(a2,b2)
print(c2)
print ("real part of complex matrix")
printMatrix(c2.real)
print ("imaginary part of complex matrix")
printMatrix(c2.imag)

as input file I take in.txt:

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.02 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
3 4
1 2 -2 0
-3 4 7 2
6 0 3 1
4 2
-1 3
0 9
1 -11
4 -5

and complex_in.txt

3 4
1+1j 2+2j -2-2j 0+0j
-3-3j 4+4j 7+7j 2+2j
6+6j 0+0j 3+3j 1+1j
4 2
-1-1j 3+3j
0+0j 9+9j
1+1j -11-11j
4+4j -5-5j

and the output look like:

Matrix[4][4]
     1      1      1      1
     2      4      8     16
     3      9     27     81
     4     16     64    256

Matrix[4][3]
  4.02     -3      4
   -13     19     -7
     3     -2      7
    -1      1     -1

Matrix[3][4]
     1      2     -2      0
    -3      4      7      2
     6      0      3      1

Matrix[4][2]
    -1      3
     0      9
     1    -11
     4     -5

matrix multiplication
Matrix[4][3]
  -6.98      15       3
 -35.96      70      20
-104.94     189      57
-255.92     420      96

Matrix[3][2]
    -3     43
    18    -60
     1    -20

[[ 1.+1.j  2.+2.j -2.-2.j  0.+0.j]
 [-3.-3.j  4.+4.j  7.+7.j  2.+2.j]
 [ 6.+6.j  0.+0.j  3.+3.j  1.+1.j]]
[[ -1. -1.j   3. +3.j]
 [  0. +0.j   9. +9.j]
 [  1. +1.j -11.-11.j]
 [  4. +4.j  -5. -5.j]]
complex matrix multiplication
[[ 0.  -6.j  0. +86.j]
 [ 0. +36.j  0.-120.j]
 [ 0.  +2.j  0. -40.j]]
real part of complex matrix
Matrix[3][2]
      0       0
      0       0
      0       0

imaginary part of complex matrix
Matrix[3][2]
     -6      86
     36    -120
      2     -40

How to fix docker: Got permission denied issue

use this command

sudo usermod -aG docker $USER

then restart your computer this worked for me.

Rounded table corners CSS only

Firstly, you'll need more than just -moz-border-radius if you want to support all browsers. You should specify all variants, including plain border-radius, as follows:

-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;

Secondly, to directly answer your question, border-radius doesn't actually display a border; it just sets how the corners look of the border, if there is one.

To turn on the border, and thus get your rounded corners, you also need the border attribute on your td and th elements.

td, th {
   border:solid black 1px;
}

You will also see the rounded corners if you have a background colour (or graphic), although of course it would need to be a different background colour to the surrounding element in order for the rounded corners to be visible without a border.

It's worth noting that some older browsers don't like putting border-radius on tables/table cells. It may be worth putting a <div> inside each cell and styling that instead. However this shouldn't affect current versions of any browsers (except IE, that doesn't support rounded corners at all - see below)

Finally, not that IE doesn't support border-radius at all (IE9 beta does, but most IE users will be on IE8 or less). If you want to hack IE to support border-radius, look at http://css3pie.com/

[EDIT]

Okay, this was bugging me, so I've done some testing.

Here's a JSFiddle example I've been playing with

It seems like the critical thing you were missing was border-collapse:separate; on the table element. This stops the cells from linking their borders together, which allows them to pick up the border radius.

Hope that helps.

How to darken a background using CSS?

It might be possible to do this with box-shadow

however, I can't get it to actually apply to an image. Only on solid color backgrounds

_x000D_
_x000D_
body {_x000D_
  background: #131418;_x000D_
  color: #999;_x000D_
  text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
  margin: 2% auto;_x000D_
  border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
  background: red_x000D_
}_x000D_
.blue {_x000D_
  background: blue_x000D_
}_x000D_
.yellow {_x000D_
  background: yellow_x000D_
}_x000D_
.green {_x000D_
  background: green_x000D_
}_x000D_
#darken {_x000D_
  box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
  /*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
_x000D_
_x000D_

How to put a tooltip on a user-defined function

I just create a "help" version of the function. Shows up right below the function in autocomplete - the user can select it instead in an adjacent cell for instructions.

Public Function Foo(param1 as range, param2 as string) As String

    Foo = "Hello world"

End Function

Public Function Foo_Help() as String

Foo_Help = "The Foo function was designed to return the Foo value for a specified range a cells given a specified constant." & CHR(10) & "Parameters:" & CHR(10)
& "  param1 as Range   :   Specifies the range of cells the Foo function should operate on." & CHR(10)
&"  param2 as String  :   Specifies the constant the function should use to calculate Foo"
&" contact the Foo master at [email protected] for more information."

END FUNCTION

The carriage returns improve readability with wordwrap on. 2 birds with one stone, now the function has some documentation.

Convert UNIX epoch to Date object

Go via POSIXct and you want to set a TZ there -- here you see my (Chicago) default:

R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05" 
R> 

Edit: A few years later, we can now use the anytime package:

R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R> 

Note how all this works without any format or origin arguments.

ng serve not detecting file changes automatically

Restarting the server worked for me.

How to programmatically modify WCF app.config endpoint address setting?

SomeServiceClient client = new SomeServiceClient();

var endpointAddress = client.Endpoint.Address; //gets the default endpoint address

EndpointAddressBuilder newEndpointAddress = new EndpointAddressBuilder(endpointAddress);
                newEndpointAddress.Uri = new Uri("net.tcp://serverName:8000/SomeServiceName/");
                client = new SomeServiceClient("EndpointConfigurationName", newEndpointAddress.ToEndpointAddress());

I did it like this. The good thing is it still picks up the rest of your endpoint binding settings from the config and just replaces the URI.

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

First step in such case is to check whether the GC is allowed to unload classes from PermGen. The standard JVM is rather conservative in this regard – classes are born to live forever. So once loaded, classes stay in memory even if no code is using them anymore. This can become a problem when the application creates lots of classes dynamically and the generated classes are not needed for longer periods. In such a case, allowing the JVM to unload class definitions can be helpful. This can be achieved by adding just one configuration parameter to your startup scripts:

-XX:+CMSClassUnloadingEnabled

By default this is set to false and so to enable this you need to explicitly set the following option in Java options. If you enable CMSClassUnloadingEnabled, GC will sweep PermGen too and remove classes which are no longer used. Keep in mind that this option will work only when UseConcMarkSweepGC is also enabled using the below option. So when running ParallelGC or, God forbid, Serial GC, make sure you have set your GC to CMS by specifying:

-XX:+UseConcMarkSweepGC

How to format Joda-Time DateTime to only mm/dd/yyyy?

I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:

dateTime.toString(DateTimeFormat.longDate());

This is most of the options printed out with their format:

shortDate:         11/3/16
shortDateTime:     11/3/16 4:25 AM
mediumDate:        Nov 3, 2016
mediumDateTime:    Nov 3, 2016 4:25:35 AM
longDate:          November 3, 2016
longDateTime:      November 3, 2016 4:25:35 AM MDT
fullDate:          Thursday, November 3, 2016
fullDateTime:      Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In case someone is using git svn, I had the same problem but could not remove the file since it was not there!. After checking permissions, touching the file and deleting it, and I don't remember what else, this did the trick:

  • checkout the master branch.
  • git svn rebase (on master)
  • checkout the branch you were working on
  • git svn rebase

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Tools for creating Class Diagrams

I use GenMyModel, first released in 2013. It's a real UML modeler, not a drawing tool. Your diagrams are UML-compliant, generate code and can be exported as UML/XMI files. It's web-based and free so it matches your criteria.

How do I Alter Table Column datatype on more than 1 column?

ALTER TABLE can do multiple table alterations in one statement, but MODIFY COLUMN can only work on one column at a time, so you need to specify MODIFY COLUMN for each column you want to change:

ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100);

Also, note this warning from the manual:

When you use CHANGE or MODIFY, column_definition must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Laravel 5 - redirect to HTTPS

In Laravel 5.1, I used: File: app\Providers\AppServiceProvider.php

public function boot()
{
    if ($this->isSecure()) {
        \URL::forceSchema('https');
    }
}

public function isSecure()
{
    $isSecure = false;
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $isSecure = true;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
        $isSecure = true;
    }

    return $isSecure;
}

NOTE: use forceSchema, NOT forceScheme

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

Documenting another source of errors for installing gcc-10 on Amazon Linux 2 from source.

After running sudo make install and then testing gcc-10 I got this error:

gcc-10: fatal error: cannot execute ‘cc1’: execvp: No such file or directory

The reason was that the new g++ directories under /usr/local/ were created by sudo make install have 700 permissions so non-root users cannot see the directories content.

I fixed it by running

sudo find /usr/local/ -type d -exec chmod 755 {} \;

Note that I followed this snippet https://gist.github.com/nchaigne/ad06bc867f911a3c0d32939f1e930a11

onclick go full screen

I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen vs FullScreen. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.

function fullScreenTgl() {
    let doc=document,elm=doc.documentElement;
    if      (elm.requestFullscreen      ) { (!doc.fullscreenElement   ? elm.requestFullscreen()       : doc.exitFullscreen()        ) }
    else if (elm.mozRequestFullScreen   ) { (!doc.mozFullScreen       ? elm.mozRequestFullScreen()    : doc.mozCancelFullScreen()   ) }
    else if (elm.msRequestFullscreen    ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen()     : doc.msExitFullscreen()      ) }
    else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen  ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
    else                                  { console.log("Fullscreen support not detected.");                                          }
    }

How to remove all whitespace from a string?

The function str_squish() from package stringr of tidyverse does the magic!

library(dplyr)
library(stringr)

df <- data.frame(a = c("  aZe  aze s", "wxc  s     aze   "), 
                 b = c("  12    12 ", "34e e4  "), 
                 stringsAsFactors = FALSE)
df <- df %>%
  rowwise() %>%
  mutate_all(funs(str_squish(.))) %>%
  ungroup()
df

# A tibble: 2 x 2
  a         b     
  <chr>     <chr> 
1 aZe aze s 12 12 
2 wxc s aze 34e e4

List files recursively in Linux CLI with path relative to the current directory

Use find:

find . -name \*.txt -print

On systems that use GNU find, like most GNU/Linux distributions, you can leave out the -print.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

SQL - How do I get only the numbers after the decimal?

I had the same problem and solved with '%' operator:

select 12.54 % 1;

Using npm behind corporate proxy .pac

You can check Fiddler if NPM is giving Authentication error. It is easy to install and configure. Set Fiddler Rule to Automatically Authenticated.In .npmrc set these properties

registry=http://registry.npmjs.org
proxy=http://127.0.0.1:8888
https-proxy=http://127.0.0.1:8888
http-proxy=http://127.0.0.1:8888
strict-ssl=false

It worked for me :)

Failed to resolve: com.android.support:appcompat-v7:28.0

Add the following code on build.gragle (project) for adding Google maven repository

allprojects {
    repositories {
    ...
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    ...
    }
}

How to stop flask application without using ctrl-c

My method can be proceeded via bash terminal/console

1) run and get the process number

$ ps aux | grep yourAppKeywords

2a) kill the process

$ kill processNum

2b) kill the process if above not working

$ kill -9 processNum

What order are the Junit @Before/@After called?

Yes, this behaviour is guaranteed:

@Before:

The @Before methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.

@After:

The @After methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.

Check if PHP session has already started

Replace session_start(); with:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        session_start();
        $a = TRUE;
    }
}

CKEditor instance already exists

Its pretty simple. In my case, I ran the below jquery method that will destroy ckeditor instances during a page load. This did the trick and resolved the issue -

JQuery method -

function resetCkEditorsOnLoad(){

    for(var i in CKEDITOR.instances) {
        editor = CKEDITOR.instances[i];
            editor.destroy();
            editor = null;
    }
}

$(function() {

            $(".form-button").button();
    $(".button").button();

    resetCkEditorsOnLoad(); // CALLING THE METHOD DURING THE PAGE LOAD

            .... blah.. blah.. blah.... // REST OF YOUR BUSINESS LOGIC GOES HERE

       });

That's it. I hope it helps you.

Cheers, Sirish.

How can I get Docker Linux container information from within the container itself?

This will get the full container id from within a container:

cat /proc/self/cgroup | grep "cpu:/" | sed 's/\([0-9]\):cpu:\/docker\///g'

Unable to set default python version to python3 in ubuntu

To change Python 3.6.8 as the default in Ubuntu 18.04 from Python 2.7 you can try the command line tool update-alternatives.

sudo update-alternatives --config python

If you get the error "no alternatives for python" then set up an alternative yourself with the following command:

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 2

Change the path /usr/bin/python3 to your desired python version accordingly.

The last argument specified it priority means, if no manual alternative selection is made the alternative with the highest priority number will be set. In our case we have set a priority 2 for /usr/bin/python3.6.8 and as a result the /usr/bin/python3.6.8 was set as default python version automatically by update-alternatives command.

we can anytime switch between the above listed python alternative versions using below command and entering a selection number:

update-alternatives --config python

python for increment inner loop

I read all the above answers and those are actually good.

look at this code:

for i in range(1, 4):
    print("Before change:", i)
    i = 20 # changing i variable
    print("After change:", i) # this line will always print 20

When we execute above code the output is like below,

Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20

in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

You can use while loop instead of for loop to do same thing what you want,

i = 0
while i < 6:
    print(i)
    j = 0
    while j < 5:
        i += 2 # to increase `i` by 2

This will give,

0
2
4

Thank you !

Spring Boot War deployed to Tomcat

This guide explains in detail how to deploy Spring Boot app on Tomcat:
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file

Essentially I needed to add following class:

public class WebInitializer extends SpringBootServletInitializer {   
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(App.class);
    }    
}

Also I added following property to POM:

<properties>        
    <start-class>mypackage.App</start-class>
</properties>

How do I display the current value of an Android Preference in the Preference summary?

Since in androidx Preference class has the SummaryProvider interface, it can be done without OnSharedPreferenceChangeListener. Simple implementations are provided for EditTextPreference and ListPreference. Building on EddieB's answer it can look like this. Tested on androidx.preference:preference:1.1.0-alpha03.

package com.example.util.timereminder.ui.prefs;

import android.os.Bundle;

import com.example.util.timereminder.R;

import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;

/**
 * Displays different preferences.
 */
public class PrefsFragmentExample extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.preferences);

        initSummary(getPreferenceScreen());
    }

    /**
     * Walks through all preferences.
     *
     * @param p The starting preference to search from.
     */
    private void initSummary(Preference p) {
        if (p instanceof PreferenceGroup) {
            PreferenceGroup pGrp = (PreferenceGroup) p;
            for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
                initSummary(pGrp.getPreference(i));
            }
        } else {
            setPreferenceSummary(p);
        }
    }

    /**
     * Sets up summary providers for the preferences.
     *
     * @param p The preference to set up summary provider.
     */
    private void setPreferenceSummary(Preference p) {
        // No need to set up preference summaries for checkbox preferences because
        // they can be set up in xml using summaryOff and summary On
        if (p instanceof ListPreference) {
            p.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
        } else if (p instanceof EditTextPreference) {
            p.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
        }
    }
}

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Try using a format file since your data file only has 4 columns. Otherwise, try OPENROWSET or use a staging table.

myTestFormatFiles.Fmt may look like:

9.0
4
1       SQLINT        0       3       ","      1     StudentNo      ""
2       SQLCHAR       0       100     ","      2     FirstName      SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       100     ","      3     LastName       SQL_Latin1_General_CP1_CI_AS
4       SQLINT        0       4       "\r\n"   4     Year           "


(source: microsoft.com)

This tutorial on skipping a column with BULK INSERT may also help.

Your statement then would look like:

USE xta9354
GO
BULK INSERT xta9354.dbo.Students
    FROM 'd:\userdata\xta9_Students.txt' 
    WITH (FORMATFILE = 'C:\myTestFormatFiles.Fmt')

Android charting libraries

You can use MPAndroidChart.

It's native, free, easy to use, fast and reliable.

Core features, benefits:

  • LineChart, BarChart (vertical, horizontal, stacked, grouped), PieChart, ScatterChart, CandleStickChart (for financial data), RadarChart (spider web chart), BubbleChart
  • Combined Charts (e.g. lines and bars in one)
  • Scaling on both axes (with touch-gesture, axes separately or pinch-zoom)
  • Dragging / Panning (with touch-gesture)
  • Separate (dual) y-axes
  • Highlighting values (with customizeable popup-views)
  • Save chart to SD-Card (as image)
  • Predefined color templates
  • Legends (generated automatically, customizeable)
  • Customizeable Axes (both x- and y-axis)
  • Animations (build up animations, on both x- and y-axis)
  • Limit lines (providing additional information, maximums, ...)
  • Listeners for touch, gesture & selection callbacks
  • Fully customizeable (paints, typefaces, legends, colors, background, dashed lines, ...)
  • Realm.io mobile database support via MPAndroidChart-Realm library
  • Smooth rendering for up to 10.000 data points in Line- and BarChart
  • Lightweight (method count ~1.4K)
  • Available as .jar file (only 500kb in size)
  • Available as gradle dependency and via maven
  • Good documentation
  • Example Project (code for demo-application)
  • Google-PlayStore Demo Application
  • Widely used, great support on both GitHub and stackoverflow - mpandroidchart
  • Also available for iOS: Charts (API works the same way)
  • Also available for Xamarin: MPAndroidChart.Xamarin

Drawbacks:

Disclaimer: I am the developer of this library.

How to find all the subclasses of a class given its name?

Here's a version without recursion:

def get_subclasses_gen(cls):

    def _subclasses(classes, seen):
        while True:
            subclasses = sum((x.__subclasses__() for x in classes), [])
            yield from classes
            yield from seen
            found = []
            if not subclasses:
                return

            classes = subclasses
            seen = found

    return _subclasses([cls], [])

This differs from other implementations in that it returns the original class. This is because it makes the code simpler and:

class Ham(object):
    pass

assert(issubclass(Ham, Ham)) # True

If get_subclasses_gen looks a bit weird that's because it was created by converting a tail-recursive implementation into a looping generator:

def get_subclasses(cls):

    def _subclasses(classes, seen):
        subclasses = sum(*(frozenset(x.__subclasses__()) for x in classes))
        found = classes + seen
        if not subclasses:
            return found

        return _subclasses(subclasses, found)

    return _subclasses([cls], [])

Tar a directory, but don't store full absolute paths in the archive

Found tar -cvf site1-$seqNumber.tar -C /var/www/ site1 as more friendlier solution than tar -cvf site1-$seqNumber.tar -C /var/www/site1 . (notice the . in the second solution) for the following reasons

  • Tar file name can be insignificant as the original folder is now an archive entry
  • Tar file name being insignificant to the content can now be used for other purposes like sequence numbers, periodical backup etc.

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    OR
    echo -n "hello with no new line printed at end"

How do I convert a double into a string in C++?

Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.

Installing Bootstrap 3 on Rails App

For me, the simplest way to do this is

1) Download and unzip bootstrap into vendor

2) Add the bootstrap path to your config

config.assets.paths << Rails.root.join("vendor/bootstrap-3.3.6-dist")

3) Require them

in css *= require css/bootstrap

in js //= require js/bootstrap

Done!

This methods makes the fonts load without any other special configuration and doesn't require moving the bootstrap files out of their self-contained directory.

Pandas create empty DataFrame with only column names

Creating colnames with iterating

df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)

# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []

to_html() operations

print(df.to_html())

# <table border="1" class="dataframe">
#   <thead>
#     <tr style="text-align: right;">
#       <th></th>
#       <th>colname_0</th>
#       <th>colname_1</th>
#       <th>colname_2</th>
#       <th>colname_3</th>
#       <th>colname_4</th>
#     </tr>
#   </thead>
#   <tbody>
#   </tbody>
# </table>

this seems working

print(type(df.to_html()))
# <class 'str'>

The problem is caused by

when you create df like this

df = pd.DataFrame(columns=COLUMN_NAMES)

it has 0 rows × n columns, you need to create at least one row index by

df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])

now it has 1 rows × n columns. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

I think it's better to divide my answer to 2 parts:


A-Create everything from scratch (using SVG, JavaScript, and HTML5):

  1. Create a new HTML5 page
  2. Create a new SVG file, each clickable area (province) should be a separate SVG Polygon in your SVG file, (I'm using Adobe Illustrator for creating SVG files but you can find many alternative software products too, for example Inkscape)
  3. Add mouseover and click events to your polygons one by one
    <polygon points="200,10 250,190 160,210" style="fill:lime;stroke:purple;stroke-width:1" 
        onmouseover="mouseOverHandler(evt)"
        onclick="clickHandler(evt)" />
    
  4. Add a handler for each event in your JavaScript code and add your desired code to the handler
    function mouseOverHandler(evt) {};
    function clickHandler(evt) {};
    
  5. Add the SVG file to your HTML page (I prefer inline SVG but you can use linked SVG file too)
  6. Upload the files to your server

B-Use a software like FLDraw Interactive Image Creator (only if you have a map image and want to make it interactive):

  1. Create an empty project and choose your map image as your base image when creating the new project
  2. Add a Polygon element (from the Shape menu) for each province
  3. For each polygon double click it to open the Properties window where you can choose an event type for mouse-over and click, also change the shape opacity to 0 to make it invisible
  4. Save your project and Publish it to HTML5, FLDraw will create a new folder that contains all of the required files for your project that you can upload to your server.

Option (A) is very good if you are programmer or you have someone to create the required code and SVG file for you, Option (B) is good if you don't want to hire someone or spend your own time for creating everything from scratch

You have some other options too, for example using HTML5 Canvas instead of SVG, but it's not very easy to create a Zoomable map using HTML5 Canvas, maybe there are some other ways too that I'm not aware of.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

For Microsoft Query you can go into Connections --> Properties and untick "Enable background refresh".

This will stop anything happening while the refresh is taking place. I needed to refresh data upon entry and then run a userform on the refreshed data, and this method worked perfectly for me.

How do I check for null values in JavaScript?

AFAIK in JAVASCRIPT when a variable is declared but has not assigned value, its type is undefined. so we can check variable even if it would be an object holding some instance in place of value.

create a helper method for checking nullity that returns true and use it in your API.

helper function to check if variable is empty:

function isEmpty(item){
    if(item){
        return false;
    }else{
        return true;
    }
}

try-catch exceptional API call:

try {

    var pass, cpass, email, cemail, user; // only declared but contains nothing.

    // parametrs checking
    if(isEmpty(pass) || isEmpty(cpass) || isEmpty(email) || isEmpty(cemail) || isEmpty(user)){
        console.log("One or More of these parameter contains no vlaue. [pass] and-or [cpass] and-or [email] and-or [cemail] and-or [user]");
    }else{
        // do stuff
    }

} catch (e) {
    if (e instanceof ReferenceError) {
        console.log(e.message); // debugging purpose
        return true;
    } else {
        console.log(e.message); // debugging purpose
        return true;
    }
}

some test cases:

var item = ""; // isEmpty? true
var item = " "; // isEmpty? false
var item; // isEmpty? true
var item = 0; // isEmpty? true
var item = 1; // isEmpty? false
var item = "AAAAA"; // isEmpty? false
var item = NaN; // isEmpty? true
var item = null; // isEmpty? true
var item = undefined; // isEmpty? true

console.log("isEmpty? "+isEmpty(item));

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

Filter by process/PID in Wireshark

Use Microsoft Message Analyzer v1.4

Navigate to ProcessId from the field chooser.

Etw
-> EtwProviderMsg
--> EventRecord
---> Header
----> ProcessId

Right click and Add as Column

How do I set adaptive multiline UILabel text?

Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
self.view.addSubview(label)
// SET AUTOLAYOUT ANCHORS
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// OPTIONALLY, YOU CAN USE THIS INSTEAD OF THE WIDTH ANCHOR (OR LEFT/RIGHT)
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)
label.text = "YOUR LONG TEXT GOES HERE"
label.sizeToFit()

If setting frame.width dynamically using UIScreen:

extension UIScreen {   // OPTIONAL IF USING A DYNAMIC FRAME WIDTH
    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        }
        return width
    }
}

How to replace captured groups only?

With two capturing groups would have been also possible; I would have also included two dashes, as additional left and right boundaries, before and after the digits, and the modified expression would have looked like:

(.*name=".+_)\d+(_[^"]+".*)

_x000D_
_x000D_
const regex = /(.*name=".+_)\d+(_[^"]+".*)/g;_x000D_
const str = `some_data_before name="some_text_0_some_text" and then some_data after`;_x000D_
const subst = `$1!NEW_ID!$2`;_x000D_
const result = str.replace(regex, subst);_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Difference between a View's Padding and Margin

Padding is the space inside the border, between the border and the actual view's content. Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent).

Margins are the spaces outside the border, between the border and the other elements next to this view. In the image, the margin is the grey area outside the entire object. Note that, like the padding, the margin goes completely around the content: there are margins on the top, bottom, right, and left sides.

An image says more than 1000 words (extracted from Margin Vs Padding - CSS Properties):

alt text

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Using DirectoryIterator and recursion correctly:

function deleteFilesThenSelf($folder) {
    foreach(new DirectoryIterator($folder) as $f) {
        if($f->isDot()) continue; // skip . and ..
        if ($f->isFile()) {
            unlink($f->getPathname());
        } else if($f->isDir()) {
            deleteFilesThenSelf($f->getPathname());
        }
    }
    rmdir($folder);
}

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

There is a lot of confusion about these methods, but it is actually not that complicated. Most of the confusion is because:

  1. If your View/ViewGroup or any of its children do not return true in onTouchEvent, dispatchTouchEvent and onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN. Without a true from onTouchEvent, the parent view will assume your view does not need the MotionEvents.
  2. When none of the children of a ViewGroup return true in onTouchEvent, onInterceptTouchEvent will ONLY be called for MotionEvent.ACTION_DOWN, even if your ViewGroup returns true in onTouchEvent.

Processing order is like this:

  1. dispatchTouchEvent is called.
  2. onInterceptTouchEvent is called for MotionEvent.ACTION_DOWN or when any of the children of the ViewGroup returned true in onTouchEvent.
  3. onTouchEvent is first called on the children of the ViewGroup and when none of the children returns true it is called on the View/ViewGroup.

If you want to preview TouchEvents/MotionEvents without disabling the events on your children, you must do two things:

  1. Override dispatchTouchEvent to preview the event and return super.dispatchTouchEvent(ev);
  2. Override onTouchEvent and return true, otherwise you won’t get any MotionEvent except MotionEvent.ACTION_DOWN.

If you want to detect some gesture like a swipe event, without disabling other events on your children as long as you did not detect the gesture, you can do it like this:

  1. Preview the MotionEvents as described above and set a flag when you detected your gesture.
  2. Return true in onInterceptTouchEvent when your flag is set to cancel MotionEvent processing by your children. This is also a convenient place to reset your flag, because onInterceptTouchEvent won’t be called again until the next MotionEvent.ACTION_DOWN.

Example of overrides in a FrameLayout (my example in is C# as I’m programming with Xamarin Android, but the logic is the same in Java):

public override bool DispatchTouchEvent(MotionEvent e)
{
    // Preview the touch event to detect a swipe:
    switch (e.ActionMasked)
    {
        case MotionEventActions.Down:
            _processingSwipe = false;
            _touchStartPosition = e.RawX;
            break;
        case MotionEventActions.Move:
            if (!_processingSwipe)
            {
                float move = e.RawX - _touchStartPosition;
                if (move >= _swipeSize)
                {
                    _processingSwipe = true;
                    _cancelChildren = true;
                    ProcessSwipe();
                }
            }
            break;
    }
    return base.DispatchTouchEvent(e);
}

public override bool OnTouchEvent(MotionEvent e)
{
    // To make sure to receive touch events, tell parent we are handling them:
    return true;
}

public override bool OnInterceptTouchEvent(MotionEvent e)
{
    // Cancel all children when processing a swipe:
    if (_cancelChildren)
    {
        // Reset cancel flag here, as OnInterceptTouchEvent won't be called until the next MotionEventActions.Down:
        _cancelChildren = false;
        return true;
    }
    return false;
}

How can I add a class to a DOM element in JavaScript?

There is also the DOM way of doing this in JavaScript:

// Create a div and set class
var new_row = document.createElement("div");
new_row.setAttribute("class", "aClassName");
// Add some text
new_row.appendChild(document.createTextNode("Some text"));
// Add it to the document body
document.body.appendChild(new_row);

Downloading jQuery UI CSS from Google's CDN

You could use this one if you mean the jQuery UI css:

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

How to pass prepareForSegue: an object

In Swift 4.2 I would do something like that:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let yourVC = segue.destination as? YourViewController {
        yourVC.yourData = self.someData
    }
}

Using OpenSSL what does "unable to write 'random state'" mean?

I have come accross this problem today on AWS Lambda. I created an environment variable RANDFILE = /tmp/.random

That did the trick.

How to create correct JSONArray in Java using JSONObject

Please try this ... hope it helps

JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();

jsonObj1=new JSONObject();
jsonObj2=new JSONObject();


array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);

Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

Iterating over dictionaries using 'for' loops

If you are looking for a clear and visual example:

cat  = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
   print(key, ': ', value)

Result:

name:  Snowy
color:  White
age:  14

Make a number a percentage

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

How do you create a dropdownlist from an enum in ASP.NET MVC?

I am very late on this one but I just found a really cool way to do this with one line of code, if you are happy to add the Unconstrained Melody NuGet package (a nice, small library from Jon Skeet).

This solution is better because:

  1. It ensures (with generic type constraints) that the value really is an enum value (due to Unconstrained Melody)
  2. It avoids unnecessary boxing (due to Unconstrained Melody)
  3. It caches all the descriptions to avoid using reflection on every call (due to Unconstrained Melody)
  4. It is less code than the other solutions!

So, here are the steps to get this working:

  1. In Package Manager Console, "Install-Package UnconstrainedMelody"
  2. Add a property on your model like so:

    //Replace "YourEnum" with the type of your enum
    public IEnumerable<SelectListItem> AllItems
    {
        get
        {
            return Enums.GetValues<YourEnum>().Select(enumValue => new SelectListItem { Value = enumValue.ToString(), Text = enumValue.GetDescription() });
        }
    }
    

Now that you have the List of SelectListItem exposed on your model, you can use the @Html.DropDownList or @Html.DropDownListFor using this property as the source.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Make sure all services windows are closed before starting install/uninstall

MySQL Like multiple values

More work examples:

SELECT COUNT(email) as count FROM table1 t1 
JOIN (
      SELECT company_domains as emailext FROM table2 WHERE company = 'DELL'
     ) t2 
ON t1.email LIKE CONCAT('%', emailext) WHERE t1.event='PC Global Conference";

Task was count participants at an event(s) with filter if email extension equal to multiple company domains.

Get next / previous element using JavaScript?

that's so simple

var element = querySelector("div")
var nextelement = element.ParentElement.querySelector("div+div")

Here is the browser supports https://caniuse.com/queryselector