Programs & Examples On #Lotus formula

Internal Lotus Notes formula language. All commands start with the '@' symbol, and because of that another name for Lotus formulas is "@-formulas".

Can I automatically increment the file build version when using Visual Studio?

Set the version number to "1.0.*" and it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight)

Creating CSS Global Variables : Stylesheet theme management

You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }

PHP Pass variable to next page

try this code

using hidden field we can pass php varibale to another page

page1.php

<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
 <input type="hidden" name="text" value="<?php echo $myVariable; ?>">
 <button type="submit">Submit</button>
</form>

pass php variable to hidden field value so you can access this variable into another page

page2.php

<?php
 $text=$_POST['text'];
 echo $text;
?>

Reduce git repository size

This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.

You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules directory. To make redundant submodule files gone away, see this question.

However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules, and do a, for example, git gc --aggressive --prune.

These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.

Hibernate Annotations - Which is better, field or property access?

By default, JPA providers access the values of entity fields and map those fields to database columns using the entity’s JavaBean property accessor (getter) and mutator (setter) methods. As such, the names and types of the private fields in an entity do not matter to JPA. Instead, JPA looks at only the names and return types of the JavaBean property accessors. You can alter this using the @javax.persistence.Access annotation, which enables you to explicitly specify the access methodology that the JPA provider should employ.

@Entity
@Access(AccessType.FIELD)
public class SomeEntity implements Serializable
{
...
}

The available options for the AccessType enum are PROPERTY (the default) and FIELD. With PROPERTY, the provider gets and sets field values using the JavaBean property methods. FIELD makes the provider get and set field values using the instance fields. As a best practice, you should just stick to the default and use JavaBean properties unless you have a compelling reason to do otherwise.

You can put these property annotations on either the private fields or the public accessor methods. If you use AccessType.PROPERTY (default) and annotate the private fields instead of the JavaBean accessors, the field names must match the JavaBean property names. However, the names do not have to match if you annotate the JavaBean accessors. Likewise, if you use AccessType.FIELD and annotate the JavaBean accessors instead of the fields, the field names must also match the JavaBean property names. In this case, they do not have to match if you annotate the fields. It’s best to just be consistent and annotate the JavaBean accessors for AccessType.PROPERTY and the fields for AccessType.FIELD.

It is important that you should never mix JPA property annotations and JPA field annotations in the same entity. Doing so results in unspecified behavior and is very likely to cause errors.

How do you set your pythonpath in an already-created virtualenv?

The comment by @s29 should be an answer:

One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do

mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path

If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth

Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/

Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv

MySQL case sensitive query

MySQL queries are not case-sensitive by default. Following is a simple query that is looking for 'value'. However it will return 'VALUE', 'value', 'VaLuE', etc…

SELECT * FROM `table` WHERE `column` = 'value'

The good news is that if you need to make a case-sensitive query, it is very easy to do using the BINARY operator, which forces a byte by byte comparison:

SELECT * FROM `table` WHERE BINARY `column` = 'value'

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

How to detect iPhone 5 (widescreen devices)?

Really simple solution

if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
    CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.height == 480)
    {
        // iPhone Classic
    }
    if(result.height == 568)
    {
        // iPhone 5
    }
}

How to return data from promise

You have to return a promise instead of a variable. So in your function just return:

return relationsManagerResource.GetParentId(nodeId)

And later resolve the returned promise. Or you can make another deferred and resolve theParentId with it.

Scanner method to get a char

You can use the Console API (which made its appearance in Java 6) as follows:

Console cons = System.console();
if(cons != null) {
  char c = (char) cons.reader().read();  // Checking for EOF omitted
  ...
}

If you just need a single line you don't even need to go through the reader object:

String s = cons.readLine();

AngularJS : When to use service instead of factory

Factory and Service are the most commonly used method. The only difference between them is that the Service method works better for objects that need inheritance hierarchy, while the Factory can produce JavaScript primitives and functions.

The Provider function is the core method and all the other ones are just syntactic sugar on it. You need it only if you are building a reusable piece of code that needs global configuration.

There are five methods to create services: Value, Factory, Service, Provider and Constant. You can learn more about this here angular service, this article explain all this methods with practical demo examples.

.

Adding and removing extensionattribute to AD object

Or the -Remove parameter

Set-ADUser -Identity anyUser -Remove @{extensionAttribute4="myString"}

How to add a “readonly” attribute to an <input>?

jQuery <1.9

$('#inputId').attr('readonly', true);

jQuery 1.9+

$('#inputId').prop('readonly', true);

Read more about difference between prop and attr

Configure cron job to run every 15 minutes on Jenkins

It should be,

*/15 * * * *  your_command_or_whatever

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

Try

Date.ParseExact("9/1/2009", "M/d/yyyy", new CultureInfo("en-US"))

How to access URL segment(s) in blade in Laravel 5?

Here is code you can get url segment.

{{ Request::segment(1) }}

If you don't want the data to be escaped then use {!! !!} else use {{ }}.

{!! Request::segment(1) !!}

https://laravel.com/docs/4.2/requests

how do you view macro code in access?

In Access 2010, go to the Create tab on the ribbon. Click Macro. An "Action Catalog" panel should appear on the right side of the screen. Underneath, there's a section titled "In This Database." Clicking on one of the macro names should display its code.

Convert a 1D array to a 2D array in numpy

If your sole purpose is to convert a 1d array X to a 2d array just do:

X = np.reshape(X,(1, X.size))

Convert timestamp in milliseconds to string formatted time in Java

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

How to select data where a field has a min value in MySQL?

Efficient way (with any number of records):

SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Java HTML Parsing

Several years ago I used JTidy for the same purpose:

http://jtidy.sourceforge.net/

"JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML.

JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers.

More information on JTidy can be found on the JTidy SourceForge project page ."

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

My problem was I was registering table view cell inside dispatch queue asynchronously. If you have registered table view source and delegate reference in storyboard then dispatch queue would delay the registration of cell as name suggests it will happen asynchronously and your table view is looking for the cells.

DispatchQueue.main.async {
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

Either you shouldn't use dispatch queue for registration OR do this:

DispatchQueue.main.async {
    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.tableView.register(CampaignTableViewCell.self, forCellReuseIdentifier: CampaignTableViewCell.identifier())
    self.tableView.reloadData()
}

Java, return if trimmed String in List contains String

You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
    if(str.trim().contains(search))
       return true;
}
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop
if(str.trim().toLowerCase().contains(search))

Using 'starts with' selector on individual class names

Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

How to convert a string with comma-delimited items to a list in Python?

To convert a string having the form a="[[1, 3], [2, -6]]" I wrote yet not optimized code:

matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
    row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
    matrixAr.append(row)
print matrixAr

How do I check CPU and Memory Usage in Java?

From here

    OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    int availableProcessors = operatingSystemMXBean.getAvailableProcessors();
    long prevUpTime = runtimeMXBean.getUptime();
    long prevProcessCpuTime = operatingSystemMXBean.getProcessCpuTime();
    double cpuUsage;
    try
    {
        Thread.sleep(500);
    }
    catch (Exception ignored) { }

    operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long upTime = runtimeMXBean.getUptime();
    long processCpuTime = operatingSystemMXBean.getProcessCpuTime();
    long elapsedCpu = processCpuTime - prevProcessCpuTime;
    long elapsedTime = upTime - prevUpTime;

    cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
    System.out.println("Java CPU: " + cpuUsage);

How to configure robots.txt to allow everything?

That file will allow all crawlers access

User-agent: *
Allow: /

This basically allows all user agents (the *) to all parts of the site (the /).

What is the difference between SQL, PL-SQL and T-SQL?

  • SQL is a query language to operate on sets.

    It is more or less standardized, and used by almost all relational database management systems: SQL Server, Oracle, MySQL, PostgreSQL, DB2, Informix, etc.

  • PL/SQL is a proprietary procedural language used by Oracle

  • PL/pgSQL is a procedural language used by PostgreSQL

  • TSQL is a proprietary procedural language used by Microsoft in SQL Server.

Procedural languages are designed to extend SQL's abilities while being able to integrate well with SQL. Several features such as local variables and string/data processing are added. These features make the language Turing-complete.

They are also used to write stored procedures: pieces of code residing on the server to manage complex business rules that are hard or impossible to manage with pure set-based operations.

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Difference between single and double quotes in Bash

The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a as well as an indexed array arr.

If we set

a=apple      # a simple variable
arr=(apple)  # an indexed array with a single element

and then echo the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.

# Expression Result Comments
1 "$a" apple variables are expanded inside ""
2 '$a' $a variables are not expanded inside ''
3 "'$a'" 'apple' '' has no special meaning inside ""
4 '"$a"' "$a" "" is treated literally inside ''
5 '\'' invalid can not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting)
6 "red$arocks" red $arocks does not expand $a; use ${a}rocks to preserve $a
7 "redapple$" redapple$ $ followed by no variable name evaluates to $
8 '\"' \" \ has no special meaning inside ''
9 "\'" \' \' is interpreted inside "" but has no significance for '
10 "\"" " \" is interpreted inside ""
11 "*" * glob does not work inside "" or ''
12 "\t\n" \t\n \t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13 "`echo hi`" hi `` and $() are evaluated inside "" (backquotes are retained in actual output)
14 '`echo hi`' echo hi `` and $() are not evaluated inside '' (backquotes are retained in actual output)
15 '${arr[0]}' ${arr[0]} array access not possible inside ''
16 "${arr[0]}" apple array access works inside ""
17 $'$a\'' $a' single quotes can be escaped inside ANSI-C quoting
18 "$'\t'" $'\t' ANSI-C quoting is not interpreted inside ""
19 '!cmd' !cmd history expansion character '!' is ignored inside ''
20 "!cmd" cmd args expands to the most recent command matching "cmd"
21 $'!cmd' !cmd history expansion character '!' is ignored inside ANSI-C quotes

See also:

How to add shortcut keys for java code in eclipse

I've been Eclipse-free for over a year now, but I believe Eclipse calls these "Templates". Look in your settings for them. You invoke a template by typing its abbreviation and pressing the normal code completion hotkey (ctrl+space by default) or using the Tab key. The standard eclipse shortcut for System.out.println() is "sysout", so "sysout" would do what you want.

Here's another stackoverflow question that has some more details about it: How to use the "sysout" snippet in Eclipse with selected text?

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

What do the different readystates in XMLHttpRequest mean, and how can I use them?

The full list of readyState values is:

State  Description
0      The request is not initialized
1      The request has been set up
2      The request has been sent
3      The request is in process
4      The request is complete

(from https://www.w3schools.com/js/js_ajax_http_response.asp)

In practice you almost never use any of them except for 4.

Some XMLHttpRequest implementations may let you see partially received responses in responseText when readyState==3, but this isn't universally supported and shouldn't be relied upon.

Spring schemaLocation fails when there is no internet connection

In case anyone arrives here via the same root I did - I hit this problem because I was building a single JAR with all dependencies, including Spring JARs. As a result the spring.schemas file in some of the META-INF directories of Spring JARs was overwritten.

I found suggested solutions here: How to create spring-based executable jar with maven?

White spaces are required between publicId and systemId

If you're working from some network that requires you to use a proxy in your browser to connect to the internet (likely an office building), that might be it. I had the same issue and adding the proxy configs to the network settings solved it.

  • Go to your preferences (Eclipse -> Preferences on a Mac, or Window -> Preferences on a Windows)
  • Then -> General -> expand to view the list underneath -> Select Network Connections (don't expand)
  • At the top of the page that appears there is a drop down, select "Manual."
  • Then select "HTTP" in the list directly below the drop down (which now should have all it's options checked) and then click the "Edit" button to the right of the list.
  • Enter in the proxy url and port you need to connect to the internet in your web browser normally.
  • Repeat for "HTTPS."

If you don't know the proxy url and port, talk to your network admin.

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

The for loop loops until i=26 (where 26 is total.length) and then your if is executed, going over the bounds of the array. Remove the ; at the end of the for loop.

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

jQuery .scrollTop(); + animation

jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");
    });

Dynamic tabs with user-click chosen components

update

Angular 5 StackBlitz example

update

ngComponentOutlet was added to 4.0.0-beta.3

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
  @Input() type: Type<Component>;
  cmpRef: ComponentRef<Component>;
  private isViewInitialized:boolean = false;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      // when the `type` input changes we destroy a previously 
      // created component before creating the new one
      this.cmpRef.destroy();
    }

    let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
    this.cmpRef = this.target.createComponent(factory)
    // to access the created instance use
    // this.compRef.instance.someProperty = 'someValue';
    // this.compRef.instance.someOutput.subscribe(val => doSomething());
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Usage example

// Use dcl-wrapper component
@Component({
  selector: 'my-tabs',
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}
@Component({
  selector: 'my-app',
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  // The list of components to create tabs from
  types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
  entryComponents: [C1, C2, C3],
  bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

Update - use ViewContainerRef.createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private resolver: ComponentResolver) {}

  updateComponent() {
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
   this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
      this.cmpRef = this.target.createComponent(factory)
      // to access the created instance use
      // this.compRef.instance.someProperty = 'someValue';
      // this.compRef.instance.someOutput.subscribe(val => doSomething());
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example RC.4
Plunker example beta.17

Update - use loadNextToLocation

export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private dcl:DynamicComponentLoader) {}

  updateComponent() {
    // should be executed every time `type` changes but not before `ngAfterViewInit()` was called 
    // to have `target` initialized
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }

  ngOnDestroy() {
    if(this.cmpRef) {
      this.cmpRef.destroy();
    }    
  }
}

Plunker example beta.17

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({
  selector: 'dcl-wrapper',
  template: `<div #target></div>`
})
export class DclWrapper {
  constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
  @Input() type;

  ngOnChanges() {
    if(this.cmpRef) {
      this.cmpRef.dispose();
    }
    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }
}

@Component({
  selector: 'c1',
  template: `<h2>c1</h2>`

})
export class C1 {
}

@Component({
  selector: 'c2',
  template: `<h2>c2</h2>`

})
export class C2 {
}

@Component({
  selector: 'c3',
  template: `<h2>c3</h2>`

})
export class C3 {
}

@Component({
  selector: 'my-tabs',
  directives: [DclWrapper],
  template: `
  <h2>Tabs</h2>
  <div *ngFor="let tab of tabs">
    <dcl-wrapper [type]="tab"></dcl-wrapper>
  </div>
`
})
export class Tabs {
  @Input() tabs;
}


@Component({
  selector: 'my-app',
  directives: [Tabs]
  template: `
  <h2>Hello {{name}}</h2>
  <my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
  types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

    this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
  cmpRef.instance.someProperty = someData;
  this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

Scale iFrame css width 100% like an image

@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.

The most reliable, simplest answer is:

_x000D_
_x000D_
body {_x000D_
  /* for demo */_x000D_
  background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
  /* anything or nothing, it doesn't matter */_x000D_
  width: 60%;_x000D_
  /* only need if other rulesets give this padding */_x000D_
  padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
  height: 0;_x000D_
  /* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
  padding: 0 0 56.25%;_x000D_
  position: relative;_x000D_
  /* only need next 2 rules if other rulesets change these */_x000D_
  margin: 0;_x000D_
  width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  /* for demo */_x000D_
  border: 0;_x000D_
  background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
  <div class="fixed-aspect-padder">_x000D_
    <iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

calling Jquery function from javascript

You can't.

function(){

    function my_fun(){
           /.. some operations ../
    }
}

That is a closure. my_fun() is defined only inside of that anonymous function. You can only call my_fun() if you declare it at the correct level of scope, i.e., globally.

$(function () {/* something */}) is an IIFE, meaning it executes immediately when the DOM is ready. By declaring my_fun() inside of that anonymous function, you prevent the rest of the script from "seeing" it.

Of course, if you want to run this function when the DOM has fully loaded, you should do the following:

function my_fun(){
    /* some operations */
}

$(function(){
    my_fun(); //run my_fun() ondomready
});

// just js
function js_fun(){
   my_fun(); //== call my_fun() again
}

What's the best way to do a backwards loop in C/C#/C++?

That's definitely the best way for any array whose length is a signed integral type. For arrays whose lengths are an unsigned integral type (e.g. an std::vector in C++), then you need to modify the end condition slightly:

for(size_t i = myArray.size() - 1; i != (size_t)-1; i--)
    // blah

If you just said i >= 0, this is always true for an unsigned integer, so the loop will be an infinite loop.

React-Router open Link in new tab

target="_blank" is enough to open in a new tab, when you are using react-router

eg: <Link to={/admin/posts/error-post-list/${this.props.errorDate}} target="_blank"> View Details </Link>

How to use the PI constant in C++

Since the official standard library doesn't define a constant PI you would have to define it yourself. So the answer to your question "How can I get PI without defining it manually?" is "You don't -- or you rely on some compiler-specific extensions.". If you're not concerned about portability you could check your compiler's manual for this.

C++ allows you to write

const double PI = std::atan(1.0)*4;

but the initialization of this constant is not guaranteed to be static. The G++ compiler however handles those math functions as intrinsics and is able to compute this constant expression at compile-time.

Check if a Windows service exists and delete in PowerShell

One could use Where-Object

if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) { "Service Exists" }

matplotlib.pyplot will not forget previous plots - how can I flush/refresh?

I discovered that this behaviour only occurs after running a particular script, similar to the one in the question. I have no idea why it occurs.

It works (refreshes the graphs) if I put

plt.clf()
plt.cla()
plt.close()

after every plt.show()

Activate a virtualenv with a Python script

The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:

#!/path/to/project/venv/bin/python

Make the script executable:

chmod u+x script.py

Run the script:

./script.py

Voila!

How to implement LIMIT with SQL Server?

This is one of the reasons I try to avoid using MS Server... but anyway. Sometimes you just don't have an option (yei! and I have to use an outdated version!!).

My suggestion is to create a virtual table:

From:

SELECT * FROM table

To:

CREATE VIEW v_table AS    
    SELECT ROW_NUMBER() OVER (ORDER BY table_key) AS row,* FROM table

Then just query:

SELECT * FROM v_table WHERE row BETWEEN 10 AND 20

If fields are added, or removed, "row" is updated automatically.

The main problem with this option is that ORDER BY is fixed. So if you want a different order, you would have to create another view.

UPDATE

There is another problem with this approach: if you try to filter your data, it won't work as expected. For example, if you do:

SELECT * FROM v_table WHERE field = 'test' AND row BETWEEN 10 AND 20

WHERE becomes limited to those data which are in the rows between 10 and 20 (instead of searching the whole dataset and limiting the output).

Find which rows have different values for a given column in Teradata SQL

Personally, I would print them to a file using Perl or Python in the format

<COL_NAME>:  <COL_VAL>

for each row so that the file has as many lines as there are columns. Then I'd do a diff between the two files, assuming you are on Unix or compare them using some equivalent utilty on another OS. If you have multiple recordsets (i.e. more than one row), I would prepend to each file row and then the file would have NUM_DB_ROWS * NUM_COLS lines

Property 'json' does not exist on type 'Object'

UPDATE: for rxjs > v5.5

As mentioned in some of the comments and other answers, by default the HttpClient deserializes the content of a response into an object. Some of its methods allow passing a generic type argument in order to duck-type the result. Thats why there is no json() method anymore.

import {throwError} from 'rxjs';
import {catchError, map} from 'rxjs/operators';

export interface Order {
  // Properties
}

interface ResponseOrders {
  results: Order[];
}

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get<ResponseOrders >(this.baseUrl,{
       params
    }).pipe(
       map(res => res.results || []),
       catchError(error => _throwError(error.message || error))
    );
} 

Notice that you could easily transform the returned Observable to a Promise by simply invoking toPromise().

ORIGINAL ANSWER:

In your case, you can

Assumming that your backend returns something like:

{results: [{},{}]}

in JSON format, where every {} is a serialized object, you would need the following:

// Somewhere in your src folder

export interface Order {
  // Properties
}

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Order } from 'somewhere_in_src';    

@Injectable()
export class FooService {
 ctor(private http: HttpClient){}

 fetch(startIndex: number, limit: number): Observable<Order[]> {
    let params = new HttpParams();
    params = params.set('startIndex',startIndex.toString()).set('limit',limit.toString());
    // base URL should not have ? in it at the en
    return this.http.get(this.baseUrl,{
       params
    })
    .map(res => res.results as Order[] || []); 
   // in case that the property results in the res POJO doesnt exist (res.results returns null) then return empty array ([])
  }
} 

I removed the catch section, as this could be archived through a HTTP interceptor. Check the docs. As example:

https://gist.github.com/jotatoledo/765c7f6d8a755613cafca97e83313b90

And to consume you just need to call it like:

// In some component for example
this.fooService.fetch(...).subscribe(data => ...); // data is Order[]

How to check Grants Permissions at Run-Time?

You can also query by following code snippet as backward compatible;

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) {
    //Do smthng
}

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

You need to install popperjs along with bootstrap to get rid of this error.Note that if you are using "bootstrap": "^4.4.1", and @popperjs/core v2.x combinations,bootstrap may not support popperjs version. So downgrade your version.

Option 1: npm install popper.js@^1.12.9 --save

and Add following script between jquery and bootstrap scripts.

"node_modules/popper.js/dist/umd/popper.min.js",

Option 2: Add following script tag to index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script

Restoring Nuget References?

Try re-installing the packages.

In the NuGet Package Manager Console enter the following command:

Update-Package -Reinstall -ProjectName Your.Project.Name

If you want to re-install packages and restore references for the whole solution omit the -ProjectName parameter.

android get real path by Uri.getPath()

This helped me to get uri from Gallery and convert to a file for Multipart upload

File file = FileUtils.getFile(this, fileUri);

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How to add a WiX custom action that happens only on uninstall (via MSI)?

The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.

Anyway, to have an action only execute during uninstall add a Condition element with:

REMOVE ~= "ALL"

the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.

PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.

Understanding typedefs for function pointers in C

A function pointer is like any other pointer, but it points to the address of a function instead of the address of data (on heap or stack). Like any pointer, it needs to be typed correctly. Functions are defined by their return value and the types of parameters they accept. So in order to fully describe a function, you must include its return value and the type of each parameter is accepts. When you typedef such a definition, you give it a 'friendly name' which makes it easier to create and reference pointers using that definition.

So for example assume you have a function:

float doMultiplication (float num1, float num2 ) {
    return num1 * num2; }

then the following typedef:

typedef float(*pt2Func)(float, float);

can be used to point to this doMulitplication function. It is simply defining a pointer to a function which returns a float and takes two parameters, each of type float. This definition has the friendly name pt2Func. Note that pt2Func can point to ANY function which returns a float and takes in 2 floats.

So you can create a pointer which points to the doMultiplication function as follows:

pt2Func *myFnPtr = &doMultiplication;

and you can invoke the function using this pointer as follows:

float result = (*myFnPtr)(2.0, 5.1);

This makes good reading: http://www.newty.de/fpt/index.html

How to remove an iOS app from the App Store

To remove an app from the App Store, deselect all territories in your app's Rights and Pricing section on the App Summary page accessible from the Manage Your Applications module. Your app status will change to Developer Removed from Sale and will be removed from the App Store until you make it available again using the Rights and Pricing section.

How to get current route in Symfony 2?

All I'm getting from that is _internal

I get the route name from inside a controller with $this->getRequest()->get('_route'). Even the code tuxedo25 suggested returns _internal

This code is executed in what was called a 'Component' in Symfony 1.X; Not a page's controller but part of a page which needs some logic.

The equivalent code in Symfony 1.X is: sfContext::getInstance()->getRouting()->getCurrentRouteName();

How do I convert a number to a letter in Java?

public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
    result = (char)('A' + value % 26 ) + result;
    value /= 26;
}
return result;
}

To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE `Table A` a
SET a.`text`=(
        SELECT group_concat(b.`B-num`,' from ',b.`date` SEPARATOR ' / ') 
        FROM `Table B` b WHERE (a.`A-num`=b.`A-num`)
)

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

Decreasing for loops in Python impossible?

>>> range(6, 0, -1)
[6, 5, 4, 3, 2, 1]

Go: panic: runtime error: invalid memory address or nil pointer dereference

Since I got here with my problem I will add this answer although it is not exactly relevant to the original question. When you are implementing an interface make sure you do not forget to add the type pointer on your member function declarations. Example:

type AnimalSounder interface {
    MakeNoise()
}

type Dog struct {
    Name string
    mean bool
    BarkStrength int
}

func (dog *Dog) MakeNoise() {
    //implementation
}

I forgot the *(dog Dog) part, I do not recommend it. Then you get into ugly trouble when calling MakeNoice on an AnimalSounder interface variable of type Dog.

Linq select to new object

This is a great article for syntax needed to create new objects from a LINQ query.

But, if the assignments to fill in the fields of the object are anything more than simple assignments, for example, parsing strings to integers, and one of them fails, it is not possible to debug this. You can not create a breakpoint on any of the individual assignments.

And if you move all the assignments to a subroutine, and return a new object from there, and attempt to set a breakpoint in that routine, you can set a breakpoint in that routine, but the breakpoint will never be triggered.

So instead of:

var query2 = from c in doc.Descendants("SuggestionItem")
                select new SuggestionItem
                       { Phrase = c.Element("Phrase").Value
                         Blocked = bool.Parse(c.Element("Blocked").Value),
                         SeenCount = int.Parse(c.Element("SeenCount").Value)
                       };

Or

var query2 = from c in doc.Descendants("SuggestionItem")
                         select new SuggestionItem(c);

I instead did this:

List<SuggestionItem> retList = new List<SuggestionItem>();

var query = from c in doc.Descendants("SuggestionItem") select c;

foreach (XElement item in query)
{
    SuggestionItem anItem = new SuggestionItem(item);
    retList.Add(anItem);
}

This allowed me to easily debug and figure out which assignment was failing. In this case, the XElement was missing a field I was parsing for to set in the SuggestionItem.

I ran into these gotchas with Visual Studio 2017 while writing unit tests for a new library routine.

Python 3 Online Interpreter / Shell

I recently came across Python 3 interpreter at CompileOnline.

How to define global variable in Google Apps Script

    var userProperties = PropertiesService.getUserProperties();


function globalSetting(){
  //creating an array
  userProperties.setProperty('gemployeeName',"Rajendra Barge");
  userProperties.setProperty('gemployeeMobile',"9822082320");
  userProperties.setProperty('gemployeeEmail'," [email protected]");
  userProperties.setProperty('gemployeeLastlogin',"03/10/2020");
  
  
  
}


var userProperties = PropertiesService.getUserProperties();
function showUserForm(){

  var templete = HtmlService.createTemplateFromFile("userForm");
  
  var html = templete.evaluate();
  html.setTitle("Customer Data");
  SpreadsheetApp.getUi().showSidebar(html);


}

function appendData(data){
 globalSetting();
 
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  ws.appendRow([data.date,
                data.name,
                data.Kindlyattention,
                data.senderName,
                data.customereMail,
                userProperties.getProperty('gemployeeName'),
                ,
                ,
                data.paymentTerms,
                ,
                userProperties.getProperty('gemployeeMobile'),
                userProperties.getProperty('gemployeeEmail'),
                Utilities.formatDate(new Date(), "GMT+05:30", "dd-MM-yyyy HH:mm:ss")
                
                
  ]);
  
}

function errorMessage(){

Browser.msgBox("! All fields are mandetory");

}

Redirect Windows cmd stdout and stderr to a single file

Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

PHP cURL HTTP CODE return 0

Try this after curl_exec to see what's the problem:

print curl_error($ch);

If it's print something like 'malformed' then check your URL format.

How can I pass a member function where a free function is expected?

If you actually don't need to use the instance a (i.e. you can make it static like @mathengineer 's answer) you can simply pass in a non-capture lambda. (which decay to function pointer)


#include <iostream>

class aClass
{
public:
   void aTest(int a, int b)
   {
      printf("%d + %d = %d", a, b, a + b);
   }
};

void function1(void (*function)(int, int))
{
    function(1, 1);
}

int main()
{
   //note: you don't need the `+`
   function1(+[](int a,int b){return aClass{}.aTest(a,b);}); 
}

Wandbox


note: if aClass is costly to construct or has side effect, this may not be a good way.

Convert date field into text in Excel

If that is one table and have nothing to do with this - the simplest solution can be copy&paste to notepad then copy&paste back to excel :P

ORA-00054: resource busy and acquire with NOWAIT specified

Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.

If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.

When do you use the "this" keyword?

You should not use "this" unless you absolutely must.

There IS a penalty associated with unnecessary verbosity. You should strive for code that is exactly as long as it needs to be, and no longer.

How to create empty constructor for data class in Kotlin Android

Non-empty secondary constructor for data class in Kotlin:

data class ChemicalElement(var name: String,
                           var symbol: String,
                           var atomicNumber: Int,
                           var atomicWeight: Double,
                           var nobleMetal: Boolean?) {

    constructor(): this("Silver",
                        "Ag", 
                        47,
                        107.8682,
                        true)
}

fun main() {
    var chemicalElement = ChemicalElement()
    println("RESULT: ${chemicalElement.symbol} means ${chemicalElement.name}")
    println(chemicalElement)
}

// RESULT: Ag means Silver
// ChemicalElement(name=Silver, symbol=Ag, atomicNumber=47, atomicWeight=107.8682, nobleMetal=true)

Empty secondary constructor for data class in Kotlin:

data class ChemicalElement(var name: String,
                           var symbol: String,
                           var atomicNumber: Int,
                           var atomicWeight: Double,
                           var nobleMetal: Boolean?) {

    constructor(): this("",
                        "", 
                        -1,
                        0.0,
                        null)
}

fun main() {
    var chemicalElement = ChemicalElement()
    println(chemicalElement)
}

// ChemicalElement(name=, symbol=, atomicNumber=-1, atomicWeight=0.0, nobleMetal=null)

How to set a header for a HTTP GET request, and trigger file download?

i want to post my solution here which was done AngularJS, ASP.NET MVC. The code illustrates how to download file with authentication.

WebApi method along with helper class:

[RoutePrefix("filess")]
class FileController: ApiController
{
    [HttpGet]
    [Route("download-file")]
    [Authorize(Roles = "admin")]
    public HttpResponseMessage DownloadDocument([FromUri] int fileId)
    {
        var file = "someFile.docx"// asking storage service to get file path with id
        return Request.ReturnFile(file);
    }
}

static class DownloadFIleFromServerHelper
{
    public static HttpResponseMessage ReturnFile(this HttpRequestMessage request, string file)
    {
        var result = request.CreateResponse(HttpStatusCode.OK);

        result.Content = new StreamContent(new FileStream(file, FileMode.Open, FileAccess.Read));
        result.Content.Headers.Add("x-filename", Path.GetFileName(file)); // letters of header names will be lowercased anyway in JS.
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = Path.GetFileName(file)
        };

        return result;
    }
}

Web.config file changes to allow sending file name in custom header.

<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
                <add name="Access-Control-Allow-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Expose-Headers" value="Authorization,Content-Type,x-filename" />
                <add name="Access-Control-Allow-Origin" value="*" />

Angular JS Service Part:

function proposalService($http, $cookies, config, FileSaver) {
        return {
                downloadDocument: downloadDocument
        };

    function downloadFile(documentId, errorCallback) {
    $http({
        url: config.apiUrl + "files/download-file?documentId=" + documentId,
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=utf-8",
            "Authorization": "Bearer " + $cookies.get("api_key")
        },
        responseType: "arraybuffer"  
        })
    .success( function(data, status, headers) {
        var filename = headers()['x-filename'];

        var blob = new Blob([data], { type: "application/octet-binary" });
        FileSaver.saveAs(blob, filename);
    })
    .error(function(data, status) {
        console.log("Request failed with status: " + status);
        errorCallback(data, status);
    });
};
};

Module dependency for FileUpload: angular-file-download (gulp install angular-file-download --save). Registration looks like below.

var app = angular.module('cool',
[
    ...
    require('angular-file-saver'),
])
. // other staff.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

You need to place google-services.json into app/ dir. And for each build type, there should be accordant director in app/src folder.

For example, if you have release and debug:

app/google-services.json
app/src/debug/google-services.json

In all google-services.json files you should specify correct package_name according to build type.

For example, inside debug dir it should be like {com.myapp}.debug

What's a good way to extend Error in JavaScript?

How about this solution?

Instead of throwing your custom Error using:

throw new MyError("Oops!");

You would wrap the Error object (kind of like a Decorator):

throw new MyError(Error("Oops!"));

This makes sure all of the attributes are correct, such as the stack, fileName lineNumber, et cetera.

All you have to do then is either copy over the attributes, or define getters for them. Here is an example using getters (IE9):

function MyError(wrapped)
{
        this.wrapped = wrapped;
        this.wrapped.name = 'MyError';
}

function wrap(attr)
{
        Object.defineProperty(MyError.prototype, attr, {
                get: function()
                {
                        return this.wrapped[attr];
                }
        });
}

MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

wrap('name');
wrap('message');
wrap('stack');
wrap('fileName');
wrap('lineNumber');
wrap('columnNumber');

MyError.prototype.toString = function()
{
        return this.wrapped.toString();
};

Javascript decoding html entities

There is a jQuery solution in this thread. Try something like this:

var decoded = $("<div/>").html('your string').text();

This sets the innerHTML of a new <div> element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized

Below solution is a clean work around.It does not compromises security because we are using same strict firewall.

The Steps for fixing is as below:

STEP 1 : Create a Class overriding StrictHttpFirewall as below.

package com.biz.brains.project.security.firewall;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpMethod;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.FirewalledRequest;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;

public class CustomStrictHttpFirewall implements HttpFirewall {
    private static final Set<String> ALLOW_ANY_HTTP_METHOD = Collections.unmodifiableSet(Collections.emptySet());

    private static final String ENCODED_PERCENT = "%25";

    private static final String PERCENT = "%";

    private static final List<String> FORBIDDEN_ENCODED_PERIOD = Collections.unmodifiableList(Arrays.asList("%2e", "%2E"));

    private static final List<String> FORBIDDEN_SEMICOLON = Collections.unmodifiableList(Arrays.asList(";", "%3b", "%3B"));

    private static final List<String> FORBIDDEN_FORWARDSLASH = Collections.unmodifiableList(Arrays.asList("%2f", "%2F"));

    private static final List<String> FORBIDDEN_BACKSLASH = Collections.unmodifiableList(Arrays.asList("\\", "%5c", "%5C"));

    private Set<String> encodedUrlBlacklist = new HashSet<String>();

    private Set<String> decodedUrlBlacklist = new HashSet<String>();

    private Set<String> allowedHttpMethods = createDefaultAllowedHttpMethods();

    public CustomStrictHttpFirewall() {
        urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);

        this.encodedUrlBlacklist.add(ENCODED_PERCENT);
        this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        this.decodedUrlBlacklist.add(PERCENT);
    }

    public void setUnsafeAllowAnyHttpMethod(boolean unsafeAllowAnyHttpMethod) {
        this.allowedHttpMethods = unsafeAllowAnyHttpMethod ? ALLOW_ANY_HTTP_METHOD : createDefaultAllowedHttpMethods();
    }

    public void setAllowedHttpMethods(Collection<String> allowedHttpMethods) {
        if (allowedHttpMethods == null) {
            throw new IllegalArgumentException("allowedHttpMethods cannot be null");
        }
        if (allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            this.allowedHttpMethods = ALLOW_ANY_HTTP_METHOD;
        } else {
            this.allowedHttpMethods = new HashSet<>(allowedHttpMethods);
        }
    }

    public void setAllowSemicolon(boolean allowSemicolon) {
        if (allowSemicolon) {
            urlBlacklistsRemoveAll(FORBIDDEN_SEMICOLON);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_SEMICOLON);
        }
    }

    public void setAllowUrlEncodedSlash(boolean allowUrlEncodedSlash) {
        if (allowUrlEncodedSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_FORWARDSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_FORWARDSLASH);
        }
    }

    public void setAllowUrlEncodedPeriod(boolean allowUrlEncodedPeriod) {
        if (allowUrlEncodedPeriod) {
            this.encodedUrlBlacklist.removeAll(FORBIDDEN_ENCODED_PERIOD);
        } else {
            this.encodedUrlBlacklist.addAll(FORBIDDEN_ENCODED_PERIOD);
        }
    }

    public void setAllowBackSlash(boolean allowBackSlash) {
        if (allowBackSlash) {
            urlBlacklistsRemoveAll(FORBIDDEN_BACKSLASH);
        } else {
            urlBlacklistsAddAll(FORBIDDEN_BACKSLASH);
        }
    }

    public void setAllowUrlEncodedPercent(boolean allowUrlEncodedPercent) {
        if (allowUrlEncodedPercent) {
            this.encodedUrlBlacklist.remove(ENCODED_PERCENT);
            this.decodedUrlBlacklist.remove(PERCENT);
        } else {
            this.encodedUrlBlacklist.add(ENCODED_PERCENT);
            this.decodedUrlBlacklist.add(PERCENT);
        }
    }

    private void urlBlacklistsAddAll(Collection<String> values) {
        this.encodedUrlBlacklist.addAll(values);
        this.decodedUrlBlacklist.addAll(values);
    }

    private void urlBlacklistsRemoveAll(Collection<String> values) {
        this.encodedUrlBlacklist.removeAll(values);
        this.decodedUrlBlacklist.removeAll(values);
    }

    @Override
    public FirewalledRequest getFirewalledRequest(HttpServletRequest request) throws RequestRejectedException {
        rejectForbiddenHttpMethod(request);
        rejectedBlacklistedUrls(request);

        if (!isNormalized(request)) {
            request.setAttribute("isNormalized", new RequestRejectedException("The request was rejected because the URL was not normalized."));
        }

        String requestUri = request.getRequestURI();
        if (!containsOnlyPrintableAsciiCharacters(requestUri)) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The requestURI was rejected because it can only contain printable ASCII characters."));
        }
        return new FirewalledRequest(request) {
            @Override
            public void reset() {
            }
        };
    }

    private void rejectForbiddenHttpMethod(HttpServletRequest request) {
        if (this.allowedHttpMethods == ALLOW_ANY_HTTP_METHOD) {
            return;
        }
        if (!this.allowedHttpMethods.contains(request.getMethod())) {
            request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the HTTP method \"" +
                    request.getMethod() +
                    "\" was not included within the whitelist " +
                    this.allowedHttpMethods));
        }
    }

    private void rejectedBlacklistedUrls(HttpServletRequest request) {
        for (String forbidden : this.encodedUrlBlacklist) {
            if (encodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
        for (String forbidden : this.decodedUrlBlacklist) {
            if (decodedUrlContains(request, forbidden)) {
                request.setAttribute("isNormalized",  new RequestRejectedException("The request was rejected because the URL contained a potentially malicious String \"" + forbidden + "\""));
            }
        }
    }

    @Override
    public HttpServletResponse getFirewalledResponse(HttpServletResponse response) {
        return new FirewalledResponse(response);
    }

    private static Set<String> createDefaultAllowedHttpMethods() {
        Set<String> result = new HashSet<>();
        result.add(HttpMethod.DELETE.name());
        result.add(HttpMethod.GET.name());
        result.add(HttpMethod.HEAD.name());
        result.add(HttpMethod.OPTIONS.name());
        result.add(HttpMethod.PATCH.name());
        result.add(HttpMethod.POST.name());
        result.add(HttpMethod.PUT.name());
        return result;
    }

    private static boolean isNormalized(HttpServletRequest request) {
        if (!isNormalized(request.getRequestURI())) {
            return false;
        }
        if (!isNormalized(request.getContextPath())) {
            return false;
        }
        if (!isNormalized(request.getServletPath())) {
            return false;
        }
        if (!isNormalized(request.getPathInfo())) {
            return false;
        }
        return true;
    }

    private static boolean encodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getContextPath(), value)) {
            return true;
        }
        return valueContains(request.getRequestURI(), value);
    }

    private static boolean decodedUrlContains(HttpServletRequest request, String value) {
        if (valueContains(request.getServletPath(), value)) {
            return true;
        }
        if (valueContains(request.getPathInfo(), value)) {
            return true;
        }
        return false;
    }

    private static boolean containsOnlyPrintableAsciiCharacters(String uri) {
        int length = uri.length();
        for (int i = 0; i < length; i++) {
            char c = uri.charAt(i);
            if (c < '\u0020' || c > '\u007e') {
                return false;
            }
        }

        return true;
    }

    private static boolean valueContains(String value, String contains) {
        return value != null && value.contains(contains);
    }

    private static boolean isNormalized(String path) {
        if (path == null) {
            return true;
        }

        if (path.indexOf("//") > -1) {
            return false;
        }

        for (int j = path.length(); j > 0;) {
            int i = path.lastIndexOf('/', j - 1);
            int gap = j - i;

            if (gap == 2 && path.charAt(i + 1) == '.') {
                // ".", "/./" or "/."
                return false;
            } else if (gap == 3 && path.charAt(i + 1) == '.' && path.charAt(i + 2) == '.') {
                return false;
            }

            j = i;
        }

        return true;
    }

}

STEP 2 : Create a FirewalledResponse class

package com.biz.brains.project.security.firewall;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

class FirewalledResponse extends HttpServletResponseWrapper {
    private static final Pattern CR_OR_LF = Pattern.compile("\\r|\\n");
    private static final String LOCATION_HEADER = "Location";
    private static final String SET_COOKIE_HEADER = "Set-Cookie";

    public FirewalledResponse(HttpServletResponse response) {
        super(response);
    }

    @Override
    public void sendRedirect(String location) throws IOException {
        // TODO: implement pluggable validation, instead of simple blacklisting.
        // SEC-1790. Prevent redirects containing CRLF
        validateCrlf(LOCATION_HEADER, location);
        super.sendRedirect(location);
    }

    @Override
    public void setHeader(String name, String value) {
        validateCrlf(name, value);
        super.setHeader(name, value);
    }

    @Override
    public void addHeader(String name, String value) {
        validateCrlf(name, value);
        super.addHeader(name, value);
    }

    @Override
    public void addCookie(Cookie cookie) {
        if (cookie != null) {
            validateCrlf(SET_COOKIE_HEADER, cookie.getName());
            validateCrlf(SET_COOKIE_HEADER, cookie.getValue());
            validateCrlf(SET_COOKIE_HEADER, cookie.getPath());
            validateCrlf(SET_COOKIE_HEADER, cookie.getDomain());
            validateCrlf(SET_COOKIE_HEADER, cookie.getComment());
        }
        super.addCookie(cookie);
    }

    void validateCrlf(String name, String value) {
        if (hasCrlf(name) || hasCrlf(value)) {
            throw new IllegalArgumentException(
                    "Invalid characters (CR/LF) in header " + name);
        }
    }

    private boolean hasCrlf(String value) {
        return value != null && CR_OR_LF.matcher(value).find();
    }
}

STEP 3: Create a custom Filter to suppress the RejectedException

package com.biz.brains.project.security.filter;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestRejectedExceptionFilter extends GenericFilterBean {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                RequestRejectedException requestRejectedException=(RequestRejectedException) servletRequest.getAttribute("isNormalized");
                if(Objects.nonNull(requestRejectedException)) {
                    throw requestRejectedException;
                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (RequestRejectedException requestRejectedException) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                log
                    .error(
                            "request_rejected: remote={}, user_agent={}, request_url={}",
                            httpServletRequest.getRemoteHost(),  
                            httpServletRequest.getHeader(HttpHeaders.USER_AGENT),
                            httpServletRequest.getRequestURL(), 
                            requestRejectedException
                    );

                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
}

STEP 4: Add the custom filter to spring filter chain in security configuration

@Override
protected void configure(HttpSecurity http) throws Exception {
     http.addFilterBefore(new RequestRejectedExceptionFilter(),
             ChannelProcessingFilter.class);
}

Now using above fix, we can handle RequestRejectedException with Error 404 page.

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

counting the number of lines in a text file

with for-loop:

std::ifstream myFile;
std::string line;
int lines;

myFile.open(path);

for(lines = 0; std::getline(myFile,line); lines++);

std::cout << lines << std::endl;

How do I get console input in javascript?

You can try something like process.argv, that is if you are using node.js to run the program.
console.log(process.argv) => Would print an array containing

[                                                                                                                                                                                          
  '/usr/bin/node',                                                                                                                                                                         
  '/home/user/path/filename.js',                                                                                                                                            
  'your_input'                                                                                                                                                                                   
]

You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


Example:

var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);

If you are building a command-line program then the npm package yargs would be really helpful.

when do you need .ascx files and how would you use them?

When you are building a basic asp.net website using webcontrols is a good idea when you want to be able to use your controls at more then one location in your website. Separating code from the layout ascx files will be holding the controls that are used to display the layout, the cs files that belong to the ascx files will be holding the code that fills those controls.

For some basic understanding of usercontrols you can try this website

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes

sp_spaceused ‘Tablename’

pandas convert some columns into rows

UPDATE
From v0.20, melt is a first order function, you can now use

df.melt(id_vars=["location", "name"], 
        var_name="Date", 
        value_name="Value")

  location    name        Date  Value
0        A  "test"    Jan-2010     12
1        B   "foo"    Jan-2010     18
2        A  "test"    Feb-2010     20
3        B   "foo"    Feb-2010     20
4        A  "test"  March-2010     30
5        B   "foo"  March-2010     25

OLD(ER) VERSIONS: <0.20

You can use pd.melt to get most of the way there, and then sort:

>>> df
  location  name  Jan-2010  Feb-2010  March-2010
0        A  test        12        20          30
1        B   foo        18        20          25
>>> df2 = pd.melt(df, id_vars=["location", "name"], 
                  var_name="Date", value_name="Value")
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
1        B   foo    Jan-2010     18
2        A  test    Feb-2010     20
3        B   foo    Feb-2010     20
4        A  test  March-2010     30
5        B   foo  March-2010     25
>>> df2 = df2.sort(["location", "name"])
>>> df2
  location  name        Date  Value
0        A  test    Jan-2010     12
2        A  test    Feb-2010     20
4        A  test  March-2010     30
1        B   foo    Jan-2010     18
3        B   foo    Feb-2010     20
5        B   foo  March-2010     25

(Might want to throw in a .reset_index(drop=True), just to keep the output clean.)

Note: pd.DataFrame.sort has been deprecated in favour of pd.DataFrame.sort_values.

How to import popper.js?

It turns out that Popper.js doesn't provide compiled files on its GitHub repository. Therefore, one has to compile the project on his/her own or download compiled files from CDNs. It cannot be automatically imported.

PHPExcel Make first row bold

$objPHPExcel->getActiveSheet()->getStyle('1:1')->getFont()->setBold(true);

That way you get the complete first row

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

Jacob Helwig mentions in his answer that:

It looks like rev-parse is being used without sufficient error checking before-hand

Commit 62f162f from Jeff King (peff) should improve the robustness of git rev-parse in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):

For cases where we do not match (e.g., "doesnotexist..HEAD"), we would then want to try to treat the argument as a filename.
try_difference() gets this right, and always unmunges in this case.
However, try_parent_shorthand() never unmunges, leading to incorrect error messages, or even incorrect results:

$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

What is the difference between 'my' and 'our' in Perl?

This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.

#!/usr/bin/perl

our $foo = "BAR";

print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";

Output:

BAR
BAZ

This won't work if you change 'our' to 'my'.

Save string to the NSUserDefaults?

Here For Swift i create two function which call for save and retrive value for key from Preference

may be this is help full for u

// for saving object

static func setObject(value:AnyObject ,key:String)
{
    let pref = NSUserDefaults.standardUserDefaults()
    pref.setObject(value, forKey: key)
    pref.synchronize()
}

static func getObject(key:String) -> AnyObject
{
    let pref = NSUserDefaults.standardUserDefaults()
    return pref.objectForKey(key)!
}

Making HTTP Requests using Chrome Developer tools

Since the Fetch API is supported by Chrome (and most other browsers), it is now quite easy to make HTTP requests from the devtools console.

To GET a JSON file for instance:

_x000D_
_x000D_
fetch('https://jsonplaceholder.typicode.com/posts/1')_x000D_
  .then(res => res.json())_x000D_
  .then(console.log)
_x000D_
_x000D_
_x000D_

Or to POST a new resource:

_x000D_
_x000D_
fetch('https://jsonplaceholder.typicode.com/posts', {_x000D_
  method: 'POST',_x000D_
  body: JSON.stringify({_x000D_
    title: 'foo',_x000D_
    body: 'bar',_x000D_
    userId: 1_x000D_
  }),_x000D_
  headers: {_x000D_
    'Content-type': 'application/json; charset=UTF-8'_x000D_
  }_x000D_
})_x000D_
.then(res => res.json())_x000D_
.then(console.log)
_x000D_
_x000D_
_x000D_

Chrome Devtools actually also support new async/await syntax (even though await normally only can be used within an async function):

const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
console.log(await response.json())

Notice that your requests will be subject to the same-origin policy, just like any other HTTP-request in the browser, so either avoid cross-origin requests, or make sure the server sets CORS-headers that allow your request.

Using a plugin (old answer)

As an addition to previously posted suggestions I've found the Postman plugin for Chrome to work very well. It allow you to set headers and URL parameters, use HTTP authentication, save request you execute frequently and so on.

"Specified argument was out of the range of valid values"

It seems that you are trying to get 5 items out of a collection with 5 items. Looking at your code, it seems you're starting at the second value in your collection at position 1. Collections are zero-based, so you should start with the item at index 0. Try this:

TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[0].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_rate");

Space between two divs

If you don't require support for IE6:

h1 {margin-bottom:20px;}
div + div {margin-top:10px;}

The second line adds spacing between divs, but will not add any before the first div or after the last one.

Split string with multiple delimiters in Python

This is how the regex look like:

import re
# "semicolon or (a comma followed by a space)"
pattern = re.compile(r";|, ")

# "(semicolon or a comma) followed by a space"
pattern = re.compile(r"[;,] ")

print pattern.split(text)

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

Passing a URL with brackets to curl

Globbing uses brackets, hence the need to escape them with a slash \. Alternatively, the following command-line switch will disable globbing:

--globoff (or the short-option version: -g)

Ex:

curl --globoff https://www.google.com?test[]=1

How do you keep parents of floated elements from collapsing?

Solution 1:

The most reliable and unobtrusive method appears to be this:

Demo: http://jsfiddle.net/SO_AMK/wXaEH/

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>?

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
}

?With a little CSS targeting, you don't even need to add a class to the parent DIV.

This solution is backward compatible with IE8 so you don't need to worry about older browsers failing.

Solution 2:

An adaptation of solution 1 has been suggested and is as follows:

Demo: http://jsfiddle.net/wXaEH/162/

HTML:

<div class="clearfix">
    <div style="float: left;">Div 1</div>
    <div style="float: left;">Div 2</div>
</div>?

CSS:

.clearfix::after { 
   content: " ";
   display: block; 
   height: 0; 
   clear: both;
   *zoom: expression( this.runtimeStyle['zoom'] = '1', this.innerHTML += '<div class="ie7-clear"></div>' );
}

.ie7-clear {
    display: block;
    clear: both;
}

This solution appears to be backward compatible to IE5.5 but is untested.

Solution 3:

It's also possible to set display: inline-block; and width: 100%; to emulate a normal block element while not collapsing.

Demo: http://jsfiddle.net/SO_AMK/ae5ey/

CSS:

.clearfix {
    display: inline-block;
    width: 100%;
}

This solution should be backward compatible with IE5.5 but has only been tested in IE6.

Where's my JSON data in my incoming Django request?

Its important to remember Python 3 has a different way to represent strings - they are byte arrays.

Using Django 1.9 and Python 2.7 and sending the JSON data in the main body (not a header) you would use something like:

mydata = json.loads(request.body)

But for Django 1.9 and Python 3.4 you would use:

mydata = json.loads(request.body.decode("utf-8"))

I just went through this learning curve making my first Py3 Django app!

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

Differences between ConstraintLayout and RelativeLayout

Reported by @davidpbr ConstraintLayout performance

I made two similar 7-child layouts, one each with a parent ConstraintLayout and RelativeLayout. Based on Android Studio method tracing tool, it appears the ConstraintLayout spends more time in onMeasure and performs additional work in onFinishInflate.

Library used (support-v4, appcompat-v7…):

com.android.support.constraint:constraint-layout:1.0.0-alpha1

Devices/Android versions reproduced on: Samsung Galaxy S6 (SM-G920A. Sorry, no Nexus atm). Android 5.0.2

Quick method tracing comparison:

1

Sample Github repo: https://github.com/OnlyInAmerica/ConstraintLayoutPerf

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

Python: TypeError: cannot concatenate 'str' and 'int' objects

The easiest and least confusing solution:

a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a  + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c

I found this on http://freecodeszone.blogspot.com/

Rounded table corners CSS only

This is css3, only recent non-IE<9 browser will support it.

Check out here, it derives the round property for all available browsers

How to specify line breaks in a multi-line flexbox layout?

Another possible solution that doesn't require to add any extra markup is to add some dynamic margin to separate the elements.

In the case of the example, this can be done with the help of calc(), just adding margin-left and margin-right to the 3n+2 element (2, 5, 8)

.item:nth-child(3n+2) {
  background: silver;
  margin: 10px calc(50% - 175px);
}

Snippet Example

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: gold;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px;_x000D_
}_x000D_
.item:nth-child(3n+2) {_x000D_
  background: silver;_x000D_
  margin: 10px calc(50% - 175px);_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
  <div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

How do I switch between command and insert mode in Vim?

Using jj

In my case, the .vimrc (or in gVim it is in _vimrc) setting below.

inoremap jj <Esc>   """ jj key is <Esc> setting

Why use prefixes on member variables in C++ classes

Those conventions are just that. Most shops use code conventions to ease code readability so anyone can easily look at a piece of code and quickly decipher between things such as public and private members.

Add column in dataframe from list

Just assign the list directly:

df['new_col'] = mylist

Alternative
Convert the list to a series or array and then assign:

se = pd.Series(mylist)
df['new_col'] = se.values

or

df['new_col'] = np.array(mylist)

How to replace NaNs by preceding values in pandas DataFrame?

In my case, we have time series from different devices but some devices could not send any value during some period. So we should create NA values for every device and time period and after that do fillna.

df = pd.DataFrame([["device1", 1, 'first val of device1'], ["device2", 2, 'first val of device2'], ["device3", 3, 'first val of device3']])
df.pivot(index=1, columns=0, values=2).fillna(method='ffill').unstack().reset_index(name='value')

Result:

        0   1   value
0   device1     1   first val of device1
1   device1     2   first val of device1
2   device1     3   first val of device1
3   device2     1   None
4   device2     2   first val of device2
5   device2     3   first val of device2
6   device3     1   None
7   device3     2   None
8   device3     3   first val of device3

How to install trusted CA certificate on Android device?

Did you try: Settings -> Security -> Install from SD Card? – Alexander Egger Dec 20 '10 at 20:11

I'm not sure why is this not an answer already, but I just followed this advice and it worked.

Getting current device language in iOS?

In Swift, there is a way simpler answer to get the current app language:

Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode!

It could be switched over like this for example:

let supportUrl: URL = {
    switch Locale(identifier: Bundle.main.preferredLocalizations[0]).languageCode {
    case "de":
        return Constants.supportUrlGerman

    default:
        return Constants.supportUrlEnglish
    }
}

I hope this helps!

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

Java Replace Character At Specific Position Of String?

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

this happened to me when I imported an Android Studio App into eclipse.

I figured out the andoridmanifest.xml file needs to be slightly modified when importing from android studio project. I created a new test project, and copied over the headings to make it match. voila, issue solved.

Display PDF file inside my android application

You can download the source from here(Display PDF file inside my android application)

Add this dependency in your gradle file:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


    </RelativeLayout>

MainActivity.java

package pdfviewer.pdfviewer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }


    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}

How to use if - else structure in a batch file?

AFAIK you can't do an if else in batch like you can in other languages, it has to be nested if's.

Using nested if's your batch would look like

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    ) ELSE (
        IF %F%==1 IF %C%==0(
        ::moving the file c to d
        move "%sourceFile%" "%destinationFile%"
        ) ELSE (
            IF %F%==0 IF %C%==1(
            ::copying a directory c from d, /s:  bos olanlar hariç, /e:bos olanlar dahil
            xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
            ) ELSE (
                IF %F%==0 IF %C%==0(
                ::moving a directory
                xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
                rd /s /q "%sourceMoveDirectory%"
                )
            )
        )
    )

or as James suggested, chain your if's, however I think the proper syntax is

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

correct PHP headers for pdf file download

Can you try this, readfile need the full file path.

        $filename='/pdf/jobs/pdffile.pdf';            
        $url_download = BASE_URL . RELATIVE_PATH . $filename;            

        //header("Content-type:application/pdf");   
        header("Content-type: application/octet-stream");                       
        header("Content-Disposition:inline;filename='".basename($filename)."'");            
        header('Content-Length: ' . filesize($filename));
        header("Cache-control: private"); //use this to open files directly                     
        readfile($filename);

When do you use POST and when do you use GET?

Use POST for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action. So a URL like:

http://myblog.org/admin/posts/delete/357

Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way.

POST is also more secure than GET, because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea.

One final note: POST can transmit a larger amount of information than GET. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.

MS Access: how to compact current database in VBA

If you have the database with a front end and a back end. You can use the following code on the main form of your front end main navigation form:

Dim sDataFile As String, sDataFileTemp As String, sDataFileBackup As String
Dim s1 As Long, s2 As Long

sDataFile = "C:\MyDataFile.mdb"
sDataFileTemp = "C:\MyDataFileTemp.mdb"
sDataFileBackup = "C:\MyDataFile Backup " & Format(Now, "YYYY-MM-DD HHMMSS") & ".mdb"

DoCmd.Hourglass True

'get file size before compact
Open sDataFile For Binary As #1
s1 = LOF(1)
Close #1

'backup data file
FileCopy sDataFile, sDataFileBackup

'only proceed if data file exists
If Dir(sDataFileBackup vbNormal) <> "" Then

        'compact data file to temp file
        On Error Resume Next
        Kill sDataFileTemp
        On Error GoTo 0
        DBEngine.CompactDatabase sDataFile, sDataFileTemp

        If Dir(sDataFileTemp, vbNormal) <> "" Then
            'delete old data file data file
            Kill sDataFile

            'copy temp file to data file
            FileCopy sDataFileTemp, sDataFile

            'get file size after compact
            Open sDataFile For Binary As #1
            s2 = LOF(1)
            Close #1

            DoCmd.Hourglass False
            MsgBox "Compact complete " & vbCrLf & vbCrLf _
                & "Size before: " & Round(s1 / 1024 / 1024, 2) & "Mb" & vbCrLf _
                & "Size after:    " & Round(s2 / 1024 / 1024, 2) & "Mb", vbInformation
        Else
            DoCmd.Hourglass False
            MsgBox "ERROR: Unable to compact data file"
        End If

Else
        DoCmd.Hourglass False
        MsgBox "ERROR: Unable to backup data file"
End If

DoCmd.Hourglass False

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt

Now, Next add this downloaded files into your project:

Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

MySQL Fire Trigger for both Insert and Update

In response to @Zxaos request, since we can not have AND/OR operators for MySQL triggers, starting with your code, below is a complete example to achieve the same.

1. Define the INSERT trigger:

DELIMITER //
DROP TRIGGER IF EXISTS my_insert_trigger//
CREATE DEFINER=root@localhost TRIGGER my_insert_trigger
    AFTER INSERT ON `table`
    FOR EACH ROW

BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    -- NEW.id is an example parameter passed to the procedure but is not required
    -- if you do not need to pass anything to your procedure.
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

2. Define the UPDATE trigger

DELIMITER //
DROP TRIGGER IF EXISTS my_update_trigger//

CREATE DEFINER=root@localhost TRIGGER my_update_trigger
    AFTER UPDATE ON `table`
    FOR EACH ROW
BEGIN
    -- Call the common procedure ran if there is an INSERT or UPDATE on `table`
    CALL procedure_to_run_processes_due_to_changes_on_table(NEW.id);
END//
DELIMITER ;

3. Define the common PROCEDURE used by both these triggers:

DELIMITER //
DROP PROCEDURE IF EXISTS procedure_to_run_processes_due_to_changes_on_table//

CREATE DEFINER=root@localhost PROCEDURE procedure_to_run_processes_due_to_changes_on_table(IN table_row_id VARCHAR(255))
READS SQL DATA
BEGIN

    -- Write your MySQL code to perform when a `table` row is inserted or updated here

END//
DELIMITER ;

You note that I take care to restore the delimiter when I am done with my business defining the triggers and procedure.

How to print the data in byte array as characters?

byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
    System.out.format("%d ", c);
}
System.out.println();

gets you

1 -2 5 66 

Doctrine - How to print out the real sql, not just the prepared statement?

Solution:1
====================================================================================

function showQuery($query)
{
    return sprintf(str_replace('?', '%s', $query->getSql()), $query->getParams());
}

// call function  
echo showQuery($doctrineQuery);

Solution:2
====================================================================================

function showQuery($query)
{
    // define vars              
    $output    = NULL;
    $out_query = $query->getSql();
    $out_param = $query->getParams();

    // replace params
   for($i=0; $i<strlen($out_query); $i++) {
       $output .= ( strpos($out_query[$i], '?') !== FALSE ) ? "'" .str_replace('?', array_shift($out_param), $out_query[$i]). "'" : $out_query[$i];
   }

   // output
   return sprintf("%s", $output);
}

// call function  
echo showQuery($doctrineQueryObject);

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.

"Strict Standards: Only variables should be passed by reference" error

Instead of parsing it manually it's better to use pathinfo function:

$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];

How to insert TIMESTAMP into my MySQL table?

In addition to checking your table setup to confirm that the field is set to NOT NULL with a default of CURRENT_TIMESTAMP, you can insert date/time values from PHP by writing them in a string format compatible with MySQL.

 $timestamp = date("Y-m-d H:i:s");

This will give you the current date and time in a string format that you can insert into MySQL.

How to reset par(mfrow) in R

You can reset the plot by doing this:

dev.off()

SQL: Return "true" if list of records exists?

I know this is old but I think this will help anyone else who comes looking...

SELECT CAST(COUNT(ProductID) AS bit) AS [EXISTS] FROM Products WHERE(ProductID = @ProductID)

This will ALWAYS return TRUE if exists and FALSE if it doesn't (as opposed to no row).

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

How can I convert an RGB image into grayscale in Python?

If you're using NumPy/SciPy already you may as well use:

scipy.ndimage.imread(file_name, mode='L')

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Renaming a branch in GitHub

As mentioned, delete the old one on GitHub and re-push, though the commands used are a bit more verbose than necessary:

git push origin :name_of_the_old_branch_on_github
git push origin new_name_of_the_branch_that_is_local

Dissecting the commands a bit, the git push command is essentially:

git push <remote> <local_branch>:<remote_branch>

So doing a push with no local_branch specified essentially means "take nothing from my local repository, and make it the remote branch". I've always thought this to be completely kludgy, but it's the way it's done.

As of Git 1.7 there is an alternate syntax for deleting a remote branch:

git push origin --delete name_of_the_remote_branch

As mentioned by @void.pointer in the comments

Note that you can combine the 2 push operations:

git push origin :old_branch new_branch

This will both delete the old branch and push the new one.

This can be turned into a simple alias that takes the remote, original branch and new branch name as arguments, in ~/.gitconfig:

[alias]
    branchm = "!git branch -m $2 $3 && git push $1 :$2 $3 -u #"

Usage:

git branchm origin old_branch new_branch

Note that positional arguments in shell commands were problematic in older (pre 2.8?) versions of Git, so the alias might vary according to the Git version. See this discussion for details.

Disable webkit's spin buttons on input type="number"?

The below css works for both Chrome and Firefox

input[type=number]::-webkit-outer-spin-button,
input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

input[type=number] {
    -moz-appearance:textfield;
}

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

This error

Failure [INSTALL_FAILED_OLDER_SDK]

Means that you're trying to install an app that has a higher minSdkVersion specified in its manifest than the device's API level. Change that number to 8 and it should work. I'm not sure about the other error, but it may be related to this one.

Angular cli generate a service and include the provider in one step

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts

how do I get a new line, after using float:left?

Also such way

<br clear="all" />

What is the difference between "::" "." and "->" in c++

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

Google Maps v2 - set both my location and zoom in

You cannot animate two things (like zoom in and go to my location) in one google map?

From a coding standpoint, you would do them sequentially:

    CameraUpdate center=
        CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

    map.moveCamera(center);
    map.animateCamera(zoom);

Here, I move the camera first, then animate the camera, though both could be animateCamera() calls. Whether GoogleMap consolidates these into a single event, I can't say, as it goes by too fast. :-)

Here is the sample project from which I pulled the above code.


Sorry, this answer is flawed. See Rob's answer for a way to truly do this in one shot, by creating a CameraPosition and then creating a CameraUpdate from that CameraPosition.

Reload the page after ajax success

use this Reload page

success: function(data){
   if(data.success == true){ // if true (1)
      setTimeout(function(){// wait for 5 secs(2)
           location.reload(); // then reload the page.(3)
      }, 5000); 
   }
}

Is it possible to animate scrollTop with jQuery?

But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles

Make an image responsive - the simplest way

I would also recommend to use all the CSS properties in a different file than the HTML file, so you can have your code organized better.

So to make your img responsive, I would do:

First, name your <img> tag using a class or id attribute in your HTML file:

<img src="IMAGE LINK" border="0" class="responsive-image" alt="Null">

Then, in my CSS file I would make the changes to make it responsive:

.responsive-image {
  height: auto;
  width: 100%;
}

How to assign a heredoc value to a variable in Bash?

I found myself having to read a string with NULL in it, so here is a solution that will read anything you throw at it. Although if you actually are dealing with NULL, you will need to deal with that at the hex level.

$ cat > read.dd.sh

read.dd() {
     buf= 
     while read; do
        buf+=$REPLY
     done < <( dd bs=1 2>/dev/null | xxd -p )

     printf -v REPLY '%b' $( sed 's/../ \\\x&/g' <<< $buf )
}

Proof:

$ . read.dd.sh
$ read.dd < read.dd.sh
$ echo -n "$REPLY" > read.dd.sh.copy
$ diff read.dd.sh read.dd.sh.copy || echo "File are different"
$ 

HEREDOC example (with ^J, ^M, ^I):

$ read.dd <<'HEREDOC'
>       (TAB)
>       (SPACES)
(^J)^M(^M)
> DONE
>
> HEREDOC

$ declare -p REPLY
declare -- REPLY="  (TAB)
      (SPACES)
(^M)
DONE

"

$ declare -p REPLY | xxd
0000000: 6465 636c 6172 6520 2d2d 2052 4550 4c59  declare -- REPLY
0000010: 3d22 0928 5441 4229 0a20 2020 2020 2028  =".(TAB).      (
0000020: 5350 4143 4553 290a 285e 4a29 0d28 5e4d  SPACES).(^J).(^M
0000030: 290a 444f 4e45 0a0a 220a                 ).DONE

CSS flexbox not working in IE10

Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/

edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/

The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

Dialog to pick image from gallery or from camera

I have merged some solutions to make a complete util for picking an image from Gallery or Camera. These are the features of ImagePicker util gist (also in a Github lib):

  • Merged intents for Gallery and Camera resquests.
  • Resize selected big images (e.g.: 2500 x 1600)
  • Rotate image if necesary

Screenshot:

ImagePicker starting intent

Edit: Here is a fragment of code to get a merged Intent for Gallery and Camera apps together. You can see the full code at ImagePicker util gist (also in a Github lib):

public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
    List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
    for (ResolveInfo resolveInfo : resInfo) {
        String packageName = resolveInfo.activityInfo.packageName;
        Intent targetedIntent = new Intent(intent);
        targetedIntent.setPackage(packageName);
        list.add(targetedIntent);
    }
    return list;
}

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

How do I bind the enter key to a function in tkinter?

Try running the following program. You just have to be sure your window has the focus when you hit Return--to ensure that it does, first click the button a couple of times until you see some output, then without clicking anywhere else hit Return.

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Then you just have tweak things a little when making both the button click and hitting Return call the same function--because the command function needs to be a function that takes no arguments, whereas the bind function needs to be a function that takes one argument(the event object):

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event=None):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

Or, you can just forgo using the button's command argument and instead use bind() to attach the onclick function to the button, which means the function needs to take one argument--just like with Return:

import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")

def onclick(event):
    print("You clicked the button")

root.bind('<Return>', onclick)

button = tk.Button(root, text="click me")
button.bind('<Button-1>', onclick)
button.pack()

root.mainloop()

Here it is in a class setting:

import tkinter as tk

class Application(tk.Frame):
    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry("300x200")

        tk.Frame.__init__(self, self.root)
        self.create_widgets()

    def create_widgets(self):
        self.root.bind('<Return>', self.parse)
        self.grid()

        self.submit = tk.Button(self, text="Submit")
        self.submit.bind('<Button-1>', self.parse)
        self.submit.grid()

    def parse(self, event):
        print("You clicked?")

    def start(self):
        self.root.mainloop()


Application().start()

How to show soft-keyboard when edittext is focused

This is wild, but actually does work

fun showKeyboard(view: View) {
    try {
        InputMethodManager::class.java.getMethod(
                "showSoftInputUnchecked",
                Int::class.javaPrimitiveType,
                ResultReceiver::class.java
        ).apply {
            isAccessible = true
            invoke(view.context.inputMethodManager, 0, null)
        }
    }
    catch (e: Exception) {
       e.printStackTrace()
    }
}

django order_by query set, ascending and descending

Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.

class MyModel(models.Model):

    check_in = models.DateField()

    class Meta:
        ordering = ('-check_in',)

how to set the background color of the whole page in css

The body's size is dynamic, it is only as large as the size of its contents. In the css file you could use: * {background-color: black} // All elements now have a black background.

or

html {background-color: black} // The page now have a black background, all elements remain the same.

Find a class somewhere inside dozens of JAR files?

ClassFinder is a program that's designed to solve this problem. It allows you to search recursively through directories and jar files to find all instances of a class matching a pattern. It is written in Java, not python. It has a nice GUI which makes it easy to use. And it runs fast. This release is precompiled in a runnable jar so you don't have to build it from source.

Download it here: ClassFinder 1.0

Component is part of the declaration of 2 modules

This module is added automatically when you run ionic command. However it's not necessery. So an alternative solution is to remove add-event.module.ts from the project.

How to get UTC value for SYSDATE on Oracle

You can use

SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;

You may also need to change your timezone

ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';

Or read it

SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has already implemented promises, so it's better to use this technology and not move events logic to options parameter. I made a jQuery plugin that adds progress promise and now it's easy to use just as other promises:

$.ajax(url)
  .progress(function(){
    /* do some actions */
  })
  .progressUpload(function(){
    /* do something on uploading */
  });

Check it out at github

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

How can I update npm on Windows?

This works fine for me to update npm on Windows 7 x64:

  • Windows start
  • All Programs
  • Node.js
  • Node.js command prompt (alternative click)
  • Run as administrator

    $ npm -g install npm

  • remove C:\Program Files\nodejs\npm.cmd the new npm will be at C:\Users\username\appdata\roaming\npm\npm.cmd

Hope this helps.

Can I get the name of the current controller in the view?

Use controller.controller_name

In the Rails Guides, it says:

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values

ActionController Parameters

So let's say you have a CSS class active , that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages controller with an about action, you can then highlight the link like so in your view:

<li>
  <a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
      About Us
  </a>
</li>

Entity Framework Queryable async

The problem seems to be that you have misunderstood how async/await work with Entity Framework.

About Entity Framework

So, let's look at this code:

public IQueryable<URL> GetAllUrls()
{
    return context.Urls.AsQueryable();
}

and example of it usage:

repo.GetAllUrls().Where(u => <condition>).Take(10).ToList()

What happens there?

  1. We are getting IQueryable object (not accessing database yet) using repo.GetAllUrls()
  2. We create a new IQueryable object with specified condition using .Where(u => <condition>
  3. We create a new IQueryable object with specified paging limit using .Take(10)
  4. We retrieve results from database using .ToList(). Our IQueryable object is compiled to sql (like select top 10 * from Urls where <condition>). And database can use indexes, sql server send you only 10 objects from your database (not all billion urls stored in database)

Okay, let's look at first code:

public async Task<IQueryable<URL>> GetAllUrlsAsync()
{
    var urls = await context.Urls.ToListAsync();
    return urls.AsQueryable();
}

With the same example of usage we got:

  1. We are loading in memory all billion urls stored in your database using await context.Urls.ToListAsync();.
  2. We got memory overflow. Right way to kill your server

About async/await

Why async/await is preferred to use? Let's look at this code:

var stuff1 = repo.GetStuff1ForUser(userId);
var stuff2 = repo.GetStuff2ForUser(userId);
return View(new Model(stuff1, stuff2));

What happens here?

  1. Starting on line 1 var stuff1 = ...
  2. We send request to sql server that we want to get some stuff1 for userId
  3. We wait (current thread is blocked)
  4. We wait (current thread is blocked)
  5. .....
  6. Sql server send to us response
  7. We move to line 2 var stuff2 = ...
  8. We send request to sql server that we want to get some stuff2 for userId
  9. We wait (current thread is blocked)
  10. And again
  11. .....
  12. Sql server send to us response
  13. We render view

So let's look to an async version of it:

var stuff1Task = repo.GetStuff1ForUserAsync(userId);
var stuff2Task = repo.GetStuff2ForUserAsync(userId);
await Task.WhenAll(stuff1Task, stuff2Task);
return View(new Model(stuff1Task.Result, stuff2Task.Result));

What happens here?

  1. We send request to sql server to get stuff1 (line 1)
  2. We send request to sql server to get stuff2 (line 2)
  3. We wait for responses from sql server, but current thread isn't blocked, he can handle queries from another users
  4. We render view

Right way to do it

So good code here:

using System.Data.Entity;

public IQueryable<URL> GetAllUrls()
{
   return context.Urls.AsQueryable();
}

public async Task<List<URL>> GetAllUrlsByUser(int userId) {
   return await GetAllUrls().Where(u => u.User.Id == userId).ToListAsync();
}

Note, than you must add using System.Data.Entity in order to use method ToListAsync() for IQueryable.

Note, that if you don't need filtering and paging and stuff, you don't need to work with IQueryable. You can just use await context.Urls.ToListAsync() and work with materialized List<Url>.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

Try this

SELECT t1.*
FROM 
 some_table t1,
  (SELECT relevant_field
  FROM some_table
  GROUP BY relevant_field
  HAVING COUNT (*) > 1) t2
WHERE
 t1.relevant_field = t2.relevant_field;

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="mycheck" type="checkbox">
    </body>

    <script language="javascript">
        var=check;
        document.getElementById("mycheck");
        check.checked="false";
    </script>
</html>

How to get a variable type in Typescript?

I suspect you can adjust your approach a little and use something along the lines of the example here:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Update MongoDB field using value of another field

I tried the above solution but I found it unsuitable for large amounts of data. I then discovered the stream feature:

MongoClient.connect("...", function(err, db){
    var c = db.collection('yourCollection');
    var s = c.find({/* your query */}).stream();
    s.on('data', function(doc){
        c.update({_id: doc._id}, {$set: {name : doc.firstName + ' ' + doc.lastName}}, function(err, result) { /* result == true? */} }
    });
    s.on('end', function(){
        // stream can end before all your updates do if you have a lot
    })
})

500 Internal Server Error for php file not for html

500 Internal Server Error is shown if your php code has fatal errors but error displaying is switched off. You may try this to see the error itself instead of 500 error page:

In your php file:

ini_set('display_errors', 1);

In .htaccess file:

php_flag display_errors 1

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

I had the same issue using a node module with a react application written in typescript. The module was successfully installed using npm i --save my-module. It is written in javascript and exports a Client class.

With:

import * as MyModule from 'my-module';
let client: MyModule.Client = new MyModule.Client();

Compilation fails with the error:

Could not find a declaration file for module 'my-module'. 
'[...]/node_modules/my-module/lib/index.js' implicitly has an 'any' type.
  Try `npm install @types/my-module` if it exists or add a new declaration (.d.ts) file containing `declare module 'my-module';`

@types/my-module does not exist, so I added a my-module.d.ts file next to the one where my-module is imported, with the suggested line. I then got the error:

Namespace '"my-module"' has no exported member 'Client'.

The client is actually exported and works normally if I use it in a js app. Also, the previous message tells me that the compiler is looking in the right file (/node_modules/my-module/lib/index.js is defined in my-module/package.json "main" element).

I solved the issue by telling the compiler I do not care about implicit any, that is, I set to false the following line of the tsconfig.json file:

    "noImplicitAny": false,

What does "ulimit -s unlimited" do?

When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.

To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s. If we remove that limit via ulimit -s unlimited, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.

int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.

Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.

Impact on performace is minor but does exist. Using the time command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).

IPhone/IPad: How to get screen width programmatically?

Take a look at UIScreen.

eg.

CGFloat width = [UIScreen mainScreen].bounds.size.width;

Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).

UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGFloat width = CGRectGetWidth(self.view.bounds);
}

If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.

How to select first parent DIV using jQuery?

Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' ');

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' ');

How to store custom objects in NSUserDefaults

Synchronize the data/object that you have saved into NSUserDefaults

-(void)saveCustomObject:(Player *)object
{ 
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [prefs setObject:myEncodedObject forKey:@"testing"];
    [prefs synchronize];
}

Hope this will help you. Thanks

urllib2 and json

To read json response use json.loads(). Here is the sample.

import json
import urllib
import urllib2

post_params = {
    'foo' : bar
}

params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

How to check if android checkbox is checked within its onClick method (declared in XML)?

This will do the trick:

  public void itemClicked(View v) {
    if (((CheckBox) v).isChecked()) {
        Toast.makeText(MyAndroidAppActivity.this,
           "Checked", Toast.LENGTH_LONG).show();
    }
  }

Shell script : How to cut part of a string

$ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
9
10

Python: Append item to list N times

Use extend to add a list comprehension to the end.

l.extend([x for i in range(100)])

See the Python docs for more information.

Generating a random hex color code with PHP

This is heavily based on the @Galen version above, however, I wanted to add range control that could limit the colour produced to be red, green, blue, lighter or darker. It might be of use to others.

function random_colour_part($lower, $upper)
{
    //randomly select colour in range and convert to hexidecimal
    return str_pad(dechex(mt_rand($lower, $upper)), 2, '0', STR_PAD_LEFT);
}

function random_colour($colour)
{
    //loop through colour
    foreach ($colour as $key => $value)
    {
        //retrieve each r,g,b colour range and generate random hexidecimal colour
        if ($key == "r") $r = random_colour_part($value[0], $value[1]);
        if ($key == "g") $g = random_colour_part($value[0], $value[1]);
        if ($key == "b") $b = random_colour_part($value[0], $value[1]);
    }

    //return hexidecimal colour
    return "#" . $r . $g . $b;
}

//generate a random red-based colour
echo random_colour(["r"=>[0,255], "g"=>[0,0], "b"=>[0,0]]);

//generate a random light green-based colour (use only half of the 255 range)
echo random_colour(["r"=>[0,0], "g"=>[127,255], "b"=>[0,0]]);

//generate a random colour of any sort
echo random_colour(["r"=>[0,255], "g"=>[0,255], "b"=>[0,255]]);

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)

or

  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create module-info.java file

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

How can I remove Nan from list Python/NumPy

import numpy as np

mylist = [3, 4, 5, np.nan]
l = [x for x in mylist if ~np.isnan(x)]

This should remove all NaN. Of course, I assume that it is not a string here but actual NaN (np.nan).

How can I save a base64-encoded image to disk?

Converting from file with base64 string to png image.

4 variants which works.

var {promisify} = require('util');
var fs = require("fs");

var readFile = promisify(fs.readFile)
var writeFile = promisify(fs.writeFile)

async function run () {

  // variant 1
  var d = await readFile('./1.txt', 'utf8')
  await writeFile("./1.png", d, 'base64')

  // variant 2
  var d = await readFile('./2.txt', 'utf8')
  var dd = new Buffer(d, 'base64')
  await writeFile("./2.png", dd)

  // variant 3
  var d = await readFile('./3.txt')
  await writeFile("./3.png", d.toString('utf8'), 'base64')

  // variant 4
  var d = await readFile('./4.txt')
  var dd = new Buffer(d.toString('utf8'), 'base64')
  await writeFile("./4.png", dd)

}

run();

Format date as dd/MM/yyyy using pipes

Angular: 8.2.11

<td>{{ data.DateofBirth | date }}</td>

Output: Jun 9, 1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>

Output: 09/06/1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>

Output: 09/06/1973 12:00 AM

Passing the argument to CMAKE via command prompt

CMake 3.13 on Ubuntu 16.04

This approach is more flexible because it doesn't constraint MY_VARIABLE to a type:

$ cat CMakeLists.txt 
message("MY_VARIABLE=${MY_VARIABLE}")
if( MY_VARIABLE ) 
    message("MY_VARIABLE evaluates to True")
endif()

$ mkdir build && cd build

$ cmake ..
MY_VARIABLE=
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=True
MY_VARIABLE=True
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=False
MY_VARIABLE=False
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=1
MY_VARIABLE=1
MY_VARIABLE evaluates to True
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

$ cmake .. -DMY_VARIABLE=0
MY_VARIABLE=0
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/build

JQuery .on() method with multiple event handlers to one selector

That's the other way around. You should write:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, "td");