prompt stringlengths 49 4.73k | response stringlengths 238 35k |
|---|---|
Iterating through a golang map
I have a map of type: `map[string]interface{}`
And finally, I get to create something like (after deserializing from a yml file using goyaml)
```
mymap = map[foo:map[first: 1] boo: map[second: 2]]
```
How can I iterate through this map? I tried the following:
```
for k, v := ran... | For example,
```
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]int
m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
//m = map[foo:map[first: 1] boo: map[second: 2]]
fmt.Println("m:", m)
for k, v := range m {
fmt.Println("k:... |
Ingress Nginx - how to serve assets to application
I have an issue, I am deploying an application on [hostname]/product/console, but the .css .js files are being requested from [hostname]/product/static, hence they are not being loaded and I get 404.
I have tried `nginx.ingress.kubernetes.io/rewrite-target:` to no av... | **TL;DR**
To diagnose the reason why you get error 404 you can check in `nginx-ingress` controller pod logs. You can do it with below command:
`kubectl logs -n ingress-nginx INGRESS_NGINX_CONTROLLER_POD_NAME`
You should get output similar to this (depending on your use case):
```
CLIENT_IP - - [12/May/2020:1... |
why ({}+{})="[object Object][object Object]"?
I have tested the code:
```
{}+{} = NaN;
({}+{}) = "[object Object][object Object]";
```
Why does adding the `()` change the result?
| `{}+{}` is a *block* followed by an expression. The first `{}` is the block (like the kind you attach to an `if` statement), the `+{}` is the expression. The first `{}` is a block because when the parser is looking for a statement and sees `{`, it interprets it as the opening of a block. That block, being empty, does n... |
ZFS storage on Docker
I would like to try out ZFS on Ubuntu(16.04) docker container. Followed the following <https://docs.docker.com/engine/userguide/storagedriver/zfs-driver/>
```
> lsmod | grep zfs
zfs 2813952 5
zunicode 331776 1 zfs
zcommon 57344 1 zfs
znvpair ... | Assuming you have:
- a ZFS pool (let's call it `data`)
- a ZFS dataset mounted on `/var/lib/docker` (created with a command along the line of: `zfs create -o mountpoint=/var/lib/docker data/docker`)
Then:
Stop your docker daemon (eg. `systemctl stop docker.service`)
Create a file `/etc/docker/daemon.json` or am... |
How to return the result from Task?
I have the following methods:
```
public int getData() { return 2; } // suppose it is slow and takes 20 sec
// pseudocode
public int GetPreviousData()
{
Task<int> t = new Task<int>(() => getData());
return _cachedData; // some previous value
_cachedData = t.Result; //... | You might want to use an `out` parameter here:
```
public Task<int> GetPreviousDataAsync(out int cachedData)
{
Task<int> t = Task.Run(() => getData());
cachedData = _cachedData; // some previous value
return t; // _cachedData == 2
}
int cachedData;
cachedData = await GetPreviousDataAsync(out int cachedD... |
Most efficient way to find an entry in a C++ vector
I'm trying to construct an output table containing 80 rows of table status, that could be `EMPTY` or `USED` as below
```
+-------+-------+
| TABLE | STATE |
+-------+-------+
| 00 | USED |
| 01 | EMPTY |
| 02 | EMPTY |
..
..
| 79 | EMPTY |
+-------+--... | # Header files
It's strange that this code uses the C header `<string.h>` but the C++ versions of `<cmath>`, `<ctime>` and `<cstdlib>`. I recommend sticking to the C++ headers except on the rare occasions that you need to compile the same code with a C compiler. In this case, I don't see anything using `<cstring>`, s... |
When searchController is active, status bar style changes
Throughout my app I have set the status bar style to light content.[](https://i.stack.imgur.com/st8JB.png)
However, when the search controller is active, it resets to the default style: [![ent... | a couple of option, and this could be a problem that is a bug, but in the mean time, have you tried this:
**Option 1:**
info.plist, set up the option in your info.plist for "Status bar style", this is a string value with the value of "UIStatusBarStyleLightContent"
Also, in your infor.plist, set up the variable "... |
Remote Desktop Forgets Multi Monitor Configuration
By default, I RDP from my personal PC to my work laptop, in order to make use of all my monitors without needing to resort to a KVM.
On my old laptop, it would remember the position of windows between RDP sessions, provided that I had not logged into the machine phys... | I think this is a bug courtesy of the latest [two] windows updates (1903 as is listed in the tags in the original post.. but also the more recently released 1909) because I had the same exact issue that was resolved by rollback to 1809.
I have a 12 monitor local computer and rdp into a host computer with only 1 monit... |
Does NSPasteboard retain owner objects?
You can call `NSPasteboard` like this:
```
[pboard declareTypes:types owner:self];
```
Which means that the pasteboard will later ask the owner to supply data for a type as needed. However, what I can't find from the docs (and maybe I've missed something bleeding obvious), i... | The docs:
>
> *newOwner*
>
>
> The object responsible for writing
> data to the pasteboard, or nil if you
> provide data for all types
> immediately. If you specify a newOwner
> object, it must support all of the
> types declared in the newTypes
> parameter and must remain valid for as
> long as the data i... |
I can't start a new project on Netbeans
## The issue:
When I open the "add new project" dialog (screenshot below), I can't create a new project. The loading message (hourglass icon) stays on forever. Except for "cancel", the other buttons are disabled.
It was working fine a few days ago, I haven't changed any sett... | Just posted the same question [here](https://askubuntu.com/questions/326933/netbeans-broken-after-openjdk-update) ... the solution for me was to downgrade OpenJDK from **6b27** to **6b24** (look at the link for details).
My NetBeans was looking ***excactly*** like in your sreenshot and also had some other strange pro... |
Recyclerview item click ripple effect
I am trying to add `Ripple` Effect to `RecyclerView`'s item. I had a look online, but could not find what I need. I have tried `android:background` attribute to the `RecyclerView` itself and set it to `"?android:selectableItemBackground"` but it did not work.:
My Parent layout is... | Adding the `android:background="?attr/selectableItemBackground"` to the top most parent of your item layout should do the trick.
However in some cases it still misses the animation, adding the `android:clickable="true"` does it.
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.... |
C++ name mangling and linker symbol resolution
The name mangling schemes of C++ compilers vary, but they are documented publicly. Why aren't linkers made to decode a mangled symbol from an object file and attempt to find a mangled version via any of the mangling conventions across the other object files/static librarie... | Name mangling is a very small part of the problem.
Object layout is only defined in the C++ standard for a very restricted set of classes (essentially only standard layout types - and then only as much as the C standard does, alignment and padding are still to be considered). For anything that has virtuals, any form ... |
apply function not changing original value
Related to question on this page: [Randomly associate elements of two vectors given conditions](https://stackoverflow.com/questions/25221199/randomly-associate-elements-of-two-vectors-given-conditions)
If I have following data:
```
loss=c(45,10,5,1)
capitals = structure(li... | `apply` is evaluating a function, and assignment within functions do not affect the enclosing environment. A copy is being modified, and that copy is destroyed when the function exits.
Instead, to make use of `apply`, you should build an object, letting `apply` return each element. Something like this perhaps:
```... |
IIS\_IUSRS and IUSR permissions in IIS8
I've just moved away from IIS6 on Win2003 to IIS8 on Win2012 for hosting ASP.NET applications.
Within one particular folder in my application I need to Create & Delete files. After copying the files to the new server, I kept seeing the following errors when I tried to delete fi... | I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.
In short - **you do not need to edit any Windows user account privileges at all**. Doing so only introduces risk. The process is entirely managed in... |
How much space does BigInteger use?
How many bytes of memory does a BigInteger object use in general ?
| BigInteger internally uses an `int[]` to represent the huge numbers you use.
Thus it really **depends on the size of the number you store in it**. The `int[]` will grow if the current number doesn't fit in dynamically.
To get the number of bytes your `BigInteger` instance *currently* uses, you can make use of the `In... |
Single quote Issue when executing Linux command in Java
I need to execute Linux command like this using Runtime.getRuntime().exec() :
```
/opt/ie/bin/targets --a '10.1.1.219 10.1.1.36 10.1.1.37'
```
Basically, this command is to connect each targets to server one by one (10.1.1.219, 10.1.1.36, 10.1.1.37). It works... | Quote characters are interpreted by the shell, to control how it splits up the command line into a list of arguments. But when you call `exec` from Java, you're not using a shell; you're invoking the program directly. When you pass a single `String` to `exec`, it's split up into command arguments using a `StringTokeniz... |
Python csv.DictReader: parse string?
I am downloading a CSV file directly from a URL using `requests`.
How can I parse the resulting string with `csv.DictReader`?
Right now I have this:
```
r = requests.get(url)
reader_list = csv.DictReader(r.text)
print reader_list.fieldnames
for row in reader_list:
print ... | From the documentation of [`csv`](https://docs.python.org/3/library/csv.html#csv.reader), the first argument to [`csv.reader`](https://docs.python.org/3/library/csv.html#csv.reader) or [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictReader) is `csvfile` -
>
> *csvfile* can be any object which ... |
Regular expression to check if a String is a positive natural number
I want to check if a string is a positive natural number but I don't want to use `Integer.parseInt()` because the user may enter a number larger than an int. Instead I would prefer to use a regex to return false if a numeric String contains all "0" ch... | You'd be better off using [`BigInteger`](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) if you're trying to work with an arbitrarily large integer, however the following pattern should match a series of digits containing at least one non-zero character.
```
\d*[1-9]\d*
```
 I see many references such as:
>
> # Reflecting content attributes in IDL attributes
>
>
> Some IDL attributes are defined to ref... | The IDL ([Interface Definition Language](https://en.wikipedia.org/wiki/Interface_description_language)) comes from the [Web IDL](http://dev.w3.org/2006/webapi/WebIDL/) spec:
>
> This document defines an interface definition language, Web IDL, that
> can be used to describe interfaces that are intended to be implem... |
What is the difference between "workflow engine" and "business process management engine"?
I have heard about these two concepts after a lot of time.
Such as "windows workflow foundation" and Activiti and jBPM and other project is "business process management engine".
Are these two nouns ("workflow engine" and "bus... | In Wikipedia, a ["Workflow Engine"](https://en.wikipedia.org/wiki/Workflow_engine) is defined as:
>
> A software application that manages and executes modeled computer processes.
>
>
>
and from the same source, ["Business Process Management"](https://en.wikipedia.org/wiki/Business_process_management) is define... |
Why does map return an additional element when using ranges in Haskell?
I've just started learning Haskell and found a strange thing.
Let we have a list:
```
ghci> [0,2..5]
[0,2,4]
```
It has 3 elements. When I use `map` with this list I get 3 element as output, for example:
```
ghci> map (+ 1) [0,2..5]
[1,3,... | It's due to the implementation of `Enum` for `Float` and `Double`:
```
> [0,2..5] :: [Float]
[0.0,2.0,4.0,6.0]
```
It's not `map` doing it, but `Float`. Specifically, if you call `enumFromThenTo 0 2 5 :: [Float]`, you'll get the same list. You'll see the same results for `Double`.
This is hinted at in [the haske... |
How to check the uniqueness inside a for-loop?
Is there a way to check slices/maps for the presence of a value?
I would like to add a value to a slice ***only*** if it does ***not*** exist in the slice.
This works, but it seems verbose. Is there a better way to do this?
```
orgSlice := []int{1, 2, 3}
newSlice :=... | Your approach would take linear time for each insertion. A better way would be to use a `map[int]struct{}`. Alternatively, you could also use a `map[int]bool` or something similar, but the empty `struct{}` has the advantage that it doesn't occupy any additional space. Therefore `map[int]struct{}` is a popular choice fo... |
Does using a 'foreign' domain as email sender reduce email reputation?
We want to send emails through our webapp.
Users of the app provide their email adresses.
In some cases, we want to send transactional email from the webapp, using the current user as a sender.
Does using the User's name and email adress in the em... | You would be opening a whole can of worms if you do not authenticate the email address first.
This would allow users to send emails with any from address. If you get each user to authenticate the email address they want to use, i.e. send an email to the address they specify, and get them to provide information in tha... |
Guice don't inject to Jersey's resources
Parsed allover the whole internet, but can't figure out why this happens. I've got a simplest possible project (over jersey-quickstart-grizzly2 archetype) with one Jersey resource. I'm using Guice as DI because CDI doesn't want to work with Jersey either. The problem is that Gui... | Jersey 2 already has a DI framework, [HK2](https://hk2.java.net/2.4.0-b07/). You can either use it, or if you want, you can use the HK2/Guice bridge to bride your Guice module with HK2.
If you want to work with HK2, at the most basic level, it's not much different from the Guice module. For example, in your current c... |
Text based game in Java
To help with learning code in my class, I've been working on this text based game to keep myself coding (almost) every day. I have a class called `BasicUnit`, and in it I have methods to create a custom class. I use 2 methods for this, allowing the user to enter the information for the class. I'... | Welcome to Code Review and thanks for sharing your code!
# General issues
## Naming
Finding good names is the hardest part in programming. So always take your time to think carefully of your identifier names.
### Naming Conventions
It looks like you already know the
[Java Naming Conventions](http://www.oracl... |
Disable Python requests SSL validation for an imported module
I'm running a Python script that uses the `requests` package for making web requests. However, the web requests go through a proxy with a self-signed cert. As such, requests raise the following Exception:
`requests.exceptions.SSLError: ("bad handshake: Err... | **Note**: This solution is a complete hack.
**Short answer**: Set the `CURL_CA_BUNDLE` environment variable to an empty string.
Before:
```
$ python
import requests
requests.get('http://www.google.com')
<Response [200]>
requests.get('https://www.google.com')
...
File "/usr/local/lib/python2.7/site-packages/requ... |
Preserve default arguments of wrapped/decorated Python function in Sphinx documentation
How can I replace `*args` and `**kwargs` with the real signature in the documentation of decorated functions?
Let's say I have the following decorator and decorated function:
```
import functools
def mywrapper(func):
@func... | I came up with a monkey-patch for `functools.wraps`.
Accordingly, I simply added this to the `conf.py` script in my project documentation's sphinx `source` folder:
```
# Monkey-patch functools.wraps
import functools
def no_op_wraps(func):
"""Replaces functools.wraps in order to undo wrapping.
Can be used t... |
difference between "address in use" with bind() in Windows and on Linux - errno=98
I have a small TCP server that listens on a port. While debugging it's common for me to CTRL-C the server in order to kill the process.
On Windows I'm able to restart the service quickly and the socket can be rebound. On Linux I have t... | You want to use the `SO_REUSEADDR` option on the socket on Linux. The relevant manpage is [`socket(7)`](http://linux.die.net/man/7/socket). Here's an [example](http://beej.us/guide/bgnet/output/html/multipage/setsockoptman.html) of its usage. [This question](https://stackoverflow.com/questions/775638/using-so-reuseaddr... |
How to implement blurred background for Modal Bottome Sheet in Flutter?
I am working with Modal Bottom sheet and want to give blurred background, but the type of the parameter *barriercolor* is Color, so I cannot use BackdropFiter().
Does anyone know how to implement blurred background for Modal Bottom Sheet??
| Update:
Sorry for my careless.
You can set `backgroundColor:Colors.transparent` and `expand:true` and make your own `barrier` in `builder`.
It may look like this:
```
showMaterialModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
expand: true,
builder: (context) ... |
Can I associate a CODE reference with a HASH reference that contains it in Perl?
I want to create a hash reference with code references mapped to scalars (strings) as its members.
So far I have a map reference that looks something like this:
```
my $object;
$object = {
'code1' => sub {
print $_[0];
... | You are doing sub calls (not method calls), so you simply forgot to pass `$self` as a parameter.
```
my $object = {
code1 => sub {
print $_[0];
},
code2 => sub {
return 'Hello, World!';
},
code3 => sub {
my $self = shift;
$self->{code1}->( $self, $self->{code2}->($... |
TinyMCE editor with React Cannot access local files
Im using the tinyMCE editor plugin with react js. Im trying to upload files from my local machine to the editor and then to s3. I can drag and drop photos into the editor, however, when I click insert photo button i cannot gain access to my file system. Any suggestion... | I wrote a hack for a workaround. Put an input in the html and then grabbed it with an onlick handler
```
import React from 'react';
import TinyMCE from 'react-tinymce';
class Editor extends React.Component{
handleEditorChange = (e) => {
console.log('e',e);
console.log('Content was updated:', e... |
Android SDK having trouble with ADB
So, I installed the Android SDK, Eclipse, and the ADT. Upon firing up Eclipse the first time after setting up the ADT, this error popped up:
```
[2012-05-29 12:11:06 - adb] /home/drsmith/Downloads/android-sdk-linux/platform-tools/adb: error while loading shared libraries: libncurs... | Android SDK platform tools requires `ia32-libs`, which itself is a big package of libraries:
```
sudo apt-get install ia32-libs
```
---
**UPDATE:**
Below are the [latest instructions from Google](https://developer.android.com/sdk/installing/index.html?pkg=tools) on how to install Android SDK library dependen... |
Tail Recursion in Dataweave
Is there a way to take a recursive function (like the following) and make it tail recursive? I have an input like this:
```
{
"message": "Test ",
"read": [
{
"test": " t "
}
]
}
```
and this Dataweave function
```
fun trimWS(item) = item ... | I reworked a little bit your existing function to simplify it and I also run a few tests under Mule 4.2.1.
By building a data structure with over 840 levels deep, I was able to navigate and trim the fields. My guess is because of the structure of the data and lazy evaluation I am able to get past 256 depths which is ... |
Redirecting from getInitialProps in \_error.js in nextjs?
Any way to redirect to another url from getInitialProps in **\_error.js** in nextjs?
Already tried **res.redirect('/');** inside getInitialProps.
Its giving
*TypeError: res.redirect is not a function*
| Although, this redirect from `_error.js` doesn't feel right to me, you can try something like below:
```
import Router from 'next/router'
// in your getInitialProps
if (res) { // server
res.writeHead(302, {
Location: '/'
});
res.end();
} else { // client
Router.push('/');
}
```
Since `getInitialProps... |
deprecation warning when compiling: eta expansion of zero argument method
When compiling this snippet, the scala compiler issues the following warning:
>
> Eta-expansion of zero-argument method values is deprecated. Did you
> intend to write Main.this.porFiles5()? [warn] timerFunc(porFiles5)
>
>
>
It occurs w... | `porFiles5` is *not* a function. It is a *method*, which is something completely different in Scala.
If you have a method, but you need a function, you can use η-expansion to lift the method into a function, like this:
```
someList.foreach(println _)
```
Scala will, in some cases, also perform η-expansion automa... |
Primefaces dataExporter to xls Float number becomes text in spreadsheet cell
Environment:
- jsf 2.2
- primefaces 6.1
- wilfly 10
I'm trying to export a dataTable to an excel with dataExporter from primefaces, but I'm firstly getting
```
<p:commandButton id="btnExpExcel"
alt="#{msgs.inv_exportinv... | All the fields in p:dataTable are exported as text.
If you want to convert a value in a different format, you have to implement a postProcessor method.
Example:
page.xhtml
```
<p:dataExporter type="xls" target="lstFactures" fileName="invoices" postProcessor="#{bean.ppMethod}" />
```
Class Bean
```
public v... |
Foreign language characters in Regular expression in C#
In C# code, I am trying to pass chinese characters: `" 中文ABC123"`.
When I use alphanumeric in general using `"^[a-zA-Z0-9\s]+$"`,
it doesn't pass for `"中文ABC123"` and regex validation fails.
What other expressions do I need to add for C#?
| To match any letter character from any language use:
```
\p{L}
```
If you also want to match numbers:
```
[\p{L}\p{Nd}]+
```
`\p{L}` ... matches a character of the unicode category letter.
it is the short form for [\p{Ll}\p{Lu}\p{Lt}\p{Lm}\p{Lo}]
`\p{Ll}` ... matches lo... |
How to define empty character array in matlab?
```
for i=1:POPULATION_SIZE
for j=1:NO_PARAMETERS
c=dec2bin(parameters(j),NO_BITS_PARAMETER);
chromosomes(i) = [chromosomes(i) c];
end
end
```
above code is giving the following error:
>
> ??? Undefined function or method 'chromosomes' for in... | Do you want chromosomes to be character array (when all rows have the same size) or cell array (with variable size of ith elements)?
In the first case you define the variable as:
```
chromosomes = char(zeros(POPULATION_SIZE,NO_PARAMETERS*NO_BITS_PATAMETER));
```
or
```
chromosomes = repmat(' ',POPULATION_SIZE... |
MariaDB Cluster vs Percona Cluster for MySQL
What are the advantages and and disadvantages between the two? I've only been able to find information on these two implementations without any specifics on clusters.
I'm currently implementing a Percona Cluster but my only concern currently is with MYISAM databases for re... | Both platforms use the same mechanism for replication: [Galera](http://codership.com/content/using-galera-cluster). On the page at that link, you'll notice there are images featuring both PXC and MariaDB Cluster.
Galera library provides *transactional* replication. MyISAM doesn't do transactions, so the problems you ... |
Nginx Site Config Templates and Variables
Hi I am looking to set up a simple nginx config, I read you can set variables using `set $variable content;` but so far I've had no luck...
Below is what I have come up with so far/what I am trying to achieve:
```
server {
#################################################... | The [nginx FAQ](http://nginx.org/en/docs/faq/variables_in_config.html) is pretty clear on this topic:
>
> Q: Is there a proper way to use nginx variables to make sections of the configuration shorter, using them as macros for making parts of configuration work as templates?
>
>
> A: **Variables should not be used... |
C++ pure virtual function have body
Pure virtual functions (when we set `= 0`) can also have a function body.
What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?
| Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called *dynamically*, through a virtual dispatch mechanism. Yet, this very same function can easily be called *statically*, *non-virtually*, *direc... |
Erase all characters in string between the first parenthesis "(" andthe last parenthesis "(" including these parentheses C++
I have a trouble to remove all the characters between the first parenthesis "(" and the last parenthesis "(" including them. Here is the test program I use to make it work, but without success...... | Rephrasing the problem as "I want to extract the double immediately following the last '('", a C++ translation is pretty straightforward:
```
int main()
{
string str = "( 1221 ( 0 0 0 ) (1224.478541112155452 (1.32544e-7 0 0 ) ) )";
// Locate the last '('.
string::size_type pos = str.find_last_of("(");
... |
What is the right way to typecheck dependent lambda abstraction using 'bound'?
I am implementing a simple dependently-typed language, similar to the one [described by Lennart Augustsson](http://augustss.blogspot.dk/2007/10/simpler-easier-in-recent-paper-simply.html), while also using [bound](https://hackage.haskell.org... | We need some kind of context to keep track of the lambda arguments. However, we don't necessarily need to instantiate them, since `bound` gives us de Bruijn indices, and we can use those indices to index into the context.
Actually using the indices is a bit involved, though, because of the type-level machinery that r... |
Can re ignore a lazy quantifier?
Given this code (Python 3.6):
```
>>> import re
>>> a = re.search(r'\(.+?\)$', '(canary) (wharf)')
>>> a
<_sre.SRE_Match object; span=(0, 16), match='(canary) (wharf)'>
>>>
```
Why doesn't re stop searching at the first parethesis closure?
The expected output is `None`. The searc... | The lazy flag isn't being ignored.
You get a match on the entire string because `.+?` means match *anything* one or more times until you find a match, *expanding as needed*. If the [regex was `\([^)]+?\)$`](https://regex101.com/r/kicH9t/1) it would have matched only the last `(wharf)` because we excluded the `+?` fro... |
Programmatically setting instance name with the OpenStack Nova API
I have resigned myself to the fact that many of the features that EC2 users are accustomed to (in particular, tagging) do not exist in OpenStack. There is, however, one piece of functionality whose absence is driving me crazy.
Although OpenStack doesn... | The Python `novaclient.v1_1` package has a method on the `server` object:
```
def update(self, server, name=None):
"""
Update the name or the password for a server.
:param server: The :class:`Server` (or its ID) to update.
:param name: Update the server's name.
"""
if name is None:
r... |
Understanding Recursive Algebraic Types in Functional Programming
Hey I'm having some trouble understanding how Recursive Algebraic Types work and how to use them exactly. For example, take the below RAT definition for the natural numbers:
```
data Nat = Zero | Succ Nat
```
We're using a RAT here because the set ... | This states that:
- `Nat` is a type.
- `Zero` has type `Nat`. This represents the natural number 0.
- If `n` has type `Nat`, then `Succ n` has type `Nat`. This represents the natural number *n*+1.
So, for example, `Succ (Succ Zero)` represents 2, `Succ (Succ (Succ Zero))` represents 3, `Succ (Succ (Succ (Succ Zero)... |
Rails 3 & jQuery - How the two work together to create a web app?
I need helping understanding the end to end flow in Rails.
I could use help with the following example.. Lets take Facebook.
When you're on Facebook.com, and click MESSAGES, the URL changes to (facebook.com/?sk=messages) and then AJAX is used to do... | Presumably Rails works just like any other major framework out there. Typically, you want your AJAX and GET requests to work nicely together. So imagine you have this url:
>
> <http://www.example.com/messages>
>
>
>
Going here will load up the messages section of your site without having to make an AJAX call. ... |
Extracting text OpenCV
I am trying to find the bounding boxes of text in an image and am currently using this approach:
```
// calculate the local variances of the grayscale image
Mat t_mean, t_mean_2;
Mat grayF;
outImg_gray.convertTo(grayF, CV_32F);
int winSize = 35;
blur(grayF, t_mean, cv::Size(winSize,winSize));
... | You can detect text by finding close edge elements (inspired from a LPD):
```
#include "opencv2/opencv.hpp"
std::vector<cv::Rect> detectLetters(cv::Mat img)
{
std::vector<cv::Rect> boundRect;
cv::Mat img_gray, img_sobel, img_threshold, element;
cvtColor(img, img_gray, CV_BGR2GRAY);
cv::Sobel(img_gra... |
Recursive iteration over type lists and concatenation into a result type list
Consider a scenario having various classes/structs, some having complex data members, which can contain more of them itself. In order to setup / initialize, a list of all dependencies is required before instantiantion.
Because the types are... | I'll just look at the metaprogramming part. As always, the solution is to use Boost.Mp11. In this case, it's one of the more involved algorithms: [`mp_iterate`](https://www.boost.org/doc/libs/develop/libs/mp11/doc/html/mp11.html#mp_iteratev_f_r).
This applies a function to a value until failure - that's how we can ac... |
requestAnimationFrame loop not correct FPS
I have a javascript function that my game loops through (hopefully) 60 times a second that controls input, drawing, etc.
The way it is currently coded it seems to be always be around 52, noticeably lower than 60 fps, and it even dips to 25-30 fps even when nothing else is ha... | ## Don`t use setTimeout or setInterval for animation.
The problem is that you are calling a timer event from within the request animation event. Remove the timeout and just use requestAnimationFrame.
```
function loop(time){ // microsecond timer 1/1,000,000 accuracy in ms 1/1000th
// render code here
requ... |
Receiving 32-bit registers from 64-bit nasm code
I am learning 64-bit nasm, I assemble the .nasm file, which ONLY contains 64-bit registers, by doing the following
```
nasm -f elf64 HelloWorld.nasm -o HelloWorld.o
```
and link it doing the following
```
ld HelloWorld.o -o HelloWorld
```
the program runs corr... | Why does
```
...
mov rax, 1
mov rdi, 1
mov rsi, hello_world
...
```
gets disassembled as
```
...
4000b0: b8 01 00 00 00 mov eax,0x1
4000b5: bf 01 00 00 00 mov edi,0x1
4000ba: 48 be d8 00 60 00 00 movabs rsi,0x6000d8
4000c1: 00 00 00
...
```
Because the litera... |
jQuery - match element that has a class that starts with a certain string
I have a few links that look like this:
```
<a href="#" class="somelink rotate-90"> ... </a>
```
How can I bind a function to all elements that have a class that starts with "`rotate-`" ?
| You can use [starts with](http://api.jquery.com/attribute-starts-with-selector/) selector like this:
```
$('a[class^="rotate-"]')
```
---
>
> Description: Selects elements that
> have the specified attribute with a
> value beginning exactly with a given
> string.
>
>
>
So your code should be:
```
... |
Multiple-Target Assignments
I am reading a book about Python and there is a special part in the book about Multiple-Target Assignments. Now the book explains it like this:

but I dont see use of this. This makes no sense for me. Why would you use m... | A very good use for multiple assignment is setting a bunch of variables to the same number.
Below is a demonstration:
```
>>> vowels = consonants = total = 0
>>> mystr = "abcdefghi"
>>> for char in mystr:
... if char in "aeiou":
... vowels += 1
... elif char in "bcdfghjklmnpqrstvwxyz":
... ... |
knitr: how to use child .Rnw docs with (relative) figure paths?
I have a parent and a child `Rnw` document. The child doc is located in the subfolder `children`, i.e.
```
+-- parent.Rnw
+-- children
+-- child.Rnw
+-- figure
+-- test.pdf
```
Now I want to create the (margin) figure `test.pdf` from ... | For me the following solution is suitable:
At the top of the child doc, I define a function that adjusts a relative path depending on whether the doc is run as a child or not:
```
# rp: a relative path
adjust_path <- function(path_to_child_folder, rp)
{
is.child <- knitr:::child_mode()
function(rp)
{
if... |
Confusion in array operation in numpy
I generally use `MATLAB` and `Octave`, and i recently switching to `python` `numpy`.
In numpy when I define an array like this
```
>>> a = np.array([[2,3],[4,5]])
```
it works great and size of the array is
```
>>> a.shape
(2, 2)
```
which is also same as MATLAB
But when... | A 1D numpy array\* is literally 1D - it has no size in any second dimension, whereas in MATLAB, a '1D' array is actually 2D, with a size of 1 in its second dimension.
If you want your array to have size 1 in its second dimension you can use its `.reshape()` method:
```
a = np.zeros(5,)
print(a.shape)
# (5,)
# exp... |
Why doesn't nodelist have forEach?
I was working on a short script to change `<abbr>` elements' inner text, but found that `nodelist` does not have a `forEach` method. I know that `nodelist` doesn't inherit from `Array`, but doesn't it seem like `forEach` would be a useful method to have? Is there a particular implemen... | ## NodeList now has forEach() in all major browsers
See [nodeList forEach() on MDN](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach).
## Original answer
None of these answers explain *why* NodeList doesn't inherit from Array, thus allowing it to have `forEach` and all the rest.
The answer is f... |
Why doesn't trunc() turn a float into an integer?
When doing `trunc(3.5)`, it returns a float, `3.0`, why?
I know that you can do `trunc(Int64, 3.5)`, but isn't the purpose of `trunc` to convert a float into an integer? Why does it work this way?
| Let us focus on the case when you pass a `Float64` to `trunc` (the analysis can be similarly extended to other types). Take that the value you want to truncate is `x`.
First note that then `trunc` can always perform the truncation of `x` to the nearest integral value less or equal than it. So in short - this operatio... |
Why can swapping standard library containers be problematic in C++11 (involving allocators)?
**Note:** Originially asked by [GreenScape](https://stackoverflow.com/users/966376/greenscape) as [comment](https://stackoverflow.com/questions/23754223/why-are-the-swap-member-functions-in-stl-containers-not-declared-noexcept/... | Let's start of by digging into the Standard ([N3797](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3797.pdf)):
>
> `23.2.1p9` **General Container Requirements** `[container.requirements.general]`
>
>
>
> >
> > If
> > `allocator_traits<allocator_type>::propagate_on_container_swap::value`
> > is `tru... |
Media Information Extractor for Java
I need a media information extraction library (pure Java or JNI wrapper) that can handle common media formats. I primarily use it for video files and I need at least these information:
1. Video length (Runtime)
2. Video bitrate
3. Video framerate
4. Video format and codec
5. Video... | After a few days of asking this question, I have found [MediaInfo](http://mediainfo.sourceforge.net) which supplies dozens of technical and tag information about a video or audio file.
There is a JNI wrapper for MediaInfo in [subs4me](http://code.google.com/p/subs4me/)'s [source tree](http://code.google.com/p/subs4me... |
LoadMask image - extjs
I have used mask on loading in my view.
Right now it is showing me default loading image (x-mask-loading)
I want to add my own image instead of that default image.
Can anybody having some idea?
Please let me know.
| You can change loading icon by appliing css rules to loadMask Element (see [loadingCls](http://docs.sencha.com/ext-js/4-1/#!/api/Ext.view.AbstractView-cfg-loadingCls) config):
```
Ext.create('Ext.view.View', {
loadingCls: 'custom-loader'
// ...
});
```
```
/* CSS */
.x-mask-msg .custom-loader {
backgr... |
What is the difference between qDebug() used as a stream and as a function
I have seen bits of Qt code that uses qDebug as if it were `printf()`
```
qDebug( format, ... );
```
Mostly i see it used like `std::cout`
```
qDebug() << "one " << var_one;
```
What is the difference in the usages and when is it corre... | `qDebug(pattern, object1, object2)` it's basically the old fashioned `fprintf(stderr, pattern, object1, object2)`, as such you depend on compiler support to avoid - for instance - to crash your program with wrong patterns, like `int x; qDebug("%s\n", x);`. Well, GCC catches this one, but the compiler *cannot always* kn... |
Element-wise Matrix Replication in MATLAB
I have a 3 dimensional matrix. I want to replicate the matrix of size 8x2x9 to a specified number of times in the third dimension given by a vector say `[3, 2, 1, 1, 5, 4, 2, 2, 1]` so that the resultant matrix is of size 8x2x21. Is there any built-in MATLAB function (I'm runni... | ## For R2015a and newer...
According to the documentation for [`repelem`](http://www.mathworks.com/help/matlab/ref/repelem.html) (first introduced in version R2015a), it can operate on matrices as well. I believe the following code should accomplish what you want (I can't test it because I have an older version):
... |
JDBC driver for Oracle 10G XE
I have installed Oracle 10G XE. I want to connect to it using JDBC . Which driver should i use for it and from where can i download it ?
Thank You.
| On the machine you have installed the server, Oracle JDBC drivers are in `ORACLE_HOME/jdbc/lib`. Just put `ojdbc14.jar` on your classpath (`ojdbc14_g.jar` is the same as `ojdbc14.jar`, except that classes were compiled with "javac -g" and contain some tracing information).
**EDIT:** According to [Oracle Database 10g ... |
combine(Flow...) is not working with 3 Flows
I'm trying to use `combine()` to combine 3 flows but nothing happens. This is my code:
```
combine(flowX, flowY, flowZ) { x, y, z ->
println("$x, $y, $z") // this line is never reached
}
```
I know my flows are good because this works:
```
val x = flowX.first()
v... | `combine()` is not a terminal flow operator. It only creates a new flow and returns it, but it doesn't start collecting the flow. You still need to collect the flow to actually start executing it:
```
combine(flowX, flowY, flowZ) { x, y, z ->
println("$x, $y, $z")
}.collect {}
```
This solution seems a little ... |
Insert screenshots in SpecRun/SpecFlow test execution reports
I'm using **SpecFlow** with **Selenium WebDriver** and **SpecRun** as test runner to create and execute automated test cases and I'm looking for a solution to insert screenshots in the test execution report.
I wrote a method to create screenshots after eve... | (reposting from <https://groups.google.com/forum/#!topic/specrun/8-G0TgOBUbY>)
Yes, this is possible. You have to do the following steps:
1. save the screenshot to the output folder (this is the current working folder where the tests are running).
2. Write out a file line to the console from the test: Console.Write... |
Switching between JPanels in a JFrame
Now I know there are many, many questions on this and I've read a dozen. But I've just hit a wall, I can't make heads or tails of it.
Heres my question.
I have 3 Panel classes.
```
ConfigurePanel.java
ConnectServerPanel.java
RunServerPanel.java
```
and my JFrame class
... |
>
> "What do I need to put inside the if blocks to change panel views? I would have assumed jPanel1.something() but I don't know what that something is."
>
>
>
1. Don't compare string with `==`, it will not work. Use `.equals`.. `if("runserver".equals(str)){`
2. You need to use the method `.show` from the `CardL... |
How to check if a string already exists and if it does add +1 at the end?
Let's say i check if
```
$strig = "red-hot-chili-peppers-californication";
```
already exists in my database:
```
$query = dbquery("SELECT * FROM `videos` WHERE `slug` = '".$strig."';");
$checkvideo = dbrows($query);
if($checkvideo == 1){... | I can offer you the source of [Codeigniter's](http://codeigniter.com/user_guide/helpers/string_helper.html) `increment_string()` function:
```
/**
* CodeIgniter String Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link htt... |
What is the idea behind using nn.Identity for residual learning?
So, I've read about half the original ResNet paper, and am trying to figure out how to make my version for tabular data.
I've read a few blog posts on how it works in PyTorch, and I see heavy use of `nn.Identity()`. Now, the paper also frequently uses t... |
>
> What is the idea behind using nn.Identity for residual learning?
>
>
>
There is none (almost, see the end of the post), all [`nn.Identity`](https://pytorch.org/docs/stable/generated/torch.nn.Identity.html) does is forwarding the input given to it (basically `no-op`).
As shown in [PyTorch repo issue](https:... |
Why does ForEach behave differently than % even though they are both aliases of ForEach-Object in Powershell?
For some reason the % alias for ForEach-Object throws an exception when using the ( $Thing in $Things) syntax while the ForEach alias works fine.
Here are two examples:
**Using the % alias:**
```
$ints ... | These are two different things:
`%` is the alias for the cmdlet `ForEach-Object` and `foreach` is *also* the alias for the cmdlet `ForEach-Object`... *and* `foreach` is a looping statement which *does not* work with pipelining.
As written, your first command expands to:
```
ForEach-Object ($i in $ints) {
Write... |
Can 2 result sets be viewed from bigquery.client.query()?
I would like to run 2 Select parameters using the bigquery API.
for example, if I run the below query
```
SELECT 1;
SELECT 2;
```
When I run this using the following python script I only obtain the result of 2nd query.
```
def runquery();
bqclient ... | Here's a quick example of walking a script. In this example you parent job is of type script, which is composed of two child jobs that are both select statements. Once the parent is complete, you can invoke `list_jobs` with a parent filter to find the child jobs and interrogate them for results. Child jobs don't nest, ... |
Make an animation for collapsing | with Bootstrap
So, I have a bootstrap table:
```
<table class="table">
<tr class="content-row" id="content_1">
<td><a id="more_1" class="more" role="button" data-toggle="collapse" href="#additional_row1" aria-expanded="false" aria-controls="collapseExample">More</a>
<... | The answer that was given wasn't actually providing the correct solution. It was a solution, but when you need to keep the `tr` and `td` elements this solution is more complete
The fact is that there is no way in bootstrap to animate `tr` `td` elements.
What you can do is instead of toggling the `tr` or `td` is creat... |
Add highlight/background to only text using Swift
I want to highlight or add a background only on a text on a label that is not center-aligned.
I already tried Attributed Strings (<https://stackoverflow.com/a/38069772/676822>) and using regex but didn't get near a good solution.
NSAttributedString won't work because ... | As far as I have tried its not possible to get what you want simply with attributed text because using:
```
let attributedText = NSMutableAttributedString(string: "Evangelizing Desing Thinking",
attributes: [
.font: UIFont.systemFont(ofSize: 14),
.backgroundColor: UIColor.gray
]
)
```
Will ... |
UILabel with mutiple lines to truncate one long word
I have a `UIlabel` view which allow to show two lines of strings. But in my case, there is one long word only. Whatever I set the line break mode to `UILineBreakModeTailTruncation` or `UILineBreakModeWordWrap`, it always break the word into two lines. Like this:
"xxx... | In order to do what you're asking you need to find out if there is only one word. If there is, set the number of lines to 1 and the auto-shrink should fix things. If there is not, then set the number of lines to 0.
e.g.
```
UILabel *label = [[UILabel alloc] init];
label.font = [UIFont systemFontOfSize:12.0];
label... |
What's the default /etc/network/interfaces?
I messed up my network configuration. Can anyone help me and copy the default `/etc/network/interfaces`?
| **For eth0 with dhcp:**
```
# The loopback network interface
auto lo eth0
iface lo inet loopback
# The primary network interface
iface eth0 inet dhcp
```
**For eth0 static:**
```
# The loopback network interface
auto lo eth0
iface lo inet loopback
# The primary network interface
iface eth0 inet static
add... |
richtext control doesn't store the input content
my XPage has a RT-control in which the user can fill with text snippets, plus complete the content with more text.
The eventHandler of the "filling button":
```
<xp:eventHandler event="onclick" submit="true" refreshMode="partial" refreshId="Body1">
<xp:this.ac... | The problem is that you are not refreshing the richtext completly, only the textarea with the id of the richttext component. But there are two other components which has to be refreshed: inputRichText1\_mod and inputRichText1\_h, two automatically generated fields from the *XspInputRichText* component.
If you refresh... |
Executing a function at specific intervals
The task is to execute a function (say `Processfunction()`) every x (say x=10) seconds.
With below code, I'm able to call `Processfunction()` every x seconds.
**Question:** How to handle the case where the function takes more than 10 seconds to finish execution?
One way... | Why do you need a timer for this?
You could just measure the execution time and take a sleep according to the relation of elapsed time to desired interval duration.
Example:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main() {
srand(1);
for (;;) {
double ... |
Translating VBA to VBScript for removing duplicates in a column
I have a sheet in an Excel file in which I want to remove duplicate values from column 1. In Excel it has this feature when you click under Data, then Remove Duplicates on the column named "Code" which is the first column. I am trying to translate this as ... | You can't use named parameters in VBScript. You just need to provide parameters in the proper order, as they appear in the function declaration. Also you won't be able to use Excel's constants (`xlNo`, `xlYes`, etc) without first defining them yourself.
For your `RemoveDuplicates()` function, the VBScript equivalent ... |
How to download a file without knowing it's type or filename?
I've got a download link like this:
```
https://someURL.com/PiPki.aspx?ident=594907&jezik=de
```
The download result could be a file with any file type. For example `Picture.jpg` or `something.pdf`.
How is it possible to download whatever file is behind... | Via HTTP there is not only the possibility to transmit payload data, but there is also a header you can use to transmit meta-data. On the receiver side you can use that data e.g. to determine the name to store the file as.
In order to determine the file type, the HTTP response must have the correct `Content-Type` hea... |
How to style text in action overflow menu on device with Android>4.0 and hardware button?
I would like custom background & text color for my overflow menu. It works fine with devices without hardware menu button, but I'm not able to style devices with hardware menu button. See the screenshots:
![Screnshot from Galaxy... | I've looked into the problem. And there seems to be no way in changing `textColor` for the options menu for Android >= 4.0 devices with HW menu key. Not even changing primary, secondary or tertiary colors affected the text color.
The only "solution" that comes to my mind now is some pretty nasty use of java reflecti... |
Kotlin general setter function
I am new to kotlin. I wonder if this is possible
I wish to create a function that will change the value of the properties of the object and return the object itself. The main benefit is that I can chain this setter.
```
class Person {
var name:String? = null
var age:Int? = null... | Why not just simplify your answer to
```
fun setter(propName: String, value: Any): Person {
val property = this::class.memberProperties.find { it.name == propName }
when (property) {
is KMutableProperty<*> ->
property.setter.call(this, value)
null ->
// no such proper... |
Remove signing from an assembly
I have a project open in Visual Studio (it happens to be Enyim.Caching). This assembly wants to be delay-signed. In fact, it desires so strongly to be delay-signed, that I am unable to force Visual studio to compile it *without* delay signing.
1. I have unchecked "Delay sign only" and ... | **In this case, the problem is a project "common properties" reference.**
Inside of the project .csproj file is this innocuous little line:
>
> <Import Project="..\build\CommonProperties.targets" />
>
>
>
Unfortunately, the file (`CommonProperties.targets`) instructs VS to re-write the properties, but it doe... |
"TypeError: 'type' object is not subscriptable" in a function signature
Why am I receiving this error when I run this code?
```
Traceback (most recent call last):
File "... | **The following answer only applies to Python < 3.9**
The expression `list[int]` is attempting to subscript the object [`list`](https://docs.python.org/3/library/functions.html#func-list), which is a class. Class objects are of the type of their metaclass, which is [`type`](https://docs.python.org/3/library/functions... |
Android Studio publish local library
I've recently switched to Android Studio from Eclipse, and its better for the most part.
But now I'm at the point of wanting to create libraries to be reused later. I know about modules, but don't want to use them, as it seems to copy a duplicate in each project (I'd rather have a... | You can use [maven-publish](https://docs.gradle.org/current/userguide/publishing_maven.html) plugin to publish your artifacts to any repository you have access to. [I am using it combined with Amazon S3](https://github.com/sm4/s3repo-demo). The repository can be your local maven repo (the .m2 directory), local Artifact... |
How to point AWS API gateway stage to specific lambda function alias?
So as per the AWS documentaion
>
> Instead of using Amazon Resource Names (ARNs) for Lambda function in
> event source mappings, you can use an alias ARN. This approach means
> that you don't need to update your event source mappings when you
>... | I found it
<https://aws.amazon.com/blogs/compute/using-api-gateway-stage-variables-to-manage-lambda-functions/>
Here are the steps I followed:
1. After creating lambda function, create 2 aliases for lambda
function. `dev` pointing to `$latest` version and `prod` pointing a
particular version you want to use in p... |
Why is REMOTE\_ADDR only sometimes available as an Apache environment variable?
To avoid having to parse `X-Forwarded-For` in Varnish, I'm trying to just set a header on the SSL terminator (currently Apache) that stores the direct client IP in a header.
On our development machine, this works:
```
RequestHeader set... | Looking through the sources, `REMOTE_ADDR` is set only for these handlers that come with the server itself: mod\_proxy\_scgi, mod\_ext\_filter, mod\_include, mod\_isapi, mod\_cgid, and mod\_cgi (only they call `ap_add_common_vars`) so somehow one of these handlers is getting called before mod\_headers or mod\_log\_conf... |
Scanf allow space between words
I am try to read in some data with an id followed by firstname lastname from a text file and I cannot seem to get scanf to allow the space.
input may look like:
123456 FirstName LastName
`scanf("%d%s", &id, fullName)` doesn't work because it cuts off at the space between first and la... | You can use the set notation to specify a set of allowable characters in your name, and explicitly allow spaces:
```
scanf("%d %[ a-zA-Z]", &id, fullName);
```
Here, `[]` specifies a set of characters to allow (see [man 3 scanf](http://linux.die.net/man/3/scanf)), and within there there is a space, `a-z`, which me... |
How to Running celeryd as a daemon in ubuntu?
i am trying to install an init.d script, to run celery for scheduling tasks. when i tried to start it by `sudo /etc/init.d/celeryd start`, it throws error `"User does not exist: 'celery'"`
my celery configuration file (`/etc/default/celeryd`) contains these:
```
# Work... | I am adding a proper answer in order to be clearly visible:
Workers are unix processes that will run the various celery tasks. As you can see in the documentation, the CELERYD\_USER and CELERYD\_GROUP determine the name of user and group these workers will be run in your Unix environment.
So, what happened initial... |
Very generic argmax function in C++ wanted
I'm a spoiled Python programmer who is used to calculating the [argmax](https://en.wikipedia.org/wiki/Argmax) of a `collection` with respect to some `function` with
```
max(collection, key=function)
```
For example:
```
l = [1,43,10,17]
a = max(l, key=lambda x: -1 * ab... | Since @leemes solutions are too many. All are correct, except that none attempts to *imitate* the Python version in your example, Here is my attempt to imitate that:
Convenient generic argmax-function just like Python version:
```
template<typename Container, typename Fn>
auto max(Container const & c, Fn && key) -... |
Make LazyColumn items be as large as the largest item in the list
```
@Composable
fun PreviewLayout() {
fun getRandomString(length: Int): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
... | 1. You need to calculate width of the widest element separately. You can do it by placing an invisible copy of you cell with widest content in a `Box` along with `LazyColumn`.
In your sample it's easy - just get the longest string. If in the real project you can't decide which of contents is gonna be the widest one, ... |
How to program a Yes/No answer as buttons in an HTML form, without using radio buttons or checkboxes?
How do you program the following in a webform:
Are you male or female?
[](https://i.stack.imgur.com/fptpW.png)
| You can simulate using the labels of radio buttons.
```
input[type="radio"] {
display: none;
}
label {
padding: 10px 20px;
background-color: orange;
border: thin solid darkorange;
border-radius: 10px;
margin:5px;
display: inline-block;
}
input[type="radio"]:checked + label {
bac... |
How to translate Symfony2 Exception
I'm using yml format to translate my web app but I've one problem.
What I would like to do:
```
#exception.en.yml
exception.bad: 'Bad credentials'
```
What I know is possible to do:
```
#exception.en.yml
'Bad credentials': 'Bad credentials'
```
Is this the only method to ... | simply put in the translator and remember to add the `trans` statement on the messagge error dump in the Twig template.
Here an xliff example:
```
messages.en.xlf
<trans-unit id="1">
<source>User account is disabled.</source>
<target>Account disabled or waiting for confirm</tar... |
Debug into Maven Dependency Source w/IntelliJ
I'm debugging a Maven project in IntelliJ and I'm trying to figure out how to step into the source of one of my dependencies that's specified in my pom.xml. Specifically, my project has a dependency on Crawler4J I'm seeing some weird behaviour from Parser.parse(), and I wan... | I just set up the same dependency and I have no problems to download the source code.

Now I created a simple Main class with a Parser. I do `Ctrl` + Left-click and it will bring me to the Parser class.
, that is editable/create-able via a jQuery web app. It's a bit more hierarchical (jobs can have sub-jobs, etc.) so depending on what method... | It depends. If your user base is web savvy, I would recommend an edit in place approach because of the natural editing flow it provides.
---
**Edit in place**
When you edit a section of a heirarchy, you edit inline with the rest of the information. This allows you to check how your edits apply to the other info... |
How do I stop eclipse from removing whitespace when formatting
I am using eclipse to do some LWJGL programming and when I create arrays for holding the vertices, I tend to use a lot of whitespace to show what group of floats hold a vertex.
```
//Array for holding the vertices of a hexagon
float [ ] Vertices = {
... | Disable the Eclipse formatter for the part of code where you want to ignore the formatter and re-enable it in this way :
```
//Array for holding the vertices of a hexagon
// @formatter:off
float [ ] Vertices = {
// Vertex 0
-0.5f , 1.0f , 0.0f ,
// Vertex 1
-1.0f , 0.0f , 0.0f ,
// Vertex 2
... |
lambda parameter with optional return value
I'm trying to write a function like `std::for_each`, that in addition to the normal usage, can also take a `std::function<bool (param)>`. A false return value means that I want to break out of the loop. The code below is what I've gotten so far.
The second call to `a.visit(... | Here's how I would implement `for_almost_each`; I'm `using namespace std` plus type aliases for readability purposes.
```
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
template<class Iter, class Func>
Iter
for_almost_each_impl(Iter begin, Iter end, Func func, std::true_type)
{... |
Typescript [number, number] vs number[]
Can someone help me understand why I get a type error with the following code:
```
function sumOfTwoNumbersInArray(a: [number, number]) {
return a[0] + a[1];
}
sumOfTwoNumbersInArray([1, 2]); // Works
let foo = [1, 2];
sumOfTwoNumbersInArray(foo); // Error
```
The erro... | The parameter `a` in `sumOfTwoNumbersInArray` is a tuple.
It is not the same as `number[]`.
The following works okay because all variables are basic arrays
```
function sumOfTwoNumbersInArray(a: number[]) { // parameter declared as array
return a[0] + a[1];
}
let foo = [1, 2]; // initialization defaults to arr... |
Purpose of "import std;" in C++
I have seen following small piece of code on [cppdepend](http://cppdepend.com/blog/?p=228) site.
```
import std; // Module import directive.
int main()
{
std::cout<<"Hello World\n";
}
```
So, What is the purpose of `import std;` in C++? How to use `import std;` instead of `usi... |
>
> So, What is the purpose of import std; C++?
>
>
>
Its purpose is to make names from the `std` module available. Modules are a language feature that has been proposed for inclusion in a future C++ standard.
>
> How to use `import std;` instead of using `namespace std;` in C++?
>
>
>
They are not excl... |
ASP.NET MVC Html.DropDownList populated by Ajax call to controller?
I wanted to create an editor template for a field type that is represented as a dropdownlist. In the definition of the editor template I would like to populate the DropDownList using a call to an action on the controller returning the results as JSON -... | In the editor template provide an empty dropdown:
```
<%= Html.DropDownListFor(
x => x.PropertyToHoldSelectedValue,
Enumerable.Empty<SelectListItem>(),
"-- Loading Values --",
new { id = "foo" })
%>
```
Then setup a controller action that will return the values:
```
public class FooController... |
Determine a normal distribution given its quantile information
I was wondering how I could have R tell me the **SD** (as an argument in the **qnorm()** built in R) for a normal distribution whose 95% limit values are already known?
As an example, I know the two 95% limit values for my normal are 158, and 168, respect... | # A general procedure for Normal distribution
Suppose we have a Normal distribution `X ~ N(mu, sigma)`, with unknown mean `mu` and unknown standard deviation `sigma`. And we aim to solve for `mu` and `sigma`, given two quantile equations:
```
Pr(X < q1) = alpha1
Pr(X < q2) = alpha2
```
We consider standardizatio... |
Step by step instruction to install Rust and Cargo for mingw with Msys2?
I tried to install Rust on Cygwin but failed to be able link with mingw. Now I am trying to install it with Msys2. I already installed Msys2 and Mingw. I tried to follow [this wiki page](https://github.com/rust-lang/rust-wiki-backup/blob/master/Us... | The *Using Rust on Windows* page you linked to dates from before rustup replaced the installer as the default option to install Rust. [Installers](https://www.rust-lang.org/en-US/other-installers.html#standalone-installers) are still available, but you should use rustup if possible, because it makes it easy to update a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.