qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
|---|---|---|---|---|---|
69,537,695
|
So I have an array of objects `[{}, {}, {}]`
and simple array `[true, false, true]`
Is there any way to make first array `[{value: true}, {value: false}, {value: true}]`?
I mapped over the object array
```
const a = [{a: 1}, {a: 2}, {a: 3}] const b = [true, false, true] const c = a.map((item) => {...item, value: })
```
I don't understand how to assign the value from the second array.
|
2021/10/12
|
[
"https://Stackoverflow.com/questions/69537695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16633314/"
] |
Assuming your array of objects is called `objects` and your simple array is called `array`, then you can execute:
```
objects.forEach((o, i) => o['value'] = array[i])
```
|
An alternative way of accomplishing this is by using the `unshift()` method which will add the new elements to the beggining of the array.
```js
var arr1 = [true, false, true], arr2 = [{}, {}, {}];
for(el of arr1){ arr2.unshift({'value': el}) }
console.log(arr2);
```
If you want to loose the last three empty objects in the array, slice them like so: `arr2.slice(0,3)`
|
69,537,695
|
So I have an array of objects `[{}, {}, {}]`
and simple array `[true, false, true]`
Is there any way to make first array `[{value: true}, {value: false}, {value: true}]`?
I mapped over the object array
```
const a = [{a: 1}, {a: 2}, {a: 3}] const b = [true, false, true] const c = a.map((item) => {...item, value: })
```
I don't understand how to assign the value from the second array.
|
2021/10/12
|
[
"https://Stackoverflow.com/questions/69537695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16633314/"
] |
You can map each element of the array to the object:
```js
console.log([true, false, true].map(el => ({ value: el })));
```
or if you want to overwrite the elements in the first array
```js
const arr = [{}, {}, {}];
const arr2 = [true, false, true];
arr.forEach((el, idx) => el.value = arr2[idx]);
console.log(arr);
```
|
An alternative way of accomplishing this is by using the `unshift()` method which will add the new elements to the beggining of the array.
```js
var arr1 = [true, false, true], arr2 = [{}, {}, {}];
for(el of arr1){ arr2.unshift({'value': el}) }
console.log(arr2);
```
If you want to loose the last three empty objects in the array, slice them like so: `arr2.slice(0,3)`
|
331,617
|
How do I get the usual inter-line spacing after "Calculation of the edge length of the octagon" and the contents of the `minipage` environment? I know how to put the contents of a `minipage` environment to the left of a `TikZ` diagram, but I do not insist on using a `minipage` environment.
```
\documentclass[10pt]{amsart}
\usepackage{mathtools}
\begin{document}
\noindent \textbf{Calculation of the edge length of the octagon} \\
\noindent \begin{minipage}[t]{4.5in}
\vskip0pt
\noindent \raggedright{The sum of the measures of (interior) angles in the octagon \\
is $(8 - 2)180^{\circ} = 1080^{\circ}$, and so, the measure of the (interior) \\
angles is $135^{\circ}$. The angles that are supplementary to the \\
(interior) angles of the octagon all have the same measure \\
--- $45^{\circ}$. So, the four right triangles at the corners of the \\
square are isosceles right triangles. If $x$ is the edge length \\
of the octagon,}
\end{minipage}
%
\hspace{-0.25cm}
%
\begin{tikzpicture}[baseline=(current bounding box.north)]
%A regular octagon is drawn.
\draw (0,{3/2-(3/2)*(sqrt(2)-1)}) coordinate (A) -- (0,{3/2+(3/2)*(sqrt(2)-1)}) coordinate (B)
-- ({3/2-(3/2)*(sqrt(2)-1)},3) coordinate (C) -- ({3/2+(3/2)*(sqrt(2)-1)},3) coordinate (D)
-- (3,{3/2+(3/2)*(sqrt(2)-1)}) coordinate (E) -- (3,{3/2-(3/2)*(sqrt(2)-1)}) coordinate (F)
-- ({3/2+(3/2)*(sqrt(2)-1)},0) coordinate (G) -- ({3/2-(3/2)*(sqrt(2)-1)},0) coordinate (H)
-- cycle;
%The vertices of the octagon are typeset.
\node[font=\footnotesize, anchor=east, inner sep=0] at ($(0,{3/2-(3/2)*(sqrt(2)-1)}) +(-0.15,0)$){$A$};
\node[font=\footnotesize, anchor=east, inner sep=0] at ($(0,{3/2+(3/2)*(sqrt(2)-1)}) +(-0.15,0)$){$B$};
\node[font=\footnotesize, anchor=south,inner sep=0] at ($({3/2-(3/2)*(sqrt(2)-1)},3) +(0,0.15)$){$C$};
\node[font=\footnotesize, anchor=south,inner sep=0] at ($({3/2+(3/2)*(sqrt(2)-1)},3) +(0,0.15)$){$D$};
\node[font=\footnotesize, anchor=west,inner sep=0] at ($(3,{3/2+(3/2)*(sqrt(2)-1)}) +(0.15,0)$){$E$};
\node[font=\footnotesize, anchor=west,inner sep=0] at ($(3,{3/2-(3/2)*(sqrt(2)-1)}) +(0.15,0)$){$F$};
\node[font=\footnotesize, anchor=north, inner sep=0] at ($({3/2+(3/2)*(sqrt(2)-1)},0) +(0,-0.15)$){$G$};
\node[font=\footnotesize, anchor=north, inner sep=0] at ($({3/2-(3/2)*(sqrt(2)-1)},0) +(0,-0.15)$){$H$};
%A triangle is inscribed in the octagon.
\draw[dashed] (A) -- (F);
\draw[dashed] (A) -- (C);
\draw[dashed] (C) -- (F);
\node[anchor=north, inner sep=0, font=small, font=\scriptsize] at ($($(A)!0.5!(F)$) +(0,-0.15)$){8};
\end{tikzpicture}
\end{document}
```
|
2016/09/27
|
[
"https://tex.stackexchange.com/questions/331617",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/63219/"
] |
Some options:
`edge`
------
```
\draw[->]
(x) edge (sum6)
(sum6) edge (K0)
% ...
;
```
`\foreach`
----------
```
\foreach \a/\b in {
x/sum6,
sum6/K0,
% ...
} \draw[->] (\a) -- (\b);
```
`scope`
-------
At least, the common option can be set in environment `scope`:
```
\begin{scope}[->]
\draw (x) -- (sum6);
\draw (sum6) -- (K0);
% ...
\end{scope}
```
|
As it has been suggested `chains` library could be an option. Information about this library can be found in section [46 Chains](http://www.texdoc.net/pkg/pgf#page=541) from `TikZ` documentation.
The main advantage is that for each element on a `chain` a `join` definition can be defined, so just `chaining` elements, all joins are drawn.
In following code, a `matrix of nodes` has been used to place all the elements and, later on, they have been added to two chains, on for the upper row and a second for the lower one.
Vertical joins and feedback join have been drawn with individual commands.
`scopes` library has been used to type `{[start chain]...}` instead of `\begin{scope}[start chain]...\end{scope}`.
```
\documentclass[border=6mm]{standalone}
\usepackage{tikz}
\usepackage{nccmath}
\usetikzlibrary{shapes,shadows,arrows, matrix, chains, scopes}
\begin{document}
\begin{tikzpicture}[node distance=5mm, auto,
blockcolors/.style={
% The rest
thick,draw=black,
top color=white,
bottom color=black!10,
font=\sffamily\small
},
blockheight/.style = {
minimum height=10mm
},
block/.style={
% The shape:
rectangle, minimum size=6mm, minimum width=12mm,
blockheight,
node distance=5mm,
blockcolors,
drop shadow
},
phantom/.style={
},
open circle/.style={
circle, inner sep=0pt,
thick,draw=black,
fill = white,
},
input/.style={open circle, minimum size=2mm, node distance=8mm, fill=green!70!black},
output/.style={input},
junction/.style={open circle, minimum size=0.5mm,fill=black, node distance=5mm},
sum/.style={open circle, minimum size=4mm, node distance=8mm},
gain/.style={
draw,
shape border rotate=-90,
inner sep=0.5mm,
regular polygon,
regular polygon sides=3,
blockcolors, drop shadow
},
every label/.style={
font=\sffamily\scriptsize
},
>=latex,
every on chain/.style=join,
every join/.style={->},
]
\matrix (A) [matrix of nodes, row sep=1mm, column sep=5mm, nodes={anchor=center}]
{
%first row
& |[gain, inner sep=-.4mm]|$K_I$
& |[block]| $\medint\int dt$
& |[junction]|
& |[input, label={[font=\normalsize]above:$\hat{\omega}_e$}]|
& |[input, label={[font=\normalsize]above:$x$}]|\\
%second row
|[junction]|
& |[gain, inner sep=-.65mm]|$K_P$
&
& |[sum]|
& |[block]| $\medint\int dt$
& |[sum]|
& |[gain, inner sep=0pt]| $K_0$ \\
};
{[start chain]
\chainin (A-2-1);
\chainin (A-2-2);
\chainin (A-2-4);
\chainin (A-2-5);
\chainin (A-2-6);
\chainin (A-2-7);
}
{[start chain]
\chainin (A-1-2);
\chainin (A-1-3);
\chainin (A-1-5);
}
\draw[->] (A-1-4)--(A-2-4);
\draw[->] (A-1-6)--(A-2-6);
\draw[->] (A-2-7)--++(0:1cm)--++(-90:1cm)-|(A-2-1)|-(A-1-2);
\end{tikzpicture}
\end{document}
```
[](https://i.stack.imgur.com/cYVqd.png)
**2nd Version: `\graph`**
An alternative to `chains` library could be `graphs` library. Although `graphs` offers a lot of possibilities which implies using `LuaLaTeX`, this simple example will work with `pdfLaTeX`.
At the moment of writing this answer I don't know how to solve what seems to be an incompatibility between node's names with hyphens (i.e. A-1-1) and `\graph` command (see: [`graph` command doesn't accept nodes named with `-`](https://tex.stackexchange.com/questions/331731/graph-command-doesnt-accept-nodes-named-with?noredirect=1#comment812946_331731)). So, I've introduced syntax `(namewithouthyphen)` in every matrix node to allow using `graph` command.
Instead of just
```
& |[gain, inner sep=-.4mm]|$K_I$
```
every node has been preceded by a name declaration:
```
& |(A12)[gain, inner sep=-.4mm]|$K_I$
```
Another valid syntax could be `|[name=A12, gain, inner sep=-.4mm]|`
`\graph` command accepts some already defined edges between nodes, but it's possible to define new ones. In this case, `feedback` and `cornerupright` have been defined as following `to path`:
```
feedback/.style={to path={--++(0:1cm)--++(-90:1cm)-|(\tikztotarget)}},
cornerupright/.style={to path={|-(\tikztotarget)}},
```
With all these changes, all connections except two can be defined within a unique line:
```
\graph[use existing nodes]{%
A21->A22->A24->A25->A26->A27--[feedback]A21->[cornerupright]A12->A13->A15;
A14->A24;
A16->A26;
};
```
The result is exactly the same obtained with `chains` library.
The complete code is:
```
\documentclass[border=6mm]{standalone}
\usepackage{tikz}
\usepackage{nccmath}
\usetikzlibrary{shapes, shadows, arrows, matrix, graphs}
\begin{document}
\begin{tikzpicture}[node distance=5mm, auto,
blockcolors/.style={
% The rest
thick,draw=black,
top color=white,
bottom color=black!10,
font=\sffamily\small
},
blockheight/.style = {
minimum height=10mm
},
block/.style={
% The shape:
rectangle, minimum size=6mm, minimum width=12mm,
blockheight,
node distance=5mm,
blockcolors,
drop shadow
},
phantom/.style={
},
open circle/.style={
circle, inner sep=0pt,
thick,draw=black,
fill = white,
},
input/.style={open circle, minimum size=2mm, node distance=8mm, fill=green!70!black},
output/.style={input},
junction/.style={open circle, minimum size=0.5mm,fill=black, node distance=5mm},
sum/.style={open circle, minimum size=4mm, node distance=8mm},
gain/.style={
draw,
shape border rotate=-90,
inner sep=0.5mm,
regular polygon,
regular polygon sides=3,
blockcolors, drop shadow
},
every label/.style={
font=\sffamily\scriptsize
},
>=latex,
feedback/.style={to path={--++(0:1cm)--++(-90:1cm)-|(\tikztotarget)}},
cornerupright/.style={to path={|-(\tikztotarget)}},
]
\matrix (A) [matrix of nodes, row sep=1mm, column sep=5mm, nodes={anchor=center}]
{
%first row
& |(A12)[gain, inner sep=-.4mm]|$K_I$
& |(A13)[block]| $\medint\int dt$
& |(A14)[junction]|
& |(A15)[input, label={[font=\normalsize]above:$\hat{\omega}_e$}]|
& |(A16)[input, label={[font=\normalsize]above:$x$}]|\\
%second row
|(A21)[junction]|
& |(A22)[gain, inner sep=-.65mm]|$K_P$
&
& |(A24)[sum]|
& |(A25)[block]| $\medint\int dt$
& |(A26)[sum]|
& |(A27)[gain, inner sep=0pt]| $K_0$ \\
};
\graph[use existing nodes]{%
A21->A22->A24->A25->A26->A27--[feedback]A21->[cornerupright]A12->A13->A15;
A14->A24;
A16->A26;};
\end{tikzpicture}
\end{document}
```
|
70,201,965
|
I'm building a simple recipe app, and so far I have two models: `Ingredient` and `Recipe`.
Each recipe should have multiple ingredients, so I laid out my model like this:
```
class Ingredient(models.Model):
name = models.CharField(max_length=50)
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE)
instructions = JSONField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon')
```
When I makemigrations, I get nothing, but when I migrate, I get this ValueError:
`ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?)`
Following the example here ([Django: Add foreign key in same model but different class](https://stackoverflow.com/questions/49484971/django-add-foreign-key-in-same-model-but-different-class)), I've tried setting `ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE)` as well as using lazy syntax `ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE)`, but each time, `makemigrations` shows no changes, and `migrate` gives me the same `ValueError`.
*Edit*
My imports:
```
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields.json import JSONField
from django.utils import timezone
from django.contrib.auth.models import User```
```
|
2021/12/02
|
[
"https://Stackoverflow.com/questions/70201965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13642780/"
] |
[`slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) works for strings, too.
```js
const
data = ['7177576', '4672769', '2445142', '9293878', '5764392'],
result = data.map(string => string.slice(0, 3));
console.log(result);
```
|
JavaScript has many [methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) for manipulating arrays. The [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method creates a new array populated with the results of calling a provided function on every element in the calling array. As Nina Scholz mentions above you can use [slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) on strings as well.
The issue you are having is that you are calling slice on the array and not on the items of the array.
You need to do something like Nina [Suggest](https://stackoverflow.com/a/70201983/1134764) which is to map over the main array and call your slice function for each item.
|
555,686
|
I have a 4.1 GB USB drive that has become unusable now. It previously had a Live version of Ubuntu 14.04 on it. I tried formatting it a couple of times through different techniques on GParted and the Disks Utility. None of them worked properly
Gparted would tell me that a Partition Table was required. When I tried creating a partition table, it would give me a I/O error. When I tried the Discs utility, I would get a 'No Media Found' error.
I tried using the Ignore option on GParted tool.
Now whenever I start GParted, I get a error popup saying
>
> Input/output error during read on /dev/sdc
>
>
>
The Window is titled "Libparted Bug Found!"
sdc is the USB drive.
Screenshot after clicking on Ignore:
[](https://i.imgur.com/wskNAnG.png)
|
2014/12/02
|
[
"https://askubuntu.com/questions/555686",
"https://askubuntu.com",
"https://askubuntu.com/users/351587/"
] |
### Here is the easy answer:
1. Open `gparted`
2. Select the correct device in the menu `Devices`
3. Go to `Device` → `Create Partition Table`
4. Choose `msdos`
5. If that fails, throw away the USB stick: *It's broken.* **:-(**
6. Now format
7. If that fails, throw away the USB stick: *It's broken.* **:-(**
|
I got this hint from <http://ubuntuforums.org/showthread.php?t=2084152>
Try one or both.
>
> 1. Since I have an extended partition containing many logical partitions including swap and boot, I used a USB install of GParted to
> add the label "lba".
> 2. I booted into Windows Vista and ran chkdsk /f twice. The first time showed a lot of errors / bad sectors but the second run was clean.
>
>
>
|
555,686
|
I have a 4.1 GB USB drive that has become unusable now. It previously had a Live version of Ubuntu 14.04 on it. I tried formatting it a couple of times through different techniques on GParted and the Disks Utility. None of them worked properly
Gparted would tell me that a Partition Table was required. When I tried creating a partition table, it would give me a I/O error. When I tried the Discs utility, I would get a 'No Media Found' error.
I tried using the Ignore option on GParted tool.
Now whenever I start GParted, I get a error popup saying
>
> Input/output error during read on /dev/sdc
>
>
>
The Window is titled "Libparted Bug Found!"
sdc is the USB drive.
Screenshot after clicking on Ignore:
[](https://i.imgur.com/wskNAnG.png)
|
2014/12/02
|
[
"https://askubuntu.com/questions/555686",
"https://askubuntu.com",
"https://askubuntu.com/users/351587/"
] |
### Here is the easy answer:
1. Open `gparted`
2. Select the correct device in the menu `Devices`
3. Go to `Device` → `Create Partition Table`
4. Choose `msdos`
5. If that fails, throw away the USB stick: *It's broken.* **:-(**
6. Now format
7. If that fails, throw away the USB stick: *It's broken.* **:-(**
|
I know this is not a ubuntu program however <https://www.sdcard.org/downloads/formatter_4/> is confirmed to be very good by most manufacturers and has gotten me out of situations sd card related. Also failing that you may want to do a low level format of the sd
|
555,686
|
I have a 4.1 GB USB drive that has become unusable now. It previously had a Live version of Ubuntu 14.04 on it. I tried formatting it a couple of times through different techniques on GParted and the Disks Utility. None of them worked properly
Gparted would tell me that a Partition Table was required. When I tried creating a partition table, it would give me a I/O error. When I tried the Discs utility, I would get a 'No Media Found' error.
I tried using the Ignore option on GParted tool.
Now whenever I start GParted, I get a error popup saying
>
> Input/output error during read on /dev/sdc
>
>
>
The Window is titled "Libparted Bug Found!"
sdc is the USB drive.
Screenshot after clicking on Ignore:
[](https://i.imgur.com/wskNAnG.png)
|
2014/12/02
|
[
"https://askubuntu.com/questions/555686",
"https://askubuntu.com",
"https://askubuntu.com/users/351587/"
] |
### Here is the easy answer:
1. Open `gparted`
2. Select the correct device in the menu `Devices`
3. Go to `Device` → `Create Partition Table`
4. Choose `msdos`
5. If that fails, throw away the USB stick: *It's broken.* **:-(**
6. Now format
7. If that fails, throw away the USB stick: *It's broken.* **:-(**
|
using `sudo fdisk /dev/sdc`
folow the help, using `o` option to create a new partition table
after that you can use Disk Utility or GPart to format you flashdisk
Alternative way:
```
sudo parted -a optimal /dev/sdc
mklabel msdos
```
If success, continue to use Disk Utilities
Good luck!
|
33,137,577
|
I'm a SQL novice who has taken apart from a number of examples that pertain to what I am trying to get, but can't seem to put together all of the pieces, or even confirm if it is doable in one query. My example data structure is:
**Table**: *user*
**Fields**: *'id'* (integer) and *'start\_date'* (date in YYYY-MM-DD format)
I'm trying to write a single query to return a listing of the count of members ('id') where their 'start\_date' falls within the last fiscal year of June 1 - May 31. However, more than that I would like to return with a listing of previous fiscal years as well. The best I've been able to piece together is:
```
SELECT COUNT(user.id) As "Total Members" FROM user WHERE user.start_date BETWEEN '2010-06-01' and '2011-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2011-06-01' and '2012-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2012-06-01' and '2013-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2013-06-01' and '2014-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2014-06-01' and '2015-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2015-06-01' and DATE(CURDATE())
```
There are two issues with this, other than it seems inelegant. One is that while it does return the correct count in a column, I need to add a reference year in an adjacent column to get something along the lines of:
```
Fiscal Year | Total Members
----------------------------
2011 | ####
2012 | ####
2013 | ####
2014 | ####
2015 | ####
CURRENT | ####
```
and the current query will only return the Total Members. And secondly, I am trying to generate this going about 40 years back (from 150,000+ member records) and I feel like there might be a better way by using a modifier on a year function of some kind instead of hard-coding the ranges (YEAR -1, YEAR -2, etc). Thinking that through logically, I also image potential problem with getting the correct reference returned with the correct range without getting overly complicated. Any help or advice would be greatly appreciated. I recognize my limitations, and if what I am looking to write is too complex to maintain I can stick with my existing example list (which goes back another 40 years) if need be. Thanks in advance to all that contribute!
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33137577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712885/"
] |
You can replace any group of two or more of `.`:
```
[.]{2,}
```
with `...`
|
You can do that by negation, detecting everything that *is not* one or more words followed by a "correct" ellipse, and fix the ellipse by using a regular expression like:
```
line.replaceAll("[^\\w* ]+([.]{1,})", "...")
```
this has the advantage of not replacing other punctuation than the malformed ellipses.
|
33,137,577
|
I'm a SQL novice who has taken apart from a number of examples that pertain to what I am trying to get, but can't seem to put together all of the pieces, or even confirm if it is doable in one query. My example data structure is:
**Table**: *user*
**Fields**: *'id'* (integer) and *'start\_date'* (date in YYYY-MM-DD format)
I'm trying to write a single query to return a listing of the count of members ('id') where their 'start\_date' falls within the last fiscal year of June 1 - May 31. However, more than that I would like to return with a listing of previous fiscal years as well. The best I've been able to piece together is:
```
SELECT COUNT(user.id) As "Total Members" FROM user WHERE user.start_date BETWEEN '2010-06-01' and '2011-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2011-06-01' and '2012-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2012-06-01' and '2013-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2013-06-01' and '2014-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2014-06-01' and '2015-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2015-06-01' and DATE(CURDATE())
```
There are two issues with this, other than it seems inelegant. One is that while it does return the correct count in a column, I need to add a reference year in an adjacent column to get something along the lines of:
```
Fiscal Year | Total Members
----------------------------
2011 | ####
2012 | ####
2013 | ####
2014 | ####
2015 | ####
CURRENT | ####
```
and the current query will only return the Total Members. And secondly, I am trying to generate this going about 40 years back (from 150,000+ member records) and I feel like there might be a better way by using a modifier on a year function of some kind instead of hard-coding the ranges (YEAR -1, YEAR -2, etc). Thinking that through logically, I also image potential problem with getting the correct reference returned with the correct range without getting overly complicated. Any help or advice would be greatly appreciated. I recognize my limitations, and if what I am looking to write is too complex to maintain I can stick with my existing example list (which goes back another 40 years) if need be. Thanks in advance to all that contribute!
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33137577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712885/"
] |
Why not keep it simple?
```
\.\.+
```
If you really don't want it to mess with groups of 3 there's this:
```
\.{4,}|(?<!\.)\.{2}(?!\.)
```
What this does is this looks for groups larger than 3 first then it looks for groups of 2. The special thing about "..." is there are 2 groups of ".." in "...". So in `(?!\.)` you look for the 3rd "." after the first 2. If that 3rd "." exists then discard that result. This is called negative lookahead. To discard the 2nd ".." you have to perform negative lookbehind. So `(?<!\.)` looks for that "." before the 2nd ".." and this result is discarded if found.
Negative lookbehind can't be perform by javascript so I used one that uses the Java compiler.
Link: <https://www.myregextester.com/?r=d41b2f7e>
|
You can do that by negation, detecting everything that *is not* one or more words followed by a "correct" ellipse, and fix the ellipse by using a regular expression like:
```
line.replaceAll("[^\\w* ]+([.]{1,})", "...")
```
this has the advantage of not replacing other punctuation than the malformed ellipses.
|
33,137,577
|
I'm a SQL novice who has taken apart from a number of examples that pertain to what I am trying to get, but can't seem to put together all of the pieces, or even confirm if it is doable in one query. My example data structure is:
**Table**: *user*
**Fields**: *'id'* (integer) and *'start\_date'* (date in YYYY-MM-DD format)
I'm trying to write a single query to return a listing of the count of members ('id') where their 'start\_date' falls within the last fiscal year of June 1 - May 31. However, more than that I would like to return with a listing of previous fiscal years as well. The best I've been able to piece together is:
```
SELECT COUNT(user.id) As "Total Members" FROM user WHERE user.start_date BETWEEN '2010-06-01' and '2011-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2011-06-01' and '2012-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2012-06-01' and '2013-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2013-06-01' and '2014-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2014-06-01' and '2015-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2015-06-01' and DATE(CURDATE())
```
There are two issues with this, other than it seems inelegant. One is that while it does return the correct count in a column, I need to add a reference year in an adjacent column to get something along the lines of:
```
Fiscal Year | Total Members
----------------------------
2011 | ####
2012 | ####
2013 | ####
2014 | ####
2015 | ####
CURRENT | ####
```
and the current query will only return the Total Members. And secondly, I am trying to generate this going about 40 years back (from 150,000+ member records) and I feel like there might be a better way by using a modifier on a year function of some kind instead of hard-coding the ranges (YEAR -1, YEAR -2, etc). Thinking that through logically, I also image potential problem with getting the correct reference returned with the correct range without getting overly complicated. Any help or advice would be greatly appreciated. I recognize my limitations, and if what I am looking to write is too complex to maintain I can stick with my existing example list (which goes back another 40 years) if need be. Thanks in advance to all that contribute!
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33137577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712885/"
] |
You can replace any group of two or more of `.`:
```
[.]{2,}
```
with `...`
|
You want something like below (in unescaped form):
```
(?<!\.)\.{2}(?!\.)|\.{4,}
```
[Online examples](https://regex101.com/r/qC2hG2/1)
Basically, in the two-dot case, negative lookbehind and lookahead are used to prevent them from matching the three-dot sequence.
|
33,137,577
|
I'm a SQL novice who has taken apart from a number of examples that pertain to what I am trying to get, but can't seem to put together all of the pieces, or even confirm if it is doable in one query. My example data structure is:
**Table**: *user*
**Fields**: *'id'* (integer) and *'start\_date'* (date in YYYY-MM-DD format)
I'm trying to write a single query to return a listing of the count of members ('id') where their 'start\_date' falls within the last fiscal year of June 1 - May 31. However, more than that I would like to return with a listing of previous fiscal years as well. The best I've been able to piece together is:
```
SELECT COUNT(user.id) As "Total Members" FROM user WHERE user.start_date BETWEEN '2010-06-01' and '2011-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2011-06-01' and '2012-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2012-06-01' and '2013-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2013-06-01' and '2014-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2014-06-01' and '2015-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2015-06-01' and DATE(CURDATE())
```
There are two issues with this, other than it seems inelegant. One is that while it does return the correct count in a column, I need to add a reference year in an adjacent column to get something along the lines of:
```
Fiscal Year | Total Members
----------------------------
2011 | ####
2012 | ####
2013 | ####
2014 | ####
2015 | ####
CURRENT | ####
```
and the current query will only return the Total Members. And secondly, I am trying to generate this going about 40 years back (from 150,000+ member records) and I feel like there might be a better way by using a modifier on a year function of some kind instead of hard-coding the ranges (YEAR -1, YEAR -2, etc). Thinking that through logically, I also image potential problem with getting the correct reference returned with the correct range without getting overly complicated. Any help or advice would be greatly appreciated. I recognize my limitations, and if what I am looking to write is too complex to maintain I can stick with my existing example list (which goes back another 40 years) if need be. Thanks in advance to all that contribute!
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33137577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712885/"
] |
You can replace any group of two or more of `.`:
```
[.]{2,}
```
with `...`
|
Why not keep it simple?
```
\.\.+
```
If you really don't want it to mess with groups of 3 there's this:
```
\.{4,}|(?<!\.)\.{2}(?!\.)
```
What this does is this looks for groups larger than 3 first then it looks for groups of 2. The special thing about "..." is there are 2 groups of ".." in "...". So in `(?!\.)` you look for the 3rd "." after the first 2. If that 3rd "." exists then discard that result. This is called negative lookahead. To discard the 2nd ".." you have to perform negative lookbehind. So `(?<!\.)` looks for that "." before the 2nd ".." and this result is discarded if found.
Negative lookbehind can't be perform by javascript so I used one that uses the Java compiler.
Link: <https://www.myregextester.com/?r=d41b2f7e>
|
33,137,577
|
I'm a SQL novice who has taken apart from a number of examples that pertain to what I am trying to get, but can't seem to put together all of the pieces, or even confirm if it is doable in one query. My example data structure is:
**Table**: *user*
**Fields**: *'id'* (integer) and *'start\_date'* (date in YYYY-MM-DD format)
I'm trying to write a single query to return a listing of the count of members ('id') where their 'start\_date' falls within the last fiscal year of June 1 - May 31. However, more than that I would like to return with a listing of previous fiscal years as well. The best I've been able to piece together is:
```
SELECT COUNT(user.id) As "Total Members" FROM user WHERE user.start_date BETWEEN '2010-06-01' and '2011-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2011-06-01' and '2012-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2012-06-01' and '2013-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2013-06-01' and '2014-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2014-06-01' and '2015-05-31' UNION
SELECT COUNT(user.id) FROM user WHERE user.start_date BETWEEN '2015-06-01' and DATE(CURDATE())
```
There are two issues with this, other than it seems inelegant. One is that while it does return the correct count in a column, I need to add a reference year in an adjacent column to get something along the lines of:
```
Fiscal Year | Total Members
----------------------------
2011 | ####
2012 | ####
2013 | ####
2014 | ####
2015 | ####
CURRENT | ####
```
and the current query will only return the Total Members. And secondly, I am trying to generate this going about 40 years back (from 150,000+ member records) and I feel like there might be a better way by using a modifier on a year function of some kind instead of hard-coding the ranges (YEAR -1, YEAR -2, etc). Thinking that through logically, I also image potential problem with getting the correct reference returned with the correct range without getting overly complicated. Any help or advice would be greatly appreciated. I recognize my limitations, and if what I am looking to write is too complex to maintain I can stick with my existing example list (which goes back another 40 years) if need be. Thanks in advance to all that contribute!
|
2015/10/14
|
[
"https://Stackoverflow.com/questions/33137577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2712885/"
] |
Why not keep it simple?
```
\.\.+
```
If you really don't want it to mess with groups of 3 there's this:
```
\.{4,}|(?<!\.)\.{2}(?!\.)
```
What this does is this looks for groups larger than 3 first then it looks for groups of 2. The special thing about "..." is there are 2 groups of ".." in "...". So in `(?!\.)` you look for the 3rd "." after the first 2. If that 3rd "." exists then discard that result. This is called negative lookahead. To discard the 2nd ".." you have to perform negative lookbehind. So `(?<!\.)` looks for that "." before the 2nd ".." and this result is discarded if found.
Negative lookbehind can't be perform by javascript so I used one that uses the Java compiler.
Link: <https://www.myregextester.com/?r=d41b2f7e>
|
You want something like below (in unescaped form):
```
(?<!\.)\.{2}(?!\.)|\.{4,}
```
[Online examples](https://regex101.com/r/qC2hG2/1)
Basically, in the two-dot case, negative lookbehind and lookahead are used to prevent them from matching the three-dot sequence.
|
231,286
|
I'm writing a sudoku col/row validator, what is does is:
1. Reads user input on how many Sudoku instances to validate.
2. Reads the sudoku matrix grid 9x9 (for me, in my specific case 9x9) into a 2d array. Each line read/row should contain something like: `8 2 1 3 6 4 9 7 5`.
3. Validates each row and column by flipping a 9 bit bitset to test whether all columns and rows contains nums from 1-9.
Please note that the only purpose of this program is to validate sudoku columns/rows as specified and not to completely validate it. i.e also checking each sudoku block.
How can I improve my code? I believe there's lots to it, naming conventions, fundamental approach...etc..etc.
```
#include <iostream>
#include <sstream>
#include <bitset>
namespace Constants
{
constexpr int ROW_COL_SIZE = 9;
const std::string STR_YES = "YES";
const std::string STR_NO = "NO";
}
template<unsigned int N>
class Sudoku
{
private:
int m_matrix[N][N] {{0}};
public:
void ReadRows();
std::string strIsValid() const;
};
template<unsigned int N>void Sudoku<N>::ReadRows()
{
for(unsigned int row{0}; row<N; row++)
{
static std::string line;
std::getline(std::cin, line);
std::istringstream issline(line);
int readnum {0};
for(unsigned int i{0}; i<N; i++)
{
issline >> readnum;
m_matrix[row][i] = readnum;
}
}
}
template<unsigned int N>std::string Sudoku<N>::strIsValid() const
{
//9bit default ctor all zeroes, 000000000
std::bitset<N> bitRow[N];
std::bitset<N> bitCol[N];
for(int i{0}; i<N; i++)
{
for(int j{0}; j<N; j++)
{
bitRow[i].flip(m_matrix[i][j]-1); //verify nums 1-9 row, bitset index is 0 not 1.
bitCol[i].flip(m_matrix[j][i]-1); //verify nums 1-9 col
}
if(!bitRow[i].all() && !bitCol[i].all())
{
return Constants::STR_NO;
}
}
return Constants::STR_YES;
}
int main(int, char**)
{
int instances {0};
std::cin >> instances;
std::cin.clear();
std::cin.ignore();
for(int i{0}; i<instances; i++)
{
std::cout << "Instance " << i+1 << std::endl;
Sudoku<Constants::ROW_COL_SIZE> sudokuInstance;
sudokuInstance.ReadRows();
std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;
}
return 0;
}
```
|
2019/10/24
|
[
"https://codereview.stackexchange.com/questions/231286",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/143492/"
] |
*It is not a complete answer. Just some of my thoughts about this code.*
C++
---
* **Do not compare integers of different signedness**. Loop counters `i` and `j` in function `strIsValid` are declared as `int`, but they are compared with `N` which is `unsigned int`. It could lead to some problems. Make the counters `unsigned`.
* **Use strict compilation flags**. The compiler would tell you about your signed/unsigned issue if you pass it `-Wall` key.
You should always achieve that the compiler will not display any diagnostic messages with the most strict compilation keys (`-Wall`, `-Wextra`, `-pedantic`, etc).
But you probably would [not want](https://quuxplusone.github.io/blog/2018/12/06/dont-use-weverything/) to use Clang's `-Weverything`.
* **What happened with your `main`?** Your `main` function looks very unnatural:
>
>
> ```
> int main(int, char**)
>
> ```
>
>
If you do not need `argc` and `argv`, write just
```
int main()
```
* **About `std::endl`**. You should avoid globally using `std::endl`. It is not the same as just `\n`. There is a [good answer](https://stackoverflow.com/a/14395960/8086115) on SO about this topic.
And why are you printing `std::endl` twice?
>
>
> ```
> std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;
>
> ```
>
>
* **You do not have to explicitly return from `main`**. You [don't have](https://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c) to explicitly `return 0;` at the end of main.
Programming
-----------
* **Minimize the scope of local variables**. You should always minimize the scope of local variables. In your case, for example, scope of the `readnum` variable can be reduced. Some [reading](https://refactoring.com/catalog/reduceScopeOfVariable.html) about this topic.
* **The predicative function should return boolean**. Your `strIsValid` is a *predicative function*. It means that this function checks something and returns either true or false. But you return *string* `"YES"` (true) or `"NO"` (false). You should return `bool` instead.
* **What the `strIsValid` function does?** The name of this function doesn't answer the question.
Architecture
------------
* **Validate user's input**. At this time you do not validate user's input in `ReadRows`. What if I'll input a number which is greater than 9? Or less than 0? If I'll input too many numbers?..
In this case, you store invalid data into `m_matrix`. Then this invalid data will be used as arguments of `std::bitset`'s `flip()` which will cause `std::out_of_range`.
* **Split row and cols validating and reading user's input**. The `Sudoku` class should know nothing about reading user's input. The only thing that it should do is validate Sudoku columns and rows! This is called the Single Responsibility Principle ([SRP](https://en.wikipedia.org/wiki/Single_responsibility_principle)).
|
First, I just want to remark that this is excellent use of `std::bitset<>`!
Further, I'm just adding to eanmos's comments.
Don't define constants that are named after their value
=======================================================
Apart from the fact that, as already mentioned, `strIsValid()` should return a `bool`, you define the constants `Constants::STR_YES` and `Constants::STR_NO`. These constants are longer to type than literal `"YES"` and `"NO"`. Also, consider that you would ever change the value of `STR_YES`. The code was written with the assumption that the constant would be the literal `"YES"`, as that is what its name clearly says, but now you are breaking that assumption. So in `main()`, just I would just write:
```
std::cout << sudokuInstance.strIsValid() ? "YES\n" : "NO\n";
```
If the goal is to make it easy to translate the program, then you should use a so-called internationalization library to do this, such as [gettext](https://en.wikipedia.org/wiki/Gettext). Writing constants like this doesn't scale for programs with a large amount of text.
Consider returning a meaningful value from `main()`
===================================================
Your program prints whether each Sudoku instance is valid to standard output, but the exit code is always 0. It is custom to have the exit code be non-zero if an error happened. While technically your program still runs perfectly fine if you feed it an invalid Sudoku, you might consider returning 1 if it has encountered any non-valid Sudoku. This is similar to what some command line tools do, like `cmp` or `grep -q`.
This way, you can call your program from a shell script, and have the shell script react to the result of your program in an easy way, making it easy to integrate it into larger projects.
|
33,405,628
|
database name : test
table name : employee
structur
```
+-----+------------+----------+--------+
| id | name | Password | code |
+-----+------------+----------+--------+
| 11 | John | test122 | A1 |
| 12 | Johana | test124 | A2 |
| 13 | David | test125 | A3 |
| 14 | Anna | test126 | A1 |
| 15 | Mike | test127 | A5 |
+-----+------------+----------+--------+
```
table name : code\_id
structur
```
+-------+------------+
| code | codename |
+-------+------------+
| A1 | Security |
| A2 | Manager |
| A3 | Admin |
| A4 | guest |
| A5 | CEO |
+-------+------------+
```
i want to say welcome and it success
```
$strSQL = "SELECT * FROM employee";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
$idcode = $row['code'];
}
mysql_close();
```
echo $idcode
result:
welcome, A1
---
now i want
to echo
welcome, Manager
or
welcome CEO
how to query that on php ?
|
2015/10/29
|
[
"https://Stackoverflow.com/questions/33405628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5258785/"
] |
Try this query
```
$strSQL = "select a.*,b.codename from employee as a join code_id as b on a.code=b.code";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
$idcode = $row['codename'];
}
mysql_close();
```
|
An easier way without querying can be this,
```
<?php
function convertCode($code) {
$codes = [
"A1" => "Security",
"A2" => "Manager",
"A3" => "Admin",
"A4" => "guest",
"A5" => "CEO"
];
return $codes[$code];
}
?>
```
Then in your loop,
```
echo "Welcome " . convertCode($row['code']) . ".";
```
**Edit 1**
You shouldn't be using `mysql` any more as it has been officially deprecated. You should change to `mysqli` or `PDO`.
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
If the URL you're using (as an `img` src here) might contain quotes, you should use URL quoting.
For python, use the [urllib.quote](http://docs.python.org/library/urllib.html#urllib.quote) method before passing the URL string to your template:
```
img_url = 'test".jpg'
__string__ = urllib.quote(img_url)
```
|
The best way to escape XML or HTML in python is probably with triple quotes. Note that you can also escape carriage returns.
```
"""<foo bar="1" baz="2" bat="3">
<ack/>
</foo>
"""
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
```
import cgi
s = cgi.escape('test".jpg', True)
```
<http://docs.python.org/library/cgi.html#cgi.escape>
Note that the `True` flag tells it to escape double quotes. If you need to escape single quotes as well (if you're one of those rare individuals who use single quotes to surround html attributes) read the note in that documentation link about xml.sax.saxutils.quoteattr(). The latter does both kinds of quotes, though it is about three times as slow:
```
>>> timeit.Timer( "escape('asdf\"asef', True)", "from cgi import escape").timeit()
1.2772219181060791
>>> timeit.Timer( "quoteattr('asdf\"asef')", "from xml.sax.saxutils import quoteattr").timeit()
3.9785079956054688
```
|
The best way to escape XML or HTML in python is probably with triple quotes. Note that you can also escape carriage returns.
```
"""<foo bar="1" baz="2" bat="3">
<ack/>
</foo>
"""
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
If your value being escaped might contain quotes, the best thing is to use the `quoteattr` method: <http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils>
This is referenced right beneath the docs on the cgi.escape() method.
|
The best way to escape XML or HTML in python is probably with triple quotes. Note that you can also escape carriage returns.
```
"""<foo bar="1" baz="2" bat="3">
<ack/>
</foo>
"""
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function `html.escape(s, quote=True)`.
If the optional flag quote is true, the characters `(")` and `(')` are also translated.
Usage:
```
>>> import html
>>> html.escape('x > 2 && x < 7')
'x > 2 && x < 7'
```
|
The best way to escape XML or HTML in python is probably with triple quotes. Note that you can also escape carriage returns.
```
"""<foo bar="1" baz="2" bat="3">
<ack/>
</foo>
"""
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
If your value being escaped might contain quotes, the best thing is to use the `quoteattr` method: <http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils>
This is referenced right beneath the docs on the cgi.escape() method.
|
If the URL you're using (as an `img` src here) might contain quotes, you should use URL quoting.
For python, use the [urllib.quote](http://docs.python.org/library/urllib.html#urllib.quote) method before passing the URL string to your template:
```
img_url = 'test".jpg'
__string__ = urllib.quote(img_url)
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function `html.escape(s, quote=True)`.
If the optional flag quote is true, the characters `(")` and `(')` are also translated.
Usage:
```
>>> import html
>>> html.escape('x > 2 && x < 7')
'x > 2 && x < 7'
```
|
If the URL you're using (as an `img` src here) might contain quotes, you should use URL quoting.
For python, use the [urllib.quote](http://docs.python.org/library/urllib.html#urllib.quote) method before passing the URL string to your template:
```
img_url = 'test".jpg'
__string__ = urllib.quote(img_url)
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
If your value being escaped might contain quotes, the best thing is to use the `quoteattr` method: <http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils>
This is referenced right beneath the docs on the cgi.escape() method.
|
```
import cgi
s = cgi.escape('test".jpg', True)
```
<http://docs.python.org/library/cgi.html#cgi.escape>
Note that the `True` flag tells it to escape double quotes. If you need to escape single quotes as well (if you're one of those rare individuals who use single quotes to surround html attributes) read the note in that documentation link about xml.sax.saxutils.quoteattr(). The latter does both kinds of quotes, though it is about three times as slow:
```
>>> timeit.Timer( "escape('asdf\"asef', True)", "from cgi import escape").timeit()
1.2772219181060791
>>> timeit.Timer( "quoteattr('asdf\"asef')", "from xml.sax.saxutils import quoteattr").timeit()
3.9785079956054688
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function `html.escape(s, quote=True)`.
If the optional flag quote is true, the characters `(")` and `(')` are also translated.
Usage:
```
>>> import html
>>> html.escape('x > 2 && x < 7')
'x > 2 && x < 7'
```
|
```
import cgi
s = cgi.escape('test".jpg', True)
```
<http://docs.python.org/library/cgi.html#cgi.escape>
Note that the `True` flag tells it to escape double quotes. If you need to escape single quotes as well (if you're one of those rare individuals who use single quotes to surround html attributes) read the note in that documentation link about xml.sax.saxutils.quoteattr(). The latter does both kinds of quotes, though it is about three times as slow:
```
>>> timeit.Timer( "escape('asdf\"asef', True)", "from cgi import escape").timeit()
1.2772219181060791
>>> timeit.Timer( "quoteattr('asdf\"asef')", "from xml.sax.saxutils import quoteattr").timeit()
3.9785079956054688
```
|
3,096,948
|
i have a `<img src=__string__>` but **string** might contain ", what should I do to escape it?
Example:
```
__string__ = test".jpg
<img src="test".jpg">
```
doesn't work.
|
2010/06/22
|
[
"https://Stackoverflow.com/questions/3096948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101823/"
] |
If your value being escaped might contain quotes, the best thing is to use the `quoteattr` method: <http://docs.python.org/library/xml.sax.utils.html#module-xml.sax.saxutils>
This is referenced right beneath the docs on the cgi.escape() method.
|
In Python 3.2 a new `html` module was introduced, which is used for escaping reserved characters from HTML markup.
It has one function `html.escape(s, quote=True)`.
If the optional flag quote is true, the characters `(")` and `(')` are also translated.
Usage:
```
>>> import html
>>> html.escape('x > 2 && x < 7')
'x > 2 && x < 7'
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
you can use [`Split()`](https://msdn.microsoft.com/ru-ru/library/system.string.split(v=vs.110).aspx) and [`Substring()`](https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)
```
var str = @"Sat, 02/04/1708:00 PM";
var res = str.Split(' ')[1].Substring(0, 8);
```
|
you can use **substring**
`string str="Sat, 02/04/1708:00 PM";`
`string newStr=str.Substring(5,8);`
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
you can use [`Split()`](https://msdn.microsoft.com/ru-ru/library/system.string.split(v=vs.110).aspx) and [`Substring()`](https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)
```
var str = @"Sat, 02/04/1708:00 PM";
var res = str.Split(' ')[1].Substring(0, 8);
```
|
```
String str = @"Sat, 02/04/1708:00 PM";
String expected = str.split(' ')[1].Substring(0,8);
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
you can use [`Split()`](https://msdn.microsoft.com/ru-ru/library/system.string.split(v=vs.110).aspx) and [`Substring()`](https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)
```
var str = @"Sat, 02/04/1708:00 PM";
var res = str.Split(' ')[1].Substring(0, 8);
```
|
You can also do this:
```
string strInput = @"Sat, 02/04/1708:00 PM";
var dateResult = strInput.Split(' ', ',')[2];
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
you can use [`Split()`](https://msdn.microsoft.com/ru-ru/library/system.string.split(v=vs.110).aspx) and [`Substring()`](https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx)
```
var str = @"Sat, 02/04/1708:00 PM";
var res = str.Split(' ')[1].Substring(0, 8);
```
|
This might do the trick for you.
```
string smdt = "Sun, 02/04/1708:00 PM";
string format = "ddd, dd/MM/yyhh:mm tt";
DateTime dt = DateTime.ParseExact(smdt, format, CultureInfo.InvariantCulture, DateTimeStyles.None);
string extractedDate = dt.ToString("dd/MM/yy");
```
The problem with the Question was the Date `02/04/17` is not a `Saturday` instead it will be `Sunday` and thus it will not be able to convert to a `DateTime`. When I change `Sat to Sun`. The `extractedDate` is the result which you are looking for.
One liner answer could be
```
string smdt = "Sun, 02/04/1708:00 PM";
string extractedDate = DateTime.ParseExact(
smdt,
"ddd, dd/MM/yyhh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None
).ToString("dd/MM/yy");
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
Regex rg = new Regex(@"[01]?\d[/-][0123]?\d[/-]\d{2}");
Match m = rg.Match("Sat, 02/04/1708:00 PM");
Console.Write(m.ToString());
```
**[`WORKING FIDDLE`](https://dotnetfiddle.net/EwmHKe)**
|
you can use **substring**
`string str="Sat, 02/04/1708:00 PM";`
`string newStr=str.Substring(5,8);`
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
Regex rg = new Regex(@"[01]?\d[/-][0123]?\d[/-]\d{2}");
Match m = rg.Match("Sat, 02/04/1708:00 PM");
Console.Write(m.ToString());
```
**[`WORKING FIDDLE`](https://dotnetfiddle.net/EwmHKe)**
|
```
String str = @"Sat, 02/04/1708:00 PM";
String expected = str.split(' ')[1].Substring(0,8);
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
Regex rg = new Regex(@"[01]?\d[/-][0123]?\d[/-]\d{2}");
Match m = rg.Match("Sat, 02/04/1708:00 PM");
Console.Write(m.ToString());
```
**[`WORKING FIDDLE`](https://dotnetfiddle.net/EwmHKe)**
|
You can also do this:
```
string strInput = @"Sat, 02/04/1708:00 PM";
var dateResult = strInput.Split(' ', ',')[2];
```
|
41,606,259
|
I need the following string trimmed
```
Sat, 02/04/1708:00 PM
```
so that the result is 02/04/17
How can I accomplish this?
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41606259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
Regex rg = new Regex(@"[01]?\d[/-][0123]?\d[/-]\d{2}");
Match m = rg.Match("Sat, 02/04/1708:00 PM");
Console.Write(m.ToString());
```
**[`WORKING FIDDLE`](https://dotnetfiddle.net/EwmHKe)**
|
This might do the trick for you.
```
string smdt = "Sun, 02/04/1708:00 PM";
string format = "ddd, dd/MM/yyhh:mm tt";
DateTime dt = DateTime.ParseExact(smdt, format, CultureInfo.InvariantCulture, DateTimeStyles.None);
string extractedDate = dt.ToString("dd/MM/yy");
```
The problem with the Question was the Date `02/04/17` is not a `Saturday` instead it will be `Sunday` and thus it will not be able to convert to a `DateTime`. When I change `Sat to Sun`. The `extractedDate` is the result which you are looking for.
One liner answer could be
```
string smdt = "Sun, 02/04/1708:00 PM";
string extractedDate = DateTime.ParseExact(
smdt,
"ddd, dd/MM/yyhh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None
).ToString("dd/MM/yy");
```
|
55,482,837
|
Say I have a rectangle `[a,b]x[c,d]`, where `a,b,c,d` are reals.
I would like to produce `k` points `(x,y)` sampled uniformly from this rectangle, i.e. `a <= x <= c` and `b <= y <= d`.
Obviously, if sampling from `[0,1]x[0,1]` is possible, then
the problem is solved. How to achieve any of the two goals, in `python`?
Or, another tool such as `R`, for example?
|
2019/04/02
|
[
"https://Stackoverflow.com/questions/55482837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015315/"
] |
You can use `random.uniform()`:
```
import random
x, y = random.uniform(a, b), random.uniform(c, d)
```
If you want k of them a list comprehension will do
```
coords = [(random.uniform(a, b), random.uniform(c, d)) for _ in range(k)]
```
|
I think modulo operator (%) is your friend to check if x and y are in [a,c] and [b,d]
If you can't use random between 2 numbers (others 0 and 1), you can try to make `x = (random() *(c-a)+a)`
Same with y :)
EDIT : Oh, i send it just after Merig
|
21,008,492
|
I have this simple ldap client which uses obsolete `Hashtable` collection.
```
class SAuth {
public static void main(String[] args) {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext(env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
Is there any modern collection which I can use without breaking the code instead of Hashtable?
Update:
```
class tSAuth {
public static void main(String[] args) {
Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext((Hashtable<?, ?>) env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
|
2014/01/08
|
[
"https://Stackoverflow.com/questions/21008492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103606/"
] |
Use `HashMap` instead of `HashTable` like this:
```
Map env = new HashMap();
```
I'm not sure the exact type of `Context.*`, however, if it's `String`, then you could write the code like this:
```
Map<String, String> env = new HashMap<String, String>();
```
**EDIT:**
The [`InitialDirContext`](http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/InitialDirContext.html#InitialDirContext%28java.util.Hashtable%29) constructor's parameter type is `Hashtable<?,?>`. So you should `Hashtable` in this case. Perhaps you can code like this:
```
Hashtable<String, String> env = new Hashtable<String, String>();
```
|
You have to use a Hashtable according to the java documentation for InitialDirContext. <http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/InitialDirContext.html#InitialDirContext%28java.util.Hashtable%29>
|
21,008,492
|
I have this simple ldap client which uses obsolete `Hashtable` collection.
```
class SAuth {
public static void main(String[] args) {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext(env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
Is there any modern collection which I can use without breaking the code instead of Hashtable?
Update:
```
class tSAuth {
public static void main(String[] args) {
Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext((Hashtable<?, ?>) env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
|
2014/01/08
|
[
"https://Stackoverflow.com/questions/21008492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103606/"
] |
Use `HashMap` instead of `HashTable` like this:
```
Map env = new HashMap();
```
I'm not sure the exact type of `Context.*`, however, if it's `String`, then you could write the code like this:
```
Map<String, String> env = new HashMap<String, String>();
```
**EDIT:**
The [`InitialDirContext`](http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/InitialDirContext.html#InitialDirContext%28java.util.Hashtable%29) constructor's parameter type is `Hashtable<?,?>`. So you should `Hashtable` in this case. Perhaps you can code like this:
```
Hashtable<String, String> env = new Hashtable<String, String>();
```
|
You should be able to use [`java.util.Properties`](https://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) here, since it extends `java.util.Hashtable<Object,Object>`.
|
21,008,492
|
I have this simple ldap client which uses obsolete `Hashtable` collection.
```
class SAuth {
public static void main(String[] args) {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext(env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
Is there any modern collection which I can use without breaking the code instead of Hashtable?
Update:
```
class tSAuth {
public static void main(String[] args) {
Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext((Hashtable<?, ?>) env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
```
|
2014/01/08
|
[
"https://Stackoverflow.com/questions/21008492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103606/"
] |
You have to use a Hashtable according to the java documentation for InitialDirContext. <http://docs.oracle.com/javase/7/docs/api/javax/naming/directory/InitialDirContext.html#InitialDirContext%28java.util.Hashtable%29>
|
You should be able to use [`java.util.Properties`](https://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) here, since it extends `java.util.Hashtable<Object,Object>`.
|
1,890,844
|
I'm trying to write an array of objects that implement [Parcelable](http://developer.android.com/reference/android/os/Parcelable.html) into a [Parcel](http://developer.android.com/reference/android/os/Parcel.html) using [writeParcelableArray](http://developer.android.com/reference/android/os/Parcel.html#writeParcelableArray%28T%5B%5D,%20int%29).
The objects I'm trying to write are defined (as you'd expect) as:
```
public class Arrival implements Parcelable {
/* All the right stuff in here... this class compiles and acts fine. */
}
```
And I'm trying to write them into a `Parcel' with:
```
@Override
public void writeToParcel(Parcel dest, int flags) {
Arrival[] a;
/* some stuff to populate "a" */
dest.writeParcelableArray(a, 0);
}
```
When Eclipse tries to compile this I get the error:
>
> Bound mismatch: The generic method
> writeParcelableArray(T[], int) of type
> Parcel is not applicable for the
> arguments (Arrival[], int). The
> inferred type Arrival is not a valid
> substitute for the bounded parameter
> < T extends Parcelable >
>
>
>
I completely don't understand this error message. `Parcelable` is an interface (not a class) so you can't extend it. Anyone have any ideas?
**UPDATE:** I'm having basically the same problem when putting an `ArrayList` of `Parcelable`s into an `Intent`:
```
Intent i = new Intent();
i.putParcelableArrayListExtra("locations", (ArrayList<Location>) locations);
```
yields:
>
> The method putParcelableArrayListExtra(String, ArrayList< ? extends Parcelable >) in the type Intent is not applicable for the arguments (String, ArrayList< Location >)
>
>
>
This may be because `Location` was the class I was working on above (that wraps the `Arrival`s), but I don't think so.
|
2009/12/11
|
[
"https://Stackoverflow.com/questions/1890844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76835/"
] |
It turns out it just wanted me to build an array of Parcelables. To use the example from the question:
```
@Override
public void writeToParcel(Parcel dest, int flags) {
Parcelable[] a;
/*
some stuff to populate "a" with Arrival
objects (which implements Parcelable)
*/
dest.writeParcelableArray(a, 0);
}
```
|
Actually, you can extend an interface, and it looks like you need to do just that. The generics parameter in writeParcelableArray is asking for an extended interface (not the interface itself). Try creating an interface MyParcelable extends Parcelable. Then declaring your array using the interface, but the impl should be your Arrival extends MyParcelable.
|
1,890,844
|
I'm trying to write an array of objects that implement [Parcelable](http://developer.android.com/reference/android/os/Parcelable.html) into a [Parcel](http://developer.android.com/reference/android/os/Parcel.html) using [writeParcelableArray](http://developer.android.com/reference/android/os/Parcel.html#writeParcelableArray%28T%5B%5D,%20int%29).
The objects I'm trying to write are defined (as you'd expect) as:
```
public class Arrival implements Parcelable {
/* All the right stuff in here... this class compiles and acts fine. */
}
```
And I'm trying to write them into a `Parcel' with:
```
@Override
public void writeToParcel(Parcel dest, int flags) {
Arrival[] a;
/* some stuff to populate "a" */
dest.writeParcelableArray(a, 0);
}
```
When Eclipse tries to compile this I get the error:
>
> Bound mismatch: The generic method
> writeParcelableArray(T[], int) of type
> Parcel is not applicable for the
> arguments (Arrival[], int). The
> inferred type Arrival is not a valid
> substitute for the bounded parameter
> < T extends Parcelable >
>
>
>
I completely don't understand this error message. `Parcelable` is an interface (not a class) so you can't extend it. Anyone have any ideas?
**UPDATE:** I'm having basically the same problem when putting an `ArrayList` of `Parcelable`s into an `Intent`:
```
Intent i = new Intent();
i.putParcelableArrayListExtra("locations", (ArrayList<Location>) locations);
```
yields:
>
> The method putParcelableArrayListExtra(String, ArrayList< ? extends Parcelable >) in the type Intent is not applicable for the arguments (String, ArrayList< Location >)
>
>
>
This may be because `Location` was the class I was working on above (that wraps the `Arrival`s), but I don't think so.
|
2009/12/11
|
[
"https://Stackoverflow.com/questions/1890844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76835/"
] |
Actually, you can extend an interface, and it looks like you need to do just that. The generics parameter in writeParcelableArray is asking for an extended interface (not the interface itself). Try creating an interface MyParcelable extends Parcelable. Then declaring your array using the interface, but the impl should be your Arrival extends MyParcelable.
|
I know the problem is solved but my solution was other so I'm posting it here: in my case Eclipse automatically imported wrong package because of classes names abiguity(some dom.Comment instead of my Comment class).
|
1,890,844
|
I'm trying to write an array of objects that implement [Parcelable](http://developer.android.com/reference/android/os/Parcelable.html) into a [Parcel](http://developer.android.com/reference/android/os/Parcel.html) using [writeParcelableArray](http://developer.android.com/reference/android/os/Parcel.html#writeParcelableArray%28T%5B%5D,%20int%29).
The objects I'm trying to write are defined (as you'd expect) as:
```
public class Arrival implements Parcelable {
/* All the right stuff in here... this class compiles and acts fine. */
}
```
And I'm trying to write them into a `Parcel' with:
```
@Override
public void writeToParcel(Parcel dest, int flags) {
Arrival[] a;
/* some stuff to populate "a" */
dest.writeParcelableArray(a, 0);
}
```
When Eclipse tries to compile this I get the error:
>
> Bound mismatch: The generic method
> writeParcelableArray(T[], int) of type
> Parcel is not applicable for the
> arguments (Arrival[], int). The
> inferred type Arrival is not a valid
> substitute for the bounded parameter
> < T extends Parcelable >
>
>
>
I completely don't understand this error message. `Parcelable` is an interface (not a class) so you can't extend it. Anyone have any ideas?
**UPDATE:** I'm having basically the same problem when putting an `ArrayList` of `Parcelable`s into an `Intent`:
```
Intent i = new Intent();
i.putParcelableArrayListExtra("locations", (ArrayList<Location>) locations);
```
yields:
>
> The method putParcelableArrayListExtra(String, ArrayList< ? extends Parcelable >) in the type Intent is not applicable for the arguments (String, ArrayList< Location >)
>
>
>
This may be because `Location` was the class I was working on above (that wraps the `Arrival`s), but I don't think so.
|
2009/12/11
|
[
"https://Stackoverflow.com/questions/1890844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76835/"
] |
It turns out it just wanted me to build an array of Parcelables. To use the example from the question:
```
@Override
public void writeToParcel(Parcel dest, int flags) {
Parcelable[] a;
/*
some stuff to populate "a" with Arrival
objects (which implements Parcelable)
*/
dest.writeParcelableArray(a, 0);
}
```
|
I know the problem is solved but my solution was other so I'm posting it here: in my case Eclipse automatically imported wrong package because of classes names abiguity(some dom.Comment instead of my Comment class).
|
70,508,319
|
I have to change my custom defined spring properties (defined via @ConfigurationProperties beans) during runtime of my Spring Boot application.
Is there any elegant way of doing this using Spring Cloud Config?
I don't want to use an external application.properties in a git repository (as the spring boot application gets shipped to customers and I dont' want to create a git repository for everyone of them).
I just want to access and change the local application.properties (the one in the classpath, located in src/main/resources) file in my Spring container or (if thats not possible) in the Spring Cloud Config Server, which I could embed into my Spring Boot app. Is that possible somehow?
BTW: The goal is to create a visual editor for the customers, so that they can change the application.properties during runtime in their spring boot app.
|
2021/12/28
|
[
"https://Stackoverflow.com/questions/70508319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10084505/"
] |
Spring Boot supports profile based application configuration. Just add `application-<profile>.properties` file. Then just when running the application select a profile depending on the environment making use of `spring.profiles.active`.
```
-Dspring.profiles.active=dev
```
This will run the application with `application-dev.properties` file (overriding the default `application.properties`, i.e you can just leave the common stuff in the default file and change the rest depending on the env)
On a side note, having a repo for configuration is not a must. You could just place them in the class path and give a `search-location`.
```
spring:
application:
name: config-server
profiles:
active: native
cloud:
config:
server:
native:
search-locations: classpath:configs/
```
|
Maybe what your looking for could be achieved with Spring cloud config and spring cloud bus. It's explained here: <https://cloud.spring.io/spring-cloud-config/reference/html/#_push_notifications_and_spring_cloud_bus>
In summary, any change on configuration sent an event to the spring cloud bus and you can then reload app context or configuration with new properties.
|
70,508,319
|
I have to change my custom defined spring properties (defined via @ConfigurationProperties beans) during runtime of my Spring Boot application.
Is there any elegant way of doing this using Spring Cloud Config?
I don't want to use an external application.properties in a git repository (as the spring boot application gets shipped to customers and I dont' want to create a git repository for everyone of them).
I just want to access and change the local application.properties (the one in the classpath, located in src/main/resources) file in my Spring container or (if thats not possible) in the Spring Cloud Config Server, which I could embed into my Spring Boot app. Is that possible somehow?
BTW: The goal is to create a visual editor for the customers, so that they can change the application.properties during runtime in their spring boot app.
|
2021/12/28
|
[
"https://Stackoverflow.com/questions/70508319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10084505/"
] |
It actually is possible and in the end quite easy to achieve. It just took me a whole day to get all the information together. Maybe this helps someone:
You basically just need Spring Actuator, but for a certain endpoint, you also need the spring cloud dependency. (to make Post requests to the /env endpoint of Spring Actuator)
To alter your config at runtime, just add the following to your application.properties:
```
management.endpoints.web.exposure.include: env,refresh
management.endpoint.env.post.enabled: true //this property is only available when spring cloud is added as dependency to your project
```
If you (like me) don't need the feature of an externalized config, then you also have to add the following (otherwise, your Spring app will not start and throw an error that some config is missing)
```
spring.cloud.config.enabled: false
```
Now, if you send a POST request to /actuator/env endpoint with an object in the HTTP body in the form of {"name":"...", "value":"..."} (name is the name of a config property), then your config gets changed. To check that, you can do a GET request to /actuator/env/[name\_of\_config\_property] and see that your config property has changed. No need to restart your app.
Don't forget to secure the /actuator endpoint in your SecurityConfig if you use a custom one.
It seems to me that you neither need the @RefreshScope annotation at your config classes nor the /actuator/refresh endpoint to "apply" the config changes.
|
Maybe what your looking for could be achieved with Spring cloud config and spring cloud bus. It's explained here: <https://cloud.spring.io/spring-cloud-config/reference/html/#_push_notifications_and_spring_cloud_bus>
In summary, any change on configuration sent an event to the spring cloud bus and you can then reload app context or configuration with new properties.
|
40,599,960
|
First time posting here. I recently implemented Binary Search but sometimes my outputs will return a giant negative number instead. Now my first thought is that I'm printing a number where my pointer is pointing at a random memory location. Can someone help me with the logic and how I can improve my code?
```
#include <stdio.h>
#include <stdlib.h>
int binarysearch(int *array, int size, int target);
int main() {
int array[] = { 1, 2, 3, 4, 5, 6 };
printf("%d\n", binarysearch(array, 8, 15));
return 0;
}
int binarysearch(int *array, int size, int target) {
int mid;
mid = size / 2;
if (size < 1) {
return -1;
}
if (size == 1) {
return array[0];
}
if (target == array[mid]) {
return target;
} else
if (target < array[mid]) {
binarysearch(array, mid, target);
} else{
binarysearch(array + mid, size - mid, target);
}
}
```
|
2016/11/15
|
[
"https://Stackoverflow.com/questions/40599960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7159403/"
] |
You call `binarysearch(array, 8, 15))` but your array has only 6 entries.
Here is how to compute the proper size automatically:
```
int main(void) {
int array[] = { 1, 2, 3, 4, 5, 6 };
printf("%d\n", binarysearch(array, sizeof(array) / sizeof(array[0]), 15));
return 0;
}
```
Note that your function `binarysearch` has problems too:
1. Returning the array entry is bogus, what do you return if the target is less than the first entry? `-1` is not necessarily less than the first entry.
2. You are supposed to return the index into the array with the entry if found and `-1` if not found.
3. When you recurse, you do not return the value from these recursive calls: you should compile with warnings enabled (for example: `gcc -Wall -W`) and look at all the helpful diagnostic messages the compiler produces.
Here is a modified version:
```
int binarysearch(const int *array, int size, int target) {
int a, b;
for (a = 0, b = size; a < b;) {
int mid = a + (b - a) / 2;
if (target <= array[mid]) {
b = mid;
} else {
a = mid + 1;
}
}
// a is the offset where target is or should be inserted
if (a < size && target == array[a])
return a;
else
return -1;
}
```
Notes:
* Computing `mid = (a + b) / 2;` would be potentially incorrect for large sizes as there may be an arithmetic overflow. `mid = a + (b - a) / 2;` does not have this problem since `a < b`.
* The time-complexity is **O(Log N)**, and for a given `size`, the function performs the same number of steps for all target values.
* If the array contains multiple identical values equal to target, the index returned by `binarysearch` is that of the matching entry with the lowest index.
|
You could make this problem easier by using the [`bsearch`](https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm) function offered by the `<stdlib.h>` library.
Something like this:
```
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b);
int
main(void) {
int array[] = {1, 2, 3, 4, 5, 6};
size_t n = sizeof(array)/sizeof(*array);
int *item;
int key = 15;
item = bsearch(&key, array, n, sizeof(*array), cmpfunc);
if (item != NULL) {
printf("Found item = %d\n", *item);
} else {
printf("Item = %d could not be found\n", key);
}
return 0;
}
int
cmpfunc(const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
```
If you don't want to use `bsearch`, then this method will be fine also:
```
#include <stdio.h>
#include <stdlib.h>
#define BSFOUND 1
#define BS_NOT_FOUND 0
int cmpfunc(const void * a, const void * b);
int binary_search(int A[], int lo, int hi, int *key, int *locn);
int
main(void) {
int array[] = {1, 2, 3, 4, 5, 6};
size_t n = sizeof(array)/sizeof(*array);
int key = 4, locn;
if ((binary_search(array, 0, n, &key, &locn)) == BSFOUND) {
printf("Found item = %d\n", array[locn]);
} else {
printf("Item = %d cound not be found\n", key);
}
return 0;
}
int
binary_search(int A[], int lo, int hi, int *key, int *locn) {
int mid, outcome;
if (lo >= hi) {
return BS_NOT_FOUND;
}
mid = lo + (hi - lo) / 2;
if ((outcome = cmpfunc(key, A+mid)) < 0) {
return binary_search(A, lo, mid, key, locn);
} else if(outcome > 0) {
return binary_search(A, mid+1, hi, key, locn);
} else {
*locn = mid;
return BSFOUND;
}
}
int
cmpfunc(const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
```
|
40,599,960
|
First time posting here. I recently implemented Binary Search but sometimes my outputs will return a giant negative number instead. Now my first thought is that I'm printing a number where my pointer is pointing at a random memory location. Can someone help me with the logic and how I can improve my code?
```
#include <stdio.h>
#include <stdlib.h>
int binarysearch(int *array, int size, int target);
int main() {
int array[] = { 1, 2, 3, 4, 5, 6 };
printf("%d\n", binarysearch(array, 8, 15));
return 0;
}
int binarysearch(int *array, int size, int target) {
int mid;
mid = size / 2;
if (size < 1) {
return -1;
}
if (size == 1) {
return array[0];
}
if (target == array[mid]) {
return target;
} else
if (target < array[mid]) {
binarysearch(array, mid, target);
} else{
binarysearch(array + mid, size - mid, target);
}
}
```
|
2016/11/15
|
[
"https://Stackoverflow.com/questions/40599960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7159403/"
] |
For starters you call the function with an invalid number of elements in the array that has only 6 elements.
```
int array[] = { 1, 2, 3, 4, 5, 6 };
printf("%d\n", binarysearch(array, 8, 15));
^^^
```
Also this snippet
```
if (size == 1) {
return array[0];
}
```
is incorrect. It is not necessary that the first element is equal to target.
This statement
```
binarysearch(array + mid, size - mid, target);
```
has to be written like
```
binarysearch(array + mid + 1, size - mid - 1, target);
```
And at last the function has undefined behavior because it returns nothing in these cases
```
if (target < array[mid]) {
binarysearch(array, mid, target);
} else{
binarysearch(array + mid, size - mid, target);
}
```
You need to write
```
if (target < array[mid]) {
return binarysearch(array, mid, target);
} else{
return binarysearch(array + mid, size - mid, target);
}
```
And two words about the programming style. It is better to name the function either like `binary_search` or like `binarySearch` or at last like `BinarySearch`than like `binarysearch`.
In general it is not a good design of the function. Imagine that the array has an element with the value -1. How will you determine whether this element is present in the array or is absent?
Usually such functions return pointer to the target element in case if it is found or NULL pointer otherwise.
Here is a demonstrative program that shows how this approach can be implemented.
```
#include <stdio.h>
int * binary_search( const int *a, size_t n, int target )
{
if ( n == 0 ) return NULL;
size_t middle = n / 2;
if ( a[middle] < target )
{
return binary_search( a + middle + 1, n - middle - 1, target );
}
else if ( target < a[middle] )
{
return binary_search( a, middle, target );
}
return a + middle;
}
int main(void)
{
int array[] = { 1, 2, 3, 4, 5, 6 };
const size_t N = sizeof( array ) / sizeof( *array );
for ( int i = 0; i < 8; i++ )
{
int *target = binary_search( array, N, i );
if ( target )
{
printf( "%d is found at position %d\n", *target, ( int )(target - array ) );
}
else
{
printf( "%d is not found\n", i );
}
}
return 0;
}
```
The program output is
```
0 is not found
1 is found at position 0
2 is found at position 1
3 is found at position 2
4 is found at position 3
5 is found at position 4
6 is found at position 5
7 is not found
```
By the way according to the C Standard function main without parameters shall be declared like
```
int main( void )
```
|
You could make this problem easier by using the [`bsearch`](https://www.tutorialspoint.com/c_standard_library/c_function_bsearch.htm) function offered by the `<stdlib.h>` library.
Something like this:
```
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b);
int
main(void) {
int array[] = {1, 2, 3, 4, 5, 6};
size_t n = sizeof(array)/sizeof(*array);
int *item;
int key = 15;
item = bsearch(&key, array, n, sizeof(*array), cmpfunc);
if (item != NULL) {
printf("Found item = %d\n", *item);
} else {
printf("Item = %d could not be found\n", key);
}
return 0;
}
int
cmpfunc(const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
```
If you don't want to use `bsearch`, then this method will be fine also:
```
#include <stdio.h>
#include <stdlib.h>
#define BSFOUND 1
#define BS_NOT_FOUND 0
int cmpfunc(const void * a, const void * b);
int binary_search(int A[], int lo, int hi, int *key, int *locn);
int
main(void) {
int array[] = {1, 2, 3, 4, 5, 6};
size_t n = sizeof(array)/sizeof(*array);
int key = 4, locn;
if ((binary_search(array, 0, n, &key, &locn)) == BSFOUND) {
printf("Found item = %d\n", array[locn]);
} else {
printf("Item = %d cound not be found\n", key);
}
return 0;
}
int
binary_search(int A[], int lo, int hi, int *key, int *locn) {
int mid, outcome;
if (lo >= hi) {
return BS_NOT_FOUND;
}
mid = lo + (hi - lo) / 2;
if ((outcome = cmpfunc(key, A+mid)) < 0) {
return binary_search(A, lo, mid, key, locn);
} else if(outcome > 0) {
return binary_search(A, mid+1, hi, key, locn);
} else {
*locn = mid;
return BSFOUND;
}
}
int
cmpfunc(const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
```
|
66,392,180
|
i've this absurd repeted html structure (without classes) and i need to capture all links and the below text.
I can easily get all links with the supersimple css query selector `a` but i need to catch another text placed in a sibling of the link's ancestor (the captured text must be captured alongside the link).
so i should to go up through the divs levels and then go down again
Some suggestion how to climb and than to descend by css selector?
```
...
...
...
<div> <----first level of div
<div> <----second level of div
<span>
<span>
<div> <----third level of div
<a href=""> <----element that i can get easily
</div>
</span>
</span>
</div>
<div></div>
<div>
<span>
<span>
text to capture <----text i need to capture
</span>
</span>
</div>
<div>
...
...
...
```
|
2021/02/26
|
[
"https://Stackoverflow.com/questions/66392180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820422/"
] |
I don't know R at all, but I would guess your bearer token is incorrect.
The header key is Authorization and the value should be "Bearer {place your token here without brackets}"
|
You have to have these three headers
```
-H 'Content-Type: application/json' \
-H 'X-Requested-With: XMLHttpRequest' \
-H 'Authorization: Bearer {place your token here without brackets}' \`
```
|
102,800
|
What is the distinction between seeds/grains for sprouting and other edible uses and seeds/grains for sowing/planting?
|
2019/10/09
|
[
"https://cooking.stackexchange.com/questions/102800",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/78514/"
] |
Generally there is no distinction, other than that the variety for eating the sprouts may be a special one developed for taste.
Having said that there is another consideration: Seeds for sowing often (not always, depends on the supplier and type of seed) are coated with anti-fungals and things to make them less attractive to pests. These seeds should not be eaten, nor should the sprouts from them!
|
The seeds grown for propagation are the same species but they may be grown differently, sometimes to the level where you wouldn't want to eat them. A good example is beans where you eat the pod, i.e. string beans and runner beans. If you want to eat them you pick them while they are technically unripe, but they are tender. If you want to grow them to plant them you let them grow until the seeds inside the pods get large and the pods start to shrivel, and they really aren't very edible by then.
|
102,800
|
What is the distinction between seeds/grains for sprouting and other edible uses and seeds/grains for sowing/planting?
|
2019/10/09
|
[
"https://cooking.stackexchange.com/questions/102800",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/78514/"
] |
Generally there is no distinction, other than that the variety for eating the sprouts may be a special one developed for taste.
Having said that there is another consideration: Seeds for sowing often (not always, depends on the supplier and type of seed) are coated with anti-fungals and things to make them less attractive to pests. These seeds should not be eaten, nor should the sprouts from them!
|
Seeds sold for sprouting are larger. They've been sorted from the smaller ones. Source: trucker who hauls them and has seen them being sorted.
|
51,396,948
|
I am unable to display images within a React component. After many trials (attempted [this](https://github.com/babel/babel-loader/issues/173), [this](https://github.com/storybooks/storybook/issues/1493), [this](https://stackoverflow.com/questions/48570731/react-webpack-module-parse-failed-unexpected-token-you-may-need-an-appro), [this](https://stackoverflow.com/questions/45848055/image-you-may-need-an-appropriate-loader-to-handle-this-file-type), [this](https://stackoverflow.com/questions/43077245/you-may-need-an-appropriate-loader-to-handle-this-file-type-upload-image-file), [this](https://survivejs.com/webpack/loading/images/), [this](https://github.com/webpack-contrib/style-loader/issues/55) and [this](https://stackoverflow.com/questions/37671342/how-to-load-image-files-with-webpack-file-loader)) and only errors, I am requesting for help. I'm in the development build (not production build).
I still get this error:
```
Module parse failed: /project/src/images/net.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
```
Component
```
import thumbnail from '../images/net.png';
<img src={thumbnail}/>
```
Webpack config:
```
devtool: 'cheap-module-eval-source-map',
entry: [
'eventsource-polyfill',
'webpack-hot-middleware/client',
'./src/index'
],
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
task `npm run build`.
publicPath: 'http://localhost:3000/',
filename: 'bundle.js'
},
devServer: {
contentBase: './src'
},
plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()],
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
},
{
test: /(\.css)$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: { sourcemap: true }
}
]
},
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
include: './src/images',
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: paths.build
}
}
}
]
}
```
Directory Structure
```
Project
-- src
-----components
-----images
-----index.js
```
How can I display the image ?
Sample code here: [githublink](https://github.com/ubersensei/pluralsight-redux-app-used-to-build-script)
See /src/components/home/HomePage.js
What can I do to see the image on the home page ?
|
2018/07/18
|
[
"https://Stackoverflow.com/questions/51396948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2619658/"
] |
I had this issue and was able to solve it by installing Xcode Command Line Tools and updating VSCode's `settings.json`
You can open this file a couple different ways. I like to do `⌘` + `Shift` + `P` then type "settings" in the command palette:
[](https://i.stack.imgur.com/fVaVt.png)
If you prefer just to open it, its location is here:
```
$HOME/Library/Application Support/Code/User/settings.json
```
Reference: [Visual Studio Code User and Workspace Settings](https://code.visualstudio.com/docs/getstarted/settings)
Then plug the following into your workspace settings (ensure that you merge your current config you may have here):
```
{
"git.path": "/usr/bin/git"
}
```
And it'll look something like this:
[](https://i.stack.imgur.com/mrIJW.png)
Now close VSCode. If you'd like to use the Terminal you can simply input this command, but you can use the GUI instead if you'd like as I'll show:
```
xcode-select --install
```
Wait for the command to complete, then start VSCode. At this point my issue was fixed; hopefully this works for you as well!
Since I'd already installed my XCode tools my dialog won't show up again, but you can see from this image which is referenced below what it looks like. Click "Install".
[](https://i.stack.imgur.com/vr1Wn.png)
Both command and image referenced from here: <http://railsapps.github.io/xcode-command-line-tools.html>
|
I found a specific issue on the [vscode github page](https://github.com/microsoft/vscode/issues/81287) related to this. The issue submitter's solution to this worked for me, which is to open a terminal and type the following command
```
sudo xcodebuild -license
```
This will prompt you to read and then accept the license agreement. Once I did this, I restarted Visual Studio Code and my issue was solved.
Apparently there is some subtle issue that keeps VS Code from recognizing git (or that git is "valid"?) until the xcodebuild license has been accepted.
|
74,654,658
|
How do I create a discriminated union where I can check either for a statusCode of '0000' or not '0000', so that the correct object type is used?
```
type Foo = {
statusCode: '0000',
something: string
} | {
statusCode: // any string that is not '0000'
somethingElse: string
}
```
|
2022/12/02
|
[
"https://Stackoverflow.com/questions/74654658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1487636/"
] |
The issue in your code is that you are checking the hour and minute separately in your if statements. For example, when you check if the store is open between 9AM and 12:30PM, you first check if the hour is greater than or equal to 9, and then you check if the hour is less than or equal to 12 and the minute is less than or equal to 30. This means that if the hour is 12 and the minute is greater than 30, your code will still print "Open" because the first condition is true (12 is greater than or equal to 9), even though the store is actually closed at that time.
To fix this issue, you can combine the hour and minute into a single value representing the total number of minutes since midnight. This way, you can compare the total number of minutes with the start and end times of the store, and accurately determine whether the store is open or closed. Here is an example of how you can modify your code to do this:
Copy code
```
function etatMagasin() {
let today = new Date()
let day = today.getDay()
let hour = today.getHours()
let minute = today.getMinutes()
let second = today.getSeconds()
// Convert the hour and minute into a total number of minutes since midnight
let totalMinutes = hour * 60 + minute
// Lundi à Vendredi
if (day < 6) {
if (totalMinutes >= 540 && totalMinutes <= 750) {
console.log("Open")
} else if (totalMinutes >= 840 && totalMinutes <= 1110) {
console.log("Open")
} else {
console.log("Close")
}
} else if (day == 6) {
if (totalMinutes >= 600 && totalMinutes <= 960) {
console.log("Open")
} else {
console.log("Close")
}
} else {
console.log("Close")
}
console.log(day + ":" + hour + ":" + minute + ":" + second)
t = setTimeout(function() {etatMagasin()}, 1000)
}
```
etatMagasin()
Note that in this example, I converted the start and end times of the store into total number of minutes since midnight as well, so that they can be compared with the current time in minutes.
|
To fix the issue with the store closing at 12:30AM and 6:30PM, you can add a check to see if the hour is 12 or 18 and the minute is greater than 30. If that's the case, you can change the hour to the next day and set the minute to 0. Here's an example:
```
function etatMagasin() {
let today = new Date()
let day = today.getDay()
let hour = today.getHours()
let minute = today.getMinutes()
let second = today.getSeconds()
// Check if the store is closing at 12:30AM or 6:30PM
if ((hour == 12 || hour == 18) && minute > 30) {
hour += 12; // Add 12 hours to the current hour
minute = 0; // Set the minutes to 0
}
// Lundi à Vendredi
if (day < 6) {
if (hour >= 9 && hour <= 12) {
console.log("Open")
} else if (hour >= 14 && hour <= 18) {
console.log("Open")
} else {console.log("Close")}
} else if (day == 6) {
if (hour >= 10 && hour <= 16) {
console.log("Open")
} else {console.log("Close")}
} else {console.log("Close")}
console.log(day + ":" + hour + ":" + minute + ":" + second)
t = setTimeout(function() {etatMagasin()}, 1000)
} etatMagasin()
```
With this updated code, the store should be marked as "Open" when it's between 9AM and 12:30PM on weekdays, between 2PM and 6:30PM on weekdays, and between 10AM and 4PM on Saturdays. On all other times, it will be marked as "Close".
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
```
git clone ssh://dev@10.11.12.13/srv/repositories/awesomeproject.git
```
|
Like you said `remote_repo_url` is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.
There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons.
You can refer to the [documentation](http://www.git-scm.com/book/en/Git-on-the-Server-The-Protocols) about protocols and how to connect to the server
You can check the rest of [chapter 4](http://www.git-scm.com/book) for more detailed information, as it's talking about how to set up your own server
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
```
git clone ssh://dev@10.11.12.13/srv/repositories/awesomeproject.git
```
|
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY\_GIT\_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
`file://\\\\189.14.666.666\MY_GIT_REPOSITORY`
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
```
git clone ssh://dev@10.11.12.13/srv/repositories/awesomeproject.git
```
|
**For Bitbucket repositories users**:
**Starting 01.03.2022** you need to generate app password:
<https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/>
You can choose what permissions you grant for this password during creation process.
Then connect by:
```
git remote add origin https://bitbucketusername:bitbucketAppPassword@bitbucket.org/your-team/your-repo.git/
```
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
It's simple and follow the small Steps to proceed:
* Install git on the remote server say some ec2 instance
* Now create a project folder `$mkdir project.git
* `$cd project and execute $git init --bare`
Let's say this project.git folder is present at your ip with address inside `home_folder/workspace/project.git`, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, `$cd` into the project folder which you want to push to git execute the below commands:
* `git init .`
* `git remote add origin username@189.14.666.666:/home/ubuntu/workspace/project.git`
* `git add .`
* `git commit -m "Initial commit"`
Below is an optional command but found it has been suggested as i was working to setup the same thing
>
> git config --global remote.origin.receivepack "git receive-pack"
>
>
>
* `git pull origin master`
* `git push origin master`
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, `cd project_folder/.git` and `cat config`, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the `project.git` folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
|
Like you said `remote_repo_url` is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.
There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons.
You can refer to the [documentation](http://www.git-scm.com/book/en/Git-on-the-Server-The-Protocols) about protocols and how to connect to the server
You can check the rest of [chapter 4](http://www.git-scm.com/book) for more detailed information, as it's talking about how to set up your own server
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
Like you said `remote_repo_url` is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.
There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons.
You can refer to the [documentation](http://www.git-scm.com/book/en/Git-on-the-Server-The-Protocols) about protocols and how to connect to the server
You can check the rest of [chapter 4](http://www.git-scm.com/book) for more detailed information, as it's talking about how to set up your own server
|
**For Bitbucket repositories users**:
**Starting 01.03.2022** you need to generate app password:
<https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/>
You can choose what permissions you grant for this password during creation process.
Then connect by:
```
git remote add origin https://bitbucketusername:bitbucketAppPassword@bitbucket.org/your-team/your-repo.git/
```
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
It's simple and follow the small Steps to proceed:
* Install git on the remote server say some ec2 instance
* Now create a project folder `$mkdir project.git
* `$cd project and execute $git init --bare`
Let's say this project.git folder is present at your ip with address inside `home_folder/workspace/project.git`, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, `$cd` into the project folder which you want to push to git execute the below commands:
* `git init .`
* `git remote add origin username@189.14.666.666:/home/ubuntu/workspace/project.git`
* `git add .`
* `git commit -m "Initial commit"`
Below is an optional command but found it has been suggested as i was working to setup the same thing
>
> git config --global remote.origin.receivepack "git receive-pack"
>
>
>
* `git pull origin master`
* `git push origin master`
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, `cd project_folder/.git` and `cat config`, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the `project.git` folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
|
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY\_GIT\_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
`file://\\\\189.14.666.666\MY_GIT_REPOSITORY`
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
It's simple and follow the small Steps to proceed:
* Install git on the remote server say some ec2 instance
* Now create a project folder `$mkdir project.git
* `$cd project and execute $git init --bare`
Let's say this project.git folder is present at your ip with address inside `home_folder/workspace/project.git`, forex- ec2 - /home/ubuntu/workspace/project.git
Now in your local machine, `$cd` into the project folder which you want to push to git execute the below commands:
* `git init .`
* `git remote add origin username@189.14.666.666:/home/ubuntu/workspace/project.git`
* `git add .`
* `git commit -m "Initial commit"`
Below is an optional command but found it has been suggested as i was working to setup the same thing
>
> git config --global remote.origin.receivepack "git receive-pack"
>
>
>
* `git pull origin master`
* `git push origin master`
This should work fine and will push the local code to the remote git repository.
To check the remote fetch url, `cd project_folder/.git` and `cat config`, this will give the remote url being used for pull and push operations.
You can also use an alternative way, after creating the `project.git` folder on git, clone the project and copy the entire content into that folder. Commit the changes and it should be the same way. While cloning make sure you have access or the key being is the secret key for the remote server being used for deployment.
|
**For Bitbucket repositories users**:
**Starting 01.03.2022** you need to generate app password:
<https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/>
You can choose what permissions you grant for this password during creation process.
Then connect by:
```
git remote add origin https://bitbucketusername:bitbucketAppPassword@bitbucket.org/your-team/your-repo.git/
```
|
20,291,733
|
I have small problem with removing a child Layer. I am not sure how to remove the layer correctly.
Here is my code sample
```
-(void)GoMoveFirst
{
//
//====HERE IS COMBOBOX START
CCMenuItemImage *lvl1 = newButton(@"retry1", 200, 590, self, @selector(onRetry));
CCMenuItemImage *lvl2 = newButton(@"retry1", 500, 590, self, @selector(onRetry)); //onHighScore:
CCMenuItemImage *lvl3 = newButton(@"retry1", 800, 590, self, @selector(onRetry));
CCMenu *menu = [CCMenu menuWithItems:lvl1, lvl2,lvl3, nil];
menu.position = ccp(0, 0);
[GameLayer addChild:menu z:103];
}
```
After I press one of this buttons, I need it to be removed.
All stuff is going here:
```
-(void)onRetry
{
//
//HERE i need remove menu Child.
//
[m_sGo runAction:[CCSequence actions:actionMove, [CCCallFunc actionWithTarget:self selector:@selector(GoMoveSecond)], nil]];
}
```
One idea was try make it invisible, but I do not think this would be a suitable option.
|
2013/11/29
|
[
"https://Stackoverflow.com/questions/20291733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2820692/"
] |
To me it sounds like the simplest way to expose your git repository on the server (which seems to be a Windows machine) would be to share it as a network resource.
Right click the folder "MY\_GIT\_REPOSITORY" and select "Sharing". This will give you the ability to share your git repository as a network resource on your local network. Make sure you give the correct users the ability to write to that share (will be needed when you and your co-workers push to the repository).
The URL for the remote that you want to configure would probably end up looking something like
`file://\\\\189.14.666.666\MY_GIT_REPOSITORY`
If you wish to use any other protocol (e.g. HTTP, SSH) you'll have to install additional server software that includes servers for these protocols. In lieu of these the file sharing method is probably the easiest in your case right now.
|
**For Bitbucket repositories users**:
**Starting 01.03.2022** you need to generate app password:
<https://support.atlassian.com/bitbucket-cloud/docs/app-passwords/>
You can choose what permissions you grant for this password during creation process.
Then connect by:
```
git remote add origin https://bitbucketusername:bitbucketAppPassword@bitbucket.org/your-team/your-repo.git/
```
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
I think there's a simpler solution: Just use the `DialogInterface` argument that is passed to the `onClick` method.
```
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
```
See, for example, <http://www.mkyong.com/android/android-alert-dialog-example>.
|
There are two ways of closing an alert dialog.
Option 1:
`AlertDialog#create().dismiss();`
Option 2:
`The DialogInterface#dismiss();`
Out of the box, the framework calls `DialogInterface#dismiss();` when you define event listeners for the buttons:
1. `AlertDialog#setNegativeButton();`
2. `AlertDialog#setPositiveButton();`
3. `AlertDialog#setNeutralButton();`
for the Alert dialog.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
To dismiss or cancel AlertDialog.Builder
```
dialog.setNegativeButton("إلغاء", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
```
you call dismiss() on the dialog interface
|
Just set the view as null that will close the AlertDialog simple.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
Here is How I close my alertDialog
```
lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
alertDialog.setTitle(clickedObj.getAd());
alertDialog.setMessage("Öğrenci Bilgileri Güncelle?");
alertDialog.setIcon(R.drawable.ic_info);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User pressed YES button. Write Logic Here
}
});
alertDialog.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//alertDialog.
alertDialog.setCancelable(true); // HERE
}
});
alertDialog.show();
return true;
}
});
```
|
There are two ways of closing an alert dialog.
Option 1:
`AlertDialog#create().dismiss();`
Option 2:
`The DialogInterface#dismiss();`
Out of the box, the framework calls `DialogInterface#dismiss();` when you define event listeners for the buttons:
1. `AlertDialog#setNegativeButton();`
2. `AlertDialog#setPositiveButton();`
3. `AlertDialog#setNeutralButton();`
for the Alert dialog.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
Try this:
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
```
|
There are two ways of closing an alert dialog.
Option 1:
`AlertDialog#create().dismiss();`
Option 2:
`The DialogInterface#dismiss();`
Out of the box, the framework calls `DialogInterface#dismiss();` when you define event listeners for the buttons:
1. `AlertDialog#setNegativeButton();`
2. `AlertDialog#setPositiveButton();`
3. `AlertDialog#setNeutralButton();`
for the Alert dialog.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
I think there's a simpler solution: Just use the `DialogInterface` argument that is passed to the `onClick` method.
```
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
```
See, for example, <http://www.mkyong.com/android/android-alert-dialog-example>.
|
To dismiss or cancel AlertDialog.Builder
```
dialog.setNegativeButton("إلغاء", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
```
you call dismiss() on the dialog interface
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
Actually there is no any `cancel()` or `dismiss()` method from AlertDialog.Builder Class.
So Instead of `AlertDialog.Builder optionDialog` use `AlertDialog` instance.
Like,
```
AlertDialog optionDialog = new AlertDialog.Builder(this).create();
```
Now, Just call `optionDialog.dismiss();`
```
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
optionDialog.dismiss();
}
});
```
|
With Kotlin:
```
fun Activity.showDialog() {
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.message_id)
.setPositiveButton(
R.string.confirm_action_text_id
) { dialogInterface, _ ->
dialogInterface.dismiss()
SignUpActivity.start(this)
}
.setNegativeButton(R.string.cancel) { _, _ -> }
builder.create().show()
}
```
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
I think there's a simpler solution: Just use the `DialogInterface` argument that is passed to the `onClick` method.
```
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setNegativeButton("cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface d, int arg1) {
db.cancel();
//here db.cancel will dismiss the builder
};
});
```
See, for example, <http://www.mkyong.com/android/android-alert-dialog-example>.
|
Just set the view as null that will close the AlertDialog simple.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
Try this:
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
```
|
To dismiss or cancel AlertDialog.Builder
```
dialog.setNegativeButton("إلغاء", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
```
you call dismiss() on the dialog interface
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
There are two ways of closing an alert dialog.
Option 1:
`AlertDialog#create().dismiss();`
Option 2:
`The DialogInterface#dismiss();`
Out of the box, the framework calls `DialogInterface#dismiss();` when you define event listeners for the buttons:
1. `AlertDialog#setNegativeButton();`
2. `AlertDialog#setPositiveButton();`
3. `AlertDialog#setNeutralButton();`
for the Alert dialog.
|
Just set the view as null that will close the AlertDialog simple.
|
14,853,325
|
I created AlertDialog that contains 4 buttons
```
OptionDialog = new AlertDialog.Builder(this);
OptionDialog.setTitle("Options");
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.options, null, false);
background = (Button) v.findViewById(R.id.bkgSpinnerLabel);
SoundVib = (Button) v.findViewById(R.id.SoundVibSpinnerLabel);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
OptionDialog.setNeutralButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
}
});
SoundVib.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent soundVibIntent = new Intent(SebhaActivity.this, EditPreferences.class);
startActivity(soundVibIntent);
}
});
OptionDialog.show();
```
I want to dismiss it after SetBackground() method, how can I do this?
thanks in advance.
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14853325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395873/"
] |
Try this:
```
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
```
|
With Kotlin:
```
fun Activity.showDialog() {
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.message_id)
.setPositiveButton(
R.string.confirm_action_text_id
) { dialogInterface, _ ->
dialogInterface.dismiss()
SignUpActivity.start(this)
}
.setNegativeButton(R.string.cancel) { _, _ -> }
builder.create().show()
}
```
|
6,772,430
|
I have developed application in VS 2008 and trying to host on godaddy server having .net 4.0 framework and IIS7.
I am getting Internal Server error 500.
I am hosting my files under sub directory.I have set the subdirectory as Application Folder.Tried to upload files and have error.When i delete web.config and upload test aspx file it runs proper.But as i again put web.config the test files stops running and showing same error.
Please kindly help me to resolve this issue.
regards,
Sunny
|
2011/07/21
|
[
"https://Stackoverflow.com/questions/6772430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202616/"
] |
>
> Since the headers and footer sections are include files so I cannot use `<title><?php echo $title;?></title>` kind of solution.
>
>
>
You can. Just because the files are included doesn't mean you can't echo things there.
If you had a `Page` object...
### index.php
```
<?php
$page = new Page('Programmers\' Palace');
include 'includes/header.php';
```
### includes/header.php
```
<head>
<title><?php echo $page->getTitle(); ?></title>
</head>
```
|
```
<?php
$title = 'My Page';
include 'header.php';
```
then in header.php:
```
<title><?php echo $title;?></title>
```
This works because file includes in php are treated as if they are "pasted in between there".
|
3,536,449
|
The integral is
$$\int\_0^1 \ln(1-x^{1/n})dx=-\sum\_{k=1}^n\frac{1}{k}$$
I tried integral by part, but cannot get the $\frac{1}{k}$ term. How can we do this integral? Any hint would be appreciated.
|
2020/02/06
|
[
"https://math.stackexchange.com/questions/3536449",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/51601/"
] |
Rewrite the integrand as a power series, so the integral is$$\begin{align}-\sum\_{k\ge1}\frac1k\int\_0^1x^{k/n}dx&=-\sum\_k\frac{n}{k(n+k)}\\&=-\sum\_k\left(\frac{1}{k}-\frac{1}{n+k}\right),\end{align}$$which simplifies to $-\sum\_{k=1}^n\frac1k$ by telescoping series. To make this argument rigorous, one should compute the sum from $k=1$ to $k=K$ for $K\ge n$ by induction.
|
Use the Taylor series of the logarithm
$$
\ln\left(1-x^\frac{1}{n}\right)=-\sum\_{k=1}^\infty\frac{x^\frac{k}{n}}{k}.
$$
Then, integrate term by term. This yields
$$
-\sum\_{k=1}^\infty\frac{1}{k\left(1+\frac{n}{k}\right)}=-\psi\_0(n+1)-\gamma
$$
being $\psi\_0$ the [digamma funtion](https://en.wikipedia.org/wiki/Digamma_function) and $\gamma$ the Euler-Mascheroni constant. By the definition of the digamma function this yields your result.
|
3,536,449
|
The integral is
$$\int\_0^1 \ln(1-x^{1/n})dx=-\sum\_{k=1}^n\frac{1}{k}$$
I tried integral by part, but cannot get the $\frac{1}{k}$ term. How can we do this integral? Any hint would be appreciated.
|
2020/02/06
|
[
"https://math.stackexchange.com/questions/3536449",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/51601/"
] |
Rewrite the integrand as a power series, so the integral is$$\begin{align}-\sum\_{k\ge1}\frac1k\int\_0^1x^{k/n}dx&=-\sum\_k\frac{n}{k(n+k)}\\&=-\sum\_k\left(\frac{1}{k}-\frac{1}{n+k}\right),\end{align}$$which simplifies to $-\sum\_{k=1}^n\frac1k$ by telescoping series. To make this argument rigorous, one should compute the sum from $k=1$ to $k=K$ for $K\ge n$ by induction.
|
Start with $x^\frac{1}{n}=u$ we have
$$I=\int\_0^1\ln(1-x^{\frac1n})\ dx=n\int\_0^1 u^{n-1}\ln(1-u)\ du$$
Now we integrate by parts but to avoid divergence, we write $\int n u^{n-1}\ du=u^n-1$.
So
$$I=\underbrace{(u^n-1)\ln(1-u)|\_0^1}\_{0}-\int\_0^1\frac{1-u^n}{1-u}\ du=-\sum\_{k=1}^n\frac1k=-H\_n$$
---
**Proof for the last result**
$$\sum\_{k=1}^n\frac1k=\sum\_{k=1}^n\int\_0^1 u^{n-1}\ du=\int\_0^1\sum\_{k=1}^n u^{n-1}\ du=\int\_0^1\frac{1-u^n}{1-u}\ du$$
|
123,225
|
I'm writing up a proposal and got stumped on the description for this element:
[](https://i.stack.imgur.com/INXRv.png)
The informative text (in pink) underneath a field is there to provide a reason for the required data, therefore answering a users uncertainty around why they need to fill in this field.
The information behind the 'i' icon plainly says you must be x years old to register so this isn't duplicate information.
Is there a specific term for this type of element within a form?
|
2019/01/18
|
[
"https://ux.stackexchange.com/questions/123225",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/107636/"
] |
### Material design refers to this as 'helper text' for its position in the form.
From **[Material Design](https://material.io/design/components/text-fields.html#anatomy)**:
>
> Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single line, being persistently visible or visible only on focus.
>
>
>
[](https://i.stack.imgur.com/IjEzU.png)
Your specific example is sort of microcopy-ish, as it's encouraging you to fill out the form (and the benefits of doing so), but not technically helping you understand *how* to do so.
|
I guess the catch-all term for this type of text would be 'microcopy', and usually they are classified or grouped based on the user interface element that they support.
So in this case I think you could call this an input field microcopy, or if you want to be even more specific then a date input field microcopy and people should have a good idea of what it is.
|
123,225
|
I'm writing up a proposal and got stumped on the description for this element:
[](https://i.stack.imgur.com/INXRv.png)
The informative text (in pink) underneath a field is there to provide a reason for the required data, therefore answering a users uncertainty around why they need to fill in this field.
The information behind the 'i' icon plainly says you must be x years old to register so this isn't duplicate information.
Is there a specific term for this type of element within a form?
|
2019/01/18
|
[
"https://ux.stackexchange.com/questions/123225",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/107636/"
] |
### Material design refers to this as 'helper text' for its position in the form.
From **[Material Design](https://material.io/design/components/text-fields.html#anatomy)**:
>
> Helper text conveys additional guidance about the input field, such as how it will be used. It should only take up a single line, being persistently visible or visible only on focus.
>
>
>
[](https://i.stack.imgur.com/IjEzU.png)
Your specific example is sort of microcopy-ish, as it's encouraging you to fill out the form (and the benefits of doing so), but not technically helping you understand *how* to do so.
|
I wouldn't say it's microcopy since there's many places where you'd include microcopy, including inside the information tooltip next to the input label.
I'd simply refer to that as "Input explanation text" or "Auxiliary input label". I think the second is preferred because the word "label" doesn't imply it's about text entered by the user.
In the end I don't think there's a standard name for that.
|
9,016,428
|
Could it be said that when you reach the point of injecting one DAO into another one, you've already gone over the DAO scope, and reached a business layer issue?
**NOTE:** I am not having a particular issue in mind, but just trying to extract a general rule of thumb regarding the use of DAOs.
|
2012/01/26
|
[
"https://Stackoverflow.com/questions/9016428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107412/"
] |
Yes. DAOs shouldn't be dependent on each other.
It's the job of the business / service layer to coordinate different DAOs.
However, if you'd describe your specific scenario we would be able to give a more accurate answer.
**Edit:**
After reading @edutesoy's answer, I see the logic in his argument.
So I'll refine my answer by saying- it's not *inherently* wrong to do that, but it is a little 'smelly'.
This is because of the normal structure of your DAO layer- you usually have a DAO for each type of entity (`CustomerDAO`, `OrdersDAO`etc) . If your `CustomerDAO` is using your `PaymentsDAO`, it smells a bit like a violation of SRP: is `CustomerDAO` responsible also for payments-related operations?
So, in conclusion- I would definitely require a very good reason for this before introducing it into my code.
|
May you should start with thinking of what a DAO is.
If you use JPA, then the entiy manager is already a generic DAO (by DAO Pattern). What the most Java EE developer call a DAO is not a DAO by DAO Pattern. It is some kind of refactoring: move out the Database related statements into an external class (and I think that is the kind of DAO you are talking about) *Don't get me wrong, I think this is usefull.*
So my understanding of this DAO is some refactoring thing. And the overall goal of refactoring is making the code more readable, maintainable. So if you code becomes better with this indirection then go on, but you should document that your project DAO-Pattern is slightly different from the DAO Pattern used by may other Java EE Developers.
|
9,016,428
|
Could it be said that when you reach the point of injecting one DAO into another one, you've already gone over the DAO scope, and reached a business layer issue?
**NOTE:** I am not having a particular issue in mind, but just trying to extract a general rule of thumb regarding the use of DAOs.
|
2012/01/26
|
[
"https://Stackoverflow.com/questions/9016428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107412/"
] |
The division between DAO and Business is "arbitrary". We say that a class is a DAO when it is used to "retrieve and store data from storage repositories". The fact that you inject a DAO in another DAO doesn't prevent it to "retrieve and store data from storage repositories", so for me the answer to your question is NO.
There is nowhere said that you cannot inject a DAO into another (even though it is not usually done).
|
May you should start with thinking of what a DAO is.
If you use JPA, then the entiy manager is already a generic DAO (by DAO Pattern). What the most Java EE developer call a DAO is not a DAO by DAO Pattern. It is some kind of refactoring: move out the Database related statements into an external class (and I think that is the kind of DAO you are talking about) *Don't get me wrong, I think this is usefull.*
So my understanding of this DAO is some refactoring thing. And the overall goal of refactoring is making the code more readable, maintainable. So if you code becomes better with this indirection then go on, but you should document that your project DAO-Pattern is slightly different from the DAO Pattern used by may other Java EE Developers.
|
119,621
|
Let's say I submit a sitemap page that contains all the links I want Google to crawl, but instead of submitting a sitemap, I fetch the page and linked pages and let Google index them. How many levels of sub-pages do those bots crawl to? Do they crawl chain-linked pages or do they only crawl the links on the fetched parent sitemap page?
|
2018/12/13
|
[
"https://webmasters.stackexchange.com/questions/119621",
"https://webmasters.stackexchange.com",
"https://webmasters.stackexchange.com/users/33912/"
] |
The "old" GSC does state:
>
> Crawl this URL and its **direct links**
>
>
>
So, that would be just *1-level* deep.
The "URL Inspection tool" in the "new" GSC doesn't appear to give you a similar option and only crawls a single URL as far as I can tell.
|
On my sites, I have an XML sitemap but I only include "real content" in it (so on WordPress, I include `posts` and `pages`, but not `tags` and `categories`) and I have an HTML sitemap that I code by hand so I have total control over what links are on it and anchor text of those links.
Those sitemaps combined with my navigation and internal linking within the content have always been enough to get the "real content" on my sites indexed but I'm not sure any of my sitemaps have had every URL I submitted indexed.
I guess what I'm saying is Google crawls whatever they want to and sitemaps are just hints to the crawler. Even using Search Console to fetch pages is no guarantee Google will include them in the index of your site.
If you have good content that you want Google to notice, the best way to do that is probably by ensuring there are external links to that content, which could be as simple as sharing the URL on Twitter or using Feedburner.
|
62,389,975
|
Suppose i have an array shaped as `a`:
```
import numpy as np
n = 10
d = 5
a = np.zeros(shape = np.repeat(n,d))
```
And that I want to obtain the values corresponding to indexes `(0,...,:,...,0)` for the `:` along dimensions, resulting in a `(n,d)`-shaped array `b`, with `b[i,j] = a[0,...,0,i,0,...,0]` where the `i` is in the `j`th dimension.
How can i extract`b` from `a` ?
|
2020/06/15
|
[
"https://Stackoverflow.com/questions/62389975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8425270/"
] |
After tinkering a bit with `transform`, this what ended up working for me:
```js
Yup.number()
.transform((_, value) => {
if (value.includes('.')) {
return null;
}
return +value.replace(/,/, '.');
})
.positive(),
```
|
I am not aware of a function in Yup to be able to parse number in different formats. But one easy way is to transform/replace the comma by nothing so it become a number
```js
number().transform((o, v) => parseInt(v.replace(/,/g, '')))
```
This way your number `10,000` become `10000` and is indeed a valid number.
On the other hand `10.000` stay `10.000` and is not valid.
|
26,342,081
|
```
var post = mongoose.Schema({
...
_createdOn: Date
});
```
I want to allow setting the `_createdOn` field only upon document creation, and disallow changing it on future updates. How is it done in Mongoose?
|
2014/10/13
|
[
"https://Stackoverflow.com/questions/26342081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1457181/"
] |
I achieved this effect by setting the `_createdOn` in the schema's pre-save hook (only upon first save):
```js
schema.pre('save', function (next) {
if (!this._createdOn) {
this._createdOn = new Date();
}
next();
});
```
... and disallowing changes from anywhere else:
```js
userSchema.pre('validate', function (next) {
if (this.isModified('_createdOn')) {
this.invalidate('_createdOn');
}
next();
});
```
|
Check this answer: <https://stackoverflow.com/a/63917295/6613333>
You can make the field as immutable.
```
var post = mongoose.Schema({
...
_createdOn: { type: Date, immutable: true }
});
```
|
41,627,315
|
When I start up vim, I get the following error printed:
```
$ vim -V9foo.log
Error detected while processing function <SNR>14_DependenciesValid:
line 12:
Traceback (most recent call last):
File "<string>", line 6, in <module>
AttributeError: 'module' object has no attribute 'vars'
Press ENTER or type command to continue
```
Looking on this site, I find a few recommendations to use -V9 to print everything vim is doing.
However, when I do this, I do not see the failure!
I can also use -V9foo.log to print everything it's doing to a log file (foo.log)
When I do that, the startup work is all printed there, but the error is printed to the terminal.
My guess thus is that the Python plugin runner does not know of the vim -V output target, or the python runtime error is printed straight to stderr.
Unfortunately, the Python error is extremely unhelpful. I cannot find a function named DependenciesValid in any of my vim plugins, and the rest of the error is all "sourced from some string, using some module, have fun finding where this is!"
I use Vundle for plug-ins, and the only reason I do that is that I want to use ensime for in-editor Scala browsing.
Commenting out ensime/ensime-vim makes the error go away, which locates the particular bundle, but doesn't get me any closer to where in the bundle the error actually happens, or why.
Here's my .vimrc:
```
set nocompatible
filetype off
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" Plugin 'jewes/Conque-Shell'
Plugin 'ensime/ensime-vim'
Plugin 'derekwyatt/vim-scala'
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
" syntastic
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
" My Stuff
set expandtab
set hidden
set ts=4
set ignorecase
set sw=4
```
I'm running on ubuntu 12.04 LTS (no, this is not currently upgradeable.)
```
$ vim --version
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled May 4 2012 04:24:26)
Included patches: 1-429
$ uname -a
Linux (hostname) 3.19.0-32-generic #37~14.04.1 SMP Fri Nov 6 00:01:52 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
```
|
2017/01/13
|
[
"https://Stackoverflow.com/questions/41627315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89233/"
] |
The `14` in `<SNR>14_DependenciesValid` refers to the script number as listed with `:scriptnames`.
|
I finally debugged this.
First, I commented out each plugin in turn until I found which one was causing the error. It was ensime-vim.
Second, I grepped the source for that plugin for the text "vars" which is the variable name it's trying to read/write from some module.
I found a few references, and looked them all up, figuring out where they are called.
It turns out, a recent change to the ensime-vim plugin did something akin to:
```
import vim
vim.vars['some_global_name'] = 1
```
The "vim" module does not contain a "vars" member in VIM 7.3, hence this fails.
Python could be more helpful about this. It says "module" does not have a member named "vars" but it doesn't tell me what the module is named. It could know.
Also, Python just says that "string" was the location of the error -- it could print the line out of the string, verbatim, to help track down the problem.
Separately, Vim could be more helpful about this. It could know which .vim file contained the Python code that errored out, and it could print the file/line that defined the Python that errored out.
It turns out, neither -D, nor -V9 (which is the general recommendation on the internet before I was told about -V13 by Meninx) was all that helpful :-(
|
459,479
|
I have an Ubuntu 10.04.4 LTS server running Samba, and joined to our Active Directory domain using PBIS (formerly likewise-open.) Samba is configured to do authentication using AD users/groups, and this is working correctly. Also, standard Linux permissions (user, group, others) world properly with Samba. BUT, Samba seems to totally ignore any permissions set with extended ACLs.
I have tried various smb.conf configurations I have seen recommended elsewhere, and none of them seem to have any effect.
Machine Setup:
* Files share is on it's own drive. Mount info from /etc/fstab for the drive is:
+ UUID=372aa637-4b7b-45cc-8340-9d028893c196 /media/news-drive ext4 user\_xattr,acl 0 2
* Machine is joined to domain using PBIS (formerly likewise-open)
* Samba config for the share is:
```
[shared]
comment = ,
nt acl support = yes
admin users =
force user =
force group = \domain^users
create mask = 0770
directory mask = 0770
```
* Global Samba Config
```
workgroup =
dns proxy = no
server string =
load printers = no
cups options = raw
guest account = pcguest
log file = /var/log/samba/%m.log
max log size = 50
security = ADS
realm =
socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192
interfaces = 172.16.0.20 10.4.1.20 127.0.0.1
bind interfaces only = yes
idmap uid = 16777216-33554431
idmap gid = 16777216-33554431
map to guest = Bad User
```
* I have also used some of these in the global config, without success
```
idmap backend = idmap_rid:=16777216-33554431
nt acl support = yes
inherit acls = Yes
map acl inherit = Yes
map archive = no
map hidden = no
map read only = no
map system = no
store dos attributes = yes
inherit permissions = Yes
template shell = /bin/false
winbind use default domain = no
```
What am I missing here, to get Samba to work with the extended ACLs?
An Example of What is Happening
-------------------------------
I have a folder in a samba share. The share itself is wide open within our domain (the "valid users" setting is set to the "Domain Users" group for the AD domain.) Within that share, I have a folder with more restrictive permissions at the file system level (owned by one AD user, with the group set to an AD group with just a few people in it and permissions chmod-ed to 770)
The issue is, I need to give access to that folder to another AD group, so I run "setfacl -m u::rwx " to give them permission to access it. This works within Linux (if I ssh in which one of those users and navigate to the folder)...but if I connect to the SMB share with that same user, and try and navigate to that folder, access is denied.
|
2012/12/19
|
[
"https://serverfault.com/questions/459479",
"https://serverfault.com",
"https://serverfault.com/users/59116/"
] |
Coming late to this question, I'd still like to point to the official [Samba documentation for support of ACLs](https://wiki.samba.org/index.php/Shares_with_Windows_ACLs). This is valid for Samba 4.0.0 onwards, which certainly was not available at the time this question got asked. But since the question pops up in search engines, this link might be helpful.
The basic steps are:
1.
Ensure the file system supports acls (ext4 nowadays does by default, no need for extra mount options)
2.
Ensure Samba was compiled with ACL support. (Yes, by default on Ubuntu 14.04 LTS):
```
smbd -b | grep HAVE_LIBACL
```
3.
Enable ACL by setting the following in the `[global]` section of `/etc/samba/smb.conf`:
```
vfs objects = acl_xattr
map acl inherit = yes
store dos attributes = yes
```
For details really visit the official docs as linked to above.
|
That's because `force user`, `force group`, `create mask` and `directory mask` enforce use of tradidional unix style permissions which can't be combined with inheriting ACLs.
Your default ACLs must reside on filesystem-level of the folder not on the samba share itself for inheritance to work but be aware that contradictory permissions will always deny access eg. when a user has permission as user but not as group samba will disallow access when using ACLs (which seems to me like a bug) eg: the user *nobody* is member of *nogroup* then ACLs needs to allow nobody *&* nogroup write permission otherwise write access is denied. Only *samba* behaves this way!
A possible way to create a folder with inheriting default permissions could be:
```
me@myHost:/shares$ getfacl myShare/
# file: myShare/
# owner: JohnDoe
# group: domain\040users
user::rwx
group::rwx #effective:r-x
group:domain\040users:rwx #effective:r-x
group:domain\040admins:rwx #effective:r-x
mask::rwx
other::r-x
default:user::rwx
default:group::rwx
default:group:domain\040users:rwx
default:group:domain\040admins:rwx
default:mask::rwx
default:other::r-x
```
The section with the `default:*` values is the interesting part for inheritance because any new file or folder will get these when created inside the *myShare* folder. See *setfacls* man page for details of setting *default:* values on a file or folder. Now the problem with using `create mask` or `directory mask` on a folder with *default:ACLs* set is that samba will then override these default values and in most cases these *mask* statements are only useful as long as you want the whole folder and it's files containing only a single owner and group. ACLs are harder to configure but offer much more flexibility as usual on windows machines.
For samba to honor these `default:*::` permissions `inherit acls` needs to be set in `[global]` section:
```
[global]
; Important if ACLs (eg: setfacl) contain default entries
; which samba honors only if this is set to 'yes'.
inherit acls = yes
[...]
[myShare]
comment = Put your files here
path = /shares/myShare
writeable = yes
```
This would allow a share where everyone can write to the share ... but (*!*)
that doesn't mean necessarily that it's allowed on filesystem-level because the *myShare* folder just allows *domain users*. Anyway for the paranoid the share permissions can be narrowed by allowing only specific groups:
```
write list = @"domain users"
```
which implicates `writeable=yes` but only for groups defined in *write list*. Ensure that permissions on share and on folder are free of contradictions eg:
```
write list = @"other group"
```
would allow *other group* to write to the share but since *myShare* folders allows only *domain users* to write it would fail obviously.
|
4,583
|
The TV series [Ray](https://www.animenewsnetwork.com/encyclopedia/anime.php?id=6163) is about a woman with "X-Ray vision" who was saved by a doctor when she was young. In the first episode of the anime, this doctor is made out to look like Black Jack:

Although you never get a look at his face but you can see that there is some stitches on the doctor's face and his hair is black and white.
Is this cameo just a bit of "fan service"/homage to the old Black Jack series or is this more like a same-universe side-story or spin-off of Black Jack? It doesn't seem like the staff of this show has worked on any of the Black Jack manga or anime.
|
2013/08/01
|
[
"https://anime.stackexchange.com/questions/4583",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/91/"
] |
[MyAnimeList](http://myanimelist.net/anime/919/Ray_The_Animation) claims that Ray is a side-story of Black Jack, while [Wikipedia](http://en.wikipedia.org/wiki/Ray_the_animation) takes the more conservative approach of just saying that they're related. However, it's not clear whether Ray is canon material in the Black Jack universe (and if so, in what sense). In any case, Ray mangaka Yoshitomi Akihito is on good terms with the current license-holders of Black Jack, and has produced [his own version](http://myanimelist.net/manga/23711/Black_Jack%3a_BJ_x_bj) based on the original but with his own artwork.
>
> Because of copyright reasons, Black Jack was only alluded to as BJ and never seen fully in the original manga, but because the anime was produced by Osamu Tezuka's own studio he is able to appear fully in the anime (though still somewhat obscured) and be referred to by his original name. Interestingly, in Black Jack 21, the sequel to the Black Jack anime, Black Jack was referred to as "BJ" by the assassins hell bent on killing him.
>
>
>
As far as I can tell, there's no official word on what the relation between the two are, so it's sort of a matter of opinion whether it's a sidestory or just a homage. My opinion is that, by animating Ray, it was more-or-less retconned into the Black Jack universe, or at least some alternate universe, so I think it can be elevated to the level of a sidestory. However, that was a decision made by whoever the current rights-holders are for Black Jack, and while it's valid in a legal sense some might argue that it shouldn't be considered a side-story but a homage. Tezuka manga purists could very-well object and describe it differently, as everything related to Ray (manga beginning in 2004) happened well after Tezuka's death in 1989.
|
It looks like a homage. [From Wikipedia](http://en.wikipedia.org/wiki/Yoshitomi_Akihito), it seems the mangaka of Ray has worked on Tezuka's Black Jack.
|
4,583
|
The TV series [Ray](https://www.animenewsnetwork.com/encyclopedia/anime.php?id=6163) is about a woman with "X-Ray vision" who was saved by a doctor when she was young. In the first episode of the anime, this doctor is made out to look like Black Jack:

Although you never get a look at his face but you can see that there is some stitches on the doctor's face and his hair is black and white.
Is this cameo just a bit of "fan service"/homage to the old Black Jack series or is this more like a same-universe side-story or spin-off of Black Jack? It doesn't seem like the staff of this show has worked on any of the Black Jack manga or anime.
|
2013/08/01
|
[
"https://anime.stackexchange.com/questions/4583",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/91/"
] |
It looks like a homage. [From Wikipedia](http://en.wikipedia.org/wiki/Yoshitomi_Akihito), it seems the mangaka of Ray has worked on Tezuka's Black Jack.
|
She literally calls him black Jack what more proof do you need I mean seriously there is no room for debate in this
|
4,583
|
The TV series [Ray](https://www.animenewsnetwork.com/encyclopedia/anime.php?id=6163) is about a woman with "X-Ray vision" who was saved by a doctor when she was young. In the first episode of the anime, this doctor is made out to look like Black Jack:

Although you never get a look at his face but you can see that there is some stitches on the doctor's face and his hair is black and white.
Is this cameo just a bit of "fan service"/homage to the old Black Jack series or is this more like a same-universe side-story or spin-off of Black Jack? It doesn't seem like the staff of this show has worked on any of the Black Jack manga or anime.
|
2013/08/01
|
[
"https://anime.stackexchange.com/questions/4583",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/91/"
] |
[MyAnimeList](http://myanimelist.net/anime/919/Ray_The_Animation) claims that Ray is a side-story of Black Jack, while [Wikipedia](http://en.wikipedia.org/wiki/Ray_the_animation) takes the more conservative approach of just saying that they're related. However, it's not clear whether Ray is canon material in the Black Jack universe (and if so, in what sense). In any case, Ray mangaka Yoshitomi Akihito is on good terms with the current license-holders of Black Jack, and has produced [his own version](http://myanimelist.net/manga/23711/Black_Jack%3a_BJ_x_bj) based on the original but with his own artwork.
>
> Because of copyright reasons, Black Jack was only alluded to as BJ and never seen fully in the original manga, but because the anime was produced by Osamu Tezuka's own studio he is able to appear fully in the anime (though still somewhat obscured) and be referred to by his original name. Interestingly, in Black Jack 21, the sequel to the Black Jack anime, Black Jack was referred to as "BJ" by the assassins hell bent on killing him.
>
>
>
As far as I can tell, there's no official word on what the relation between the two are, so it's sort of a matter of opinion whether it's a sidestory or just a homage. My opinion is that, by animating Ray, it was more-or-less retconned into the Black Jack universe, or at least some alternate universe, so I think it can be elevated to the level of a sidestory. However, that was a decision made by whoever the current rights-holders are for Black Jack, and while it's valid in a legal sense some might argue that it shouldn't be considered a side-story but a homage. Tezuka manga purists could very-well object and describe it differently, as everything related to Ray (manga beginning in 2004) happened well after Tezuka's death in 1989.
|
She literally calls him black Jack what more proof do you need I mean seriously there is no room for debate in this
|
15,964,164
|
I want to create theme, for that i created one launcher app. So when i press "home" button it shows me to select which launcher to be launch.
But I don't want that selection UI, When my app is installed it should launch automatically and sets it as default launcher.
can it be possible?
Thanks
|
2013/04/12
|
[
"https://Stackoverflow.com/questions/15964164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2232148/"
] |
A few choice examples, there are many, many more:
* [Linked lists](http://en.wikipedia.org/wiki/Linked_list)
* [PIMPL](http://en.wikipedia.org/wiki/Opaque_pointer)
* Dynamic objects (`new`, `delete`, dynamically sized arrays)
* All kinds of [factories](http://en.wikipedia.org/wiki/Abstract_factory_pattern)
* Interfacing with C-libraries
|
The very basic reason is the effective usage of stack and heap.
Stack has a very limited size and it is a container that holds variables.
The heap (or "free store") is a large pool of memory used for dynamic allocation. It's size limited to the available space in your dynamic memory (RAM).
If you try to store everything in the stack without dynamic allocation and pointers you will get into stack overflow.
You can also imagine heap as a country to travel and stack is your guide which you can get info about the location of restaurants, hotels, etc..
|
15,964,164
|
I want to create theme, for that i created one launcher app. So when i press "home" button it shows me to select which launcher to be launch.
But I don't want that selection UI, When my app is installed it should launch automatically and sets it as default launcher.
can it be possible?
Thanks
|
2013/04/12
|
[
"https://Stackoverflow.com/questions/15964164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2232148/"
] |
A pointer is just a number storing a numerical index for a memory location. Every non-trivial program in every language needs such numbers to keep track of where interesting functions and data are. In some languages the use of pointers is hidden - you just see some identifier like "employee\_name" and internally the compiler or interpreter has arranged for storage and passes the pointer thereto around as it needs to to make the program behave as stipulated by the language, but they're always there underneath.
If you can't see the pointer use, you can't always reason about which operations in the language are cheap and which incur costs.
In some dumbed-down languages like VB, it used to be that more advanced data types like associative containers (`std::map`, `std::unordered_map`), linked lists, graphs etc. weren't available; clumsy functions would have to be used that internally used C or C++ to track the relationships between data elements. Working directly in C++, you can create such data types yourself to model arbitrary relationships with the precise behavioural, performance and memory use compromises that suit you.
C++ exposes pointers so that you have explicit control over whether the memory area used by an existing object is passed around different parts of the program, potentially granting them access to change the value or even deallocate the memory. This is more efficient than other languages like Java, Ruby and C# where it's less obvious which code has access to some data versus a copy of that data, when the copying can happen, when the data is no longer needed. Things like garbage collection exist to try to track use of data, but typically introduce performance issues, inefficiencies and unpredictable timing of destruction - whether than matters depends on the application.
|
The very basic reason is the effective usage of stack and heap.
Stack has a very limited size and it is a container that holds variables.
The heap (or "free store") is a large pool of memory used for dynamic allocation. It's size limited to the available space in your dynamic memory (RAM).
If you try to store everything in the stack without dynamic allocation and pointers you will get into stack overflow.
You can also imagine heap as a country to travel and stack is your guide which you can get info about the location of restaurants, hotels, etc..
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
Heiko's approach will probably work, but will lead to none of the dependencies of the 3rd party lib to be downloaded. If you only want to exclude a specific one use `exclude`.
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("org.baz", "bam")
```
or
```
... excludeAll( ExclusionRule(organization = "org.baz") ) // does not work with generated poms!
```
|
Add *intransitive* your 3rd party library dependency, e.g.
```
libraryDependencies += "foo" %% "bar" % "1.2.3" intransitive
```
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
I met the same problem before. Solved it by adding dependency like
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("commons-logging","commons-logging")
```
or
```
libraryDependencies += "foo" % "bar" % "0.7.0" excludeAll(ExclusionRule(organization = "commons-logging"))
```
|
Add *intransitive* your 3rd party library dependency, e.g.
```
libraryDependencies += "foo" %% "bar" % "1.2.3" intransitive
```
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
For sbt 0.13.8 and above, you can also try the project-level dependency exclusion:
```scala
excludeDependencies += "commons-logging" % "commons-logging"
```
|
Add *intransitive* your 3rd party library dependency, e.g.
```
libraryDependencies += "foo" %% "bar" % "1.2.3" intransitive
```
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
Heiko's approach will probably work, but will lead to none of the dependencies of the 3rd party lib to be downloaded. If you only want to exclude a specific one use `exclude`.
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("org.baz", "bam")
```
or
```
... excludeAll( ExclusionRule(organization = "org.baz") ) // does not work with generated poms!
```
|
I met the same problem before. Solved it by adding dependency like
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("commons-logging","commons-logging")
```
or
```
libraryDependencies += "foo" % "bar" % "0.7.0" excludeAll(ExclusionRule(organization = "commons-logging"))
```
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
Heiko's approach will probably work, but will lead to none of the dependencies of the 3rd party lib to be downloaded. If you only want to exclude a specific one use `exclude`.
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("org.baz", "bam")
```
or
```
... excludeAll( ExclusionRule(organization = "org.baz") ) // does not work with generated poms!
```
|
For sbt 0.13.8 and above, you can also try the project-level dependency exclusion:
```scala
excludeDependencies += "commons-logging" % "commons-logging"
```
|
10,958,215
|
My scala/sbt project uses grizzled-slf4j and logback. A third-party dependency uses Apache Commons Logging.
With Java/Maven, I would use jcl-over-slf4j and logback-classic so that I can use logback as the unified logging backend.
I would also eliminate the commons-logging dependency that the third-party lib would let sbt pull in. I do the following in Maven (which is recommended by <http://www.slf4j.org/faq.html#excludingJCL>):
```
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
```
And the question is, how to do the same with sbt?
|
2012/06/09
|
[
"https://Stackoverflow.com/questions/10958215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/794965/"
] |
For sbt 0.13.8 and above, you can also try the project-level dependency exclusion:
```scala
excludeDependencies += "commons-logging" % "commons-logging"
```
|
I met the same problem before. Solved it by adding dependency like
```
libraryDependencies += "foo" % "bar" % "0.7.0" exclude("commons-logging","commons-logging")
```
or
```
libraryDependencies += "foo" % "bar" % "0.7.0" excludeAll(ExclusionRule(organization = "commons-logging"))
```
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
The default editor for Cscope is vi not VIM. Vi has no option for Syntax highlighting and other features of plugins etc.
Just change the default editor to vim. All your Vim settings will come to Cscope output.
```
$ export CSCOPE_EDITOR=vim
```
Done.
|
You can set color to cscope editor by changing its default editor to vim from vi.
You need to just add an environment variable `CSCOPE_EDITOR` as `/usr/bin/vim` (get your absolute path for vim using `which vim` command).
Add the below line to your `.cshrc` file in your home folder to make it retain (I tried in REDHAT).
```
setenv CSCOPE_EDITOR /usr/bin/vim
```
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
The default editor for Cscope is vi not VIM. Vi has no option for Syntax highlighting and other features of plugins etc.
Just change the default editor to vim. All your Vim settings will come to Cscope output.
```
$ export CSCOPE_EDITOR=vim
```
Done.
|
Use this in .vimrc --
syntax enable
-- rather than --
syntax on
This worked for me.
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
The default editor for Cscope is vi not VIM. Vi has no option for Syntax highlighting and other features of plugins etc.
Just change the default editor to vim. All your Vim settings will come to Cscope output.
```
$ export CSCOPE_EDITOR=vim
```
Done.
|
Exporting CSCOPE\_EDITOR in ~/.bashrc worked for me.
export CSCOPE\_EDITOR=/usr/bin/vim
Thanks Anirudh. 'which vim' will tell which executable of vim is in use.
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
The default editor for Cscope is vi not VIM. Vi has no option for Syntax highlighting and other features of plugins etc.
Just change the default editor to vim. All your Vim settings will come to Cscope output.
```
$ export CSCOPE_EDITOR=vim
```
Done.
|
For me, all the above suggestions didn't work.
What I was searching for is something like this:
[](https://i.stack.imgur.com/VkZER.png)
I achieved it by gluing up several vim commands:
```
nnoremap *
\ :exec("cs find s ".expand("<cword>"))<CR>
\ :copen<CR>
```
`*` - highlight word under cursor
`:exec("cs find s ".expand("<cword>"))<CR>` - cscope find word under cursor
`:copen` - open cscope search results window
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
Use this in .vimrc --
syntax enable
-- rather than --
syntax on
This worked for me.
|
You can set color to cscope editor by changing its default editor to vim from vi.
You need to just add an environment variable `CSCOPE_EDITOR` as `/usr/bin/vim` (get your absolute path for vim using `which vim` command).
Add the below line to your `.cshrc` file in your home folder to make it retain (I tried in REDHAT).
```
setenv CSCOPE_EDITOR /usr/bin/vim
```
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
For me, all the above suggestions didn't work.
What I was searching for is something like this:
[](https://i.stack.imgur.com/VkZER.png)
I achieved it by gluing up several vim commands:
```
nnoremap *
\ :exec("cs find s ".expand("<cword>"))<CR>
\ :copen<CR>
```
`*` - highlight word under cursor
`:exec("cs find s ".expand("<cword>"))<CR>` - cscope find word under cursor
`:copen` - open cscope search results window
|
You can set color to cscope editor by changing its default editor to vim from vi.
You need to just add an environment variable `CSCOPE_EDITOR` as `/usr/bin/vim` (get your absolute path for vim using `which vim` command).
Add the below line to your `.cshrc` file in your home folder to make it retain (I tried in REDHAT).
```
setenv CSCOPE_EDITOR /usr/bin/vim
```
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
Use this in .vimrc --
syntax enable
-- rather than --
syntax on
This worked for me.
|
Exporting CSCOPE\_EDITOR in ~/.bashrc worked for me.
export CSCOPE\_EDITOR=/usr/bin/vim
Thanks Anirudh. 'which vim' will tell which executable of vim is in use.
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
For me, all the above suggestions didn't work.
What I was searching for is something like this:
[](https://i.stack.imgur.com/VkZER.png)
I achieved it by gluing up several vim commands:
```
nnoremap *
\ :exec("cs find s ".expand("<cword>"))<CR>
\ :copen<CR>
```
`*` - highlight word under cursor
`:exec("cs find s ".expand("<cword>"))<CR>` - cscope find word under cursor
`:copen` - open cscope search results window
|
Use this in .vimrc --
syntax enable
-- rather than --
syntax on
This worked for me.
|
21,691,665
|
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
```
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
```
|
2014/02/11
|
[
"https://Stackoverflow.com/questions/21691665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097736/"
] |
For me, all the above suggestions didn't work.
What I was searching for is something like this:
[](https://i.stack.imgur.com/VkZER.png)
I achieved it by gluing up several vim commands:
```
nnoremap *
\ :exec("cs find s ".expand("<cword>"))<CR>
\ :copen<CR>
```
`*` - highlight word under cursor
`:exec("cs find s ".expand("<cword>"))<CR>` - cscope find word under cursor
`:copen` - open cscope search results window
|
Exporting CSCOPE\_EDITOR in ~/.bashrc worked for me.
export CSCOPE\_EDITOR=/usr/bin/vim
Thanks Anirudh. 'which vim' will tell which executable of vim is in use.
|
42,751,903
|
[Models.py](https://i.stack.imgur.com/6H4zB.png)
[Shell Output](https://i.stack.imgur.com/SztWE.png)
--**CODE**--
```
newArtist = Artist(name= "GBA",year_formed=1990)
newArtist.save()
album1 = Album(name = 'a',artist = newArtist)
album2 = Album(name = 'b',artist = newArtist)
album3 = Album(name = 'c',artist = newArtist)
album1.save()
album2.save()
album3.save()
allAlbums = Album.objects.all()
```
Hey, I am pretty new to Django so have been going through the documentation diligently but have an error I for the life of me can't figure out! The problem lies when dealing with the filter property.
There are 2 classes in my models file: Artist and Album. Artist is also a foreign key of Album as an Artist can have many albums. Currently I have 3 albums instances created, all saved under the Artist "newArtist" who's name is "GBA".
The problems I'm facing are
1)When attempting to filter using the artist name "GBA" an empty query set was returned
2)However when I switched the specifier to "newArtist.id" it populated the query set successfully.
Am confused as to why the artist name did not work, was it a syntactical/logic/Django rule error?
If anyone needs to see further code snippets/output, please let me know.
Thanks for your help!
|
2017/03/12
|
[
"https://Stackoverflow.com/questions/42751903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4760798/"
] |
Try this:
```
newArtist = Artist.objects.create(name= "GBA", year_formed=1990)
album1 = Album.objects.create(name = 'a', artist = newArtist)
album2 = Album.objects.create(name = 'b', artist = newArtist)
album3 = Album.objects.create(name = 'c', artist = newArtist)
allAlbums = Album.objects.all()
```
|
<https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py>
Same answer for the other question brotha!
look in the line 52 of my script!
-Cheers
|
25,388,825
|
Problem :
There is a stack consisting of N bricks. You and your friend decide to play a game using this stack. In this game, one can alternatively remove 1/2/3 bricks from the top and the numbers on the bricks removed by the player is added to his score. You have to play in such a way that you obtain maximum possible score while it is given that your friend will also play optimally and you make the first move.
Input Format
First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test case, first line will contain a number N i.e. number of element in stack and next line will contain N numbers i.e. numbers written on bricks from top to bottom.
Output Format
For each test case, print a single line containing your maximum score.
I have tried with recursion but didn't work
```
int recurse(int length, int sequence[5], int i) {
if(length - i < 3) {
int sum = 0;
for(i; i < length; i++) sum += sequence[i];
return sum;
} else {
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 += recurse(length, sequence, i+1);
sum2 += recurse(length, sequence, i+2);
sum3 += recurse(length, sequence, i+3);
return max(max(sum1,sum2),sum3);
}
}
int main() {
int sequence[] = {0, 0, 9, 1, 999};
int length = 5;
cout << recurse(length, sequence, 0);
return 0;
}
```
|
2014/08/19
|
[
"https://Stackoverflow.com/questions/25388825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3005924/"
] |
At a first sight your code seems totally wrong for a couple of reasons:
1. The player is not taken into account. You taking a brick or your friend taking a brick is not the same (you've to maximize your score, the total is of course always the total of the score on the bricks).
2. Looks just some form of recursion with no memoization and that approach will obviously explode to exponential computing time (you're using the "brute force" approach, enumerating all possible games).
A dynamic programming approach is clearly possible because the best possible continuation of a game doesn't depend on how you reached a certain state. For the state of the game you'd need
* Who's next to play (you or your friend)
* How many bricks are left on the stack
With these two input you can compute how much you can collect from that point to the end of the game. To do this there are two cases
1. It's your turn
-----------------
You need to try to collect 1, 2 or 3 and call recursively on the next game state where the opponent will have to choose. Of the three cases you keep what is the highest result
2. It's opponent turn
---------------------
You need to simulate collection of 1, 2 or 3 bricks and call recursively on next game state where you'll have to choose. Of the three cases you keep what is the **lowest** result (because the opponent is trying to maximize his/her result, not yours).
At the very begin of the function you just need to check if the same game state has been processed before, and when returning from a computation you need to store the result. Thanks to this lookup/memorization the search time will not be exponential, but linear in the number of distinct game states (just 2\*N where N is the number of bricks).
In Python:
```
memory = {}
bricks = [0, 0, 9, 1, 999]
def maxResult(my_turn, index):
key = (my_turn, index)
if key in memory:
return memory[key]
if index == len(bricks):
result = 0
elif my_turn:
result = None
s = 0
for i in range(index, min(index+3, len(bricks))):
s += bricks[i]
x = s + maxResult(False, i+1)
if result is None or x > result:
result = x
else:
result = None
for i in range(index, min(index+3, len(bricks))):
x = maxResult(True, i+1)
if result is None or x < result:
result = x
memory[key] = result
return result
print maxResult(True, 0)
```
|
here a better solution that i found on the internet without recursion.
```
#include <iostream>
#include <fstream>
#include <algorithm>
#define MAXINDEX 10001
using namespace std;
long long maxResult(int a[MAXINDEX], int LENGTH){
long long prefixSum [MAXINDEX] = {0};
prefixSum[0] = a[0];
for(int i = 1; i < LENGTH; i++){
prefixSum[i] += prefixSum[i-1] + a[i];
}
long long dp[MAXINDEX] = {0};
dp[0] = a[0];
dp[1] = dp[0] + a[1];
dp[2] = dp[1] + a[2];
for(int k = 3; k < LENGTH; k++){
long long x = prefixSum[k-1] + a[k] - dp[k-1];
long long y = prefixSum[k-2] + a[k] + a[k-1] - dp[k-2];
long long z = prefixSum[k-3] + a[k] + a[k-1] + a[k-2] - dp[k-3];
dp[k] = max(x,max(y,z));
}
return dp[LENGTH-1];
}
using namespace std;
int main(){
int cases;
int bricks[MAXINDEX];
ifstream fin("test.in");
fin >> cases;
for (int i = 0; i < cases; i++){
long n;
fin >> n;
for(int j = 0; j < n; j++) fin >> bricks[j];
reverse(bricks, bricks+n);
cout << maxResult(bricks, n)<< endl;
}
return 0;
}
```
|
25,388,825
|
Problem :
There is a stack consisting of N bricks. You and your friend decide to play a game using this stack. In this game, one can alternatively remove 1/2/3 bricks from the top and the numbers on the bricks removed by the player is added to his score. You have to play in such a way that you obtain maximum possible score while it is given that your friend will also play optimally and you make the first move.
Input Format
First line will contain an integer T i.e. number of test cases. There will be two lines corresponding to each test case, first line will contain a number N i.e. number of element in stack and next line will contain N numbers i.e. numbers written on bricks from top to bottom.
Output Format
For each test case, print a single line containing your maximum score.
I have tried with recursion but didn't work
```
int recurse(int length, int sequence[5], int i) {
if(length - i < 3) {
int sum = 0;
for(i; i < length; i++) sum += sequence[i];
return sum;
} else {
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 += recurse(length, sequence, i+1);
sum2 += recurse(length, sequence, i+2);
sum3 += recurse(length, sequence, i+3);
return max(max(sum1,sum2),sum3);
}
}
int main() {
int sequence[] = {0, 0, 9, 1, 999};
int length = 5;
cout << recurse(length, sequence, 0);
return 0;
}
```
|
2014/08/19
|
[
"https://Stackoverflow.com/questions/25388825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3005924/"
] |
My approach to solving this problem was as follows:
### Both players play optimally.
So, the solution is to be built in a manner that need not take the player into account. This is because both players are going to pick the best choice available to them for any given state of the stack of bricks.
### The base cases:
Either player, when left with the last one/two/three bricks, will choose to remove all bricks.
For the sake of convenience, let's assume that the array is actually in reverse order (i.e. a[0] is the value of the bottom-most brick in the stack) (This can easily be incorporated by performing a reverse operation on the array.)
So, the base cases are:
```
# Base Cases
dp[0] = a[0]
dp[1] = a[0]+a[1]
dp[2] = a[0]+a[1]+a[2]
```
### Building the final solution:
Now, in each iteration, a player has 3 choices.
1. pick brick (i), or,
2. pick brick (i and i-1) , or,
3. pick brick (i,i-1 and i-2)
If the player opted for choice 1, the following would result:
* player secures a[i] points from the brick (i) (+a[i])
* will not be able to procure the points on the bricks removed by the opponent. This value is stored in dp[i-1] (which the opponent will end up scoring by virtue of this choice made by the player).
* will surely procure the points on the bricks not removed by the opponent. (+ Sum of all the bricks up until brick (i-1) not removed by opponent )
A prefix array to store the partial sums of points of bricks can be computed as follows:
```
# build prefix sum array
pre = [a[0]]
for i in range(1,n):
pre.append(pre[-1]+a[i])
```
And, now, if player opted for choice 1, the score would be:
```
ans1 = a[i] + (pre[i-1] - dp[i-1])
```
Similarly, for choices 2 and 3. So, we get:
```
ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick
ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2 bricks
ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) # pick 3 bricks
```
Now, each player wants to maximize this value. So, in each iteration, we pick the maximum among ans1, ans2 and ans3.
dp[i] = max(ans1, ans2, ans3)
Now, all we have to do is to iterate from 3 through to n-1 to get the required solution.
Here is the final snippet in python:
```
a = map(int, raw_input().split())
a.reverse() # so that a[0] is bottom brick of stack
dp = [0 for x1 in xrange(n)]
dp[0] = a[0]
dp[1] = a[0]+a[1]
dp[2] = a[0]+a[1]+a[2]
# build prefix sum array
pre = [a[0]]
for i in range(1,n):
pre.append(pre[-1]+a[i])
for i in xrange(3,n):
# We can pick brick i, (i,i-1) or (i,i-1,i-2)
ans1 = a[i]+ (pre[i-1] - dp[i-1]) # if we pick only ith brick
ans2 = a[i]+a[i-1]+(pre[i-2] - dp[i-2]) # pick 2
ans3 = a[i]+a[i-1]+a[i-2]+(pre[i-3] - dp[i-3]) #pick 3
# both players maximise this value. Doesn't matter who is playing
dp[i] = max(ans1, ans2, ans3)
print dp[n-1]
```
|
At a first sight your code seems totally wrong for a couple of reasons:
1. The player is not taken into account. You taking a brick or your friend taking a brick is not the same (you've to maximize your score, the total is of course always the total of the score on the bricks).
2. Looks just some form of recursion with no memoization and that approach will obviously explode to exponential computing time (you're using the "brute force" approach, enumerating all possible games).
A dynamic programming approach is clearly possible because the best possible continuation of a game doesn't depend on how you reached a certain state. For the state of the game you'd need
* Who's next to play (you or your friend)
* How many bricks are left on the stack
With these two input you can compute how much you can collect from that point to the end of the game. To do this there are two cases
1. It's your turn
-----------------
You need to try to collect 1, 2 or 3 and call recursively on the next game state where the opponent will have to choose. Of the three cases you keep what is the highest result
2. It's opponent turn
---------------------
You need to simulate collection of 1, 2 or 3 bricks and call recursively on next game state where you'll have to choose. Of the three cases you keep what is the **lowest** result (because the opponent is trying to maximize his/her result, not yours).
At the very begin of the function you just need to check if the same game state has been processed before, and when returning from a computation you need to store the result. Thanks to this lookup/memorization the search time will not be exponential, but linear in the number of distinct game states (just 2\*N where N is the number of bricks).
In Python:
```
memory = {}
bricks = [0, 0, 9, 1, 999]
def maxResult(my_turn, index):
key = (my_turn, index)
if key in memory:
return memory[key]
if index == len(bricks):
result = 0
elif my_turn:
result = None
s = 0
for i in range(index, min(index+3, len(bricks))):
s += bricks[i]
x = s + maxResult(False, i+1)
if result is None or x > result:
result = x
else:
result = None
for i in range(index, min(index+3, len(bricks))):
x = maxResult(True, i+1)
if result is None or x < result:
result = x
memory[key] = result
return result
print maxResult(True, 0)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.