qid int64 1 74.6M | question stringlengths 45 24.2k | date stringlengths 10 10 | metadata stringlengths 101 178 | response_j stringlengths 32 23.2k | response_k stringlengths 21 13.2k |
|---|---|---|---|---|---|
142 | >
> [**ΠΕΤΡΟΥ Α΄ 5:5 (SBLGNT)**](http://www.biblegateway.com/passage/?search=1%20peter%205:5&version=SBLGNT)
>
> ὁμοίως, νεώτεροι, ὑποτάγητε **πρεσβυτέροις**. πάντες δὲ ἀλλήλοις τὴν ταπεινοφροσύνην ἐγκομβώσασθε, ὅτι Ὁ θεὸς ὑπερηφάνοις ἀντιτάσσεται ταπεινοῖς δὲ δίδωσιν χάριν.
>
>
> [**1 Peter 5:5 (ESV)**](http://www.biblegateway.com/passage/?search=1%20peter%205:5&version=ESV)
>
> Likewise, you who are younger, be subject to **the elders**. Clothe yourselves, all of you, with humility toward one another, for "God opposes the proud but gives grace to the humble."
>
>
>
Does the Greek text have any indication as to whether this means
* the elders of the local church, or
* all elderly people in general?
Which way should the passage be interpreted? | 2011/10/06 | ['https://hermeneutics.stackexchange.com/questions/142', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/93/'] | They are the pillars of the early church, not only the *old ones* – although they are from the group of the old and experienced.1 According to verse 2a they shall *"be shepherds of God's flock"*.
The technical use of the word πρεσβύτεροι for the heads of a community was usual for OT-Jewish region and "understandable" for the hellenistic environment.2
---
1: Leonahrt Goppelt, *Der erste Petrusbrief*, Göttingen 71912, p. 321
2: Bornkamm, ''Theologisches Wörterbuch zum Neuen Testament'', p. 660-666 | Semitic society (Jews, Arabs, etc.) is organized in tribes. One is not "elected" by a "committee". An elder from one family would not in any way rule over another man's family. Each family was represented in public life by the alpha male of their clan. The alpha male was by default the eldest male but if that's not an option it could be another. Respect for one's elders was crucial to an orderly society. Notice that even Egypt was organized with elders:
>
> Gen\_50:7 And Joseph went up to bury his father: and with him went up
> all the servants of Pharaoh, the elders of his house, and all the
> elders of the land of Egypt,
>
>
>
Conspicuously absent from Paul's list of offices (which were temporary) is "elder":
>
> Eph 4:11 And it is he who gifted some to be **apostles, others to be
> prophets, others to be evangelists, and still others to be pastors and
> teachers**, Eph 4:12 to equip the saints, to do the work of ministry,
> and to build up the body of the Messiah Eph 4:13 until all of us are
> united in the faith and in the full knowledge of God's Son, and until
> we attain mature adulthood and the full standard of development in the
> Messiah. Eph 4:14 Then we will no longer be little children, tossed
> like waves and blown about by every wind of doctrine, by people's
> trickery, or by clever strategies that would lead us astray.
>
>
>
So Peter knows nothing of the "Elders" in modern Churches who act as a board of directors over all of the families of the assemblies. Presbyterian style "Board of Elders" has more in common with a Roman Senate than with the thousands of years of Semitic representation by the alpha male of the family.
My primary source for my observation is the scriptures themselves. The last mention of elders in the scriptures prior to the NT is 3 Maccabees 1:25:
>
> 3Ma\_1:25 The elders who surrounded the king strove in many ways to
> divert his haughty mind from the design which he had formed.
>
>
>
Obviously these are not Presbyterians but rather Jews interacting with the king.
Joseph, War, mentions the elders as well:
>
> And when he was at Antioch, he wrote to him, and commanded him to come
> to him quickly to Ptolemais: upon which Jonathan did not intermit the
> siege of the citadel, but **took with him the elders of the people**,
> and the priests, and carried with him gold, and silver, and garments,
> and a great number of presents of friendship, and came to Demetrius,
> and presented him with them, and thereby pacified the king's anger.
>
>
>
For more background see:
<http://jewishencyclopedia.com/articles/5517-elder> |
62,542,223 | Anyone has a better idea to tackle this problem.
I have this table
```
+------+------+
|Id |Value |
+------+------+
|1 |0 |
+------+------+
|1 |5 |
+------+------+
|2 |0 |
+------+------+
|2 |1 |
+------+------+
|3 |0 |
+------+------+
```
So my goal is to get the distinct Id and get the first non-zero value if it exist.
Which would look like this
```
+------+------+
|Id |Value |
+------+------+
|1 |5 |
+------+------+
|2 |1 |
+------+------+
|3 |0 |
+------+------+
```
One of my idea is to SUM the Value since the expectation the rest are 0 but that won't work because their would be a possibility of having more than 1 value.
In this case I don't care which value I get as long as I got only one non-zero.
Is this possible in SQL or should I do this in backend?
MySQL Version: 5.7.26 | 2020/06/23 | ['https://Stackoverflow.com/questions/62542223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4099041/'] | If you are running MySQL 8.0, you can use `row_number()` - but you need an ordering column, otherwise the notion of "first" value is not defined. I assumed `ordering_id`:
```
select id, value
from (
select
t.*,
row_number() over(
partition by id
order by (value = 0), ordering_id
) rn
from mytable t
) t
where rn = 1
```
In earlier versions, one option is to use a subquery. Assuming that the primary key of your table is `pk`, you would do:
```
select t.id, t.value
from mytable t
where t.pk = (
select t1.pk
from mytable t1
where t1.id = t.id
order by (value = 0), ordering_id
limit 1
)
``` | This solution work for my need: [How can I select only the first distinct match from a field in MySQL?](https://stackoverflow.com/questions/15010763/how-can-i-select-only-the-first-distinct-match-from-a-field-in-mysql)
Instead of using MIN, I used MAX so it will get the biggest value (In my scenario this is ok since I don't care which non-zero I get as long it exist)
Cheers |
1,231,716 | I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything. | 2009/08/05 | ['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/'] | There's no reason we (the Roo team) cannot make the MavenPathResolver allow custom paths to be used, and one of the intentional reasons I created a PathResolver abstraction was to support customisation of common path locations not only to Maven non-default locations but also to other build systems like Ant+Ivy. all base Roo add-ons have been written to use the PathResolver so it shouldn't be a major effort to support this. Please add an enhancement request to the [Roo Jira instance](https://jira.springsource.org/browse/ROO) if you'd still like this support. | You can modify Maven to use a different set of conventions. The standard set are inherited from the [Maven super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html) and can be overridden by redefining the relevant property.
For example, to change the sources directory from src/main/java to src, the test directory to test-src, and the resources directory from src/main/resources to resources you would set the following in your POM:
```
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test-src</testSourceDirectory>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
</build>
```
Be aware that a few plugins might not use the standard properties to access the locations (e.g. hardcoding target/classes instead of using ${project.build.outputDirectory}, so you might have the odd problem.
---
Update: It looks like Roo currently has these [properties hardcoded](https://fisheye.springsource.org/browse/~raw,r=1/spring-roo/trunk/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenPathResolver.java). You may be able to replace the MavenPathResolver or add an additional resolver to use the custom properties.
If this is a real problem for you, you can [raise a request](http://jira.springframework.org/browse/ROO) to get the MavenPathResolver modified to allow custom locations. |
1,231,716 | I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything. | 2009/08/05 | ['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/'] | You can modify Maven to use a different set of conventions. The standard set are inherited from the [Maven super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html) and can be overridden by redefining the relevant property.
For example, to change the sources directory from src/main/java to src, the test directory to test-src, and the resources directory from src/main/resources to resources you would set the following in your POM:
```
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test-src</testSourceDirectory>
<resources>
<resource>
<directory>resources</directory>
</resource>
</resources>
</build>
```
Be aware that a few plugins might not use the standard properties to access the locations (e.g. hardcoding target/classes instead of using ${project.build.outputDirectory}, so you might have the odd problem.
---
Update: It looks like Roo currently has these [properties hardcoded](https://fisheye.springsource.org/browse/~raw,r=1/spring-roo/trunk/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenPathResolver.java). You may be able to replace the MavenPathResolver or add an additional resolver to use the custom properties.
If this is a real problem for you, you can [raise a request](http://jira.springframework.org/browse/ROO) to get the MavenPathResolver modified to allow custom locations. | As of Roo 1.2 it is not implemented. |
1,231,716 | I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything. | 2009/08/05 | ['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/'] | There's no reason we (the Roo team) cannot make the MavenPathResolver allow custom paths to be used, and one of the intentional reasons I created a PathResolver abstraction was to support customisation of common path locations not only to Maven non-default locations but also to other build systems like Ant+Ivy. all base Roo add-ons have been written to use the PathResolver so it shouldn't be a major effort to support this. Please add an enhancement request to the [Roo Jira instance](https://jira.springsource.org/browse/ROO) if you'd still like this support. | As of Roo 1.2 it is not implemented. |
8,252,731 | In my Java project I need to add versioning control to the files(Like SVN), maintain different versions to the same named files in same folder. Please help me how to do this in java programming.
Eg: in my project,i maintained a folder which have set of images which are uploaded by user.but user can upload same named image n number of times.to overcome this overhead i planned to maintain versioning to each image which are same (same named). | 2011/11/24 | ['https://Stackoverflow.com/questions/8252731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736260/'] | Source control code is not the way to do this. Rename the files to a uuid as they get uploaded and build a map of original filename->uuid filename with timestamps that you can then lookup or expire as needed. | I agree with awm. Version control is not for binary files. However, if you insist to do it like that, SVN has an API that you can use. You can access it directly from your code to commit code, update code, etc.
Here's a place to start: <http://svnkit.com/>
Go checkout out the SVNClientManager under "Subversion Client and IDE Integrations
Subversion clients and IDE integrations"
Good look.
(of course, I haven't used SVN in ages... I 'git' joy from a much better tool... :-)) |
1,167,669 | For odd integers $n$, can you prove that $10^n+1$ is **not** a perfect square? | 2015/02/27 | ['https://math.stackexchange.com/questions/1167669', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/'] | Lead the equation $10^n = (a-1)(a+1)$ to a contradiction. For instance the prime factor $5$ can appear only in one of those $2$ factors, so we have $5^n \leq a+1$, hence $(a-1)(a+1) \geq 5^n(5^n-2) > 10^n$, contradiction! | >
> In general, let $a\in\mathbb{P}$ (prime numbers) and suppose $a^n+1$ is a perfect square for some $n\in\mathbb{N}\setminus\{1\}.$
>
>
>
Then there is $x\in\mathbb{N}$ such that $x^2=a^n+1$ and therefore $a^n=(x+1)(x-1).$ Then we can write $a^p=x+1$ and $a^q=x-1$ for some integers $p,q\in\mathbb{N}\cup\{0\}$ such that $p+q=n$ and $p>q.$ This clearly implies $a^p-a^q=2.$
* If $q=0,$ we get $a=3$ and $p=1$ which implies $$3^1+1=2^2.$$
* If $q\neq 0,$ we get $a=2$ and $p=2, q=1$ which implies $$2^3+1=3^2.$$ |
1,167,669 | For odd integers $n$, can you prove that $10^n+1$ is **not** a perfect square? | 2015/02/27 | ['https://math.stackexchange.com/questions/1167669', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/'] | Since $10\equiv1\pmod3$, it suffices to note that $1^n+1=2$ is not a quadratic residue modulo $3$. (We don't even need the assumption that $n$ is odd.) | >
> In general, let $a\in\mathbb{P}$ (prime numbers) and suppose $a^n+1$ is a perfect square for some $n\in\mathbb{N}\setminus\{1\}.$
>
>
>
Then there is $x\in\mathbb{N}$ such that $x^2=a^n+1$ and therefore $a^n=(x+1)(x-1).$ Then we can write $a^p=x+1$ and $a^q=x-1$ for some integers $p,q\in\mathbb{N}\cup\{0\}$ such that $p+q=n$ and $p>q.$ This clearly implies $a^p-a^q=2.$
* If $q=0,$ we get $a=3$ and $p=1$ which implies $$3^1+1=2^2.$$
* If $q\neq 0,$ we get $a=2$ and $p=2, q=1$ which implies $$2^3+1=3^2.$$ |
13,853 | I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable.
Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once? | 2011/06/18 | ['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/'] | You can use multitexturing to do this - because you can bind a different texture to each texture unit you can then use your uniforms to select which one. The limit is hardware dependent, but usually no less than 8 and very occasionally as small as 4.
<http://www.opengl.org/resources/code/samples/sig99/advanced99/notes/node60.html>
Multitexturing predates shaders so support is fairly global.
This does mean not using a sampler array and instead using your own logic - "just" unroll a binary search, or even better use some bit magic.
It is however fastest to use one texture for all calls and for it to be an atlas of some kind. | The MSDN documentation for HLSL seems to think that you can only do this in Direct3D 10. Of course, OpenGL and Direct3D don't always exactly match their functionality, but it's usually pretty close, since the same cards target OpenGL and DirectX.
It could be that it is legal- just not for a target of the version that you are using. |
13,853 | I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable.
Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once? | 2011/06/18 | ['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/'] | >
> Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?
>
>
>
It is not necessarily the "only" way, but it is the *best* way. It is the way that works on anything, from the lowly Voodoo 1 all the way to the Radeon 6990. It doesn't require shaders (though they can be useful with this).
All it requires is a bit of pre-processing on your end to put all of the images in one large image. This is hardly an onerous burden.
That being said, how many sprites do you intend to draw per frame? If it's less than a couple of hundred, an atlas isn't that important to your rendering performance. Texture atlases matter most for things like particle systems and fonts, because you're drawing lots of them. | The MSDN documentation for HLSL seems to think that you can only do this in Direct3D 10. Of course, OpenGL and Direct3D don't always exactly match their functionality, but it's usually pretty close, since the same cards target OpenGL and DirectX.
It could be that it is legal- just not for a target of the version that you are using. |
13,853 | I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable.
Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once? | 2011/06/18 | ['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/'] | You can use multitexturing to do this - because you can bind a different texture to each texture unit you can then use your uniforms to select which one. The limit is hardware dependent, but usually no less than 8 and very occasionally as small as 4.
<http://www.opengl.org/resources/code/samples/sig99/advanced99/notes/node60.html>
Multitexturing predates shaders so support is fairly global.
This does mean not using a sampler array and instead using your own logic - "just" unroll a binary search, or even better use some bit magic.
It is however fastest to use one texture for all calls and for it to be an atlas of some kind. | >
> Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?
>
>
>
It is not necessarily the "only" way, but it is the *best* way. It is the way that works on anything, from the lowly Voodoo 1 all the way to the Radeon 6990. It doesn't require shaders (though they can be useful with this).
All it requires is a bit of pre-processing on your end to put all of the images in one large image. This is hardly an onerous burden.
That being said, how many sprites do you intend to draw per frame? If it's less than a couple of hundred, an atlas isn't that important to your rendering performance. Texture atlases matter most for things like particle systems and fonts, because you're drawing lots of them. |
9,952,128 | First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me).
I tried to create the function
```
closepan() {
$.colorbox.close();
}
```
**first case** : inside the
```
$(document).ready(function(){...});
```
but then I got the error closepan is undefined.
**second case** : before the
```
$(document).ready(function(){...});
```
but then it's the colorbox method that is undefined!
I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working!
In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button? | 2012/03/31 | ['https://Stackoverflow.com/questions/9952128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1207999/'] | No matter where you create a variable or function if you create it on `window` it will be available globally.
```
window.closepan = function() {
// hello there
}
``` | ```
function closepan() {
if($.colorbox) {
$.colorbox.close();
}
}
```
However, at the point where someone clicks your button all external scripts should have been loaded so that check shouldn't be necessary... |
9,952,128 | First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me).
I tried to create the function
```
closepan() {
$.colorbox.close();
}
```
**first case** : inside the
```
$(document).ready(function(){...});
```
but then I got the error closepan is undefined.
**second case** : before the
```
$(document).ready(function(){...});
```
but then it's the colorbox method that is undefined!
I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working!
In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button? | 2012/03/31 | ['https://Stackoverflow.com/questions/9952128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1207999/'] | No matter where you create a variable or function if you create it on `window` it will be available globally.
```
window.closepan = function() {
// hello there
}
``` | Don't forget to put the keyword `function` in front of your declaration...
```
function closepan() {
$.colorbox.close();
}
```
Working [JSFiddle](http://jsfiddle.net/axZqY/8/) |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Since toggling using `style` like:
```js
myElement.style.display = someBoolState ? "block" : "none"
```
is a really bad idea, here are some examples in JS, jQuery, HTML, CSS:
JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
====================================================================================================
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", function() {
elContent.classList.toggle("is-hidden");
});
```
```css
.is-hidden {
display: none;
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some content...</div>
```
The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever.
jQuery .toggle()
================
[`.toggle()`*Docs*](http://api.jquery.com/toggle/)
[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/)
[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/)
```js
$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
```
```css
#content{
display:none;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/)
============================================================================
`.toggle()` toggles an element's `display` `"block"/"none"` values
```js
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
```
```css
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
HTML5 - Toggle using `<summary>` and `<details>`
================================================
(unsupported on IE and Opera Mini)
```html
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
```
HTML - Toggle using `checkbox`
==============================
```css
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
```
```html
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
```
HTML - Switch using `radio`
===========================
```css
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
```
```html
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
```
CSS - Switch using `:target`
============================
(just to make sure you have it in your arsenal)
```css
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
```
```html
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
```
---
Animating class transition
--------------------------
If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example:
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", () => {
elContent.classList.toggle("is-hidden");
});
```
```css
#content {
display: inline-flex; /* or whatever */
transition: 0.6s;
}
.is-hidden {
position: relative;
visibility: hidden;
opacity: 0;
transform: scale(0);
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some Togglable content...</div>
``` | ```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
$('#content').toggle('show');
});
});
</script>
```
And the html
```
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | **Pure JavaScript:**
```
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
```
[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/hefGK/)
**jQuery**:
```
$("#button").click(function() {
// assumes element with id='button'
$("#newpost").toggle();
});
```
[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/KpFRb/) | Here's a plain Javascript way of doing toggle:
```
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Try with opacity
```css
div { transition: all 0.4s ease }
.hide { opacity: 0; }
```
```html
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">
<div id="newpost">Hello</div>
``` | ```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#hideshow').click(function(){
$('#content').toggle('show');
});
});
</script>
```
And the html
```
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Since toggling using `style` like:
```js
myElement.style.display = someBoolState ? "block" : "none"
```
is a really bad idea, here are some examples in JS, jQuery, HTML, CSS:
JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
====================================================================================================
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", function() {
elContent.classList.toggle("is-hidden");
});
```
```css
.is-hidden {
display: none;
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some content...</div>
```
The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever.
jQuery .toggle()
================
[`.toggle()`*Docs*](http://api.jquery.com/toggle/)
[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/)
[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/)
```js
$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
```
```css
#content{
display:none;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/)
============================================================================
`.toggle()` toggles an element's `display` `"block"/"none"` values
```js
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
```
```css
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
HTML5 - Toggle using `<summary>` and `<details>`
================================================
(unsupported on IE and Opera Mini)
```html
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
```
HTML - Toggle using `checkbox`
==============================
```css
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
```
```html
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
```
HTML - Switch using `radio`
===========================
```css
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
```
```html
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
```
CSS - Switch using `:target`
============================
(just to make sure you have it in your arsenal)
```css
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
```
```html
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
```
---
Animating class transition
--------------------------
If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example:
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", () => {
elContent.classList.toggle("is-hidden");
});
```
```css
#content {
display: inline-flex; /* or whatever */
transition: 0.6s;
}
.is-hidden {
position: relative;
visibility: hidden;
opacity: 0;
transform: scale(0);
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some Togglable content...</div>
``` | Here's a plain Javascript way of doing toggle:
```
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Here's a plain Javascript way of doing toggle:
```
<script>
var toggle = function() {
var mydiv = document.getElementById('newpost');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">
``` | You could use the following:
`mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Try with opacity
```css
div { transition: all 0.4s ease }
.hide { opacity: 0; }
```
```html
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">
<div id="newpost">Hello</div>
``` | This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.
```
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:#777777;
}
block1{
display:block; background-color:black; color:white; padding:20px; margin:20px;
}
block1.a{
display:none; background-color:black; color:white; padding:20px; margin:20px;
}
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Look at [jQuery Toggle](http://api.jquery.com/toggle/)
**HTML:**
```
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
```
**jQuery:**
```
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
```
For versions of jQuery 1.7 and newer use
```
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
```
For reference, kindly check this [**demo**](http://jsfiddle.net/vVsAn/1/) | This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.
```
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:#777777;
}
block1{
display:block; background-color:black; color:white; padding:20px; margin:20px;
}
block1.a{
display:none; background-color:black; color:white; padding:20px; margin:20px;
}
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | **Pure JavaScript:**
```
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
div.style.display = 'block';
}
};
```
[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/hefGK/)
**jQuery**:
```
$("#button").click(function() {
// assumes element with id='button'
$("#newpost").toggle();
});
```
[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/KpFRb/) | Try with opacity
```css
div { transition: all 0.4s ease }
.hide { opacity: 0; }
```
```html
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">
<div id="newpost">Hello</div>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Since toggling using `style` like:
```js
myElement.style.display = someBoolState ? "block" : "none"
```
is a really bad idea, here are some examples in JS, jQuery, HTML, CSS:
JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)
====================================================================================================
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", function() {
elContent.classList.toggle("is-hidden");
});
```
```css
.is-hidden {
display: none;
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some content...</div>
```
The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever.
jQuery .toggle()
================
[`.toggle()`*Docs*](http://api.jquery.com/toggle/)
[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/)
[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/)
```js
$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
```
```css
#content{
display:none;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/)
============================================================================
`.toggle()` toggles an element's `display` `"block"/"none"` values
```js
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
```
```css
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
```
HTML5 - Toggle using `<summary>` and `<details>`
================================================
(unsupported on IE and Opera Mini)
```html
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
```
HTML - Toggle using `checkbox`
==============================
```css
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
```
```html
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
```
HTML - Switch using `radio`
===========================
```css
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
```
```html
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
```
CSS - Switch using `:target`
============================
(just to make sure you have it in your arsenal)
```css
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
```
```html
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
```
---
Animating class transition
--------------------------
If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example:
```js
const elToggle = document.querySelector("#toggle");
const elContent = document.querySelector("#content");
elToggle.addEventListener("click", () => {
elContent.classList.toggle("is-hidden");
});
```
```css
#content {
display: inline-flex; /* or whatever */
transition: 0.6s;
}
.is-hidden {
position: relative;
visibility: hidden;
opacity: 0;
transform: scale(0);
}
```
```html
<button id="toggle">TOGGLE</button>
<div id="content" class="is-hidden">Some Togglable content...</div>
``` | This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none.
```
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:#777777;
}
block1{
display:block; background-color:black; color:white; padding:20px; margin:20px;
}
block1.a{
display:none; background-color:black; color:white; padding:20px; margin:20px;
}
</style>
</head>
<body>
<button onclick="document.getElementById('ID').setAttribute('class', '');">Open</button>
<button onclick="document.getElementById('ID').setAttribute('class', 'a');">Close</button>
<block1 id="ID" class="a">
<p>Testing</p>
</block1>
</body>
</html>
``` |
4,528,085 | Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button
```
<div id="newpost">
``` | 2010/12/24 | ['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/'] | Try with opacity
```css
div { transition: all 0.4s ease }
.hide { opacity: 0; }
```
```html
<input onclick="newpost.classList.toggle('hide')" type="button" value="toggle">
<div id="newpost">Hello</div>
``` | You could use the following:
`mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');` |
30,831,806 | I'm new to mysqli prepare statement and was surprised to find out the || doesn't work as expected in mysqli prepare statement query.
I have a function which check whether the user registered, and its evaluation should be based upon the unique row id and email address.Besides, since the id column and the email column are of different type, which are `Int(11)` and `VARCHAR` respectively, so I assumed it's going to have some trouble using `bind_param` because the different data type
```
public function checkUserRegistered($iden){
//The iden can be either a id or a email address
$stmt = $this->connection->prepare("SELECT `id` FROM `$this->table_name` WHERE (`email`= ? || `id`= ?) LIMIT 1 ");
$stmt->bind_param('s',$iden); // s or i ?
if($stmt->execute()){
$result = $stmt->get_result();
if($result->num_rows ==1){
$stmt->close();
return true;
}else{
return false;
}
}
}
```
What is the right way of doing this, do I have to use separate functions instead? | 2015/06/14 | ['https://Stackoverflow.com/questions/30831806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3500129/'] | You need to bind two params like this:
```
$stmt->bind_param('si',$iden, $iden);
```
as you have set two '?'.
s means string, i means integer, b is blob and d is double. | The problem is you have specified that in the prepare statement you want to bind two values. But in the bindValue statement you are only binding one value. Also coming to the issue that $iden can be the email or number then I think the best way is to generate conditional statements for them. So if I was you, I will go with:
```
public function checkUserRegistered($iden){
//making sure $iden is not empty
if ($iden) {
//if $iden is a number is equal to id
if (is_numeric($iden)) {
$stmt = $this->connection->prepare("SELECT `id` FROM `$this->table_name` WHERE `id`= ? LIMIT 1 ");
$stmt->bind_param('i',$iden); //because id is an integer
} else {
//then $iden is a varchar which is the email
$stmt = $this->connection->prepare("SELECT `id` FROM `$this->table_name` WHERE `email`= ? LIMIT 1 ");
$stmt->bind_param('s',$iden); //because email is a string
}
if ($stmt->execute()) {
$result = $stmt->get_result();
if($result->num_rows ==1){
$stmt->close();
return true;
}else{
return false;
}
}
}
```
} |
436,326 | Let $V$ be an irreducible finite dimensional complex representation of the product of groups $G\times H$. Is it necessarily isomorphic to a tensor product of irreducible representation of $G$ and $H$? If not what is a counter-example, and under what extra assumptions this is known to be true?
Remark. I think for continuous representations of compact groups this is true. | 2022/12/11 | ['https://mathoverflow.net/questions/436326', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16183/'] | If your groups are finite, then Andy’s [answer](https://mathoverflow.net/a/436339/2383) is perfectly fine. If you want to do topological groups you must be slightly (but not much) more careful. First since we are dealing with finite dimensional representations, algebraic and topological reducibility are the same.
It is enough to prove that your irreducible representation decomposes as a tensor product in the case of discrete groups. For if it is isomorphic to one of the form $U\otimes V$, then since the linear isomorphism is continuous, it is enough to observe that restricting the original representation to $G$ gives $\dim V$ copies of $U$ and restricting to $H$ gives $\dim U$ copies of $V$ and so $U$ and $V$ must give continuous representations of $G$, $H$.
So we may assume that $G$, $H$ are discrete and we are dealing with no topology. Then replacing $G$, $H$ with their group algebras and $\mathbb C$ by algebras over an algebraically closed field, it suffices to show that if $A$, $B$ are $K$-algebras with $K$ algebraically closed, then any finite dimensional irreducible representation of $A\otimes B$ is equivalent to a tensor product of irreducible representations of $A$ and $B$.
But the image of $A$ and $B$ under any finite dimensional representation is a finite dimensional algebra and so without loss of generality we may assume that $A$, $B$ are finite dimensional.
The crux of the matter, which is basically Andy’s proof in different words, is the special case that $A,B$ are matrix algebras over $K$. Then $M\_n(K)\otimes M\_m(K)\cong M\_{nm}(K)$ and the isomorphism intertwines the actions on $K^n\otimes K^m\cong K^{nm}$. Thus in the case $A$, $B$ are matrix algebras then the unique $A\otimes B$ irreducible rep is the tensor product of the unique irreducible $A$ and $B$ reps. Since arbitrary semisimple algebras over an algebraically closed field are finite direct products of matrix algebras and tensor product distributes over direct product, this handles the case $A$, $B$ are semisimple and also shows that $A\otimes B$ is semisimple in this case.
$\DeclareMathOperator\rad{rad}$If $A$, $B$ are general finite dimensional $K$-algebras with $K$-algebraically closed, then $A/{\rad(A)}\otimes B/{\rad(B)}$ is semisimple by the above. Moreover, the kernel of the natural map $A\otimes B\to A/{\rad(A)}\otimes B/{\rad(B)}$ is easily checked to be $A\otimes \rad(B)+\rad(A)\otimes B$, which is a nilpotent ideal. Thus $(A\otimes B)/{\rad(A\otimes B)}\cong A/{\rad(A)}\otimes B/{\rad(B)}$ and so the desired result that irreducible reps are tensor products follows since $C$ and $C/{\rad(C)}$ have the same irreducible reps for any $K$-algebra $C$.
**Simpler proof**
Here is an argument along the line of Andy's that works for arbitrary groups or even algebras that avoids the radical and just uses Burnside's theorem that a finite dimensional representation of a $K$-algebra over an algebraically closed field $K$ is irreducible if and only if it is surjective.
Let $A,B$ be $K$-algebras (not necessarily finite dimensional) with $K$-algebraically closed (they could be group algebras) and let $W$ be a finite dimensional irreducible $A\otimes B$-module. Let $U$ be an irreducible $A$-subrepresentation of $W$. Then the sum $S$ of all irreducible $A$-submodules of $W$ isomorphic to $U$ is invariant under any $A$-enomorphism of $W$ and hence under $B$ as the $B$-action commutes with $A$. Hence $S$ is $A\otimes B$-invariant and so $S=W$ by irreducibility. Thus $W\cong U^m$ for some $m$ as an $A$-module (this is a standard argument). Thus, up to isomorphism, we may assume that $W=U\otimes V$ with $V$ a vector space of dimension $m$ and where $A$ acts via matrices of the form $\rho(a)\otimes 1$ where $\rho$ is the irreducible representation associated to $U$. By Burnside, $\rho$ is onto $End\_k(U)$. But since $End\_K(U\otimes V)= End\_k(U)\otimes End\_k(V)$, it follows that the centralizer of $End\_K(U)\otimes 1$ in $End\_K(W)$ is $1\otimes End\_k(V)$. Since the action of $B$ commutes with that of $A$, as a representation of $B$, we have $W$ is of the form $b\mapsto 1\otimes \psi(b)$ for some representation $\psi$ of $B$ on $V$. Clearly, if $V$ is not irreducible, then neither is $U\otimes V$ and so we are done. | Most books on the representation theory of finite groups prove this using character theory. This is an efficient way of proving it, but I think it doesn’t give much insight into why it is true (and what other settings it generalizes to). I wrote up a more direct proof [here](https://www3.nd.edu/%7Eandyp/notes/RepOfProducts.pdf). |
38,838,407 | Let's say we have a dictionary
```
dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
```
How would I go about printing the code so it looks like:
>
> Dollar 12, Half-Coin 4, Quarter 3, Dime 7
>
>
> | 2016/08/08 | ['https://Stackoverflow.com/questions/38838407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5255751/'] | Use `','.join()`, passing in a generator of strings.
```
d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,v) for k,v in d.items())
```
Result:
```
Half-Coin 4, Quarter 3, Dollar 12, Dime 7
```
If you want the results to be in a predictable order, you'll need to sort the items.
```
order=('Dollar', 'Half-Coin', 'Quarter', 'Dime')
d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,d[k]) for k in sorted(d, key=order.index))
```
Result:
```
Dollar 12, Half-Coin 4, Quarter 3, Dime 7
```
Ps. Don't name your variables with names of builtin types. Your name eclipses the builtin name, so subsequent code won't be able to call `dict()`, for example. | ```
dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
out=""
for i in dict:
out += i+" "+str(dict[i])+", "
print out[:-2]
```
result:
```
Half-Coin 4, Quarter 3, Dollar 12, Dime 7
``` |
38,838,407 | Let's say we have a dictionary
```
dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
```
How would I go about printing the code so it looks like:
>
> Dollar 12, Half-Coin 4, Quarter 3, Dime 7
>
>
> | 2016/08/08 | ['https://Stackoverflow.com/questions/38838407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5255751/'] | Use `','.join()`, passing in a generator of strings.
```
d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,v) for k,v in d.items())
```
Result:
```
Half-Coin 4, Quarter 3, Dollar 12, Dime 7
```
If you want the results to be in a predictable order, you'll need to sort the items.
```
order=('Dollar', 'Half-Coin', 'Quarter', 'Dime')
d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 }
print ', '.join('{} {}'.format(k,d[k]) for k in sorted(d, key=order.index))
```
Result:
```
Dollar 12, Half-Coin 4, Quarter 3, Dime 7
```
Ps. Don't name your variables with names of builtin types. Your name eclipses the builtin name, so subsequent code won't be able to call `dict()`, for example. | ```
", ".join([x +" "+str(dict[x]) for x in dict.keys()])
``` |
295,247 | I want to plot a polynomial that is parametrized by an additional parameter d. I took samples of the domain of d and stored the coefficients of the polynomial for each of these samples in a table:
```
d a0 a1 a2 a3 a4
0 0.31632 0.038794 -0.637117 0.457322 -0.0940009
0.002 0.316319 0.0387949 -0.637115 0.457321 -0.0940008
0.4 0.130744 0.0171396 -0.292042 0.2209 -0.0479512
...
```
Now I would like to plot up to 100 of these polynomials into the same plot.
Is there a way that does not require me to hand code each polynomial to plot or to sample each polynomial in an external tool? (Doing so from within the Latex tool chain would be fine.)
To summarize it: In my case, the rows of the table don't represent coordinates to plot but coefficients of polynomials that I want to plot. Therefore, I don't see how to use pgfplot's `\addplot table` to get the output that I want.
The effect of the code should be like
```
\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2]
\addplot[mark=none] {0.31632 + x*(0.038794 + x*(-0.637117 + x*(0.457322 + x*-0.0940009)))};
\addplot[mark=none] {0.311765 + x*(0.0408345 + x*(-0.633668 + x*(0.454718 + x*-0.0935363)))};
\addplot[mark=none] {0.130744 + x*(0.0171396 + x*(-0.292042 + x*(0.2209 + x*-0.0479512)))};
\end{axis}
\end{tikzpicture}
\end{document}
```
but without the manual repetition.
The result would look like:
[](https://i.stack.imgur.com/04F4X.png) | 2016/02/22 | ['https://tex.stackexchange.com/questions/295247', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/28004/'] | Here's a way that uses a `pgfplotsinvokeforeach` approach.
[](https://i.stack.imgur.com/pH66q.png)
There are a few important parts, including:
```
% declare a polynomial function
\pgfmathdeclarefunction{mypoly}{6}{%
% #1: a0
% #2: a1
% #3: a2
% #4: a3
% #5: a4
% #6: x
\pgfmathparse{#1+#2*#6%
+#3*#6^2%
+#4*#6^3%
+#5*#6^4}%
}
```
which, as you can see, defines your polynomial.
You'll see that this is invoked in the `addplot` command as
```
\addplot[domain=0:2,red,thick]{mypoly(\aZero,\aOne,\aTwo,\aThree,\aFour,x)};
```
Here's the complete code:
```
% arara: pdflatex
% !arara: indent: {overwrite: yes}
\documentclass[tikz]{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat=1.12}
% read in the coefficients
\pgfplotstableread[col sep=space]{
d a0 a1 a2 a3 a4
0 0.31632 0.038794 -0.637117 0.457322 -0.0940009
1 0.311765 0.0408345 -0.633668 0.454718 -0.0935363
2 0.130744 0.0171396 -0.292042 0.2209 -0.0479512
}\coefficients
% count number of rows
\pgfplotstablegetrowsof\coefficients
\pgfmathsetmacro\numberofrows{\pgfplotsretval-1}
% declare a polynomial function
\pgfmathdeclarefunction{mypoly}{6}{%
% #1: a0
% #2: a1
% #3: a2
% #4: a3
% #5: a4
% #6: x
\pgfmathparse{#1+#2*#6%
+#3*#6^2%
+#4*#6^3%
+#5*#6^4}%
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2]
% loop through the rows of the table
\pgfplotsinvokeforeach{0,...,\numberofrows}{
% define each of a0, a1, a2, a3, a4
% a0
\pgfplotstablegetelem{#1}{[index]1}\of\coefficients
\pgfmathsetmacro{\aZero}{\pgfplotsretval}
% a1
\pgfplotstablegetelem{#1}{[index]2}\of\coefficients
\pgfmathsetmacro{\aOne}{\pgfplotsretval}
% a2
\pgfplotstablegetelem{#1}{[index]3}\of\coefficients
\pgfmathsetmacro{\aTwo}{\pgfplotsretval}
% a3
\pgfplotstablegetelem{#1}{[index]4}\of\coefficients
\pgfmathsetmacro{\aThree}{\pgfplotsretval}
% a4
\pgfplotstablegetelem{#1}{[index]5}\of\coefficients
\pgfmathsetmacro{\aFour}{\pgfplotsretval}
% add the polynomial plot
\addplot[domain=0:2,red,thick]{mypoly(\aZero,\aOne,\aTwo,\aThree,\aFour,x)};
}
\end{axis}
\end{tikzpicture}
\end{document}
``` | I would probably just use a scripting language and create the LaTeX source code. Here is an example in Python.
```
#!/usr/bin/env python
import csv
with open('data.csv', 'rb') as csvfile:
coeff = csv.reader(csvfile, delimiter=',')
coeff.next()
for row in coeff:
print("\\addplot[mark=none] {" + row[1] +
" + x * (" + row[2] +
" + x * (" + row[3] +
" + x * (" + row[4] +
" + x * " + row[5] + ")))};")
```
To make it easier to load the coefficients I converted your data into a proper csv file.
```
d,a0,a1,a2,a3,a4
0,0.31632,0.038794,-0.637117,0.457322,-0.0940009
0.002,0.316319,0.0387949,-0.637115,0.457321,-0.0940008
```
If you redirect the output to a file like this
```
python createPlots.py > plots.tex
```
you can then load it later within your main tex file using `\input{}`.
```
\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2]
\input{plots.tex}
\end{axis}
\end{tikzpicture}
\end{document}
```
---
**EDIT:**
You can of course also run your script from within LaTeX (needs `--shell-escape`).
```
\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.12}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2]
\immediate\write18{python createPlots.py > plots.tex}
\input{plots.tex}
\end{axis}
\end{tikzpicture}
\end{document}
```
---
**EDIT 2:**
So here is a LuaTeX solution. It expects also the properly formatted csv file.
```
\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.12}
\usepackage{luacode}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2]
\begin{luacode}
firstLineSkipped = false
for line in io.lines("data.csv") do
if firstLineSkipped then
tex.print("\\addplot[mark=none] {" .. line:gsub('.-,','', 1):gsub(",", " + x*(", 4) .. ")))};");
else
firstLineSkipped = true
end
end
\end{luacode}
\end{axis}
\end{tikzpicture}
\end{document}
``` |
84,358 | As I understand it, copyright applies to creative expression and not for examples rules of games. Does this also apply to the ISO standards ([example, costs CHF 158](https://www.iso.org/standard/30669.html))? For example, could one re-write the standards in one's own words and sell them in competition with ISO? Or is there something that would prevent this, perhaps something like [Copyright in compilation](https://en.wikipedia.org/wiki/Copyright_in_compilation)? | 2022/09/15 | ['https://law.stackexchange.com/questions/84358', 'https://law.stackexchange.com', 'https://law.stackexchange.com/users/41938/'] | Expression vs Idea
------------------
>
> As I understand it, copyright applies to creative expression and not for examples rules of games.
>
>
>
That is not correct as stated. Game rule, or more exactly the fixed expression of a set of game rule (what one finds in the package of a commercial game, or in a book such as *Hoyle's Rules of Games*, can be and usually are protected by copyright. What is **not** protected is the **ideas** expressed in a set of rules. These are sometimes called "game mechanics". For example it is a rule of bridge that 13 cards are dealt to each of 4 players. That is a fact, and so is not protected by copyright. But the exact wording of the official *Laws of Duplicate Bridge* is protected.
### "creativity" vs "originality"
Many things that might not be considered very creative are protected. US Copyright law calls not for creativity, but for an **original work**. The concepts of "creativity" and "originality" have a significant overlap, but are not at all the same.
For example, a person might watch a baseball game and write down play-by-play account of it. That might not be very creative, but it would still be protected by copyright. But the event of the game are facts, and not protected. Someone else might describe the same game in different words, covering the same facts, and that would not be copyright infringement.
Another example. A person writes a scientific paper describing in detail a series of chemical experiments and the results obtained. That is not very creative (although the design of the experiments might be). It would, however, be protected by copyright. But the facts and ideas would not be protected. Another person could desacribe the same experiments in different words, and that would not be an infringement of copyright.
### Merger Doctrine
In extreme cases, such as a basic recipe, there is no expression temperate from the facts. In such a case the ["merger doctrine"](https://en.wikipedia.org/wiki/Idea%E2%80%93expression_distinction#Merger_doctrine) applies, and there is no copyright protection at all.
Standards
---------
Standards, such as ISO standards, are normally protected by copyright. But the ideas expressed in them are not. And since
standards are highly factual, the protection afforded to them is particularly narrow. But when one is testing compliance with a standard, the exact words of the standard may be important. A compliance officer is not likely to accept a paraphrase as a valid substitute.
### Standards in Laws
The actual text of laws (and regulations), however (Federal, state, or local) is never protected by copyright. All are in the public domain. So when a law incorporated and reprints a standard, as is often done with fire and building codes, anyone may freely reproduce the codes as set down as part of law, even through the code has been copyrighted and indeed registered, as long as the source is the text of an enacted law or regulation. | “In your own words” would be fine. Trouble might come from another source. If you make people believe that the contents of your document is equivalent to a standard, but it isn’t, that could be a problem. And of course you need to be careful that your document is not a derivative work. |
725,790 | I can extract all information related with any outlook account from windows registry on windows machine. Like Incoming and outgoing server, username , encrypted password and account type(POP or IMAP). All information which I can collect from windows registry is in hex.
**I want to extract same information for account which I have configured in thunderbird**.
Is there any way to do this in windows? | 2014/03/04 | ['https://superuser.com/questions/725790', 'https://superuser.com', 'https://superuser.com/users/297714/'] | Information about Thunderbird account is stored in plain text file at user profile
```
%appdata%\thunderbird\profiles\%yourprofile%\prefs.js
```
Passwords are stored under `key3.db` and `signons.sqlite` at same location, but those are somewhat encrytped. | Nirsoft's [MailPassView](http://www.nirsoft.net/utils/mailpv.html) will extract account details from most common mail clients, including port numbers. Like all Nirsoft stuff it's a very useful little tool, although many anti-virus applications will detect it as 'Hack Tool' or 'Potentially Unwanted Program', for obvious reasons. |
14,472 | I am confused by all the excitement surrounding the EU cookie directive; why is it such a painful thing?
As far as I can see cookies that are required for your site to function are allowed such as shopping carts and site logins. Am I missing something here?
The original HTTP specification was designed to work in a stateless way so to my mind this is a stepping stone in the right direction towards stateless RESTful websites. Why should state be added to the process when it is not needed.
There is plenty of mileage left in Digest Auth etc so why is everyone worried?
An obvious answer might be that Google Analytics needs to set cookies to be able to track traffic. There is a somewhat unsatisfactory answer to this point: <http://cookies.dev.wolf-software.com>
So have I missed something that I should be panicking about? What has you worried about it? | 2011/05/27 | ['https://webmasters.stackexchange.com/questions/14472', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/7473/'] | The "excitement" relates to confusion about how the new directive (PDF: [2009/136/EC](http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ%3aL:2009:337:0011:0036%3aEn%3aPDF)) should be interpreted and implemented, and whether or not it's fair to European webmasters:
### Do the laws apply to third party cookies?
The UK data protection body in charge of enforcing the laws in Britain says in their guidelines that they're seeking clarification ([see my answer here](https://webmasters.stackexchange.com/questions/14473/google-analytics-and-the-eu-cookie-directive-who-will-fall-foul-of-the-law-goog/14478#14478)), but until then, we don't know whether we'll have to ask permission to use third-party cookies from Google Analytics, for example.
### Might the laws cripple EU websites?
If it turns out that the new laws require European webmasters to ask each visitor's permission to use third-party cookies, this will affect a lot of websites and render analytics, affiliate systems, usability testing, and even video embedding from third-parties (many of which use cookies) unusable or far less effective. It will also require many site owners who otherwise wouldn't have had to issue a request to store cookies to suddenly do so, drop the services, or seek cookie-less alternatives.
### Does the directive apply to services hosted outside of the EU?
Related to the above, if I run a business from the UK but run a blog on a hosted service outside the EU that makes use of 'unnecessary' cookies, must I rebuild my theme to request permission to use them? If so, will the service be prepared to provide this functionality? If not, do I have to migrate my blog elsewhere? These questions are yet to be answered.
### How best to obtain permission?
The new directive exists to ensure that people without technical knowledge have the same control over their privacy as more technical users. It does this by turning an opt-out system ("here's a cookie, you can always vomit it up if you don't want it") into an opt-in system ("would you like a cookie? here's what's in it...").
The new laws are great for consumers, welcomed by privacy groups, more closely aligned with opt-in email and permission marketing conduct, and in line with the sentiment expressed by movements like [Do Not Track,](http://blog.sidstamm.com/2011/01/opting-out-of-behavioral-ads.html) which hope to block information harvesting techniques employed by behavioural ad networks.
The trouble is that opt-in systems carry more interface overhead than opt-out ones, because a request for permission has to be made to every user. Article 66 of the directive says:
>
> "The methods of providing information and offering the right to refuse should
> be as user-friendly as possible."
>
>
>
Unfortunately, they leave the actual method as an exercise for the reader. This is probably a good thing, because having the method dictated might make implementing the law even more painful. That said, it still raises a lot of questions about the best way to gain consent.
The ICO has stepped in to offer a list of six methods to request cookies ([see page 6](http://www.ico.gov.uk/news/current_topics/%7E/media/documents/library/Privacy_and_electronic/Practical_application/advice_on_the_new_cookies_regulations.ashx)). They admit that no solution is ideal:
1. **Pop ups** (ugly - see [this discussion](https://ux.stackexchange.com/q/7318/5124) - and often ignored by users)
2. **New terms and conditions** (users must explicitly agree to them before using the site)
3. **Settings-led consent** (good for visual customisation, not so good for analytics)
4. **Feature-led consent** (still have to make users aware that cookies are in use)
5. **Functional uses** (they suggest a permanent 'permissions' area with notifications)
6. **Via third parties** (but they don't know how the laws apply yet)
Since there's no 'one solution fits all' approach to request permission to store cookies, each site owner has to come up with their own way of doing it. Because no real thought has been given to standardising the request format or presenting a common look and feel, we're likely to see a hodge-podge of different pop ups and implementations.
### Shouldn't browsers be handling this?
The ideal scenario might be to delegate all of this to the browser, but controls for cookies aren't mature enough and, even if browser updates brought granular cookie support, we'd still have to accommodate older browsers, which makes some kind of in-page request inevitable.
### Does it present a commercial disadvantage?
The new privacy laws might make EU Web services less attractive than US ones. As Nick Halsted of TweetMeme says:
>
> "If you go to two websites with identical functionality and one of them asks you to sign a big scary box that says ‘I am tracking everything about you’, and the U.S. one doesn’t, which one are you going to sign up for?" [[source](http://blogs.wsj.com/tech-europe/2011/05/09/confusion-surrounds-u-k-cookie-guidelines/)]
>
>
>
Not only might the addition of a modal permissions bar result in decreased sign ups and engagement, but we can't even split-test alternative request methods, because tracking the results of a split test first requires us to ask the user for permission.
What's more, if it turns out that EU businesses can't use Google Analytics et al without permission from each visitor (when US businesses can), isn't that a competitive disadvantage too? The US already has a thriving start-up community and funding ecosystem. Some would argue that privacy directives, while great for users, are a pain for businesses because they further stifle those competing with companies outside the EU.
### Has it really been thought through?
While the goal of empowering users with decisions over their own privacy is a noble one, the usability aspects haven't been thought through. The good news is that (in the UK, at least) we have until May 2012 to figure something out.
In short, it's nothing to *worry* about, but there's a lot to *think* about. Once the ICO clarifies the case for third party cookies and other EU data protection officers have done the same, it's important that European webmasters pool resources to present a unified solution. | It appears to be painful for people who read the headlines and don't know that about those allowed exceptions.
It is also painful if you have cookies for statistical purposes as they aren't allowed without consent:
>
> The exception would not apply, for
> example, just because you have
> decided that your website is more
> attractive if you remember users’
> preferences or if you decide to use a
> cookie to collect statistical
> information about the use of your
> website.
>
>
>
<http://www.ico.gov.uk/~/media/documents/library/Privacy_and_electronic/Practical_application/advice_on_the_new_cookies_regulations.pdf>
It's also painful because although it's easy to put JavaScript on your site that does statistics tracking it's not easy unless you've seen that plugin. |
14,472 | I am confused by all the excitement surrounding the EU cookie directive; why is it such a painful thing?
As far as I can see cookies that are required for your site to function are allowed such as shopping carts and site logins. Am I missing something here?
The original HTTP specification was designed to work in a stateless way so to my mind this is a stepping stone in the right direction towards stateless RESTful websites. Why should state be added to the process when it is not needed.
There is plenty of mileage left in Digest Auth etc so why is everyone worried?
An obvious answer might be that Google Analytics needs to set cookies to be able to track traffic. There is a somewhat unsatisfactory answer to this point: <http://cookies.dev.wolf-software.com>
So have I missed something that I should be panicking about? What has you worried about it? | 2011/05/27 | ['https://webmasters.stackexchange.com/questions/14472', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/7473/'] | The "excitement" relates to confusion about how the new directive (PDF: [2009/136/EC](http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ%3aL:2009:337:0011:0036%3aEn%3aPDF)) should be interpreted and implemented, and whether or not it's fair to European webmasters:
### Do the laws apply to third party cookies?
The UK data protection body in charge of enforcing the laws in Britain says in their guidelines that they're seeking clarification ([see my answer here](https://webmasters.stackexchange.com/questions/14473/google-analytics-and-the-eu-cookie-directive-who-will-fall-foul-of-the-law-goog/14478#14478)), but until then, we don't know whether we'll have to ask permission to use third-party cookies from Google Analytics, for example.
### Might the laws cripple EU websites?
If it turns out that the new laws require European webmasters to ask each visitor's permission to use third-party cookies, this will affect a lot of websites and render analytics, affiliate systems, usability testing, and even video embedding from third-parties (many of which use cookies) unusable or far less effective. It will also require many site owners who otherwise wouldn't have had to issue a request to store cookies to suddenly do so, drop the services, or seek cookie-less alternatives.
### Does the directive apply to services hosted outside of the EU?
Related to the above, if I run a business from the UK but run a blog on a hosted service outside the EU that makes use of 'unnecessary' cookies, must I rebuild my theme to request permission to use them? If so, will the service be prepared to provide this functionality? If not, do I have to migrate my blog elsewhere? These questions are yet to be answered.
### How best to obtain permission?
The new directive exists to ensure that people without technical knowledge have the same control over their privacy as more technical users. It does this by turning an opt-out system ("here's a cookie, you can always vomit it up if you don't want it") into an opt-in system ("would you like a cookie? here's what's in it...").
The new laws are great for consumers, welcomed by privacy groups, more closely aligned with opt-in email and permission marketing conduct, and in line with the sentiment expressed by movements like [Do Not Track,](http://blog.sidstamm.com/2011/01/opting-out-of-behavioral-ads.html) which hope to block information harvesting techniques employed by behavioural ad networks.
The trouble is that opt-in systems carry more interface overhead than opt-out ones, because a request for permission has to be made to every user. Article 66 of the directive says:
>
> "The methods of providing information and offering the right to refuse should
> be as user-friendly as possible."
>
>
>
Unfortunately, they leave the actual method as an exercise for the reader. This is probably a good thing, because having the method dictated might make implementing the law even more painful. That said, it still raises a lot of questions about the best way to gain consent.
The ICO has stepped in to offer a list of six methods to request cookies ([see page 6](http://www.ico.gov.uk/news/current_topics/%7E/media/documents/library/Privacy_and_electronic/Practical_application/advice_on_the_new_cookies_regulations.ashx)). They admit that no solution is ideal:
1. **Pop ups** (ugly - see [this discussion](https://ux.stackexchange.com/q/7318/5124) - and often ignored by users)
2. **New terms and conditions** (users must explicitly agree to them before using the site)
3. **Settings-led consent** (good for visual customisation, not so good for analytics)
4. **Feature-led consent** (still have to make users aware that cookies are in use)
5. **Functional uses** (they suggest a permanent 'permissions' area with notifications)
6. **Via third parties** (but they don't know how the laws apply yet)
Since there's no 'one solution fits all' approach to request permission to store cookies, each site owner has to come up with their own way of doing it. Because no real thought has been given to standardising the request format or presenting a common look and feel, we're likely to see a hodge-podge of different pop ups and implementations.
### Shouldn't browsers be handling this?
The ideal scenario might be to delegate all of this to the browser, but controls for cookies aren't mature enough and, even if browser updates brought granular cookie support, we'd still have to accommodate older browsers, which makes some kind of in-page request inevitable.
### Does it present a commercial disadvantage?
The new privacy laws might make EU Web services less attractive than US ones. As Nick Halsted of TweetMeme says:
>
> "If you go to two websites with identical functionality and one of them asks you to sign a big scary box that says ‘I am tracking everything about you’, and the U.S. one doesn’t, which one are you going to sign up for?" [[source](http://blogs.wsj.com/tech-europe/2011/05/09/confusion-surrounds-u-k-cookie-guidelines/)]
>
>
>
Not only might the addition of a modal permissions bar result in decreased sign ups and engagement, but we can't even split-test alternative request methods, because tracking the results of a split test first requires us to ask the user for permission.
What's more, if it turns out that EU businesses can't use Google Analytics et al without permission from each visitor (when US businesses can), isn't that a competitive disadvantage too? The US already has a thriving start-up community and funding ecosystem. Some would argue that privacy directives, while great for users, are a pain for businesses because they further stifle those competing with companies outside the EU.
### Has it really been thought through?
While the goal of empowering users with decisions over their own privacy is a noble one, the usability aspects haven't been thought through. The good news is that (in the UK, at least) we have until May 2012 to figure something out.
In short, it's nothing to *worry* about, but there's a lot to *think* about. Once the ICO clarifies the case for third party cookies and other EU data protection officers have done the same, it's important that European webmasters pool resources to present a unified solution. | Most complaints I've seen fall outside of the exceptions you've mentioned and more into the realm of marketing/data. Some of the big issues I see are:
1. Standard analytics (Google Analytics and others)
2. Additional testing (A/B testing etc for usability/conversion rate optimization)
3. Affiliate tracking.
4. Re-marketing there are many programs now that drop a cookie and generate dynamic ads based on user's activity.
5. Personalization - such as offering personalized product recommendations based on previously viewed products etc.
Admittedly I'm US based so I haven't followed this as closely as others may have but I don't believe any of the above fall into the "exceptions" and all are widely used. |
21,041,564 | Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC?
```
List<Long> someList = new ArrayList<Long>();
someList.add(1l);
someList = new ArrayList<Long>(); //Will this cause GC of the old `someList`?
```
So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing? | 2014/01/10 | ['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/'] | Use [ArrayList.clear();](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear%28%29) instead of creating new ArrayList
```
someList.clear();
``` | The older `ArrayList` will become eligible for garbage collection on line 3, provided there is no other reference pointing to it, as it seems is the case here. However, it isn't guaranteed to be GCed right away.
If you want to avoid extra creation of the `ArrayList`, you can simply clear it by using `List#clear()` method:
```
someList.clear();
``` |
21,041,564 | Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC?
```
List<Long> someList = new ArrayList<Long>();
someList.add(1l);
someList = new ArrayList<Long>(); //Will this cause GC of the old `someList`?
```
So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing? | 2014/01/10 | ['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/'] | The older `ArrayList` will become eligible for garbage collection on line 3, provided there is no other reference pointing to it, as it seems is the case here. However, it isn't guaranteed to be GCed right away.
If you want to avoid extra creation of the `ArrayList`, you can simply clear it by using `List#clear()` method:
```
someList.clear();
``` | I assume by your question you want to keep a reference to the old list (and also its content, otherwise whats the point)?
If so then just add a reference to it before reassigning:
```
List<Long> someList = new ArrayList<Long>();
someList.add(1L);
List<Long> oldList = someList;
someList = new ArrayList<Long>();
``` |
21,041,564 | Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC?
```
List<Long> someList = new ArrayList<Long>();
someList.add(1l);
someList = new ArrayList<Long>(); //Will this cause GC of the old `someList`?
```
So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing? | 2014/01/10 | ['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/'] | Use [ArrayList.clear();](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear%28%29) instead of creating new ArrayList
```
someList.clear();
``` | I assume by your question you want to keep a reference to the old list (and also its content, otherwise whats the point)?
If so then just add a reference to it before reassigning:
```
List<Long> someList = new ArrayList<Long>();
someList.add(1L);
List<Long> oldList = someList;
someList = new ArrayList<Long>();
``` |
38,645 | Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that "the older you are, the less detrimental the effects of radiation is." The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age?
---
Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women "were allowed back into the area," and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34). | 2017/06/10 | ['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/'] | It seems plausible that such a "pool" did exist at Auschwitz in 1944. It probably served several purposes: A pool for swimming in by hard working prisoners, a fire reservoir tank and possible to fool the West at the same time who took aerial photos of the camp in order to see the living conditions of the prisoners.
>
> Barbara Cherish, the daughter of Arthur Liebehenschel, wrote a book which was published in 2009, entitled "My father, the Auschwitz commandant." In her book, Barbara credits her father with building a swimming pool for the use of the prisoners. Liebehenschel was the Commandant of the Auschwitz main camp for five months, beginning on December 1, 1943. Liebehenschel is credited with other improvements at Auschwitz I, including the tearing down of the standing cells in Block 11. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html)
>
>
>
[](https://i.stack.imgur.com/HCqUM.jpg)
>
> The photo [above] shows what the swimming pool looked like in 1996 before preservation work began. The high diving board is at the far end in the background of the photo. The diving board itself is now gone. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html)
>
>
> | >
> Is it a "fire brigade reservoir", which I assume has something to do with fire safety although I don't know exactly what this means or why they would need it?
>
>
>
A fire brigade reservoir is a [supply of water](http://www.firerescuemagazine.com/articles/print/volume-9/issue-3/firefighting-operations/obtaining-water-without-a-hydrant.html) that can be pumped at a fire. They are often used in places where [fire hydrants are not available](http://www.bcfpd.org/index.php/faq/put-fires-no-fire-hydrants) or are insufficient to meet the demand. For example, where people get their water from a well rather than a municipal source.
As a practical matter, almost any water can be used (although some may be easier to use). So if that was something that collected water, it could be a fire brigade reservoir. That is true even if it was also used as a swimming pool.
My point being that it being a fire brigade reservoir would not prevent it from being a swimming pool. Or vice versa. They are not mutually exclusive uses.
In regards to whether this particular water was actually a swimming pool, I have nothing to add to the [other answer](https://skeptics.stackexchange.com/a/38643/30596).
Additional sources:
* [Quora](https://www.quora.com/In-neighborhoods-lacking-fire-hydrants-what-do-fire-departments-use-as-water-sources-when-dealing-with-fires)
* [Facebook](https://www.facebook.com/notes/eastern-panhandle-working-fires/what-if-there-is-not-a-fire-hydrant-nearby-where-i-live/540193675999432/) |
38,645 | Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that "the older you are, the less detrimental the effects of radiation is." The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age?
---
Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women "were allowed back into the area," and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34). | 2017/06/10 | ['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/'] | It seems plausible that such a "pool" did exist at Auschwitz in 1944. It probably served several purposes: A pool for swimming in by hard working prisoners, a fire reservoir tank and possible to fool the West at the same time who took aerial photos of the camp in order to see the living conditions of the prisoners.
>
> Barbara Cherish, the daughter of Arthur Liebehenschel, wrote a book which was published in 2009, entitled "My father, the Auschwitz commandant." In her book, Barbara credits her father with building a swimming pool for the use of the prisoners. Liebehenschel was the Commandant of the Auschwitz main camp for five months, beginning on December 1, 1943. Liebehenschel is credited with other improvements at Auschwitz I, including the tearing down of the standing cells in Block 11. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html)
>
>
>
[](https://i.stack.imgur.com/HCqUM.jpg)
>
> The photo [above] shows what the swimming pool looked like in 1996 before preservation work began. The high diving board is at the far end in the background of the photo. The diving board itself is now gone. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html)
>
>
> | According to the [Third Reich in Ruins](http://www.thirdreichruins.com/auschwitz.htm), the below photo of the pool was obtained from [Auschwitz-Birkenau State Museum](http://www.auschwitz.org/). The site says:
>
> This water tank was built as a reservoir for fire fighting purposes (there are several such fire fighting tanks around the Birkenau camp and the Auschwitz Erweiterungslager camp extension), but it was modified by the prisoner fire brigade into a swimming pool, complete with a diving board and starting blocks. Privileged Polish and other political prisoners (non-Jewish), in addition to the fire brigade, could use this pool.
>
>
>
[](https://i.stack.imgur.com/W6gZ9.jpg) |
38,645 | Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that "the older you are, the less detrimental the effects of radiation is." The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age?
---
Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women "were allowed back into the area," and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34). | 2017/06/10 | ['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/'] | According to the [Third Reich in Ruins](http://www.thirdreichruins.com/auschwitz.htm), the below photo of the pool was obtained from [Auschwitz-Birkenau State Museum](http://www.auschwitz.org/). The site says:
>
> This water tank was built as a reservoir for fire fighting purposes (there are several such fire fighting tanks around the Birkenau camp and the Auschwitz Erweiterungslager camp extension), but it was modified by the prisoner fire brigade into a swimming pool, complete with a diving board and starting blocks. Privileged Polish and other political prisoners (non-Jewish), in addition to the fire brigade, could use this pool.
>
>
>
[](https://i.stack.imgur.com/W6gZ9.jpg) | >
> Is it a "fire brigade reservoir", which I assume has something to do with fire safety although I don't know exactly what this means or why they would need it?
>
>
>
A fire brigade reservoir is a [supply of water](http://www.firerescuemagazine.com/articles/print/volume-9/issue-3/firefighting-operations/obtaining-water-without-a-hydrant.html) that can be pumped at a fire. They are often used in places where [fire hydrants are not available](http://www.bcfpd.org/index.php/faq/put-fires-no-fire-hydrants) or are insufficient to meet the demand. For example, where people get their water from a well rather than a municipal source.
As a practical matter, almost any water can be used (although some may be easier to use). So if that was something that collected water, it could be a fire brigade reservoir. That is true even if it was also used as a swimming pool.
My point being that it being a fire brigade reservoir would not prevent it from being a swimming pool. Or vice versa. They are not mutually exclusive uses.
In regards to whether this particular water was actually a swimming pool, I have nothing to add to the [other answer](https://skeptics.stackexchange.com/a/38643/30596).
Additional sources:
* [Quora](https://www.quora.com/In-neighborhoods-lacking-fire-hydrants-what-do-fire-departments-use-as-water-sources-when-dealing-with-fires)
* [Facebook](https://www.facebook.com/notes/eastern-panhandle-working-fires/what-if-there-is-not-a-fire-hydrant-nearby-where-i-live/540193675999432/) |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | I tried [android-CalendarView](http://developer.android.com/reference/android/widget/CalendarView.html), Caldroid and later switched to **[android-times-square](https://github.com/square/android-times-square)** which has this improvements:
* Much faster switching to other months due to vertical scrolling (no pagination which responds slow in Caldroid)
* Indicators, highlighted dates (at least in [this fork](https://github.com/HannahMitt/android-times-square) for android)
* iOS version available with the same look and feel
* looks cleaner than the android version because months are clearly separated

Just like Caldroid it is a part of [a productive app](http://corner.squareup.com/2013/01/times-square.html). | it is possible but not easy.
<http://jimblackler.net/blog/?p=151&cpage=2#comment-52767>
and
```
private void InsertAppointment(String strTitle, String strDescription, String strEventLocation, long StartDateTime, long EndDateTime, boolean bAllDay, boolean bHasAlarm){
int tAllday;
int tHasAlarm;
if (bAllDay = true){
tAllday = 1;
}
else
tAllday = 0;
if (bHasAlarm = true){
tHasAlarm = 1;
}
else
tHasAlarm = 0;
ContentValues event = new ContentValues();
// Calendar in which you want to add Evenet
event.put("calendar_id", CalId); //CalId
event.put("title", strTitle);
event.put("description", strDescription);
event.put("eventLocation", strEventLocation);
event.put("dtstart", StartDateTime);
event.put("dtend", EndDateTime );
event.put("allDay", 0);
event.put("hasAlarm", 0);
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
// event is added
getContentResolver().insert(eventsUri, event);
}
```
a quick search on
`content://com.android.calendar/calendars`
will help get you started. but I'm not finished mine yet I just can't get the data out yet. but it is possible |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly. | it is possible but not easy.
<http://jimblackler.net/blog/?p=151&cpage=2#comment-52767>
and
```
private void InsertAppointment(String strTitle, String strDescription, String strEventLocation, long StartDateTime, long EndDateTime, boolean bAllDay, boolean bHasAlarm){
int tAllday;
int tHasAlarm;
if (bAllDay = true){
tAllday = 1;
}
else
tAllday = 0;
if (bHasAlarm = true){
tHasAlarm = 1;
}
else
tHasAlarm = 0;
ContentValues event = new ContentValues();
// Calendar in which you want to add Evenet
event.put("calendar_id", CalId); //CalId
event.put("title", strTitle);
event.put("description", strDescription);
event.put("eventLocation", strEventLocation);
event.put("dtstart", StartDateTime);
event.put("dtend", EndDateTime );
event.put("allDay", 0);
event.put("hasAlarm", 0);
Uri eventsUri = Uri.parse("content://com.android.calendar/events");
// event is added
getContentResolver().insert(eventsUri, event);
}
```
a quick search on
`content://com.android.calendar/calendars`
will help get you started. but I'm not finished mine yet I just can't get the data out yet. but it is possible |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | Android now provides three ways to incorporate calendars in your app.
1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such.
2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar.
3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases. | You can use MFCalendarView: <https://github.com/MustafaFerhan/MFCalendarView>
set multiple events;
```
ArrayList<String> eventDays = new ArrayList<String>();
eventDays.add("2014-02-25");
eventDays.add(Util.getCurrentDate());
mf.setEvents(eventDays);
```
and handle with MFCalendarView's listener:
```
mf = (MFCalendarView) findViewById(R.id.mFCalendarView);
mf.setOnCalendarViewListener(new onMFCalendarViewListener() {
@Override
public void onDisplayedMonthChanged(int month, int year, String monthStr) {
}
@Override
public void onDateChanged(String date) {
}
});
```
It's very simple. |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | I tried [android-CalendarView](http://developer.android.com/reference/android/widget/CalendarView.html), Caldroid and later switched to **[android-times-square](https://github.com/square/android-times-square)** which has this improvements:
* Much faster switching to other months due to vertical scrolling (no pagination which responds slow in Caldroid)
* Indicators, highlighted dates (at least in [this fork](https://github.com/HannahMitt/android-times-square) for android)
* iOS version available with the same look and feel
* looks cleaner than the android version because months are clearly separated

Just like Caldroid it is a part of [a productive app](http://corner.squareup.com/2013/01/times-square.html). | You can use the android calendar picker I have created, it is open source project and you can easily add it to your project.
<https://github.com/sancarbar/Android-Calendar-Picker> |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly. | You can use the android calendar picker I have created, it is open source project and you can easily add it to your project.
<https://github.com/sancarbar/Android-Calendar-Picker> |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | I wrote Caldroid library (<https://github.com/roomorama/Caldroid>) that is simple to setup and have many features such as setup min/max date, disabled dates, select date range, swipe to change month, fully localized, support rotation properly etc. It's easy to customize the look and feel. Just to share if someone might find it useful :) | You can use MFCalendarView: <https://github.com/MustafaFerhan/MFCalendarView>
set multiple events;
```
ArrayList<String> eventDays = new ArrayList<String>();
eventDays.add("2014-02-25");
eventDays.add(Util.getCurrentDate());
mf.setEvents(eventDays);
```
and handle with MFCalendarView's listener:
```
mf = (MFCalendarView) findViewById(R.id.mFCalendarView);
mf.setOnCalendarViewListener(new onMFCalendarViewListener() {
@Override
public void onDisplayedMonthChanged(int month, int year, String monthStr) {
}
@Override
public void onDateChanged(String date) {
}
});
```
It's very simple. |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | Android now provides three ways to incorporate calendars in your app.
1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such.
2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar.
3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases. | You can use the android calendar picker I have created, it is open source project and you can easily add it to your project.
<https://github.com/sancarbar/Android-Calendar-Picker> |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly. | You can use MFCalendarView: <https://github.com/MustafaFerhan/MFCalendarView>
set multiple events;
```
ArrayList<String> eventDays = new ArrayList<String>();
eventDays.add("2014-02-25");
eventDays.add(Util.getCurrentDate());
mf.setEvents(eventDays);
```
and handle with MFCalendarView's listener:
```
mf = (MFCalendarView) findViewById(R.id.mFCalendarView);
mf.setOnCalendarViewListener(new onMFCalendarViewListener() {
@Override
public void onDisplayedMonthChanged(int month, int year, String monthStr) {
}
@Override
public void onDateChanged(String date) {
}
});
```
It's very simple. |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | This library seems really nice and with a more modern UI (Material Design) :
<https://github.com/prolificinteractive/material-calendarview>
You just have to import it with gradle:
```
compile 'com.prolificinteractive:material-calendarview:1.4.0'
```
And add it in your layout:
```
<com.prolificinteractive.materialcalendarview.MaterialCalendarView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/calendarView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:mcv_showOtherDates="all"
app:mcv_selectionColor="#00F"
/>
```
[](https://i.stack.imgur.com/Fb4xc.gif) | You can use MFCalendarView: <https://github.com/MustafaFerhan/MFCalendarView>
set multiple events;
```
ArrayList<String> eventDays = new ArrayList<String>();
eventDays.add("2014-02-25");
eventDays.add(Util.getCurrentDate());
mf.setEvents(eventDays);
```
and handle with MFCalendarView's listener:
```
mf = (MFCalendarView) findViewById(R.id.mFCalendarView);
mf.setOnCalendarViewListener(new onMFCalendarViewListener() {
@Override
public void onDisplayedMonthChanged(int month, int year, String monthStr) {
}
@Override
public void onDateChanged(String date) {
}
});
```
It's very simple. |
3,702,998 | I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling.
1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar)
2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use?
I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user. | 2010/09/13 | ['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/'] | I wrote Caldroid library (<https://github.com/roomorama/Caldroid>) that is simple to setup and have many features such as setup min/max date, disabled dates, select date range, swipe to change month, fully localized, support rotation properly etc. It's easy to customize the look and feel. Just to share if someone might find it useful :) | Android now provides three ways to incorporate calendars in your app.
1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such.
2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar.
3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases. |
30,189,605 | I've been playing around with flex box and I would like to center the "Logo" test in the upper left corner vertically in its blue container.
You can see it here: <http://codepen.io/TimRos/pen/MwKNgw>
```
* {
margin: 0;
padding: 0;
}
.box {
color: white;
font-size: 80px;
text-align: center;
text-shadow: 4px 4px 3px black;
}
/* COLORS & Style
===================================== */
.main-header { background: #e3e3e3; }
.main-footer { background: #e3e3e3; }
.main-content { background: #e3e3e3; }
.main-wrapper {
box-shadow: 2px 2px 10px #333;
}
.main-wrapper {
width: 80%;
margin: 0 auto;
}
/* HEAD
===================================== */
.main-header {
width: 100%;
height: 100px;
border-bottom: 1px solid black;
}
.main-nav {
list-style: none;
display: flex;
flex-flow: row wrap;
justify-content: flex-end;
align-items: flex-end;
height: 100%;
}
.main-nav li {
margin-left: 8px;
margin-right: 8px;
}
#logo {
margin-right: auto; /* Align Logo to Left, Nav to the right*/
margin-left: 0;
align-self: center;
}
.main-nav li:last-child {
margin-right: 0;
}
.main-nav li {
background-color: #3f8abf;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
border-bottom: 4px solid firebrick;
}
.main-nav a {
text-decoration: none;
color: white;
text-align: center;
font-weight: bold;
padding: 8px 15px;
display: block;
width: 100px;
}
#logo {
border-top-left-radius: 0;
border-bottom-right-radius: 5px;
border-bottom: 0;
border-left: 4px solid firebrick;
padding: 0;
height: 100%;
}
#logo h1 {
padding: 0;
margin: 0;
}
/* CONTENT
===================================== */
.main-content {
padding: 15px;
}
h3 {
margin-bottom: 15px;
}
/* FOOTER
===================================== */
.main-footer {
border-top: 1px solid black;
text-align: center;
padding: 5px;
}
```
I tried margin and padding auto but that doesnt seem to work, please help! | 2015/05/12 | ['https://Stackoverflow.com/questions/30189605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4400418/'] | This approach uses a public enum and sets the style variable according to the users menu choice:
```
package chess;
//...
public class Screen extends JFrame
implements ActionListener {
private JMenuItem random = new JMenuItem("Random");
private JMenuItem aggressive = new JMenuItem("Aggressive");
private JMenuItem human = new JMenuItem("Human");
public enum PlayStyle {Random, Aggressive, Human};
private PlayStyle style;
public Screen(Board board) {
//menuBar items
menu.add(random);
random.addActionListener(this);
menu.add(aggressive);
aggressive.addActionListener(this);
menu.add(human);
human.addActionListener(this);
//....
//sets up board of buttons and adds actionListener to each.
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == random) {
style=PlayStyle.Random;
}
if (e.getSource() == aggressive) {
style=PlayStyle.Aggressive;
}
if (e.getSource() == human) {
style=PlayStyle.Human;
}
//code for the board buttons - nothing to do with the menu.
//....
}
public PlayStyle getStyle(){
return style;
}
}
```
This is the class that contains the main method:
```
package chess;
import chess.Screen.PlayStyle;
public class Chess{
public static void main(String [ ] args){
Screen s = new Screen(board);
// this attempt will work
if (s.getStyle()==PlayStyle.Random) {
...
} else if (s.getStyle()==PlayStyle.Aggressive){
...
``` | You are calling a method and it seems that you want to use something that comes back from that method but the method itself returns nothing, i.e. "void". I changed your Screen class so that the method returns something now.
```
public class Screen extends JFrame
implements ActionListener {
public Source actionPerformed(ActionEvent e) {
....
if(e.getSource() == random){
}
if(e.getSource() == aggressive){
}
if(e.getSource() == human){
}
return e.getSource()
}
```
The main method will now be able to receive a result from the call and use it. |
1,328,078 | In the "Control Panel > Ease of Access Centre > Make the keyboard easier to use" is an option to "Underline keyboard shortcuts and access keys."
Is there a way of programmatically switching this on and off?
I'm using Visual Basic Scripts, but can use .NET. | 2009/08/25 | ['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/'] | 1. Run Registry Editor and go to HKEY\_CURRENT\_USER\Control Panel\Accessibility\Keyboard Preference
2. Now create or modify a String Value (REG\_SZ) called On and set its value to 1
Information is comming from:
<http://www.windowsvalley.com/get-underlined-keyboard-shortcuts-and-access-keys-permanently/> | AFAIK, there's no way to toggle this option programmatically except for automating the approproate GUI actions (opening the Control Panel, switching the option on/off and applying the changes). In this case, I'd recommend using [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) to automate the option switching. |
1,328,078 | In the "Control Panel > Ease of Access Centre > Make the keyboard easier to use" is an option to "Underline keyboard shortcuts and access keys."
Is there a way of programmatically switching this on and off?
I'm using Visual Basic Scripts, but can use .NET. | 2009/08/25 | ['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/'] | AFAIK, there's no way to toggle this option programmatically except for automating the approproate GUI actions (opening the Control Panel, switching the option on/off and applying the changes). In this case, I'd recommend using [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) to automate the option switching. | It turns out you CAN programatically change the “underline keyboard shortcuts” option in your own application. You need to send the WM\_UPDATEUISTATE message to your main form according to the documentation found at: <https://learn.microsoft.com/en-us/windows/win32/menurc/wm-updateuistate>
Since you mentioned Visual Basic, here's how to do it:
```
Private Const WM_UPDATEUISTATE = &H128
Private Const UIS_CLEAR = &H2
Private Const UISF_HIDEACCEL = &H2
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As
Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
```
Then in the "Form\_Load" event send the message and it will activate keyboard shortcuts underlining for all controls and menus present on that form:
```
Private Sub Form_Load()
PostMessage Me.hWnd, WM_UPDATEUISTATE, UIS_CLEAR + UISF_HIDEACCEL * 65536, 0
End Sub
``` |
1,328,078 | In the "Control Panel > Ease of Access Centre > Make the keyboard easier to use" is an option to "Underline keyboard shortcuts and access keys."
Is there a way of programmatically switching this on and off?
I'm using Visual Basic Scripts, but can use .NET. | 2009/08/25 | ['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/'] | 1. Run Registry Editor and go to HKEY\_CURRENT\_USER\Control Panel\Accessibility\Keyboard Preference
2. Now create or modify a String Value (REG\_SZ) called On and set its value to 1
Information is comming from:
<http://www.windowsvalley.com/get-underlined-keyboard-shortcuts-and-access-keys-permanently/> | It turns out you CAN programatically change the “underline keyboard shortcuts” option in your own application. You need to send the WM\_UPDATEUISTATE message to your main form according to the documentation found at: <https://learn.microsoft.com/en-us/windows/win32/menurc/wm-updateuistate>
Since you mentioned Visual Basic, here's how to do it:
```
Private Const WM_UPDATEUISTATE = &H128
Private Const UIS_CLEAR = &H2
Private Const UISF_HIDEACCEL = &H2
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hWnd As
Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
```
Then in the "Form\_Load" event send the message and it will activate keyboard shortcuts underlining for all controls and menus present on that form:
```
Private Sub Form_Load()
PostMessage Me.hWnd, WM_UPDATEUISTATE, UIS_CLEAR + UISF_HIDEACCEL * 65536, 0
End Sub
``` |
11,500 | The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve.
The available data are as follows:
1. I have 100 patients and I need to rank order them in terms of how healthy they are.
2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient.
Should I have some sort of doctor's "expert judgement based ranking" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2).
How would you come up with a simple "scoring" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients? | 2011/06/02 | ['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/'] | A simple approach would be to calculate the sum score or the mean. Another approach would not assume that all variables are of equal importance and we could calculate a weighted mean.
Let's assume we have the following 10 patients and variables `v1` to `v5`.
```
> set.seed(1)
> df <- data.frame(v1 = sample(1:5, 10, replace = TRUE),
+ v2 = sample(1:5, 10, replace = TRUE),
+ v3 = sample(1:5, 10, replace = TRUE),
+ v4 = sample(1:5, 10, replace = TRUE),
+ v5 = sample(1:5, 10, replace = TRUE))
>
> df
v1 v2 v3 v4 v5
1 2 2 5 3 5
2 2 1 2 3 4
3 3 4 4 3 4
4 5 2 1 1 3
5 2 4 2 5 3
6 5 3 2 4 4
7 5 4 1 4 1
8 4 5 2 1 3
9 4 2 5 4 4
10 1 4 2 3 4
```
*1. Sum score and ranks*
```
> df$sum <- rowSums(df)
> df$ranks <- abs(rank(df$sum) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks
1 2 2 5 3 5 17 4.0
2 2 1 2 3 4 12 9.5
3 3 4 4 3 4 18 2.5
4 5 2 1 1 3 12 9.5
5 2 4 2 5 3 16 5.0
6 5 3 2 4 4 18 2.5
7 5 4 1 4 1 15 6.5
8 4 5 2 1 3 15 6.5
9 4 2 5 4 4 19 1.0
10 1 4 2 3 4 14 8.0
```
*2. Mean score and ranks (note: `ranks` and `ranks2` are equal)*
```
> df$means <- apply(df[, 1:5], 1, mean)
> df$ranks2 <- abs(rank(df$mean) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks means ranks2
1 2 2 5 3 5 17 4.0 3.4 4.0
2 2 1 2 3 4 12 9.5 2.4 9.5
3 3 4 4 3 4 18 2.5 3.6 2.5
4 5 2 1 1 3 12 9.5 2.4 9.5
5 2 4 2 5 3 16 5.0 3.2 5.0
6 5 3 2 4 4 18 2.5 3.6 2.5
7 5 4 1 4 1 15 6.5 3.0 6.5
8 4 5 2 1 3 15 6.5 3.0 6.5
9 4 2 5 4 4 19 1.0 3.8 1.0
10 1 4 2 3 4 14 8.0 2.8 8.0
```
*3. Weighted mean score (i.e. I assume that V3 and V4 are more important than v1, v2 or v5)*
```
> weights <- c(0.5, 0.5, 1, 1, 0.5)
> wmean <- function(x, w = weights){weighted.mean(x, w = w)}
> df$wmeans <- sapply(split(df[, 1:5], 1:10), wmean)
> df$ranks3 <- abs(rank(df$wmeans) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks means ranks2 wmeans ranks3
1 2 2 5 3 5 17 4.0 3.4 4.0 3.571429 2.5
2 2 1 2 3 4 12 9.5 2.4 9.5 2.428571 9.0
3 3 4 4 3 4 18 2.5 3.6 2.5 3.571429 2.5
4 5 2 1 1 3 12 9.5 2.4 9.5 2.000000 10.0
5 2 4 2 5 3 16 5.0 3.2 5.0 3.285714 5.0
6 5 3 2 4 4 18 2.5 3.6 2.5 3.428571 4.0
7 5 4 1 4 1 15 6.5 3.0 6.5 2.857143 6.0
8 4 5 2 1 3 15 6.5 3.0 6.5 2.571429 8.0
9 4 2 5 4 4 19 1.0 3.8 1.0 4.000000 1.0
10 1 4 2 3 4 14 8.0 2.8 8.0 2.714286 7.0
``` | I would just simply sum them up, weighting each factor if necessary. |
11,500 | The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve.
The available data are as follows:
1. I have 100 patients and I need to rank order them in terms of how healthy they are.
2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient.
Should I have some sort of doctor's "expert judgement based ranking" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2).
How would you come up with a simple "scoring" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients? | 2011/06/02 | ['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/'] | *Any* function $f: \mathbb{R}^5 \to \mathbb{R}$ that is separately increasing in each of its arguments will work. For example, you can select positive parameters $\alpha\_i$ and any real parameters $\lambda\_i$ and rank the data $(x\_1, x\_2, x\_3, x\_4, x\_5)$ according to the values of
$$\sum\_{i=1}^{5} \alpha\_i (x\_i^{\lambda\_i} - 1) / \lambda\_i \text{.}$$
Evidently some criterion is needed to select among such a rich set of distinctly different scores. In particular, the simple obvious solutions (frequently employed, unfortunately) of just summing the scores or first "normalizing" them in some fashion and then summing them will suffer from this lack of grounding in reality. To put it another way: *any* answer that does not derive its support from additional information is a pure fabrication.
Because this problem is essentially the same as [Creating an index of quality from multiple variables to enable rank ordering](https://stats.stackexchange.com/questions/9358/creating-an-index-of-quality-from-multiple-variables-to-enable-rank-ordering), I refer you to the discussion there for more information. | I would just simply sum them up, weighting each factor if necessary. |
11,500 | The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve.
The available data are as follows:
1. I have 100 patients and I need to rank order them in terms of how healthy they are.
2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient.
Should I have some sort of doctor's "expert judgement based ranking" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2).
How would you come up with a simple "scoring" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients? | 2011/06/02 | ['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/'] | I would just simply sum them up, weighting each factor if necessary. | How about generating a synthetic binary target variable first and then running a logistic regression model?
The synthetic variable should be something like... "If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"
Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is? |
11,500 | The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve.
The available data are as follows:
1. I have 100 patients and I need to rank order them in terms of how healthy they are.
2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient.
Should I have some sort of doctor's "expert judgement based ranking" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2).
How would you come up with a simple "scoring" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients? | 2011/06/02 | ['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/'] | A simple approach would be to calculate the sum score or the mean. Another approach would not assume that all variables are of equal importance and we could calculate a weighted mean.
Let's assume we have the following 10 patients and variables `v1` to `v5`.
```
> set.seed(1)
> df <- data.frame(v1 = sample(1:5, 10, replace = TRUE),
+ v2 = sample(1:5, 10, replace = TRUE),
+ v3 = sample(1:5, 10, replace = TRUE),
+ v4 = sample(1:5, 10, replace = TRUE),
+ v5 = sample(1:5, 10, replace = TRUE))
>
> df
v1 v2 v3 v4 v5
1 2 2 5 3 5
2 2 1 2 3 4
3 3 4 4 3 4
4 5 2 1 1 3
5 2 4 2 5 3
6 5 3 2 4 4
7 5 4 1 4 1
8 4 5 2 1 3
9 4 2 5 4 4
10 1 4 2 3 4
```
*1. Sum score and ranks*
```
> df$sum <- rowSums(df)
> df$ranks <- abs(rank(df$sum) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks
1 2 2 5 3 5 17 4.0
2 2 1 2 3 4 12 9.5
3 3 4 4 3 4 18 2.5
4 5 2 1 1 3 12 9.5
5 2 4 2 5 3 16 5.0
6 5 3 2 4 4 18 2.5
7 5 4 1 4 1 15 6.5
8 4 5 2 1 3 15 6.5
9 4 2 5 4 4 19 1.0
10 1 4 2 3 4 14 8.0
```
*2. Mean score and ranks (note: `ranks` and `ranks2` are equal)*
```
> df$means <- apply(df[, 1:5], 1, mean)
> df$ranks2 <- abs(rank(df$mean) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks means ranks2
1 2 2 5 3 5 17 4.0 3.4 4.0
2 2 1 2 3 4 12 9.5 2.4 9.5
3 3 4 4 3 4 18 2.5 3.6 2.5
4 5 2 1 1 3 12 9.5 2.4 9.5
5 2 4 2 5 3 16 5.0 3.2 5.0
6 5 3 2 4 4 18 2.5 3.6 2.5
7 5 4 1 4 1 15 6.5 3.0 6.5
8 4 5 2 1 3 15 6.5 3.0 6.5
9 4 2 5 4 4 19 1.0 3.8 1.0
10 1 4 2 3 4 14 8.0 2.8 8.0
```
*3. Weighted mean score (i.e. I assume that V3 and V4 are more important than v1, v2 or v5)*
```
> weights <- c(0.5, 0.5, 1, 1, 0.5)
> wmean <- function(x, w = weights){weighted.mean(x, w = w)}
> df$wmeans <- sapply(split(df[, 1:5], 1:10), wmean)
> df$ranks3 <- abs(rank(df$wmeans) - (dim(df)[1] + 1))
> df
v1 v2 v3 v4 v5 sum ranks means ranks2 wmeans ranks3
1 2 2 5 3 5 17 4.0 3.4 4.0 3.571429 2.5
2 2 1 2 3 4 12 9.5 2.4 9.5 2.428571 9.0
3 3 4 4 3 4 18 2.5 3.6 2.5 3.571429 2.5
4 5 2 1 1 3 12 9.5 2.4 9.5 2.000000 10.0
5 2 4 2 5 3 16 5.0 3.2 5.0 3.285714 5.0
6 5 3 2 4 4 18 2.5 3.6 2.5 3.428571 4.0
7 5 4 1 4 1 15 6.5 3.0 6.5 2.857143 6.0
8 4 5 2 1 3 15 6.5 3.0 6.5 2.571429 8.0
9 4 2 5 4 4 19 1.0 3.8 1.0 4.000000 1.0
10 1 4 2 3 4 14 8.0 2.8 8.0 2.714286 7.0
``` | How about generating a synthetic binary target variable first and then running a logistic regression model?
The synthetic variable should be something like... "If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"
Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is? |
11,500 | The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve.
The available data are as follows:
1. I have 100 patients and I need to rank order them in terms of how healthy they are.
2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient.
Should I have some sort of doctor's "expert judgement based ranking" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2).
How would you come up with a simple "scoring" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients? | 2011/06/02 | ['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/'] | *Any* function $f: \mathbb{R}^5 \to \mathbb{R}$ that is separately increasing in each of its arguments will work. For example, you can select positive parameters $\alpha\_i$ and any real parameters $\lambda\_i$ and rank the data $(x\_1, x\_2, x\_3, x\_4, x\_5)$ according to the values of
$$\sum\_{i=1}^{5} \alpha\_i (x\_i^{\lambda\_i} - 1) / \lambda\_i \text{.}$$
Evidently some criterion is needed to select among such a rich set of distinctly different scores. In particular, the simple obvious solutions (frequently employed, unfortunately) of just summing the scores or first "normalizing" them in some fashion and then summing them will suffer from this lack of grounding in reality. To put it another way: *any* answer that does not derive its support from additional information is a pure fabrication.
Because this problem is essentially the same as [Creating an index of quality from multiple variables to enable rank ordering](https://stats.stackexchange.com/questions/9358/creating-an-index-of-quality-from-multiple-variables-to-enable-rank-ordering), I refer you to the discussion there for more information. | How about generating a synthetic binary target variable first and then running a logistic regression model?
The synthetic variable should be something like... "If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"
Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is? |
499,446 | My algorithm textbook has a theorem that says
'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.'
However, it does not provide proof.
Of course I know exponential grows faster than polynomial in most cases, but is it true for all case?
What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point? | 2013/09/20 | ['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/'] | Yes, it is true for all cases. This can be seen by noting that
$$\lim\_{n\to\infty} \frac{n^k}{e^n} = 0$$
for any $k$. This can be seen by an application of L'Hospital's rule a number of times, or by using induction as [here](https://math.stackexchange.com/questions/55468/how-to-prove-that-exponential-grows-faster-than-polynomial). | Hint: Yes. See Taylor expansion of exponential function. |
499,446 | My algorithm textbook has a theorem that says
'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.'
However, it does not provide proof.
Of course I know exponential grows faster than polynomial in most cases, but is it true for all case?
What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point? | 2013/09/20 | ['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/'] | Yes, it is true for all cases. This can be seen by noting that
$$\lim\_{n\to\infty} \frac{n^k}{e^n} = 0$$
for any $k$. This can be seen by an application of L'Hospital's rule a number of times, or by using induction as [here](https://math.stackexchange.com/questions/55468/how-to-prove-that-exponential-grows-faster-than-polynomial). | Let $n = k^2$.
Then $n^c = k^{2c}$ and $2^n = (2^k)^k$.
Clearly $2^k \ge k+1 > k$ so all we need is $k > 2c$.
In general if we want to find $n \in \mathbb{N}$ such that $r^n > n^c$ where $r > 1$, we can do essentially the same:
Let $n = ak^2$ where $a > \log\_r(2)$.
Then $r^n > (2^k)^k$ and $n^c = a^c k^{2c}$.
It is then enough to choose $k$ such that $k > a$ and $k > 3c$, so that $n^c < k^{3c} < (2^k)^k < 2^n$. |
499,446 | My algorithm textbook has a theorem that says
'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.'
However, it does not provide proof.
Of course I know exponential grows faster than polynomial in most cases, but is it true for all case?
What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point? | 2013/09/20 | ['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/'] | Let $n = k^2$.
Then $n^c = k^{2c}$ and $2^n = (2^k)^k$.
Clearly $2^k \ge k+1 > k$ so all we need is $k > 2c$.
In general if we want to find $n \in \mathbb{N}$ such that $r^n > n^c$ where $r > 1$, we can do essentially the same:
Let $n = ak^2$ where $a > \log\_r(2)$.
Then $r^n > (2^k)^k$ and $n^c = a^c k^{2c}$.
It is then enough to choose $k$ such that $k > a$ and $k > 3c$, so that $n^c < k^{3c} < (2^k)^k < 2^n$. | Hint: Yes. See Taylor expansion of exponential function. |
17,809,234 | I'm new to Java, in fact I know next to nothing. I've been interested in the type of data an android app is holding on me. So, I can see within an XML file this app has created strings which appear to to be encrypted using AES128-CBC.
So I've decompiled their .apk file and looking through their source I can see a method they call to decode stuff (DecodeMe). Can I pass my encrypted strings through this using their method and it will decrypt it?
Sorry, I'm not too clued up on this. | 2013/07/23 | ['https://Stackoverflow.com/questions/17809234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2359639/'] | I have no experience with Android development at all, I can only comment from the Java side of things.
If you have been able to decompile the program, you should be able to use the code as you like - so, assuming that DecodeMe really does what it's name implies, then yes it should decode the text.
Add the decompiled code to a new project in your favourite Java IDE, create your own main(...) class/method and try calling the DecodeMe - it *shouldn't* take too much effort to set up and test.
EDIT: Yes, you can use a decompiled method - you simply need to make sure all methods/classes it uses are also available. | That is a java method you just mined from the APK.
>
> private void doNothing() {}
>
>
>
Whoa, this is another. You can use it.
Sorry, just some fun. :)
Yes, you can actually use it, but check if it uses some class that is also defined in the application. You have to mine all custom classes, too. |
57,582,787 | I would like to deploy my react app onto my personal website. I currently have it deployed onto to heroku and have that linked on my personal site. But I would like to eliminate heroku from the equation and have everything on my own site. Whenever I try to deploy it, I upload the build files into my file manager public\_html. But when I try to open it, all I get is a blank page.
I have my vanilla JS projects up just fine.
My question is how do I deploy my react app, through cpanel, onto my existing site.
I've read through some stack pages already and tried npm run build and posting the zip files as well as the normal files to my cpanel file manager. But it only gives me a blank page.
When I open up dev tools for the blank page I can see that it is the html file I want but and it has the links to my build files but it's just not running them for some reason. The console is giving me an error "Failed to load resource: the server responded with a status of 404 ()"
I've tried changing the homepage destination as well.
I believe I'm just missing something really simple because I'm having a hard time finding any help on this one. I'm relatively new to react and deploying react apps so if someone could help me I would be very grateful.
I don't know if I am uploading the files to my file manager in cpanel wrong or if I'm doing something wrong with npm run build.
My git repo is here
<https://github.com/brandondorner/4-Day-Forecast-Weather-App>
Thank you. | 2019/08/20 | ['https://Stackoverflow.com/questions/57582787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11954181/'] | To deploy your react app into your web site just follow these steps :
1. Build your react app using : **npm run build**
2. Go to the app folder then to the build subfolder and you need to upload all contents to your server into the public\_html folder
I have tested these steps using create-react-app this is the ordinary way to do it, if it doesn’t work then try to check the error from the browser console | It appears you need to change the `homepage` parameter in your configuration file and change few settings with your `router`
See this as I think it can help <https://scottvinkle.me/blogs/work/how-to-deploy-a-react-app-to-a-subdirectory> |
71,229,648 | I have been using Keras/TF's [`CSVLogger`](https://keras.io/api/callbacks/csv_logger/) in order to save the training and validation accuracies. Then I was plotting those data to check the trajectory of training and validation accuracy or loss.
Yesterday, I read [this link](https://www.tutorialspoint.com/deep_learning_with_keras/deep_learning_with_keras_evaluating_model_performance.htm).
Here, they used `model.evaluate()` to plot the accuracy metric.
What is the difference between these two approaches? | 2022/02/22 | ['https://Stackoverflow.com/questions/71229648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159072/'] | Here are the big key differences between the two:
model.evaluate() gives a different loss on training data from the one in the training process, while CSVLogger tracks metrics on the validation set after every epoch in the process. | Log and plot the results
------------------------
* The `CSVLogger` will save the results **of the training** in a **CSV file**.
* The output of `fit`, normally called `history`, will have the same results ready in a variable, without needing a CSV file.
Their data should be exactly the same.
Evaluate
--------
The `evaluate` method is **not a log**. It's a method that you call **any time you want**, and will output a **single value** for each loss and metric you have in `compile` for the "current" model.
This is not registered anywhere during training, and this should usually **not be called during training**, unless you create a custom training loop and manually call `evaluate` inside this loop every epoch (this is unnecessary and inconvenient for standard use).
You can use `evaluate` with **any data you want**, including data that was neither in training nor validation data.
The link you shared
-------------------
Notice that what they plot is `history`, and `history` is the output of `fit`. It has nothing to do with `evaluate`.
```
plot.plot(history.history['acc'])
plot.plot(history.history['val_acc'])
```
See in the previous page of the link:
```
history = model.fit(...)
```
The link doesn't show exactly "where" they call evaluate, and they're probably doing it "only once after training", just to see the final results of the model (not a log of the training) |
23,314,041 | Actionscript to use Math.random what will this mean Right = 6 + Math.random() \* 2;
I know Math.random is between 0-0.99... but will it come out (6 - 7)? | 2014/04/26 | ['https://Stackoverflow.com/questions/23314041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3281613/'] | `Math.random()` returns a number greater or equal to 0 and less than 1.0, i.e.
`0 <= Math.random() < 1.0`
If we multiply this with `b` then we get a number greater or equal to 0 and less than b, i.e.
`(0 * b) <= (Math.random() * b) < (1.0 * b)`
or `0 <= (Math.random() * b) < b`
If we add `a` with this then we get a number greater or equal to `a` and less than `a + b`, i.e.
`(a + 0) <= (a + Math.random() * b) < (a + b)`
or `a <= (a + Math.random() * b) < (a + b)`
So, `6 + Math.random() * 2` returns a number greater or equal to 6 and less than 8. If you assign this to an integer then it will be either 6 or 7. | I prefer to write a function to set the scale and range for you. Like this:
```
public static function getRandomNumber(low:Number=0, high:Number=1):Number
{
return Math.floor(Math.random() * (1+high-low)) + low;
}
```
Now you can call it:
```
getRandomNumber(6, 7); //returns 6-7 inclusive
``` |
7,589,603 | I want to use a view script to render my zend form as it seems to be the best way to
control the layout/design of the form while still using the Zend\_Elements classes.
From the view script, I render the element with `$this->element->getElement('elementName')` .
I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form.
When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good.
Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element].
I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start).
Any ideas how I should handle this?
Thanks.
**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing.
It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms.
When I'm not using the PrepareElements decorator, I'm just missing the "form" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]).
May be I can just fix this somehow?
I tried to change the belongsTo but that only replaced the "subForm" prefix .
It actually seems like what is missing is a belongsTo method on the subForm.
Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators.
**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate .
**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this:
```
array(
\"formElements1-name\" => value1... \"subFormName\" => array(
\"parentFormName\" => array(
\"subFormName\" => subForm-values-array
)
)
```
...
The main problem here is the `"parentFormName" => "subFormNAme"..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form,
i.e.
values array = array(
\"formName\" => array(
formValues
), \"subFormNAme\" => array(
subFormValues
)
, while I exepct it to be
```
array(
formName => array(
subFormNAme => values-array
)
)...
```
Is it even possible to make this work? | 2011/09/28 | ['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/'] | Are you just trying to output your form using `<?php echo $this->form; ?>` from your view script?
That works well for simple forms, but for my more complex forms I tend to render each element individually but don't need to use ViewScript decorator on each individual element to do this. Just try something like this from your view script:
```
<div class="form">
<fieldset>
<legend>Some Form Name</legend>
<form action="<?php echo $this->escape($this->form->getAction()) ?>"
method="<?php echo $this->escape($this->form->getMethod()) ?>"
enctype="multipart/form-data">
<?php echo $this->form->id; // render the id element here ?>
<div class="half">
<?php echo $this->form->name; // render the user name field here ?>
</div>
<div class="half">
<?php echo $this->form->description; // render the description element here ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->address1; // render the address ?>
</div>
<div class="half">
<?php echo $this->form->address2; // render address2 ?>
</div>
<div class="clear"></div>
<div class="third">
<?php echo $this->form->zip; // render zip code ?>
</div>
<div class="third">
<?php echo $this->form->city; // render city ?>
</div>
<div class="third">
<?php echo $this->form->state; // render state ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->country; // render country ?>
</div>
<div class="clear"></div>
<?php echo $this->form->submit; ?>
</form>
</fieldset>
</div>
```
That is how I do most of my forms because I want to have some elements take up half the width and others the full width.
Surprisingly, the reference guide doesn't tell you that you can do this. I seem to remember a page about it in the past but cannot find it now. When I got started with Zend Framework, I thought the only way I could get my form to output exactly how I wanted was to create complex decorators, but that is not the case.
Matthew Weier O'Phinney has a great blog post on [rendering Zend\_Form decorators individually](http://weierophinney.net/matthew/archives/215-Rendering-Zend_Form-decorators-individually.html) which explains what I did above. I hope they add this to the first page of Zend Form because that was discouraging to me at first. The fact is, 90% of my forms render elements individually instead of just echo'ing the form itself.
Note: To stop ZF from enclosing my form elements in the dt and dd tags, I apply this decorator to all of my standard form elements. I have a base form class that I extend all of my forms from so I don't have to repeat this everywhere. This is the decorator for the element so I can use tags to enclose my elements.
```
public $elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description')),
array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
```
For my submit buttons I use
```
public $buttonDecorators = array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'class' => 'form-button'))
);
``` | The solution would be to use the `belongsTo()` form element property.
Example :
```
new Zend_Form_Element_Text('<elementName>', array('belongsTo' => '<subformName>'))
```
In this way, the render() method will use a form element name like
```
name="<subformName>[<elementName>]"
``` |
7,589,603 | I want to use a view script to render my zend form as it seems to be the best way to
control the layout/design of the form while still using the Zend\_Elements classes.
From the view script, I render the element with `$this->element->getElement('elementName')` .
I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form.
When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good.
Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element].
I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start).
Any ideas how I should handle this?
Thanks.
**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing.
It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms.
When I'm not using the PrepareElements decorator, I'm just missing the "form" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]).
May be I can just fix this somehow?
I tried to change the belongsTo but that only replaced the "subForm" prefix .
It actually seems like what is missing is a belongsTo method on the subForm.
Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators.
**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate .
**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this:
```
array(
\"formElements1-name\" => value1... \"subFormName\" => array(
\"parentFormName\" => array(
\"subFormName\" => subForm-values-array
)
)
```
...
The main problem here is the `"parentFormName" => "subFormNAme"..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form,
i.e.
values array = array(
\"formName\" => array(
formValues
), \"subFormNAme\" => array(
subFormValues
)
, while I exepct it to be
```
array(
formName => array(
subFormNAme => values-array
)
)...
```
Is it even possible to make this work? | 2011/09/28 | ['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/'] | Are you just trying to output your form using `<?php echo $this->form; ?>` from your view script?
That works well for simple forms, but for my more complex forms I tend to render each element individually but don't need to use ViewScript decorator on each individual element to do this. Just try something like this from your view script:
```
<div class="form">
<fieldset>
<legend>Some Form Name</legend>
<form action="<?php echo $this->escape($this->form->getAction()) ?>"
method="<?php echo $this->escape($this->form->getMethod()) ?>"
enctype="multipart/form-data">
<?php echo $this->form->id; // render the id element here ?>
<div class="half">
<?php echo $this->form->name; // render the user name field here ?>
</div>
<div class="half">
<?php echo $this->form->description; // render the description element here ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->address1; // render the address ?>
</div>
<div class="half">
<?php echo $this->form->address2; // render address2 ?>
</div>
<div class="clear"></div>
<div class="third">
<?php echo $this->form->zip; // render zip code ?>
</div>
<div class="third">
<?php echo $this->form->city; // render city ?>
</div>
<div class="third">
<?php echo $this->form->state; // render state ?>
</div>
<div class="clear"></div>
<div class="half">
<?php echo $this->form->country; // render country ?>
</div>
<div class="clear"></div>
<?php echo $this->form->submit; ?>
</form>
</fieldset>
</div>
```
That is how I do most of my forms because I want to have some elements take up half the width and others the full width.
Surprisingly, the reference guide doesn't tell you that you can do this. I seem to remember a page about it in the past but cannot find it now. When I got started with Zend Framework, I thought the only way I could get my form to output exactly how I wanted was to create complex decorators, but that is not the case.
Matthew Weier O'Phinney has a great blog post on [rendering Zend\_Form decorators individually](http://weierophinney.net/matthew/archives/215-Rendering-Zend_Form-decorators-individually.html) which explains what I did above. I hope they add this to the first page of Zend Form because that was discouraging to me at first. The fact is, 90% of my forms render elements individually instead of just echo'ing the form itself.
Note: To stop ZF from enclosing my form elements in the dt and dd tags, I apply this decorator to all of my standard form elements. I have a base form class that I extend all of my forms from so I don't have to repeat this everywhere. This is the decorator for the element so I can use tags to enclose my elements.
```
public $elementDecorators = array(
'ViewHelper',
'Errors',
array('Description', array('tag' => 'p', 'class' => 'description')),
array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')),
array('Label', array('class' => 'form-label', 'requiredSuffix' => '*'))
);
```
For my submit buttons I use
```
public $buttonDecorators = array(
'ViewHelper',
array('HtmlTag', array('tag' => 'div', 'class' => 'form-button'))
);
``` | I had the same problem and i solved it with a decorator
1 : Create a generic subform with elements
2 : Using a specific decorator with PrepareElements
3 : Change form to an array with setIsArray(true)
Example :
Form
```
$i = 4;
for($i = 0; $i < $nbReclam ; $i++)
{
$rowForm = new Zend_Form_SubForm($i);
$name= new Zend_Form_Element_Textarea('name');
$rowForm->addElement($name);
$this->addSubForm($rowForm, $i);
}
$this->setDecorators(array(
'PrepareElements',
array('ViewScript', array('viewScript' => 'myDecorator.phtml')),
));
$this->setIsArray(true);
```
Decorator
```
<table>
<thead>
<tr>
<th>N°</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->element->getSubForms() as $subForm) : ?>
<tr>
<td> <?php echo $i++?> </td>
<?php foreach ($subForm->getElements() as $row) : ?>
<td><?php echo $row ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
```
Enjoy
Sorry for my english, i am french |
7,589,603 | I want to use a view script to render my zend form as it seems to be the best way to
control the layout/design of the form while still using the Zend\_Elements classes.
From the view script, I render the element with `$this->element->getElement('elementName')` .
I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form.
When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good.
Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element].
I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start).
Any ideas how I should handle this?
Thanks.
**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing.
It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms.
When I'm not using the PrepareElements decorator, I'm just missing the "form" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]).
May be I can just fix this somehow?
I tried to change the belongsTo but that only replaced the "subForm" prefix .
It actually seems like what is missing is a belongsTo method on the subForm.
Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators.
**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate .
**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this:
```
array(
\"formElements1-name\" => value1... \"subFormName\" => array(
\"parentFormName\" => array(
\"subFormName\" => subForm-values-array
)
)
```
...
The main problem here is the `"parentFormName" => "subFormNAme"..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form,
i.e.
values array = array(
\"formName\" => array(
formValues
), \"subFormNAme\" => array(
subFormValues
)
, while I exepct it to be
```
array(
formName => array(
subFormNAme => values-array
)
)...
```
Is it even possible to make this work? | 2011/09/28 | ['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/'] | The current solution is to use the PrepareElements decorator on the subforms with one change - remove the recursive call in the PrepareElements code. Also, no "setElementsBelongTo" is required.
This seem to generate the correct names and ids. | The solution would be to use the `belongsTo()` form element property.
Example :
```
new Zend_Form_Element_Text('<elementName>', array('belongsTo' => '<subformName>'))
```
In this way, the render() method will use a form element name like
```
name="<subformName>[<elementName>]"
``` |
7,589,603 | I want to use a view script to render my zend form as it seems to be the best way to
control the layout/design of the form while still using the Zend\_Elements classes.
From the view script, I render the element with `$this->element->getElement('elementName')` .
I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form.
When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good.
Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element].
I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start).
Any ideas how I should handle this?
Thanks.
**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing.
It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms.
When I'm not using the PrepareElements decorator, I'm just missing the "form" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]).
May be I can just fix this somehow?
I tried to change the belongsTo but that only replaced the "subForm" prefix .
It actually seems like what is missing is a belongsTo method on the subForm.
Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators.
**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate .
**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this:
```
array(
\"formElements1-name\" => value1... \"subFormName\" => array(
\"parentFormName\" => array(
\"subFormName\" => subForm-values-array
)
)
```
...
The main problem here is the `"parentFormName" => "subFormNAme"..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form,
i.e.
values array = array(
\"formName\" => array(
formValues
), \"subFormNAme\" => array(
subFormValues
)
, while I exepct it to be
```
array(
formName => array(
subFormNAme => values-array
)
)...
```
Is it even possible to make this work? | 2011/09/28 | ['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/'] | The current solution is to use the PrepareElements decorator on the subforms with one change - remove the recursive call in the PrepareElements code. Also, no "setElementsBelongTo" is required.
This seem to generate the correct names and ids. | I had the same problem and i solved it with a decorator
1 : Create a generic subform with elements
2 : Using a specific decorator with PrepareElements
3 : Change form to an array with setIsArray(true)
Example :
Form
```
$i = 4;
for($i = 0; $i < $nbReclam ; $i++)
{
$rowForm = new Zend_Form_SubForm($i);
$name= new Zend_Form_Element_Textarea('name');
$rowForm->addElement($name);
$this->addSubForm($rowForm, $i);
}
$this->setDecorators(array(
'PrepareElements',
array('ViewScript', array('viewScript' => 'myDecorator.phtml')),
));
$this->setIsArray(true);
```
Decorator
```
<table>
<thead>
<tr>
<th>N°</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach ($this->element->getSubForms() as $subForm) : ?>
<tr>
<td> <?php echo $i++?> </td>
<?php foreach ($subForm->getElements() as $row) : ?>
<td><?php echo $row ?></td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</tbody>
</table>
```
Enjoy
Sorry for my english, i am french |
63,575,174 | Unable to set card footer as expected output
**Expected output:**
[](https://i.stack.imgur.com/Feadm.png)
**My Code:**
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
```
**jsfiddle:** <https://jsfiddle.net/sidh_41/p8sdfy7u/2/> | 2020/08/25 | ['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/'] | ```css
.card-footer:last-child {
border-radius: 0!important;
}
.card-footer {
padding: 0!important;
background-color: unset!important;
border-top: unset!important;
}
.text-center {
color: #fff;
}
.card-img-overlay {
display: flex;
flex-direction: column;
justify-content: flex-end;
height: 100%;
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
</div>
``` | ```
<div class="row">
<div class="col-md-3">
<div class="card">
<img class="card-img" src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
</div></div>
```
I think you need to add another div surrounding the card. This div needs to have the class `row` |
63,575,174 | Unable to set card footer as expected output
**Expected output:**
[](https://i.stack.imgur.com/Feadm.png)
**My Code:**
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
```
**jsfiddle:** <https://jsfiddle.net/sidh_41/p8sdfy7u/2/> | 2020/08/25 | ['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/'] | ```css
.card-footer:last-child {
border-radius: 0!important;
}
.card-footer {
padding: 0!important;
background-color: unset!important;
border-top: unset!important;
}
.text-center {
color: #fff;
}
.card-img-overlay {
display: flex;
flex-direction: column;
justify-content: flex-end;
height: 100%;
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
</div>
``` | ```css
.img-wrapper{
position: relative;
text-align: center;
color: white;
}
.card-footer{
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
}
h3, h1{
color: #fff
}
```
```html
<div class="col-md-3">
<div class="card">
<div class="img-wrapper">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
</div>
</div>
<div class="card-footer text-center">
<h3>
Africa
</h3>
<h1>
Kenya
</h1>
</div>
</div>
</div>
``` |
63,575,174 | Unable to set card footer as expected output
**Expected output:**
[](https://i.stack.imgur.com/Feadm.png)
**My Code:**
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
```
**jsfiddle:** <https://jsfiddle.net/sidh_41/p8sdfy7u/2/> | 2020/08/25 | ['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/'] | Try this:
```css
.card-footer:last-child {
border-radius: 0!important;
}
.card-footer {
padding: 0!important;
background-color: unset!important;
border-top: unset!important;
}
.text-center {
color: #fff;
}
.card-img-overlay {
display: flex;
flex-direction: column;
justify-content: flex-end;
height: 100%;
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6 class="m-0 small">
AFRICA
</h6>
<h1>
Kenya
</h1>
</div>
</div>
</div>
</div>
``` | ```
<div class="row">
<div class="col-md-3">
<div class="card">
<img class="card-img" src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
</div></div>
```
I think you need to add another div surrounding the card. This div needs to have the class `row` |
63,575,174 | Unable to set card footer as expected output
**Expected output:**
[](https://i.stack.imgur.com/Feadm.png)
**My Code:**
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
<div class="card-footer text-center">
<h6>
Africa
</h6>
<h4>
Kenya
</h4>
</div>
</div>
</div>
```
**jsfiddle:** <https://jsfiddle.net/sidh_41/p8sdfy7u/2/> | 2020/08/25 | ['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/'] | Try this:
```css
.card-footer:last-child {
border-radius: 0!important;
}
.card-footer {
padding: 0!important;
background-color: unset!important;
border-top: unset!important;
}
.text-center {
color: #fff;
}
.card-img-overlay {
display: flex;
flex-direction: column;
justify-content: flex-end;
height: 100%;
}
```
```html
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-md-3">
<div class="card">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
<div class="card-footer text-center">
<h6 class="m-0 small">
AFRICA
</h6>
<h1>
Kenya
</h1>
</div>
</div>
</div>
</div>
``` | ```css
.img-wrapper{
position: relative;
text-align: center;
color: white;
}
.card-footer{
position: absolute;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
}
h3, h1{
color: #fff
}
```
```html
<div class="col-md-3">
<div class="card">
<div class="img-wrapper">
<img src="https://images.unsplash.com/photo-1523805009345-7448845a9e53?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h5 class="card-title"></h5>
</div>
</div>
</div>
<div class="card-footer text-center">
<h3>
Africa
</h3>
<h1>
Kenya
</h1>
</div>
</div>
</div>
``` |
6,176,627 | I am getting problems when generating a multi-dimensional array with unknown size. How can I fix it? | 2011/05/30 | ['https://Stackoverflow.com/questions/6176627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737369/'] | To generate a multi-dimensional array with unknown size is called a jagged array.
For example:
```
String[][] array = new String[5][];
```
Java uses arrays of arrays for multi-dimensional arrays. I think you have to specify the first size. Otherwise, use list of lists.
```
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
``` | Array is static. ArrayList is dynamic.
Before creating an array you should be aware of the size of the array. To create a multidimensional array without knowing array size is not possible.
Better you have to use a nested `ArrayList` or nested `Vector`:
```
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
``` |
26,172,820 | ```
some text here
<span class="my--class-name--here" id="some--id">some -- text--here</span>
test text--here
<div class="another--class-name">test --test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->
```
For the above content, I want some help in writing code to replace all occurrence of double dash (`--`) with `—`.
But, it should not replace the double dash for any attributes inside the html elements. For e.g., the double dash in the class name (`my--class-name--here`) and id name (`id="some--id"`) should not replaced.
And, also it should not replace double dash in `<!--[if IE 9]>` and `<![endif]-->` | 2014/10/03 | ['https://Stackoverflow.com/questions/26172820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227325/'] | If you are wanting a one-liner to replace outside of `<` and `>`, you can use the following.
```
$html = preg_replace('~<[^>]*>(*SKIP)(*F)|--~', '—', $html);
```
The idea is to skip any content that is located between an opening and closing bracket character.
On the left side of the alternation operator we match the subpattern we do not want. Making it fail and forcing the regular expression engine to not retry the substring using backtracking control verbs.
[`Working Demo`](https://eval.in/201333) | Use a negative lookahead to match `--` which was not inside any html tags.
```
--(?![^><]*>)
```
Replace the matched `--` with `—`.
[DEMO](http://regex101.com/r/lJ1fL0/2)
```
<?php
$string = <<<EOT
some text here
<span class="my--class-name--here" id="some--id">some -- text--here</span>
test text--here
<div class="another--class-name">test --test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->
EOT;
echo preg_replace('~--(?![^><]*>)~', '—', $string);
?>
```
Output:
```
some text here
<span class="my--class-name--here" id="some--id">some — text—here</span>
test text—here
<div class="another--class-name">test —test</div>
<!--[if IE 9]><video style="display: none;"><![endif]-->
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | Javascript (E6) 156 ~~162 164 186~~
===================================
**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition
```
F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))}
```
Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])`
**Ungolfed**
```
F = (t,s) =>
{
D = a => Math.abs(a[1]/t-1);
for (i=r=[]; a=s[j=i++]; r[l]=[a,a])
for(; b=s[j--];)
l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]);
return r.sort((a,b) => D(a)-D(b))
}
``` | Perl, 213 199 185 bytes
=======================
**213 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>;
```
**199 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>;
```
**185 bytes:**
```
$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)>
```
Pass all available resistors as arguments. The target resistance should be the last:
```
$ perl -E 'code' R1 R2 R3 ... Rn target
```
### How it works (old code)
* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors.
* Set [`$"`](http://perldoc.perl.org/perlvar.html) to "," to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator
* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities:
S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ...
* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/`
* `sort` by fitness computed in subroutine `t`
### Changes in new code
* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep`
* Replace repeats of `"{@i}" with`$i`
* Introduce `$x`, `$y` instead of `$2`, `$3`
* Replace `split/=/,pop` with `$_[0]=~s!!!r`
* No need for trailing `;`
* `eval;` is equivalent to `eval $_;`
* Add `=` along with `eval`-ed answer instead of declaring it up front
### Output:
`P` represents resistors in parallel, `S` represents resistors in series.
```
P(2200,680)=519.444444444444
P(1000,1000)=500
S(330,150)=480
S(330,220)=550
S(470)=470
P(1500,680)=467.889908256881
P(3300,680)=563.819095477387
S(470,100)=570
S(220,220)=440
S(330,100)=430
P(4700,470)=427.272727272727
P(4700,680)=594.052044609665
P(1500,1000)=600
P(3300,470)=411.405835543767
P(1000,680)=404.761904761905
S(470,150)=620
P(2200,470)=387.265917602996
S(220,150)=370
S(330,330)=660
P(1500,470)=357.868020304569
S(680)=680
P(680,680)=340
P(2200,1000)=687.5
S(330)=330
S(470,220)=690
S(220,100)=320
P(1000,470)=319.727891156463
P(4700,330)=308.349900596421
S(150,150)=300
P(3300,330)=300
P(2200,330)=286.95652173913
P(680,470)=277.913043478261
P(1500,330)=270.491803278689
P(1500,1500)=750
P(3300,1000)=767.441860465116
S(150,100)=250
P(1000,330)=248.12030075188
S(680,100)=780
P(470,470)=235
P(680,330)=222.178217821782
S(470,330)=800
S(220)=220
P(4700,220)=210.162601626016
P(3300,220)=206.25
S(100,100)=200
P(2200,220)=200
P(4700,1000)=824.561403508772
P(470,330)=193.875
P(1500,220)=191.860465116279
S(680,150)=830
P(1000,220)=180.327868852459
P(680,220)=166.222222222222
P(330,330)=165
S(150)=150
P(470,220)=149.855072463768
P(4700,150)=145.360824742268
P(3300,150)=143.478260869565
P(2200,150)=140.425531914894
P(1500,150)=136.363636363636
P(330,220)=132
P(1000,150)=130.434782608696
P(2200,1500)=891.891891891892
P(680,150)=122.89156626506
S(680,220)=900
P(470,150)=113.709677419355
P(220,220)=110
P(330,150)=103.125
S(100)=100
P(4700,100)=97.9166666666667
P(3300,100)=97.0588235294118
P(2200,100)=95.6521739130435
P(1500,100)=93.75
P(1000,100)=90.9090909090909
P(220,150)=89.1891891891892
P(680,100)=87.1794871794872
P(470,100)=82.4561403508772
S(470,470)=940
P(330,100)=76.7441860465116
P(150,150)=75
P(220,100)=68.75
P(150,100)=60
P(100,100)=50
S(1000)=1000
S(680,330)=1010
P(3300,1500)=1031.25
S(1000,100)=1100
P(2200,2200)=1100
P(4700,1500)=1137.09677419355
S(680,470)=1150
S(1000,150)=1150
S(1000,220)=1220
P(3300,2200)=1320
S(1000,330)=1330
S(680,680)=1360
S(1000,470)=1470
P(4700,2200)=1498.55072463768
S(1500)=1500
S(1500,100)=1600
S(1500,150)=1650
P(3300,3300)=1650
S(1000,680)=1680
S(1500,220)=1720
S(1500,330)=1830
P(4700,3300)=1938.75
S(1500,470)=1970
S(1000,1000)=2000
S(1500,680)=2180
S(2200)=2200
S(2200,100)=2300
S(2200,150)=2350
P(4700,4700)=2350
S(2200,220)=2420
S(1500,1000)=2500
S(2200,330)=2530
S(2200,470)=2670
S(2200,680)=2880
S(1500,1500)=3000
S(2200,1000)=3200
S(3300)=3300
S(3300,100)=3400
S(3300,150)=3450
S(3300,220)=3520
S(3300,330)=3630
S(2200,1500)=3700
S(3300,470)=3770
S(3300,680)=3980
S(3300,1000)=4300
S(2200,2200)=4400
S(4700)=4700
S(3300,1500)=4800
S(4700,100)=4800
S(4700,150)=4850
S(4700,220)=4920
S(4700,330)=5030
S(4700,470)=5170
S(4700,680)=5380
S(3300,2200)=5500
S(4700,1000)=5700
S(4700,1500)=6200
S(3300,3300)=6600
S(4700,2200)=6900
S(4700,3300)=8000
S(4700,4700)=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | Mathematica, ~~151~~ 122 characters
-----------------------------------
Expects the target resistance to be stored in `r` and the list of available resistors in `l`.
```
SortBy[Join[{#,#}&/@l,Join@@(#@@@Union[Sort/@N@l~Tuples~{2}]&/@{{"+",##,#+#2}&,{"|",##,#*#2/(#+#2)}&})],Abs[#[[-1]]/r-1]&]
```
Less golf:
```
SortBy[Join[{#, #} & /@ l,
Join @@ (# @@@
Union[Sort /@ N@l~Tuples~{2}] & /@ {{"+", ##, # + #2} &, {"|", ##,
#*#2/(# + #2)} &})], Abs[#[[-1]]/r - 1] &]
```
The output format differs from the suggested one but configurations are easily determinable. The output is a list of configurations. Each configuration is of one of the following forms:
```
{R1, Total}
{"+", R1, R2, Total}
{"|", R1, R2, Total}
```
So the first three elements of the output read
```
{{"|", 680., 2200., 519.444}, {"|", 1000., 1000., 500.}, {"+", 150., 330., 480.}, ...}
```
If you're fine with rational numbers, I could save two characters from omitting `N@`. That is, the first element (for instance) would be returned as `4675/9` instead of `519.444`. | Javascript (E6) 156 ~~162 164 186~~
===================================
**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition
```
F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))}
```
Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])`
**Ungolfed**
```
F = (t,s) =>
{
D = a => Math.abs(a[1]/t-1);
for (i=r=[]; a=s[j=i++]; r[l]=[a,a])
for(; b=s[j--];)
l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]);
return r.sort((a,b) => D(a)-D(b))
}
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | APL (102)
=========
```
{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]}
```
This takes the target resistance as the left argument and a list of available resistors as the right argument.
Explanation:
* `V←{`...`}`: `V` is a function that:
+ `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`,
- `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`,
- `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value
+ `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair:
- `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.)
+ `⊃¨`: and then unbox each element.
* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`).
* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`).
* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments).
* `K←↑`: make this into a matrix and store it in `K`.
* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values.
* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration.
* `K[⍋`...`;]`: sort `K` by the distances. | Perl, 213 199 185 bytes
=======================
**213 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>;
```
**199 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>;
```
**185 bytes:**
```
$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)>
```
Pass all available resistors as arguments. The target resistance should be the last:
```
$ perl -E 'code' R1 R2 R3 ... Rn target
```
### How it works (old code)
* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors.
* Set [`$"`](http://perldoc.perl.org/perlvar.html) to "," to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator
* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities:
S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ...
* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/`
* `sort` by fitness computed in subroutine `t`
### Changes in new code
* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep`
* Replace repeats of `"{@i}" with`$i`
* Introduce `$x`, `$y` instead of `$2`, `$3`
* Replace `split/=/,pop` with `$_[0]=~s!!!r`
* No need for trailing `;`
* `eval;` is equivalent to `eval $_;`
* Add `=` along with `eval`-ed answer instead of declaring it up front
### Output:
`P` represents resistors in parallel, `S` represents resistors in series.
```
P(2200,680)=519.444444444444
P(1000,1000)=500
S(330,150)=480
S(330,220)=550
S(470)=470
P(1500,680)=467.889908256881
P(3300,680)=563.819095477387
S(470,100)=570
S(220,220)=440
S(330,100)=430
P(4700,470)=427.272727272727
P(4700,680)=594.052044609665
P(1500,1000)=600
P(3300,470)=411.405835543767
P(1000,680)=404.761904761905
S(470,150)=620
P(2200,470)=387.265917602996
S(220,150)=370
S(330,330)=660
P(1500,470)=357.868020304569
S(680)=680
P(680,680)=340
P(2200,1000)=687.5
S(330)=330
S(470,220)=690
S(220,100)=320
P(1000,470)=319.727891156463
P(4700,330)=308.349900596421
S(150,150)=300
P(3300,330)=300
P(2200,330)=286.95652173913
P(680,470)=277.913043478261
P(1500,330)=270.491803278689
P(1500,1500)=750
P(3300,1000)=767.441860465116
S(150,100)=250
P(1000,330)=248.12030075188
S(680,100)=780
P(470,470)=235
P(680,330)=222.178217821782
S(470,330)=800
S(220)=220
P(4700,220)=210.162601626016
P(3300,220)=206.25
S(100,100)=200
P(2200,220)=200
P(4700,1000)=824.561403508772
P(470,330)=193.875
P(1500,220)=191.860465116279
S(680,150)=830
P(1000,220)=180.327868852459
P(680,220)=166.222222222222
P(330,330)=165
S(150)=150
P(470,220)=149.855072463768
P(4700,150)=145.360824742268
P(3300,150)=143.478260869565
P(2200,150)=140.425531914894
P(1500,150)=136.363636363636
P(330,220)=132
P(1000,150)=130.434782608696
P(2200,1500)=891.891891891892
P(680,150)=122.89156626506
S(680,220)=900
P(470,150)=113.709677419355
P(220,220)=110
P(330,150)=103.125
S(100)=100
P(4700,100)=97.9166666666667
P(3300,100)=97.0588235294118
P(2200,100)=95.6521739130435
P(1500,100)=93.75
P(1000,100)=90.9090909090909
P(220,150)=89.1891891891892
P(680,100)=87.1794871794872
P(470,100)=82.4561403508772
S(470,470)=940
P(330,100)=76.7441860465116
P(150,150)=75
P(220,100)=68.75
P(150,100)=60
P(100,100)=50
S(1000)=1000
S(680,330)=1010
P(3300,1500)=1031.25
S(1000,100)=1100
P(2200,2200)=1100
P(4700,1500)=1137.09677419355
S(680,470)=1150
S(1000,150)=1150
S(1000,220)=1220
P(3300,2200)=1320
S(1000,330)=1330
S(680,680)=1360
S(1000,470)=1470
P(4700,2200)=1498.55072463768
S(1500)=1500
S(1500,100)=1600
S(1500,150)=1650
P(3300,3300)=1650
S(1000,680)=1680
S(1500,220)=1720
S(1500,330)=1830
P(4700,3300)=1938.75
S(1500,470)=1970
S(1000,1000)=2000
S(1500,680)=2180
S(2200)=2200
S(2200,100)=2300
S(2200,150)=2350
P(4700,4700)=2350
S(2200,220)=2420
S(1500,1000)=2500
S(2200,330)=2530
S(2200,470)=2670
S(2200,680)=2880
S(1500,1500)=3000
S(2200,1000)=3200
S(3300)=3300
S(3300,100)=3400
S(3300,150)=3450
S(3300,220)=3520
S(3300,330)=3630
S(2200,1500)=3700
S(3300,470)=3770
S(3300,680)=3980
S(3300,1000)=4300
S(2200,2200)=4400
S(4700)=4700
S(3300,1500)=4800
S(4700,100)=4800
S(4700,150)=4850
S(4700,220)=4920
S(4700,330)=5030
S(4700,470)=5170
S(4700,680)=5380
S(3300,2200)=5500
S(4700,1000)=5700
S(4700,1500)=6200
S(3300,3300)=6600
S(4700,2200)=6900
S(4700,3300)=8000
S(4700,4700)=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | APL (102)
=========
```
{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]}
```
This takes the target resistance as the left argument and a list of available resistors as the right argument.
Explanation:
* `V←{`...`}`: `V` is a function that:
+ `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`,
- `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`,
- `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value
+ `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair:
- `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.)
+ `⊃¨`: and then unbox each element.
* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`).
* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`).
* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments).
* `K←↑`: make this into a matrix and store it in `K`.
* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values.
* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration.
* `K[⍋`...`;]`: sort `K` by the distances. | Ruby 2.1, ~~156~~ 154 bytes
===========================
```
s=->(a,z){c={};a.map{|e|a.map{|f|c[e]=e;c[e+f]="#{e}+#{f}";c[1/(1.0/f+1.0/e)]="#{e}|#{f}"}};c.sort_by{|k,|(k/z.to_f-1).abs}.map{|e|puts"#{e[1]}=#{e[0]}"}}
```
Ungolfed:
---------
```
s =->(a,z) {
c={}
a.map{|e|
a.map{|f|
c[e]=e
c[e+f]="#{e}+#{f}"
c[1/(1.0/f+1.0/e)]="#{e}|#{f}"
}
}
c.sort_by{|k,|
(k/z.to_f-1).abs
}.map{|e|
puts "#{e[1]}=#{e[0]}"
}
}
```
What it does:
-------------
* For each value `e` in `a`;
+ Iterate through `a`, computing single, series, and parallel values as keys to printed values in hash `c`;
* Determine distance from `z` for each key in `c`; and,
* For each value `e[1]` for each key `e[0]` in `c`, print `e[1]=e[0]`.
Sample usage:
-------------
`s[[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700], 510]`
Sample output:
--------------
```
2200|680=519.4444444444445
1000|1000=500.0
330+150=480
330+220=550
470=470
1500|680=467.88990825688074
3300|680=563.8190954773869
.
.
.
4700+1500=6200
3300+3300=6600
4700+2200=6900
4700+3300=8000
4700+4700=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | Python 3 - ~~250~~ ~~247~~ 270 bytes
====================================
```
from itertools import*
import sys
r=sys.argv[1:]
t=int(r.pop())
p=set(map(tuple,map(sorted,product(r,r))))
a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p]
for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s)
```
Run like this:
```
python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510
```
(that is, a space-delimited list of resistors, with the target value at the end)
Output:
```
('2200|680', 519.4444444444445)
('1000|1000', 500.0)
('150+330', 480)
('220+330', 550)
('1500|680', 467.88990825688074)
('3300|680', 563.8190954773869)
[snip]
('2200+4700', 6900)
('3300+4700', 8000)
('4700+4700', 9400)
```
~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical. | Perl, 213 199 185 bytes
=======================
**213 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>;
```
**199 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>;
```
**185 bytes:**
```
$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)>
```
Pass all available resistors as arguments. The target resistance should be the last:
```
$ perl -E 'code' R1 R2 R3 ... Rn target
```
### How it works (old code)
* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors.
* Set [`$"`](http://perldoc.perl.org/perlvar.html) to "," to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator
* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities:
S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ...
* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/`
* `sort` by fitness computed in subroutine `t`
### Changes in new code
* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep`
* Replace repeats of `"{@i}" with`$i`
* Introduce `$x`, `$y` instead of `$2`, `$3`
* Replace `split/=/,pop` with `$_[0]=~s!!!r`
* No need for trailing `;`
* `eval;` is equivalent to `eval $_;`
* Add `=` along with `eval`-ed answer instead of declaring it up front
### Output:
`P` represents resistors in parallel, `S` represents resistors in series.
```
P(2200,680)=519.444444444444
P(1000,1000)=500
S(330,150)=480
S(330,220)=550
S(470)=470
P(1500,680)=467.889908256881
P(3300,680)=563.819095477387
S(470,100)=570
S(220,220)=440
S(330,100)=430
P(4700,470)=427.272727272727
P(4700,680)=594.052044609665
P(1500,1000)=600
P(3300,470)=411.405835543767
P(1000,680)=404.761904761905
S(470,150)=620
P(2200,470)=387.265917602996
S(220,150)=370
S(330,330)=660
P(1500,470)=357.868020304569
S(680)=680
P(680,680)=340
P(2200,1000)=687.5
S(330)=330
S(470,220)=690
S(220,100)=320
P(1000,470)=319.727891156463
P(4700,330)=308.349900596421
S(150,150)=300
P(3300,330)=300
P(2200,330)=286.95652173913
P(680,470)=277.913043478261
P(1500,330)=270.491803278689
P(1500,1500)=750
P(3300,1000)=767.441860465116
S(150,100)=250
P(1000,330)=248.12030075188
S(680,100)=780
P(470,470)=235
P(680,330)=222.178217821782
S(470,330)=800
S(220)=220
P(4700,220)=210.162601626016
P(3300,220)=206.25
S(100,100)=200
P(2200,220)=200
P(4700,1000)=824.561403508772
P(470,330)=193.875
P(1500,220)=191.860465116279
S(680,150)=830
P(1000,220)=180.327868852459
P(680,220)=166.222222222222
P(330,330)=165
S(150)=150
P(470,220)=149.855072463768
P(4700,150)=145.360824742268
P(3300,150)=143.478260869565
P(2200,150)=140.425531914894
P(1500,150)=136.363636363636
P(330,220)=132
P(1000,150)=130.434782608696
P(2200,1500)=891.891891891892
P(680,150)=122.89156626506
S(680,220)=900
P(470,150)=113.709677419355
P(220,220)=110
P(330,150)=103.125
S(100)=100
P(4700,100)=97.9166666666667
P(3300,100)=97.0588235294118
P(2200,100)=95.6521739130435
P(1500,100)=93.75
P(1000,100)=90.9090909090909
P(220,150)=89.1891891891892
P(680,100)=87.1794871794872
P(470,100)=82.4561403508772
S(470,470)=940
P(330,100)=76.7441860465116
P(150,150)=75
P(220,100)=68.75
P(150,100)=60
P(100,100)=50
S(1000)=1000
S(680,330)=1010
P(3300,1500)=1031.25
S(1000,100)=1100
P(2200,2200)=1100
P(4700,1500)=1137.09677419355
S(680,470)=1150
S(1000,150)=1150
S(1000,220)=1220
P(3300,2200)=1320
S(1000,330)=1330
S(680,680)=1360
S(1000,470)=1470
P(4700,2200)=1498.55072463768
S(1500)=1500
S(1500,100)=1600
S(1500,150)=1650
P(3300,3300)=1650
S(1000,680)=1680
S(1500,220)=1720
S(1500,330)=1830
P(4700,3300)=1938.75
S(1500,470)=1970
S(1000,1000)=2000
S(1500,680)=2180
S(2200)=2200
S(2200,100)=2300
S(2200,150)=2350
P(4700,4700)=2350
S(2200,220)=2420
S(1500,1000)=2500
S(2200,330)=2530
S(2200,470)=2670
S(2200,680)=2880
S(1500,1500)=3000
S(2200,1000)=3200
S(3300)=3300
S(3300,100)=3400
S(3300,150)=3450
S(3300,220)=3520
S(3300,330)=3630
S(2200,1500)=3700
S(3300,470)=3770
S(3300,680)=3980
S(3300,1000)=4300
S(2200,2200)=4400
S(4700)=4700
S(3300,1500)=4800
S(4700,100)=4800
S(4700,150)=4850
S(4700,220)=4920
S(4700,330)=5030
S(4700,470)=5170
S(4700,680)=5380
S(3300,2200)=5500
S(4700,1000)=5700
S(4700,1500)=6200
S(3300,3300)=6600
S(4700,2200)=6900
S(4700,3300)=8000
S(4700,4700)=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | Julia - ~~179~~ 163 bytes
=========================
```
f(t,s)=(\ =repmat;m=endof(s);A=A[v=(A=s\m).>=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=[" "]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:]))
```
This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using "find" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes.
Old version:
```
f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=[" "]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))
```
Within the function, here's what it's doing:
```
\ =repmat # Overloads \ operator to save lots of characters
m=endof(s) # Length of input s ("Stock")
A=s\m # Equivalent to repmat(s,m) (see first command)
B=sort(A) # Same as A but sorted - rather than cycling through
# the resistors m times, it repeats each one m times
v=find(A.>=B) # Identify which pairs for A,B have A>=B
A=A[v];B=B[v] # Remove pairs where A<B (prevents duplicates)
F=[s,C=A+B,A.*B./C] # Constructs vector containing results for single resistor,
# resistors in series, and resistors in parallel
n=endof(v) # equivalent to n=(m+1)m/2, gets number of relevant pairs
P=[" "]\m # Construct array of blank entries for use in constructing output
print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))
# The following are the components of the argument in the print statement:
[s,A,A] # Set of resistor values for resistor 1
[P,[+]\n,[|]\n] # Operator column, prints either nothing, +, or |
[P,B,B] # Set of resistor values for resistor 2 (blank for single resistor)
F # Contains resulting equivalent resistance
[sortperm(abs(F-t)),:] # Determines permutation for sorting array by distance from Target t
# and applies it to array
```
Sample output:
```
julia> f(170,[100,220,300])
300 | 300 150
100 + 100 200
300 | 220 126.92307692307692
220 220
220 | 220 110
100 100
300 | 100 75
220 | 100 68.75
100 | 100 50
300 300
220 + 100 320
300 + 100 400
220 + 220 440
300 + 220 520
300 + 300 600
``` | Perl, 213 199 185 bytes
=======================
**213 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>;
```
**199 bytes:**
```
$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>;
```
**185 bytes:**
```
$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$"=',';$i="{@ARGV}";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)>
```
Pass all available resistors as arguments. The target resistance should be the last:
```
$ perl -E 'code' R1 R2 R3 ... Rn target
```
### How it works (old code)
* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors.
* Set [`$"`](http://perldoc.perl.org/perlvar.html) to "," to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator
* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities:
S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ...
* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/`
* `sort` by fitness computed in subroutine `t`
### Changes in new code
* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep`
* Replace repeats of `"{@i}" with`$i`
* Introduce `$x`, `$y` instead of `$2`, `$3`
* Replace `split/=/,pop` with `$_[0]=~s!!!r`
* No need for trailing `;`
* `eval;` is equivalent to `eval $_;`
* Add `=` along with `eval`-ed answer instead of declaring it up front
### Output:
`P` represents resistors in parallel, `S` represents resistors in series.
```
P(2200,680)=519.444444444444
P(1000,1000)=500
S(330,150)=480
S(330,220)=550
S(470)=470
P(1500,680)=467.889908256881
P(3300,680)=563.819095477387
S(470,100)=570
S(220,220)=440
S(330,100)=430
P(4700,470)=427.272727272727
P(4700,680)=594.052044609665
P(1500,1000)=600
P(3300,470)=411.405835543767
P(1000,680)=404.761904761905
S(470,150)=620
P(2200,470)=387.265917602996
S(220,150)=370
S(330,330)=660
P(1500,470)=357.868020304569
S(680)=680
P(680,680)=340
P(2200,1000)=687.5
S(330)=330
S(470,220)=690
S(220,100)=320
P(1000,470)=319.727891156463
P(4700,330)=308.349900596421
S(150,150)=300
P(3300,330)=300
P(2200,330)=286.95652173913
P(680,470)=277.913043478261
P(1500,330)=270.491803278689
P(1500,1500)=750
P(3300,1000)=767.441860465116
S(150,100)=250
P(1000,330)=248.12030075188
S(680,100)=780
P(470,470)=235
P(680,330)=222.178217821782
S(470,330)=800
S(220)=220
P(4700,220)=210.162601626016
P(3300,220)=206.25
S(100,100)=200
P(2200,220)=200
P(4700,1000)=824.561403508772
P(470,330)=193.875
P(1500,220)=191.860465116279
S(680,150)=830
P(1000,220)=180.327868852459
P(680,220)=166.222222222222
P(330,330)=165
S(150)=150
P(470,220)=149.855072463768
P(4700,150)=145.360824742268
P(3300,150)=143.478260869565
P(2200,150)=140.425531914894
P(1500,150)=136.363636363636
P(330,220)=132
P(1000,150)=130.434782608696
P(2200,1500)=891.891891891892
P(680,150)=122.89156626506
S(680,220)=900
P(470,150)=113.709677419355
P(220,220)=110
P(330,150)=103.125
S(100)=100
P(4700,100)=97.9166666666667
P(3300,100)=97.0588235294118
P(2200,100)=95.6521739130435
P(1500,100)=93.75
P(1000,100)=90.9090909090909
P(220,150)=89.1891891891892
P(680,100)=87.1794871794872
P(470,100)=82.4561403508772
S(470,470)=940
P(330,100)=76.7441860465116
P(150,150)=75
P(220,100)=68.75
P(150,100)=60
P(100,100)=50
S(1000)=1000
S(680,330)=1010
P(3300,1500)=1031.25
S(1000,100)=1100
P(2200,2200)=1100
P(4700,1500)=1137.09677419355
S(680,470)=1150
S(1000,150)=1150
S(1000,220)=1220
P(3300,2200)=1320
S(1000,330)=1330
S(680,680)=1360
S(1000,470)=1470
P(4700,2200)=1498.55072463768
S(1500)=1500
S(1500,100)=1600
S(1500,150)=1650
P(3300,3300)=1650
S(1000,680)=1680
S(1500,220)=1720
S(1500,330)=1830
P(4700,3300)=1938.75
S(1500,470)=1970
S(1000,1000)=2000
S(1500,680)=2180
S(2200)=2200
S(2200,100)=2300
S(2200,150)=2350
P(4700,4700)=2350
S(2200,220)=2420
S(1500,1000)=2500
S(2200,330)=2530
S(2200,470)=2670
S(2200,680)=2880
S(1500,1500)=3000
S(2200,1000)=3200
S(3300)=3300
S(3300,100)=3400
S(3300,150)=3450
S(3300,220)=3520
S(3300,330)=3630
S(2200,1500)=3700
S(3300,470)=3770
S(3300,680)=3980
S(3300,1000)=4300
S(2200,2200)=4400
S(4700)=4700
S(3300,1500)=4800
S(4700,100)=4800
S(4700,150)=4850
S(4700,220)=4920
S(4700,330)=5030
S(4700,470)=5170
S(4700,680)=5380
S(3300,2200)=5500
S(4700,1000)=5700
S(4700,1500)=6200
S(3300,3300)=6600
S(4700,2200)=6900
S(4700,3300)=8000
S(4700,4700)=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | Javascript (E6) 156 ~~162 164 186~~
===================================
**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition
```
F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))}
```
Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])`
**Ungolfed**
```
F = (t,s) =>
{
D = a => Math.abs(a[1]/t-1);
for (i=r=[]; a=s[j=i++]; r[l]=[a,a])
for(; b=s[j--];)
l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]);
return r.sort((a,b) => D(a)-D(b))
}
``` | Javascript, 248 bytes
=====================
```js
function r(T,L){R=[],O="";for(i in L){R.push([a=L[i],a]);for(j=i;j<L.length;)b=L[j++],s=a+b,R.push([a+"+"+b,s],[a+"|"+b,a*b/s])}R.sort(function(a,b){A=Math.abs;return A(a[1]/T-1)-A(b[1]/T-1)});for(i in R)q=R[i],O+=q[0]+"="+q[1]+"\n";console.log(O)}
```
Usage : `r(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]);`
### Output
```
670|2200=519.4444444444445
1000|1000=500
150+330=480
(...such rows...)
2200+4700=6900
3300+4700=8000
4700+4700=9400
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | APL (102)
=========
```
{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]}
```
This takes the target resistance as the left argument and a list of available resistors as the right argument.
Explanation:
* `V←{`...`}`: `V` is a function that:
+ `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`,
- `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`,
- `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value
+ `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair:
- `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.)
+ `⊃¨`: and then unbox each element.
* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`).
* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`).
* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments).
* `K←↑`: make this into a matrix and store it in `K`.
* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values.
* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration.
* `K[⍋`...`;]`: sort `K` by the distances. | Julia - ~~179~~ 163 bytes
=========================
```
f(t,s)=(\ =repmat;m=endof(s);A=A[v=(A=s\m).>=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=[" "]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:]))
```
This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using "find" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes.
Old version:
```
f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=[" "]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))
```
Within the function, here's what it's doing:
```
\ =repmat # Overloads \ operator to save lots of characters
m=endof(s) # Length of input s ("Stock")
A=s\m # Equivalent to repmat(s,m) (see first command)
B=sort(A) # Same as A but sorted - rather than cycling through
# the resistors m times, it repeats each one m times
v=find(A.>=B) # Identify which pairs for A,B have A>=B
A=A[v];B=B[v] # Remove pairs where A<B (prevents duplicates)
F=[s,C=A+B,A.*B./C] # Constructs vector containing results for single resistor,
# resistors in series, and resistors in parallel
n=endof(v) # equivalent to n=(m+1)m/2, gets number of relevant pairs
P=[" "]\m # Construct array of blank entries for use in constructing output
print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:]))
# The following are the components of the argument in the print statement:
[s,A,A] # Set of resistor values for resistor 1
[P,[+]\n,[|]\n] # Operator column, prints either nothing, +, or |
[P,B,B] # Set of resistor values for resistor 2 (blank for single resistor)
F # Contains resulting equivalent resistance
[sortperm(abs(F-t)),:] # Determines permutation for sorting array by distance from Target t
# and applies it to array
```
Sample output:
```
julia> f(170,[100,220,300])
300 | 300 150
100 + 100 200
300 | 220 126.92307692307692
220 220
220 | 220 110
100 100
300 | 100 75
220 | 100 68.75
100 | 100 50
300 300
220 + 100 320
300 + 100 400
220 + 220 440
300 + 220 520
300 + 300 600
``` |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | APL (102)
=========
```
{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]}
```
This takes the target resistance as the left argument and a list of available resistors as the right argument.
Explanation:
* `V←{`...`}`: `V` is a function that:
+ `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`,
- `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`,
- `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value
+ `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair:
- `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.)
+ `⊃¨`: and then unbox each element.
* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`).
* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`).
* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments).
* `K←↑`: make this into a matrix and store it in `K`.
* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values.
* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration.
* `K[⍋`...`;]`: sort `K` by the distances. | Python 3 - ~~250~~ ~~247~~ 270 bytes
====================================
```
from itertools import*
import sys
r=sys.argv[1:]
t=int(r.pop())
p=set(map(tuple,map(sorted,product(r,r))))
a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p]
for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s)
```
Run like this:
```
python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510
```
(that is, a space-delimited list of resistors, with the target value at the end)
Output:
```
('2200|680', 519.4444444444445)
('1000|1000', 500.0)
('150+330', 480)
('220+330', 550)
('1500|680', 467.88990825688074)
('3300|680', 563.8190954773869)
[snip]
('2200+4700', 6900)
('3300+4700', 8000)
('4700+4700', 9400)
```
~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical. |
28,595 | ### Introduction
When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well.
### Task
You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider:
* Individual resistors
* Two resistors in series
* Two resistors in parallel
The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value.
The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance.
### Formulas
* The resistance of one resistor is `R1`
* The net resistance of two resistors in series is `R1 + R2`
* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)`
* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100.
* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement.
### Scoring
Score is measured in characters of code, per usual golf rules. Lowest score wins.
### Example
We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined):
```
680 | 2200 519.444
1000 | 1000 500.
150 + 330 480.
220 + 330 550.
470 470
680 | 1500 467.89
680 | 3300 563.819
100 + 470 570.
220 + 220 440.
100 + 330 430.
470 | 4700 427.273
680 | 4700 594.052
1000 | 1500 600.
470 | 3300 411.406
680 | 1000 404.762
150 + 470 620.
...
many more rows
...
2200 + 4700 6900.
3300 + 4700 8000.
4700 + 4700 9400.
```
In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel.
**Best of each language so far (1 June 2014):**
1. J - 70 char
2. APL - 102 char
3. Mathematica - 122 char
4. Ruby - 154 char
5. Javascript - 156 char
6. Julia - 163 char
7. Perl - 185 char
8. Python - 270 char | 2014/05/25 | ['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/'] | J - 86 71 70 char
=================
```
((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\))
```
I'm not going to bother to explain every little detail because a lot of the code is spent syncing up the results of different functions, but here's the gist of the golf:
* `;@((<@,.{:)\)` makes every possible pair of resistors, to be connected either in parallel or in series.
* `[:,/(<,.+`|,.+/;+&.%/)"1@` then connects them, in parallel and in series, making a big list of possible connections.
* `(;a:,<)"0,` adds in the possibility of using only one resistor by itself to approximate.
* `(]/:[|@<:@%~2{::"1])` sorts the list of combinations of resistors by the pseudolog distance (`|@<:@%`) between the target and the resultant resistance from each combination.
And this is how to use it:
```
rouv =: ((]/:[|@<:@%~2{::"1])(;a:,<)"0,[:,/(<,.+`|,.+/;+&.%/)"1@;@((<@,.{:)\))
# 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. how many?
143
10 {. 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. view first 10
+---------+-+-------+
|680 2200 |||519.444|
+---------+-+-------+
|1000 1000|||500 |
+---------+-+-------+
|150 330 |+|480 |
+---------+-+-------+
|220 330 |+|550 |
+---------+-+-------+
|470 | |470 |
+---------+-+-------+
|680 1500 |||467.89 |
+---------+-+-------+
|680 3300 |||563.819|
+---------+-+-------+
|100 470 |+|570 |
+---------+-+-------+
|220 220 |+|440 |
+---------+-+-------+
|100 330 |+|430 |
+---------+-+-------+
```
You don't have to only view the first 10 like I did above, but this is a function and the J REPL truncates very large return values, and the full output for this example has 287 lines. You can force it all to STDOUT with something like `tmoutput toCRLF , LF ,.~ ": blah rouv blah` on Windows—drop the `toCRLF` on Linux—but `rouv` is a function and internally, all the rows exist.
Note:
-----
The question seems to have been changed right under our noses, and now the log distance is defined as `abs(log(Rapprox/Rtarget))` instead of `abs(Rapprox/Rtarget-1)`. To correct this in my golf, we can change the `|@<:@%` to `|@^.@%`: `<:` is Decrement while `^.` is Logarithm. | Python 3 - ~~250~~ ~~247~~ 270 bytes
====================================
```
from itertools import*
import sys
r=sys.argv[1:]
t=int(r.pop())
p=set(map(tuple,map(sorted,product(r,r))))
a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p]
for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s)
```
Run like this:
```
python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510
```
(that is, a space-delimited list of resistors, with the target value at the end)
Output:
```
('2200|680', 519.4444444444445)
('1000|1000', 500.0)
('150+330', 480)
('220+330', 550)
('1500|680', 467.88990825688074)
('3300|680', 563.8190954773869)
[snip]
('2200+4700', 6900)
('3300+4700', 8000)
('4700+4700', 9400)
```
~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical. |
58,913 | I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development?
Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated. | 2009/10/22 | ['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/'] | No brainer: 64bit.
In addition to the ability to use more RAM and run 64bit apps, 64bit chips have other features the OS itself can use to get performance benefits that a 32bit OS won't know about. More registers, for example.
So even if 32bit Visual Studio is the only app you run, you're still better off running 64bit windows. Not to mention it gives you the ability to build 64bit apps. | Visual Studio is a 32 bit application only, so if that is the major reason for installing windows, 64-bit will not give you any additional features, other than it will be able to handle all 4 GB of memory, whereas 32-bit will only give 3.2 GB or so.
See this question for details about general 32-bit vs 64 bit systems:
* [32-bit vs 64-bit systems](https://superuser.com/questions/56540/32-bit-vs-64-bit-systems) |
58,913 | I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development?
Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated. | 2009/10/22 | ['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/'] | While Visual Studio is 32 bit application, depending on what type of applications you're planning to develop, you might find it beneficial to use the 64-bit version. IIRC you can run and debug both 32-bit and 64-bit executables in 64-bit Windows but not in 32-bit Windows (as the latter isn't able to run 64-bit apps). | Visual Studio is a 32 bit application only, so if that is the major reason for installing windows, 64-bit will not give you any additional features, other than it will be able to handle all 4 GB of memory, whereas 32-bit will only give 3.2 GB or so.
See this question for details about general 32-bit vs 64 bit systems:
* [32-bit vs 64-bit systems](https://superuser.com/questions/56540/32-bit-vs-64-bit-systems) |
58,913 | I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development?
Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated. | 2009/10/22 | ['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/'] | No brainer: 64bit.
In addition to the ability to use more RAM and run 64bit apps, 64bit chips have other features the OS itself can use to get performance benefits that a 32bit OS won't know about. More registers, for example.
So even if 32bit Visual Studio is the only app you run, you're still better off running 64bit windows. Not to mention it gives you the ability to build 64bit apps. | While Visual Studio is 32 bit application, depending on what type of applications you're planning to develop, you might find it beneficial to use the 64-bit version. IIRC you can run and debug both 32-bit and 64-bit executables in 64-bit Windows but not in 32-bit Windows (as the latter isn't able to run 64-bit apps). |
6,284,893 | I am using [SDAC](http://www.devart.com/sdac/) components to query a SQL Server 2008 database. It has a `recordcount`property as all datasets do and it also has the `FetchAll` property (which I think it is called `packedrecords` on `clientdatasets`). Said that, I got a few questions:
1 - If I set `FetchAll = True` the `recordcount` property returns ok. But in this case, when I have a large database and my query returns a lot of lines, sometimes the memory grows a lot (because it is fetching all data to get the `recordcount` of course).
2 - If I set `FetchAll = False`, the `recordcount` returns -1 and the memory does not grow. But I really need the recordcount. And I also wanna create a generic function for this, so I dont have to change all my existent queries.
What can I do to have the `recordcount` working and the memory usage of the application low in this case?
Please, do not post that I dont need recordcount (or that I should use EOF and BOF) because I really do and this is not the question.
I thought about using a query to determine the recordcount, but it has some problems since my query is going to be executed twice (1 for recordcount, 1 for data)
**EDIT**
@Johan pointed out a good solution, and it seems to work. Can anybody confirm this? I am using 1 `TMSCconnection` for every `TMSQuery` (because i am using threads), so I dont think this will be a problem, will it?
```
MSQuery1.FetchAll := False;
MSQuery1.FetchRows := 10;
MSQuery1.SQL.Text := 'select * from cidade';
MSQuery1.Open;
ShowMessage(IntToStr(MSQuery1.RecordCount)); //returns 10
MSQuery1.Close;
MSQuery2.SQL.Text := 'SELECT @@rowcount AS num_of_rows';
MSQuery2.Open;
ShowMessage(MSQuery2.FieldByName('num_of_rows').AsString); //returns 289
```
**EDIT 2\***
`MSQuery1` must be closed, or `MSQuery2` will not return the `num_of_rows`. Why is that?
```
MSQuery1.FetchAll := False;
MSQuery1.FetchRows := 10;
MSQuery1.SQL.Text := 'select * from cidade';
MSQuery1.Open;
ShowMessage(IntToStr(MSQuery1.RecordCount)); //returns 10
//MSQuery1.Close; <<commented
MSQuery2.SQL.Text := 'SELECT @@rowcount AS num_of_rows';
MSQuery2.Open;
ShowMessage(MSQuery2.FieldByName('num_of_rows').AsString); //returns 0
``` | 2011/06/08 | ['https://Stackoverflow.com/questions/6284893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528211/'] | This code:
```
StreamReader sourceStream = new StreamReader(filePath +"\\"+ fileName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
```
You're reading the bytestream as text with a specific encoding (UTF8)... but GIF and ZIP are binary files, not text files. The encoding is mangling them.
Try using something like [ReadAllBytes](http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx):
```
byte[] fileContents = File.ReadAllBytes("filepath");
``` | You are reading binary data to string (assuming it utf8) and converts it back to bytes array. That's completely wrong. |
50,744,257 | I have a data frame that such as below.
```
df <- data.frame(mnth = c("jan", "feb", "feb", "mar", "mar",
"mar", "apr", "apr", "apr", "apr",
"may", "may", "may", "may", "may"),
n = c(1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5),
value = c(5, 1, 3, 2, 8, 0, 6, 0, 2, 7, 2, 1, 4, 2, 6))
```
I want to add the corresponding number in the `value` field for each value of the `n` field.
In this case, the answer should be:
16, 12, 6, 9, 6
```
16 = 5 + 1 + 2 + 6 + 2 # all rows where 'n' = 1
12 = 3 + 8 + 0 + 1 # all rows where 'n' = 2
6 = 0 + 2 + 4 # all rows where 'n' = 3
9 = 7 + 2 # all rows where 'n' = 4
6 # all rows where 'n' = 5
```
How can I write the for loop to add the numbers in R? | 2018/06/07 | ['https://Stackoverflow.com/questions/50744257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5323536/'] | Use a regular expression that matches the specified string followed by anything, and the `-o` option to `grep` so it only returns the part of the line that matched:
```
grep -o 'how.*' file.txt
``` | You could use sed for this
```
$ cat file.txt
Hello, how are you?
$ sed -r "s/^.+(how.+)$/\1/" file.txt
how are you?
$
```
this used sed regex to anchor the text you want to start with - in this case, the word "how" and terminate when it finds the end of the line. |
74,401,695 | I want use Firebase Auth in Flutter project. And I am use `provider`. Everything is okey but I am facing one issue with `provider`.
My IconButtonWidget:
```
class SocialIconButton extends StatelessWidget {
final String socialIcon;
const SocialIconButton({Key? key, required this.socialIcon})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)),
child: IconButton(
onPressed: (() {
final provider =
Provider.of<GoogleSignInProvider>(context, listen: false);
provider.login();
}),
icon: Image.asset(socialIcon)),
);
}
}
```
When I press button I am facing this issue:
```
ProviderNotFoundException (Error: Could not find the correct Provider<GoogleSignInProvider> above this SocialIconButton Widget.
``` | 2022/11/11 | ['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/'] | You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`:
```bash
docker exec -it container_id psql -U my_user -d my_db --password
```
Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal. | I would also like to add, in your compose file you're not exposing any ports for the db container. So it will be unreachable via external sources (you, your app or anything that isn't ran within that container). |
74,401,695 | I want use Firebase Auth in Flutter project. And I am use `provider`. Everything is okey but I am facing one issue with `provider`.
My IconButtonWidget:
```
class SocialIconButton extends StatelessWidget {
final String socialIcon;
const SocialIconButton({Key? key, required this.socialIcon})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)),
child: IconButton(
onPressed: (() {
final provider =
Provider.of<GoogleSignInProvider>(context, listen: false);
provider.login();
}),
icon: Image.asset(socialIcon)),
);
}
}
```
When I press button I am facing this issue:
```
ProviderNotFoundException (Error: Could not find the correct Provider<GoogleSignInProvider> above this SocialIconButton Widget.
``` | 2022/11/11 | ['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/'] | You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`:
```bash
docker exec -it container_id psql -U my_user -d my_db --password
```
Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal. | I think you need to add `environment` to project container.
```
environment:
- DB_HOST=db
- DB_NAME=my_db
- DB_USER=youruser
- DB_PASS=yourpass
depends_on:
- db
```
add this before `depends_on`
And now see if it solves |
74,401,695 | I want use Firebase Auth in Flutter project. And I am use `provider`. Everything is okey but I am facing one issue with `provider`.
My IconButtonWidget:
```
class SocialIconButton extends StatelessWidget {
final String socialIcon;
const SocialIconButton({Key? key, required this.socialIcon})
: super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)),
child: IconButton(
onPressed: (() {
final provider =
Provider.of<GoogleSignInProvider>(context, listen: false);
provider.login();
}),
icon: Image.asset(socialIcon)),
);
}
}
```
When I press button I am facing this issue:
```
ProviderNotFoundException (Error: Could not find the correct Provider<GoogleSignInProvider> above this SocialIconButton Widget.
``` | 2022/11/11 | ['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/'] | You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`:
```bash
docker exec -it container_id psql -U my_user -d my_db --password
```
Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal. | You should add ports to the docker-compose for the postgres image,as this would allow postgres to be accessible outside the container
```
- ports:
"5432:5432"
```
You can checkout more here [docker-compose for postgres](https://geshan.com.np/blog/2021/12/docker-postgres/) |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works. | Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine. |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine. | Have a look at [`Io`](http://www.iolanguage.com).
It's [unicode](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Unicode) all the way down and [embeddable](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Embedding). Also it seems to provide some [C++ binding library](https://stackoverflow.com/a/3153987/12195). |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | There isn't really such a thing as a "unicode string". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though.
I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.).
Some notes about using UTF-8 strings in Lua:
* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes).
* String splitting (e.g. string.sub) must not split up UTF-8 sequences.
* String matching works (string.find, string.match) fine with ASCII patterns.
* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack.
Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua:
```
function utf8_length(str)
return select(2, string.gsub(str, "[^\128-\193]", ""));
end
```
If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings.
Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks.
In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application.
For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise. | Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine. |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine. | Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works. | Have a look at [`Io`](http://www.iolanguage.com).
It's [unicode](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Unicode) all the way down and [embeddable](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Embedding). Also it seems to provide some [C++ binding library](https://stackoverflow.com/a/3153987/12195). |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | There isn't really such a thing as a "unicode string". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though.
I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.).
Some notes about using UTF-8 strings in Lua:
* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes).
* String splitting (e.g. string.sub) must not split up UTF-8 sequences.
* String matching works (string.find, string.match) fine with ASCII patterns.
* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack.
Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua:
```
function utf8_length(str)
return select(2, string.gsub(str, "[^\128-\193]", ""));
end
```
If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings.
Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks.
In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application.
For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise. | Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works. |
10,262,114 | I need to script my app (not a game) and I have a problem, choosing a script lang for this.
Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used.
Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib).
Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app.
So, I'd like to know is there a scripting lang, which satisfies this conditions:
* unicode strings
* I can import C++ functions and then call them from
script
* Can be embedded to app (no dll's) without any problems
Reinventing the wheel is not a good idea, so I don't want to develop my own lang.
Or there is a way to write unicode strings in Lua's source? Like in C++ L"Unicode string" | 2012/04/21 | ['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/'] | Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works. | Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful |
3,926,936 | I have a directory of 9 images:
```
image_0001, image_0002, image_0003
image_0010, image_0011
image_0011-1, image_0011-2, image_0011-3
image_9999
```
I would like to be able to list them in an efficient way, like this (4 entries for 9 images):
```
(image_000[1-3], image_00[10-11], image_0011-[1-3], image_9999)
```
Is there a way in python, to return a directory of images, in a short/clear way (without listing every file)?
So, possibly something like this:
list all images, sort numerically, create a list (counting each image in sequence from start).
When an image is missing (create a new list), continue until original file list is finished.
Now I should just have some lists that contain non broken sequences.
I'm trying to make it easy to read/describe a list of numbers. If I had a sequence of 1000 consecutive files It could be clearly listed as file[0001-1000] rather than file['0001','0002','0003' etc...]
**Edit1**(based on suggestion): Given a flattened list, how would you derive the glob patterns?
**Edit2** I'm trying to break the problem down into smaller pieces. Here is an example of part of the solution:
data1 works, data2 returns 0010 as 64, data3 (the realworld data) doesn't work:
```
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
from operator import itemgetter
from itertools import *
data1=[01,02,03,10,11,100,9999]
data2=[0001,0002,0003,0010,0011,0100,9999]
data3=['image_0001','image_0002','image_0003','image_0010','image_0011','image_0011-2','image_0011-3','image_0100','image_9999']
list1 = []
for k, g in groupby(enumerate(data1), lambda (i,x):i-x):
list1.append(map(itemgetter(1), g))
print 'data1'
print list1
list2 = []
for k, g in groupby(enumerate(data2), lambda (i,x):i-x):
list2.append(map(itemgetter(1), g))
print '\ndata2'
print list2
```
returns:
```
data1
[[1, 2, 3], [10, 11], [100], [9999]]
data2
[[1, 2, 3], [8, 9], [64], [9999]]
``` | 2010/10/13 | ['https://Stackoverflow.com/questions/3926936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178686/'] | Here is a working implementation of what you want to achieve, using the code you added as a starting point:
```
#!/usr/bin/env python
import itertools
import re
# This algorithm only works if DATA is sorted.
DATA = ["image_0001", "image_0002", "image_0003",
"image_0010", "image_0011",
"image_0011-1", "image_0011-2", "image_0011-3",
"image_0100", "image_9999"]
def extract_number(name):
# Match the last number in the name and return it as a string,
# including leading zeroes (that's important for formatting below).
return re.findall(r"\d+$", name)[0]
def collapse_group(group):
if len(group) == 1:
return group[0][1] # Unique names collapse to themselves.
first = extract_number(group[0][1]) # Fetch range
last = extract_number(group[-1][1]) # of this group.
# Cheap way to compute the string length of the upper bound,
# discarding leading zeroes.
length = len(str(int(last)))
# Now we have the length of the variable part of the names,
# the rest is only formatting.
return "%s[%s-%s]" % (group[0][1][:-length],
first[-length:], last[-length:])
groups = [collapse_group(tuple(group)) \
for key, group in itertools.groupby(enumerate(DATA),
lambda(index, name): index - int(extract_number(name)))]
print groups
```
This prints `['image_000[1-3]', 'image_00[10-11]', 'image_0011-[1-3]', 'image_0100', 'image_9999']`, which is what you want.
**HISTORY:** I initially answered the question backwards, as @Mark Ransom pointed out below. For the sake of history, my original answer was:
You're looking for [glob](http://docs.python.org/library/glob.html). Try:
```
import glob
images = glob.glob("image_[0-9]*")
```
Or, using your example:
```
images = [glob.glob(pattern) for pattern in ("image_000[1-3]*",
"image_00[10-11]*", "image_0011-[1-3]*", "image_9999*")]
images = [image for seq in images for image in seq] # flatten the list
``` | ```
def ranges(sorted_list):
first = None
for x in sorted_list:
if first is None:
first = last = x
elif x == increment(last):
last = x
else:
yield first, last
first = last = x
if first is not None:
yield first, last
```
The `increment` function is left as an exercise for the reader.
**Edit:** here's an example of how it would be used with integers instead of strings as input.
```
def increment(x): return x+1
list(ranges([1,2,3,4,6,7,8,10]))
[(1, 4), (6, 8), (10, 10)]
```
For each contiguous range in the input you get a pair indicating the start and end of the range. If an element isn't part of a range, the start and end values are identical. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.