qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
4,971,909 | Is there any way of getting the "Windows Live Anonymous ID" from a PC based on the users e-mail-adress, logged in Windows-account, registry, Zune, currently usb-connected phone or else? | 2011/02/11 | [
"https://Stackoverflow.com/questions/4971909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382838/"
] | There are several guides besides the [Core Data Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/) that are relevant:
* [Model Object Implementation Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ModelObjects/)
* [Key-Value Coding Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/)
* [Creating a Managed Object Model](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CreatingMOMWithXcode/)
* [Predicate Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/)
I got the last two from the “Related Documents” section of the CDPG.
Not quite so Core Data/data-modeling related, but still useful for applying Core Data, are the documents on using Bindings:
* [Key-Value Observing Programming Guide](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/)
* [Cocoa Bindings Programming Topics](http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaBindings/)
* [Cocoa Bindings Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/CocoaBindingsRef/)
Bindings makes it easier to use built-in Cocoa views to display the data you keep in your model.
You'll also find the framework references worth bookmarking:
* [Foundation Framework Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/ObjC_classic/)
* [Application Kit Framework Reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/)
* [Core Data Framework reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/CoreData_ObjC/) | Marcus S. Zarra's "Core Data" book gets good reviews. |
23,774,871 | I have a dc.js ordinal chart whose x-axis consists of things like 'Cosmetics' and the y-axis is the number of sales. I want to sort the chart by sales decreasing, however when I use `.ordering(function(d){return -d.value.ty})` the path of the line chart is still ordered by the x-axis.
```
var departmentChart = dc.compositeChart('#mystore_department_chart'),
ndx = crossfilter(response.data),
dimension = ndx.dimension(function(d) {return d.name}),
group = dimension.group().reduce(function(p, v) {
p.ty += v.tyvalue;
p.ly += v.lyvalue;
return p;
}, function(p, v) {
p.ty -= v.tyvalue;
p.ly -= v.lyvalue;
return p;
}, function() {
return {
ty: 0,
ly: 0
}
});
departmentChart
.ordering(function(d){return -d.value.ty})
//dimensions
//.width(768)
.height(250)
.margins({top: 10, right: 50, bottom: 25, left: 50})
//x-axis
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel('Department')
//left y-axis
.yAxisLabel('Sales')
.elasticY(true)
.renderHorizontalGridLines(true)
//composition
.dimension(dimension)
.group(group)
.compose([
dc.barChart(departmentChart)
.centerBar(true)
.gap(5)
.dimension(dimension)
.group(group, 'This Year')
.valueAccessor(function(d) {return d.value.ty}),
dc.lineChart(departmentChart)
.renderArea(false)
.renderDataPoints(true)
.dimension(dimension)
.group(group, 'Last Year')
.valueAccessor(function(d) {return d.value.ly})
])
.brushOn(false)
render();
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23774871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531746/"
] | This is the hack I ended up doing. Be aware that it could have performance issues on large data sets as all() is faster than top(Infinity). For some reason I couldn't get [Gordon's answer](https://stackoverflow.com/questions/23774871/dc-js-sort-ordinal-line-chart-by-y-axis-value/23788922#23788922) to work, but in theory it should.
On my group I specified an order function
```
group.order(function(p) {
return p.myfield;
});
```
Then because all() doesn't use the order function I overrode the default all function
```
group.all = function() {
return group.top(Infinity);
}
```
And then on my chart I had to specify an order function
```
chart.ordering(function(d){
return -d.value.myfield
}); // order by myfield descending
``` | No doubt this is a bug.
As a workaround, you could sort the data yourself instead of using the ordering function, [as described in the FAQ](https://github.com/dc-js/dc.js/wiki/FAQ#filter-the-data-before-its-charted).
I filed a bug report: <https://github.com/dc-js/dc.js/issues/598> |
23,774,871 | I have a dc.js ordinal chart whose x-axis consists of things like 'Cosmetics' and the y-axis is the number of sales. I want to sort the chart by sales decreasing, however when I use `.ordering(function(d){return -d.value.ty})` the path of the line chart is still ordered by the x-axis.
```
var departmentChart = dc.compositeChart('#mystore_department_chart'),
ndx = crossfilter(response.data),
dimension = ndx.dimension(function(d) {return d.name}),
group = dimension.group().reduce(function(p, v) {
p.ty += v.tyvalue;
p.ly += v.lyvalue;
return p;
}, function(p, v) {
p.ty -= v.tyvalue;
p.ly -= v.lyvalue;
return p;
}, function() {
return {
ty: 0,
ly: 0
}
});
departmentChart
.ordering(function(d){return -d.value.ty})
//dimensions
//.width(768)
.height(250)
.margins({top: 10, right: 50, bottom: 25, left: 50})
//x-axis
.x(d3.scale.ordinal())
.xUnits(dc.units.ordinal)
.xAxisLabel('Department')
//left y-axis
.yAxisLabel('Sales')
.elasticY(true)
.renderHorizontalGridLines(true)
//composition
.dimension(dimension)
.group(group)
.compose([
dc.barChart(departmentChart)
.centerBar(true)
.gap(5)
.dimension(dimension)
.group(group, 'This Year')
.valueAccessor(function(d) {return d.value.ty}),
dc.lineChart(departmentChart)
.renderArea(false)
.renderDataPoints(true)
.dimension(dimension)
.group(group, 'Last Year')
.valueAccessor(function(d) {return d.value.ly})
])
.brushOn(false)
render();
``` | 2014/05/21 | [
"https://Stackoverflow.com/questions/23774871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/531746/"
] | This is the hack I ended up doing. Be aware that it could have performance issues on large data sets as all() is faster than top(Infinity). For some reason I couldn't get [Gordon's answer](https://stackoverflow.com/questions/23774871/dc-js-sort-ordinal-line-chart-by-y-axis-value/23788922#23788922) to work, but in theory it should.
On my group I specified an order function
```
group.order(function(p) {
return p.myfield;
});
```
Then because all() doesn't use the order function I overrode the default all function
```
group.all = function() {
return group.top(Infinity);
}
```
And then on my chart I had to specify an order function
```
chart.ordering(function(d){
return -d.value.myfield
}); // order by myfield descending
``` | It does appear to be a bug. I too couldn't make it work as intended.
I implemented a workaround; I added an example in a Plunker, link is (also) in the dc.js issue at github.
It is based upon a recent snapshot of dc.js 2.0.0-dev.
(So for now I guess this could be considered an answer)
<http://embed.plnkr.co/VItIQ4ZcW9abfzI13z64/> |
417,952 | I have a question that is similar to [How can I make a custom theorem for a definition?](https://tex.stackexchange.com/questions/83446/how-can-i-make-a-custom-theorem-for-a-definition) and also to [Custom theorem numbering italicized](https://tex.stackexchange.com/questions/286129/custom-theorem-numbering-italicized), but I'm not able to work out how to do it from these. My wish is the following:
>
> define a custom theorem style so that the body of the text is slanted via `\textsl{...}` (not italicised via `\textit{...}`).
>
>
>
For example, I would like it to look like this.
>
> \textbf{Theorem 1.1} (theorem name)\textbf{.} \textsl{Statement of theorem.}
>
>
>
This link <https://en.wikibooks.org/wiki/LaTeX/Theorems#Custom_styles> should also be helpful, but again I am unable to make it work myself.
Advice on how to do this would be most appreciated, thanks.
I'm using packages `amsmath` and `ntheorem`. I've no particular attachment to the package `ntheorem`: if changing to use a different package would make it easier, then I don't *think* this would mess up my other stuff. | 2018/03/01 | [
"https://tex.stackexchange.com/questions/417952",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/81928/"
] | (edited the answer after the OP provided more information about the desired appearance of the theorem-like environment.
I would like to suggest that you use the `amsthm` package and define a new theorem style, called `sltheoremstyle` in the example below.
[](https://i.stack.imgur.com/ooJGZ.png)
```
\documentclass{article}
\usepackage{amsthm}
\newtheoremstyle{sltheorem}
{} % Space above
{} % Space below
{\slshape} % Theorem body font % (default is "\upshape")
{} % Indent amount
{\bfseries} % Theorem head font % (default is \mdseries)
{.} % Punctuation after theorem head % default: no punctuation
{ } % Space after theorem head
{} % Theorem head spec
\theoremstyle{sltheorem}
\newtheorem{theorem}{Theorem}
\begin{document}
\begin{theorem}[Wow]
Hello World.
\end{theorem}
\end{document}
``` | Bad typography (slanted) ahead...
```
\documentclass{article}
\usepackage{blindtext}
\usepackage[most]{tcolorbox}
\newtcbtheorem{slantedtheorem}{Theorems from hell}{colback=yellow!20!white,colbacktitle={yellow!40!white},coltitle={black},fontupper=\slshape,fonttitle={\slshape}}{sltheo}
\begin{document}
\begin{slantedtheorem}{I am slanted}{ohmy}
\blindtext
\end{slantedtheorem}
\end{document}
```
[](https://i.stack.imgur.com/KvCji.png) |
56,123,544 | I have a list as follows:
```
number_list = (1, 2, 3, 4, 5, 6, 7).
```
I want to get a list which contain elements greater than 3. It should be something like this.
```
new_list = (4, 5, 6, 7)
```
I can do something like foreach, to check every elements until it is smaller than 3. But is there other way to do that? Or some List methods to do it? | 2019/05/14 | [
"https://Stackoverflow.com/questions/56123544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4566981/"
] | Have you tried *Linq* and [`Where`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=netframework-4.8)
>
> Filters a sequence of values based on a predicate.
>
>
>
```
var results = number_list.Where(x => x > someAwesomeNumber)
``` | One way is `FindAll` which returns a `List`
```
List<int> items = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
items = items.FindAll(x => x < 3);
```
another way is `Where` combined with `ToList`
```
List<int> items = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
items = items.Where(x => x < 3).ToList();
``` |
2,192,560 | Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file\_index : filename
[table2]
file\_index : celeb\_name
I want to:
Select all records from table1 where [filename] is like *aud*
and whose corresponding [file\_index] value does not
exist in table2 with with field [celeb\_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file\_index] = [table1].[file\_index]
[celeb\_name] = 'Audrey Hepburn'
There is a one to many relationship between [file\_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks | 2010/02/03 | [
"https://Stackoverflow.com/questions/2192560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265323/"
] | Will this do? Obviously add some square brackets and stuff. Not too into Access myself.
```
INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'Audrey Hepburn'
FROM table1
WHERE filename = 'aud'
AND file_index NOT IN (SELECT DISTINCT file_index
FROM table2
WHERE celeb_name = 'Audrey Hepburn')
``` | In the original question I'd modified my table and field names and inserted square brackets in to make it easier to read.
Below is the final SQL statement that worked in MS Access format. Awesome result, thanks again Tor!!
```
INSERT INTO photos_by_celebrity ( ORIG_FILE_INDEX, celebrity_name )
SELECT tblOriginal_Files.ORIG_FILE_INDEX, 'Audrey Hepburn' AS Expr1
FROM tblOriginal_Files
WHERE (((tblOriginal_Files.ORIG_FILE_INDEX) Not In (SELECT DISTINCT ORIG_FILE_INDEX
FROM photos_by_celebrity
WHERE celebrity_name = 'Audrey Hepburn')) AND ((tblOriginal_Files.ORIGINAL_FILE) Like "*aud*"));
``` |
2,192,560 | Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file\_index : filename
[table2]
file\_index : celeb\_name
I want to:
Select all records from table1 where [filename] is like *aud*
and whose corresponding [file\_index] value does not
exist in table2 with with field [celeb\_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file\_index] = [table1].[file\_index]
[celeb\_name] = 'Audrey Hepburn'
There is a one to many relationship between [file\_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks | 2010/02/03 | [
"https://Stackoverflow.com/questions/2192560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265323/"
] | Will this do? Obviously add some square brackets and stuff. Not too into Access myself.
```
INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'Audrey Hepburn'
FROM table1
WHERE filename = 'aud'
AND file_index NOT IN (SELECT DISTINCT file_index
FROM table2
WHERE celeb_name = 'Audrey Hepburn')
``` | As I said in comments, NOT IN is not well-optimized by Jet/ACE and it's usually more efficient to use an OUTER JOIN. In this case, because you need to filter on the outer side of the join, you'll need a subquery:
```
INSERT INTO photos_by_celebrity ( ORIG_FILE_INDEX, celebrity_name )
SELECT tblOriginal_Files.ORIG_FILE_INDEX, 'Audrey Hepburn'
FROM tblOriginal_Files
LEFT JOIN (SELECT DISTINCT ORIG_FILE_INDEX
FROM photos_by_celebrity
WHERE celebrity_name = 'Audrey Hepburn') AS Photos
ON tblOriginal_Files.ORIG_FILE_INDEX = Photos.ORIG_FILE_INDEX
WHERE Photos.ORIG_FILE_INDEX Is Null;
```
(that may not be exactly right -- I'm terrible with writing SQL by hand, particularly getting the JOIN syntax right)
I must say, though, that I'm wondering if this will insert too many records (and the same reservation applies to the NOT IN version). |
2,192,560 | Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file\_index : filename
[table2]
file\_index : celeb\_name
I want to:
Select all records from table1 where [filename] is like *aud*
and whose corresponding [file\_index] value does not
exist in table2 with with field [celeb\_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file\_index] = [table1].[file\_index]
[celeb\_name] = 'Audrey Hepburn'
There is a one to many relationship between [file\_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks | 2010/02/03 | [
"https://Stackoverflow.com/questions/2192560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265323/"
] | Will this do? Obviously add some square brackets and stuff. Not too into Access myself.
```
INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'Audrey Hepburn'
FROM table1
WHERE filename = 'aud'
AND file_index NOT IN (SELECT DISTINCT file_index
FROM table2
WHERE celeb_name = 'Audrey Hepburn')
``` | You can use `NOT Exists`
I think it is the best way from the side of performance.
As Follow:
```
INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'Audrey Hepburn'
FROM table1
WHERE filename = 'aud'
AND NOT Exists (SELECT file_index
FROM table2
WHERE celeb_name = 'Audrey Hepburn')
``` |
2,192,560 | Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file\_index : filename
[table2]
file\_index : celeb\_name
I want to:
Select all records from table1 where [filename] is like *aud*
and whose corresponding [file\_index] value does not
exist in table2 with with field [celeb\_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file\_index] = [table1].[file\_index]
[celeb\_name] = 'Audrey Hepburn'
There is a one to many relationship between [file\_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks | 2010/02/03 | [
"https://Stackoverflow.com/questions/2192560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265323/"
] | As I said in comments, NOT IN is not well-optimized by Jet/ACE and it's usually more efficient to use an OUTER JOIN. In this case, because you need to filter on the outer side of the join, you'll need a subquery:
```
INSERT INTO photos_by_celebrity ( ORIG_FILE_INDEX, celebrity_name )
SELECT tblOriginal_Files.ORIG_FILE_INDEX, 'Audrey Hepburn'
FROM tblOriginal_Files
LEFT JOIN (SELECT DISTINCT ORIG_FILE_INDEX
FROM photos_by_celebrity
WHERE celebrity_name = 'Audrey Hepburn') AS Photos
ON tblOriginal_Files.ORIG_FILE_INDEX = Photos.ORIG_FILE_INDEX
WHERE Photos.ORIG_FILE_INDEX Is Null;
```
(that may not be exactly right -- I'm terrible with writing SQL by hand, particularly getting the JOIN syntax right)
I must say, though, that I'm wondering if this will insert too many records (and the same reservation applies to the NOT IN version). | In the original question I'd modified my table and field names and inserted square brackets in to make it easier to read.
Below is the final SQL statement that worked in MS Access format. Awesome result, thanks again Tor!!
```
INSERT INTO photos_by_celebrity ( ORIG_FILE_INDEX, celebrity_name )
SELECT tblOriginal_Files.ORIG_FILE_INDEX, 'Audrey Hepburn' AS Expr1
FROM tblOriginal_Files
WHERE (((tblOriginal_Files.ORIG_FILE_INDEX) Not In (SELECT DISTINCT ORIG_FILE_INDEX
FROM photos_by_celebrity
WHERE celebrity_name = 'Audrey Hepburn')) AND ((tblOriginal_Files.ORIGINAL_FILE) Like "*aud*"));
``` |
2,192,560 | Hi to all you mighty SQLsuperheros out there..
Can anyone rescue me from imminent disaster and ruin?
I'm working with Microsoft Access SQL. I'd like to select records in one table (table1) that don't appear in another (table2) .. and then insert new records into table2 that are based on records in table1, as follows:
[table1]
file\_index : filename
[table2]
file\_index : celeb\_name
I want to:
Select all records from table1 where [filename] is like *aud*
and whose corresponding [file\_index] value does not
exist in table2 with with field [celeb\_name] = 'Audrey Hepburn'
With that selection I then want to insert a new record into [table2]
[file\_index] = [table1].[file\_index]
[celeb\_name] = 'Audrey Hepburn'
There is a one to many relationship between [file\_index] in [table1] and [table2]
One record in [table1], to many in [table2].
Many thanks | 2010/02/03 | [
"https://Stackoverflow.com/questions/2192560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265323/"
] | As I said in comments, NOT IN is not well-optimized by Jet/ACE and it's usually more efficient to use an OUTER JOIN. In this case, because you need to filter on the outer side of the join, you'll need a subquery:
```
INSERT INTO photos_by_celebrity ( ORIG_FILE_INDEX, celebrity_name )
SELECT tblOriginal_Files.ORIG_FILE_INDEX, 'Audrey Hepburn'
FROM tblOriginal_Files
LEFT JOIN (SELECT DISTINCT ORIG_FILE_INDEX
FROM photos_by_celebrity
WHERE celebrity_name = 'Audrey Hepburn') AS Photos
ON tblOriginal_Files.ORIG_FILE_INDEX = Photos.ORIG_FILE_INDEX
WHERE Photos.ORIG_FILE_INDEX Is Null;
```
(that may not be exactly right -- I'm terrible with writing SQL by hand, particularly getting the JOIN syntax right)
I must say, though, that I'm wondering if this will insert too many records (and the same reservation applies to the NOT IN version). | You can use `NOT Exists`
I think it is the best way from the side of performance.
As Follow:
```
INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'Audrey Hepburn'
FROM table1
WHERE filename = 'aud'
AND NOT Exists (SELECT file_index
FROM table2
WHERE celeb_name = 'Audrey Hepburn')
``` |
50,097,378 | I am hoping someone can help me!
I am trying to work out the formula(s) on how to auto populate data from two different columns based on another cells value in excel.
I have the following headings shown on the sheet that contains all the data:-
**System Size Panels | Inverter Type | Sell - FINANCE PRICE | Sell - cash PRICE**
I have the following headings where i want to populate the data:-
**Payment Type | System Size (kw) | Inverter Type | No. of Panels | RRP $**
I have created a dropdown list for the "Payment Type", as follows:-
```
-cash
-Certegy
-Brighte
-Other
```
I have also created a `dropdown` list for the `System Size (kw)`, as follows:-
```
2.7
3.24
3.78
4.32
4.86
5.4
5.94
```
SO....I want a formula so that it populates the correct `RRP$` based on the `Payment Type` for the `system size (kw)` chosen.
So basically we have a cash and finance price list so if the payment type selection from the dropdown list is `CASH`, then I want the `RRP$` cash price to populate and if `Certegy`, `Brighte` or Other are chosen then I want the `RRP$`finance price to populate. | 2018/04/30 | [
"https://Stackoverflow.com/questions/50097378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9720407/"
] | If you have only two different price levels (cash and finance) then an if statement combined with a vlookup should do it the syntax would similar to
```
=IF(payment = "Cash", vlookup(system size ,data table,cash price),vlookup(system size,datatable,finance price)
```
If you have more than two or 3 price levels IF statements would be unwieldy and vlookup with index/match would be a better approach.
[data dable](https://i.stack.imgur.com/ZC4oX.png)
[table where i want to populate data](https://i.stack.imgur.com/wFdRY.png) | I've looked at the screen shots but as they don't show the column letters and row numbers it's difficult to provide an exact syntax, but it should look a bit like the attached screenshot - you'll need to adjust the references to reflect the layout of your worksheets and use absolute ($) references for the data table so that the reference doesn't change if you need to copy the formula down the column. (if the tables are on different sheets the syntax is 'Sheet Name'!D2)
[](https://i.stack.imgur.com/S7El7.png) |
24,878 | What is the longest -1 word (or the word worth most in Scrabble for words with the same amount of letters (which is just the addition of all the letter values of the original 'word', no constraints)), where a -1 word is defined as:
* This 'word' does not have to be an actual word, just a string of letters.
* one can replace each and every letter in the 'word' with another letter to create a word that appears in the [dictionary.com](http://dictionary.com) database.
An example of a -1 word would be "gub," and the replacements one could make would be "rub," "gob," and "gun." | 2015/12/27 | [
"https://puzzling.stackexchange.com/questions/24878",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/167/"
] | Here's a 7-letter -1 word:
>
> **PASTERS** ([English word](http://dictionary.reference.com/browse/pasters), score: 9)
>
>
>
> [**M**ASTERS](http://dictionary.reference.com/browse/masters)
>
> [P**O**STERS](http://dictionary.reference.com/browse/posters)
>
> [PA**T**TERS](http://dictionary.reference.com/browse/patters)
>
> [PAS**S**ERS](http://dictionary.reference.com/browse/passers)
>
> [PAST**O**RS](http://dictionary.reference.com/browse/pastors)
>
> [PASTE**L**S](http://dictionary.reference.com/browse/pastels)
>
> [PASTER**N**](http://dictionary.reference.com/browse/pastern)
>
>
> | Ok, let's get the ball rolling with a simple 5-letter word:
>
> **SLOPS**
>
>
>
> With the changed words being:
>
> **F**LOPS
>
> S**T**OPS
>
> SL**A**PS
>
> SLO**T**S
>
> SLOP**E**
>
>
> |
24,878 | What is the longest -1 word (or the word worth most in Scrabble for words with the same amount of letters (which is just the addition of all the letter values of the original 'word', no constraints)), where a -1 word is defined as:
* This 'word' does not have to be an actual word, just a string of letters.
* one can replace each and every letter in the 'word' with another letter to create a word that appears in the [dictionary.com](http://dictionary.com) database.
An example of a -1 word would be "gub," and the replacements one could make would be "rub," "gob," and "gun." | 2015/12/27 | [
"https://puzzling.stackexchange.com/questions/24878",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/167/"
] | Here's a 7-letter -1 word:
>
> **PASTERS** ([English word](http://dictionary.reference.com/browse/pasters), score: 9)
>
>
>
> [**M**ASTERS](http://dictionary.reference.com/browse/masters)
>
> [P**O**STERS](http://dictionary.reference.com/browse/posters)
>
> [PA**T**TERS](http://dictionary.reference.com/browse/patters)
>
> [PAS**S**ERS](http://dictionary.reference.com/browse/passers)
>
> [PAST**O**RS](http://dictionary.reference.com/browse/pastors)
>
> [PASTE**L**S](http://dictionary.reference.com/browse/pastels)
>
> [PASTER**N**](http://dictionary.reference.com/browse/pastern)
>
>
> | 7 letters, score 13
-------------------
There are no 8 to 15 letter solutions using SOWPODS. The best word which is valid with both SOWPODS and dictionary.com scores 13:
>
> POPPIES
>
>
>
> KOPPIES
>
> PAPPIES or PUPPIES
>
> POTPIES
>
> POPSIES
>
> POPPLES
>
> POPPITS
>
> POPPIED
>
>
>
NB SOWPODS gives more options for some of the positions, but the above list is filtered against dictionary.com.
---
There is a 15-pointer in SOWPODS, but it isn't valid against dictionary.com:
>
> PICKIES
>
>
>
> DICKIES, HICKIES, MICKIES, SICKIES, \*BICKIES, \*TICKIES, \*WICKIES
>
> POCKIES
>
> PINKIES, \*PISKIES
>
> \*PICCIES
>
> PICKLES
>
> \*PICKINS
>
> PICKIER
>
>
>
\* Not in dictionary.com
There is only one other 7-letter answer, which Miles has already given.
---
Bonus challenge
---------------
The highest scoring word is only 4 letters and scores 25. What is it?
>
> FUZZ
>
>
>
> BUZZ
>
> FIZZ
>
> FUTZ
>
> FUZE
>
>
> |
64,664,374 | I have the following PHP function which works well in almost all cases:
```
function NormalizeWords($str, $disallowAllUppercase = false){
$parts = explode(' ', $str);
if($disallowAllUppercase){
$result = array_map(function($x){
return ucwords(strtolower($x));
}, $parts);
}else{
$result = array_map(function($x){
if (!ctype_upper($x)) {
return ucwords(strtolower($x));
}
return $x;
}, $parts);
}
return implode(' ', $result);
}
```
But here's a case where it misses the mark:
```
$testinput = "M&S ACME BUSINESS";
$testoutput = NormalizeWords($testinput);
die($testoutput);
Expected result: M&S ACME BUSINESS
Actual result: M&s ACME BUSINESS
```
The `s` goes to lowercase.
As you can see, `$disallowAllUppercase` remains false, so any upper-case characters should be left alone.
Here are a few examples of expected results:
```
"THIS IS MY BUSINESS NAME" ($disallowAllUppercase is true) - should be: "This Is My Business Name"
"THIS IS MY BUSINESS NAME" ($disallowAllUppercase is false) - should be: "THIS IS MY BUSINESS NAME"
"aNotheR BUSINESS nAME" ($disallowAllUppercase is true) - should be: "Another Business Name"
"aNotheR BUSINESS nAME" ($disallowAllUppercase is false) - should be: "Another BUSINESS Name"
```
How can I change my function to achieve that result? | 2020/11/03 | [
"https://Stackoverflow.com/questions/64664374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1136267/"
] | I just wanted to play a little and i made this
```
function normalize($str, $disallowAllUppercase = false) {
$arr = array_map(function ($w) use ($disallowAllUppercase) {
return ucfirst((strtoupper($w) !== $w || $disallowAllUppercase) ? strtolower($w) : $w);
}, explode(" ", $str));
return implode(" ", $arr);
}
```
You can try it on phpsandbox i made dumps on it
<http://sandbox.onlinephpfunctions.com/code/7ee712a7780bab56e94e3046f2dd9b87c2e99eae>
Does it answer to your need ? | As described in the documentation for `ucwords` you can use the second parameter:
<https://www.php.net/manual/en/function.ucwords.php>
>
> The optional delimiters contains the word separator characters.
>
>
>
You can define the ampersand as an additional delimiter. Note that you should pass the default values (linebreak, space etc.) as well:
```
return ucwords(strtolower($x), " \t\r\n\f\v&");
``` |
1,296,667 | Suppose we are given that $\phi : \mathbb{R}^4 \rightarrow \mathbb{R}^3$, and also that $\ker\phi$ is the span of
$\{\begin{pmatrix} 1 \\ 0 \\ 1 \\ 1 \end{pmatrix}, \begin{pmatrix} 2 \\ 1 \\ 0 \\ 1 \end{pmatrix}\}$
How can we find a matrix which corresponds to the linear map $\phi$?
Edit: I'm not looking for the unique matrix corresponding to $\phi$, merely any matrix which satisfies the given conditions. | 2015/05/24 | [
"https://math.stackexchange.com/questions/1296667",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/243088/"
] | Call your vectors $v\_1,v\_2$. Pick two vectors $v\_3,v\_4$ such that $\{ v\_1,\dots,v\_4 \}$ is a linearly independent set. Pick linearly independent images $w\_1,w\_2$ for them. (The linear independence ensures that the kernel contains *only* your given vectors.) Then you want $A$ such that
$$A \begin{bmatrix} v\_1 & v\_2 & v\_3 & v\_4 \end{bmatrix} = \begin{bmatrix} 0 & 0 & w\_1 & w\_2 \end{bmatrix}$$
which you might write as $AV=W$. So $A=W V^{-1}$. | **Short answer:** Knowing the kernel is not enough to determine the whole matrix (unless the kernel is not the whole domain).
**Explanation:** To determine a matrix uniquely, you have to know the image of each basis vector of the domain (after you fix a certain basis in the domain). So you can complete the basis of the kernel to a basis of the whole domain. Here you have to add two vectors $v\_1$ and $v\_2$. For them you can set a different image in $\mathbb R^3$ (the image shall not be zero and $\phi(v\_1)$ must be linearly independent with $\phi(v\_2)$, because you do not want to make the kernel bigger). For nearly each chose of $\phi(v\_1)$ and $\phi(v\_2)$ you will end up with a different linear map $\phi$. |
403,510 | A user uses the following strategy: when they open a new question, they go to an answer of mine (which is possibly totally unrelated to the question) and uses a comment to ask me to take a look at their question. Comments are not intended to such a practice. What should I do? Should I flag this comment? | 2020/12/09 | [
"https://meta.stackoverflow.com/questions/403510",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/1100107/"
] | Flag them as:
>
> **It's no longer needed.**
>
> This comment is outdated, conversational or not relevant to this post.
>
>
>
The comment will then be deleted by a moderator.
As for what you do after, it's up to you; you can go and answer their question or ignore it. I, personally, tend to do the latter as I choose what questions I answer, not others. That isn't to say that if I find their question via another method (such as in one of my custom filters) I'll ignore it, just that I'll ignore the comment from the user. | This is plain and simple harassment - Stack Overflow does not exist to be an on-demand helpdesk. Immediately flag such comments for moderation attention with an appropriate explanation.
If the user is smart and/or just wasn't aware of the rules (reminder: not an excuse, it's *their duty* to know those), they will desist after the mods have a word with them. If they are a classic help vampire (i.e. the opposite of smart), they will continue, at which point you modflag again, and this time the mods will hopefully be a little more... *persuasive*. |
30,287,381 | I've googled some around the internet and found some articles about the subject, but none of them satisfied me. I want to know is it good to use object-object mapper to map objects to each other? I know it depends on situation to use, but how will I realize a good or best situation to use? | 2015/05/17 | [
"https://Stackoverflow.com/questions/30287381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3569825/"
] | You should concatenate lists, and put nested list to brackets
```
>>> [[-1, y] for y in range(-1, 2)] + [[0, 1], [[1, z] for z in range(1, -2, -1)], [0, -1]]
[[-1, -1], [-1, 0], [-1, 1], [0, 1], [[1, 1], [1, 0], [1, -1]], [0, -1]]
``` | Check out [itertools](https://docs.python.org/2/library/itertools.html). Not sure from your question whether you're going to want `product`, `permutations` or `combinations` but I think one of those will be what you need.
edit: On closer inspection, you're doing something much simpler and you just missed a few brackets. Try:
```
x = [[[-1, y] for y in range(-1, 2)], [0, 1], [[1, z] for z in range(1, -2, -1)], [0, -1]]
```
List comprehensions go in their own set of brackets, it's similar to the syntax of a list literal but not the same.
edit 2:
>
> Before that I did :
>
>
>
> ```
> x = [[-1, y] for y in range(-1, 2),[0, 1]]
> x [[-1, [-1, 0, 1]], [-1, [0, 1]]]
>
> ```
>
> which tells me y is taken as iterator of for loop as well as [0, 1]. I
> am wrongly corelating comma in C and python. How do I achieve what I
> intend to do (in a single line) ? (I know that I could do it directly
> since its a small range. But what if there was a bigger one?)
>
>
>
Yes you're misunderstanding what your comma is doing there. It's turning the 2nd part of your for loop into a tuple of `(range(-1,2), [0, 1])` (2 items). What you needed to do here was close your list comprehension after `range(-1,2)`, and then wrap the whole thing in square brackets to make it a literal list declaration:
`x = [[[-1, y] for y in range(-1, 2)],[0, 1]]`
As mentioned by @YuriyKovalev, it would probably be clearer to concat the lists like so:
`x = [[-1, y] for y in range(-1, 2)] + [0, 1]` |
567,250 | I have a lot of places in my dissertation where the plus sign appears surrounded by capital letters in text, e.g. NNLL+NNLO.
The problem is that by default, the + is aligned so low vertically, that among caps it looks badly aligned.
By playing around with the `\raisebox`, I found that it looks quite a bit better if raised by `0.25ex`, and still looks fine with lowercase letters, even in situations like a+j.
Is there a way to change the default behavior of the plus sign to always appear raised in text?
I don't want to change what happens in the math mode.
I suppose a potential solution might be to globally substitute raw `+` by `\raisebox{0.25ex}{+}` (modulo the issue with space swallowing) or to make latex use a different font for rendering the +.
I just don't know if that's even possible.
---
Reporting on what I implemented based on the answers.
Here's the command I came up with that also accounts for **bold** and allows typesetting of two consecutive raised spaces with `\++`.
```
\makeatletter % https://tex.stackexchange.com/a/31660/35990
\newcommand*{\IfbfTF}{% detect bold font
\ifx\f@series\my@test@bf
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\newcommand*{\my@test@bf}{bx}
\makeatother
% https://tex.stackexchange.com/a/567256/35990
\newcommand{\textplus}[1][+]{\raisebox{% font-independent height
\dimexpr(\fontcharht\font`X-\height+\depth)/2\relax
}{\IfbfTF{$\bm{#1}$}{#1}}}
\ExplSyntaxOn
\NewDocumentCommand\+{}{
\peek_charcode_remove:NTF + {\textplus[++]}{\textplus[+]}
}
\ExplSyntaxOff
```
`\peek_charcode_remove:NTF` requires the `expl3` package. | 2020/10/17 | [
"https://tex.stackexchange.com/questions/567250",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/35990/"
] | I'm not sure that 0.25ex is the right choice: it actually makes the + sign to be slightly higher than a capital letter.
Using different fonts might also make the situation even worse. For instance, with Times you'd get
[](https://i.stack.imgur.com/2cYh9.png)
because here the + sign sits on the baseline. Can we make the raising independent of the font? Yes: a bit of algebra shows that we need to raise the symbol by half the sum of a capital letter, minus the height of + plus the height of +.
Using David's idea:
```
\newcommand{\+}{%
\raisebox{\dimexpr(\fontcharht\font`X-\height+\depth)/2\relax}{+}%
}
```
Here's the output with Times
[](https://i.stack.imgur.com/AvnUT.png)
and with Computer Modern
[](https://i.stack.imgur.com/FOTIB.png)
Here's a visual proof of the statement about the height. The first + is with my definition, the second is raised 0.25ex. Just look at the top, because at the bottom TeX always uses the baseline.
[](https://i.stack.imgur.com/F8wv4.png) | [](https://i.stack.imgur.com/9Yoch.png)
You could make + active and raise itself in text mode and not in math, but something would break, it is quite hard to catch all cases of `\dimexpr \parindent + 5pt\relax` and ensure you don't add a `\raisebox` mid-expression.
I would use a new command for it, `\+` isn't defined by default so:
```
\documentclass{article}
\newcommand\+{\raisebox{0.25ex}{+}}
\begin{document}
NNLL+NNLO
NNLL\+NNLO
\end{document}
``` |
567,250 | I have a lot of places in my dissertation where the plus sign appears surrounded by capital letters in text, e.g. NNLL+NNLO.
The problem is that by default, the + is aligned so low vertically, that among caps it looks badly aligned.
By playing around with the `\raisebox`, I found that it looks quite a bit better if raised by `0.25ex`, and still looks fine with lowercase letters, even in situations like a+j.
Is there a way to change the default behavior of the plus sign to always appear raised in text?
I don't want to change what happens in the math mode.
I suppose a potential solution might be to globally substitute raw `+` by `\raisebox{0.25ex}{+}` (modulo the issue with space swallowing) or to make latex use a different font for rendering the +.
I just don't know if that's even possible.
---
Reporting on what I implemented based on the answers.
Here's the command I came up with that also accounts for **bold** and allows typesetting of two consecutive raised spaces with `\++`.
```
\makeatletter % https://tex.stackexchange.com/a/31660/35990
\newcommand*{\IfbfTF}{% detect bold font
\ifx\f@series\my@test@bf
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\newcommand*{\my@test@bf}{bx}
\makeatother
% https://tex.stackexchange.com/a/567256/35990
\newcommand{\textplus}[1][+]{\raisebox{% font-independent height
\dimexpr(\fontcharht\font`X-\height+\depth)/2\relax
}{\IfbfTF{$\bm{#1}$}{#1}}}
\ExplSyntaxOn
\NewDocumentCommand\+{}{
\peek_charcode_remove:NTF + {\textplus[++]}{\textplus[+]}
}
\ExplSyntaxOff
```
`\peek_charcode_remove:NTF` requires the `expl3` package. | 2020/10/17 | [
"https://tex.stackexchange.com/questions/567250",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/35990/"
] | [](https://i.stack.imgur.com/9Yoch.png)
You could make + active and raise itself in text mode and not in math, but something would break, it is quite hard to catch all cases of `\dimexpr \parindent + 5pt\relax` and ensure you don't add a `\raisebox` mid-expression.
I would use a new command for it, `\+` isn't defined by default so:
```
\documentclass{article}
\newcommand\+{\raisebox{0.25ex}{+}}
\begin{document}
NNLL+NNLO
NNLL\+NNLO
\end{document}
``` | Here my solution for a `+` sign between text letters (inspired in [this answer](https://tex.stackexchange.com/questions/52503/sign-in-international-phone-numbers#52517)). It has following features:
* I offer both a solution for **capital** (`\Plus`) and **lower case** (`\plus`) letters. For the lower case, I recommend to reduce the size.
* I use a different syntax.
[](https://i.stack.imgur.com/ohv9Y.png)
```
\documentclass{article}
\usepackage{calc}
\usepackage{graphicx}
%Plus for lower case
\newlength{\heightofx}
%Plus size is reduced to 60% (0.6)
%and set at the mid height of 'x'
\newcommand{\plus}{\settoheight{\heightofx}{x}%
\raisebox{0.5\heightofx-(0.5\totalheight-\depth)}%
{\scalebox{0.6}{+}}}
%Plus for captitals
\newlength{\heightofX}
%Plus is set at the mid height of 'X'
\newcommand{\Plus}{\settoheight{\heightofX}{X}%
\raisebox{0.5\heightofX-(0.5\totalheight-\depth)}{+}}
\begin{document}
\begin{tabular}{cc}
Adapted & Raw \\
\hline
\\[-0.5em]
LOVE\Plus GRACE & LOVE+GRACE\\
love\plus grace & love+grace
\end{tabular}
\end{document}
``` |
567,250 | I have a lot of places in my dissertation where the plus sign appears surrounded by capital letters in text, e.g. NNLL+NNLO.
The problem is that by default, the + is aligned so low vertically, that among caps it looks badly aligned.
By playing around with the `\raisebox`, I found that it looks quite a bit better if raised by `0.25ex`, and still looks fine with lowercase letters, even in situations like a+j.
Is there a way to change the default behavior of the plus sign to always appear raised in text?
I don't want to change what happens in the math mode.
I suppose a potential solution might be to globally substitute raw `+` by `\raisebox{0.25ex}{+}` (modulo the issue with space swallowing) or to make latex use a different font for rendering the +.
I just don't know if that's even possible.
---
Reporting on what I implemented based on the answers.
Here's the command I came up with that also accounts for **bold** and allows typesetting of two consecutive raised spaces with `\++`.
```
\makeatletter % https://tex.stackexchange.com/a/31660/35990
\newcommand*{\IfbfTF}{% detect bold font
\ifx\f@series\my@test@bf
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\newcommand*{\my@test@bf}{bx}
\makeatother
% https://tex.stackexchange.com/a/567256/35990
\newcommand{\textplus}[1][+]{\raisebox{% font-independent height
\dimexpr(\fontcharht\font`X-\height+\depth)/2\relax
}{\IfbfTF{$\bm{#1}$}{#1}}}
\ExplSyntaxOn
\NewDocumentCommand\+{}{
\peek_charcode_remove:NTF + {\textplus[++]}{\textplus[+]}
}
\ExplSyntaxOff
```
`\peek_charcode_remove:NTF` requires the `expl3` package. | 2020/10/17 | [
"https://tex.stackexchange.com/questions/567250",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/35990/"
] | I'm not sure that 0.25ex is the right choice: it actually makes the + sign to be slightly higher than a capital letter.
Using different fonts might also make the situation even worse. For instance, with Times you'd get
[](https://i.stack.imgur.com/2cYh9.png)
because here the + sign sits on the baseline. Can we make the raising independent of the font? Yes: a bit of algebra shows that we need to raise the symbol by half the sum of a capital letter, minus the height of + plus the height of +.
Using David's idea:
```
\newcommand{\+}{%
\raisebox{\dimexpr(\fontcharht\font`X-\height+\depth)/2\relax}{+}%
}
```
Here's the output with Times
[](https://i.stack.imgur.com/AvnUT.png)
and with Computer Modern
[](https://i.stack.imgur.com/FOTIB.png)
Here's a visual proof of the statement about the height. The first + is with my definition, the second is raised 0.25ex. Just look at the top, because at the bottom TeX always uses the baseline.
[](https://i.stack.imgur.com/F8wv4.png) | Here my solution for a `+` sign between text letters (inspired in [this answer](https://tex.stackexchange.com/questions/52503/sign-in-international-phone-numbers#52517)). It has following features:
* I offer both a solution for **capital** (`\Plus`) and **lower case** (`\plus`) letters. For the lower case, I recommend to reduce the size.
* I use a different syntax.
[](https://i.stack.imgur.com/ohv9Y.png)
```
\documentclass{article}
\usepackage{calc}
\usepackage{graphicx}
%Plus for lower case
\newlength{\heightofx}
%Plus size is reduced to 60% (0.6)
%and set at the mid height of 'x'
\newcommand{\plus}{\settoheight{\heightofx}{x}%
\raisebox{0.5\heightofx-(0.5\totalheight-\depth)}%
{\scalebox{0.6}{+}}}
%Plus for captitals
\newlength{\heightofX}
%Plus is set at the mid height of 'X'
\newcommand{\Plus}{\settoheight{\heightofX}{X}%
\raisebox{0.5\heightofX-(0.5\totalheight-\depth)}{+}}
\begin{document}
\begin{tabular}{cc}
Adapted & Raw \\
\hline
\\[-0.5em]
LOVE\Plus GRACE & LOVE+GRACE\\
love\plus grace & love+grace
\end{tabular}
\end{document}
``` |
158,339 | I have removed Transparent Data Encryption (TDE) from my server, dropped the key and switched the databases to *Simple*, shrunk the log and then back to *Full*.
The LOG backups are now smaller as well as the full backups but the main mdf files are still the same size after removing TDE.
Is this normal? Is there a way to get these back to what they were before TDE?
I know the MDF files will stay the same size until you shrink them but the space available inside I would have expected to increase significantly but it didn't.
TDE seemed to double the size of them. | 2016/12/16 | [
"https://dba.stackexchange.com/questions/158339",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/33758/"
] | Yes this is normal. SQL Server will only automatically reduce the size of data files if you have `AUTO SHRINK` switched on and there is space available in the files. This setting is not recommended as it will introduce considerable fragmentation and consume considerable IO resources.
You could do a one time shrink with `DBCC SHRINKDATABASE`. See [here](https://msdn.microsoft.com/en-gb/library/ms190488.aspx) for more info. This will introduce fragmentation but it can be fixed by rebuilding your indexes.
IMHO the main considerations would be:
* Can you live with the current size of the database? If yes then shrinking is probably not worth the effort.
* Do you have a long enough maintenance window to shrink and fix the fragmentation? You could test this process by restoring a backup to a similar specced machine and running through the process.
Currently shrinking a databse will fail if you have any columnstore indexes. These need to be dropped if you want to shrink the DB as much as possible. | *Answer originally left in a comment*
TDE doesn't always double the data file sizes. It will increase because of the post-encryption data format. but depending on the original data types and sizes, you might have a much bigger (double) or just somewhat bigger data file.
If your data prior to TDE was already not highly compressible and/or was at some size that was close to the ciphertext size, then the expansion would not be as significant (it's never zero expansion).
Rebuild indexes for your large tables to ensure you're at the desired page density. – [SQLmojoe](https://dba.stackexchange.com/users/72965/sqlmojoe) |
1,969,085 | >
> Created by Microsoft as the foundation
> of its .NET technology, the Common
> Language Infrastructure (CLI) is an
> ECMA standard (ECMA-335) that allows
> applications to be written in a
> variety of high-level programming
> languages and executed in different
> *system environments*. Programming languages that conform to the CLI have
> access to the same base class library
> and are capable of being compiled into
> the same intermediate language (IL)
> and metadata. IL is then further
> compiled into native code particular
> to a specific architecture.
>
>
> Because of this intermediate step,
> applications do not have to be
> rewritten from scratch. Their IL only
> needs to be further compiled into a
> system's native code.
>
>
>
What exactly is meant by the **system environments**?
---
Additionally, while studying Ivor Horton's *Beginning Visual C++ 2008*, I noticed that he stated that there are fundamentally different kinds of C++ applications can be developed with Visual C++ 2008. These are:
1. Applications which execute natively on one's computer, which he referred to as **native C++ programs**. Native C++ programs are written in the version of C++ that is defined by the ISO/ANSI language standard.
2. Application can also be written to run under the control of the CLR in an extended version of C++, called C++/CLI. These programs were referred to as **CLR programs**, or **C++/CLI programs**.
So what is meant by native C++ programs and CLR programs? What's the difference between them? Thanks for any expert's help. | 2009/12/28 | [
"https://Stackoverflow.com/questions/1969085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239522/"
] | "System environments" means things like Linux, Windows x86, Windows x64, etc. Notice how they use the term "architecture" interchangeably at the end of the paragraph.
---
A native C++ program is one where you take standard (ANSI/ISO) C++ and you compile it into a .exe. Usually you will be compiling this for a specific environment, e.g. Windows x86, in which case it could not run under Linux and would run under the [WoW64 emulation layer](http://en.wikipedia.org/wiki/WoW64) on Windows x64. Notably, this code runs directly on the machine.
C++/CLI is a different programming language than standard C++. It, just like C# or VB.NET, runs on top of Microsoft's **C**ommon **L**anguage **I**nterface. This means it has access to all those nice things in the paragraph you quoted, like the base class library and compilation to IL which allows it to be run on different architectures. But, just like C# and VB.NET, it does not run natively on the machine. It requires the installation of the .NET Framework; part of the .NET Framework's job is translating C++/CLI programs into native programs, which means they have much less direct access to the machine. | I am getting a bit rusty and cannot recall when exactly the word "native" popped up into the common parlance. I believe it was massively used by designers of environments destined to simplify programming running on the top of other ones designed to offer optimal access to system resources with limited focus on the programming style. Which is one may change with the time, as native also may be referred some assembler code invoked from a high level language used to program an embedded system. This is why I avoid using such concepts as operating system as even CLI/CLR despite the common fad may be implemented on Linux (Mono) or on bare silicon with no OS support (.NET Micro).
In such a context the standard C++ follows the native approach and is quite tolerant on which hardware or OS (or no OS) it runs as long as it is possible to provide a compiler and the standard library for that. The standard C++ code may be easily recompiled for any such platform as far a C++ compiler exists for it.
To be referred as C++/CLI the C++ dialect implementation needs CLI/CLR support and of course a CLI platform being present but the code may be ported without recompilation using CIL and use a standard, sophisticated library and utilities. However the initial requirements are higher than in the case of the standard C++ which can play in this case the role of the native environment. |
20,045,459 | I have 'Strict On' and am getting the error quoted below. Normally, the program breaks and would offer possible ways to correct error, but not in this case. As I am a new user to VB.Net, I need to understand why this error is happening in Strict mode and not when it is turned off.
I would be grateful if someone could show me how to correct this. I have posted the code where this is happening. Many thanks
>
> Option Strict On disallows implicit conversions from 'Date' to
> 'String'
>
>
>
```
ListView1.Items.Add(CDate(dr(4).ToString())).UseItemStyleForSubItems = False
``` | 2013/11/18 | [
"https://Stackoverflow.com/questions/20045459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532468/"
] | [`ListViewItemCollection.Add`](http://msdn.microsoft.com/en-us/library/ttzhk9y3%28v=vs.110%29.aspx) has no overload that takes a `Date` but one for `String` and one for `ListVieItem`. But you are passing a `Date` which is not convertible to string implicitely. If you want to show the short date pattern you could use `ToShortDateString`:
```
ListView1.Items.Add(dr.GetDateTime(4).ToShortDateString()).UseItemStyleForSubItems = False
```
Note that i've also used `DataReader.GetdateTime`. If it's a `Date` you don't need to convert it to `String` at all. That is inefficient, less readable and could cause localization issues. | Try change it to this.
>
> ListView1.Items.Add(CDate(dr(4)).ToString()).UseItemStyleForSubItems =
> False
>
>
> |
68,500,490 | here's my table data
| firstname | lastname |
| --- | --- |
| boy | 5 |
| boy | 55 |
| boy | 6 |
| boy | 7 |
here's my codes inside a search function
```
$search = $request->search;
$users = \DB::table('users')
->where(function($query) use ($search){
$query->where('firstname', 'like', '%'.$search.'%');
$query->orWhere('lastname', 'like', '%'.$search.'%');
$query->orWhereRaw(" concat(firstname, ' ', lastname) like '%?%' ", [$search]);
$query->orWhere('email', 'like', '%'.$search.'%');
})
->orderBy('firstname', 'asc')
->limit(20)
->get();
```
type in boy to press search, a bunch of matching result on firstname will return
type in 5 to press search, both the 5 and 55 row data will return
type in the full name "boy 5" to press search, no result return.
from my research, using orWhereRaw with concat and binding in this way should be getting result.
however, things doesn't work.
is there anything wrong ? btw, am running this in laravel 7. | 2021/07/23 | [
"https://Stackoverflow.com/questions/68500490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133392/"
] | Replace
```
$query->orWhereRaw(" concat(firstname, ' ', lastname) like '%?%' ", [$search])
```
With
```
$query->orWhereRaw("concat(firstname, ' ', lastname) like ?", ['%'.$search.'%'])
``` | check out the below example and adjust your query function accordingly
```
//what is provided from search bar
$query = $request->input('query');
//db tbl that gets queried
$spa = spa::latest()->where('spa_name', 'LIKE', '%'.$query.'%')
->orwhere('more_details','LIKE', '%'.$query.'%')->get();
``` |
48,802,463 | I have a non-linear minimization problem that takes a combination of continuous and binary variables as input. Think of it as a network flow problem with valves, for which the throughput can be controlled, and with pumps, for which you can change the direction.
A "natural," minimalistic formulation could be:
```
arg( min( f(x1,y2,y3) )) s.t.
x1 \in [0,1] //a continuous variable
y2,y3 \in {0,1} //two binary variables
```
The objective function is deterministic, but expensive to solve. If I leave away the binary variables, Scipy's differential evolution algorithm turns out to be a useful solution approach for my problem (converging faster than basin hopping).
There is some evidence available already [with regard to the inclusion of integer variables in a differential evolution-based minimization problem](https://stackoverflow.com/questions/35494782/scipy-differential-evolution-with-integers/37484060#comment84605680_37484060). The suggested approaches turn y2,y3 into continuous variables x2,x3 \in [0,1], and then modify the objective function as follows:
```
(i) f(x1, round(x2), round(x3))
(ii) f(x1,x2,x3) + K( (x2-round(x2))^2 + (x3-round(x3))^2 )
with K a tuning parameter
```
A third, and probably naive approach would be to combine the binary variables into a single continuous variable z \in [0,1], and thereby to reduce the number of optimization variables.
For instance,
```
if z<0.25: y2=y3=0
elif z<0.5: y2=1, y3=0
elif z<0.75: y2=0, y3=1
else: y2=y3=1.
```
Which one of the above should be preferred, and why? I'd be very curious to hear how binary variables can be integrated in a continuous differential evolution algorithm (such as Scipy's) in a smart way.
PS. I'm aware that there's some literature available that proposes dedicated mixed-integer evolutionary algorithms. For now, I'd like to stay with Scipy. | 2018/02/15 | [
"https://Stackoverflow.com/questions/48802463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2918960/"
] | As Martin Smith suggested, you just need to use a string splitting function and `join` the results together:
```
declare @NameList nvarchar(100) = 'Hi|Hi1|Hi2';
declare @DESCLIST nvarchar(100) = 'Hii|Hii1|Hii2';
declare @SEQList nvarchar(100) = '1|2|3';
select s1.item as Name
,s2.item as [Desc]
,s3.item as Seq
from dbo.fn_StringSplit(@NameList,'|',null) as s1
join dbo.fn_StringSplit(@DESCLIST,'|',null) as s2
on s1.rn = s2.rn
join dbo.fn_StringSplit(@SEQList,'|',null) as s3
on s1.rn = s3.rn;
```
Results:
```
+------+------+------+-----+
| pkid | Name | Desc | Seq |
+------+------+------+-----+
| 1 | Hi | Hii | 1 |
| 2 | Hi1 | Hii1 | 2 |
| 3 | Hi2 | Hii2 | 3 |
+------+------+------+-----+
```
---
String Split Function:
```
create function [dbo].[fn_StringSplit]
(
@str nvarchar(max) = ' ' -- String to split.
,@delimiter as nvarchar(255) = ',' -- Delimiting value to split on.
,@num as int = null -- Which value to return, null returns all.
)
returns table
as
return
(
with d as
(
select rn = row_number() over (order by (select null))
,item = y.i.value('(./text())[1]', 'nvarchar(max)')
from(select x = convert(xml, '<i>'
+ replace((select @str for xml path('')), @delimiter, '</i><i>')
+ '</i>'
).query('.')
) AS a
cross apply x.nodes('i') AS y(i)
)
select rn
,item
from d
where rn = @num
or @num is null
);
``` | I would use the function:
```
STRING_SPLIT (string, separator)
```
with table values that divides a string into rows of substrings, according to a specified separator character and would return the records by assigning them an id through the Row\_number function that returns a sequential number to each row within a partition of a result set:
```
DECLARE @NameList VARCHAR(50) = 'Hi|Hi1|Hi2'
DECLARE @DESCLIST VARCHAR(50) = 'Hii|Hii1|Hii2'
DECLARE @SEQList VARCHAR(50) = '1|2|3'
select namelist.name,DESCLIST.descr, SEQList.SEQ from
(select value as name ,row_number() over (order by (select null)) as id from STRING_SPLIT(@NameList,'|') )
namelist inner join
(select value as descr ,row_number() over (order by (select null)) as id from STRING_SPLIT(@DESCLIST,'|') )
DESCLIST on namelist.id = DESCLIST.id inner join
(select value as SEQ ,row_number() over (order by (select null)) as id from STRING_SPLIT(@SEQList,'|'))
SEQList on DESCLIST.id = SEQList.id
``` |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | For **Django 2**:
```
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
```
That middleware must be added to `settings.MIDDLEWARE` when appropriate (in your test settings for example).
*Note: the setting isn't not called `MIDDLEWARE_CLASSES` anymore.* | Before using this solution, please read [this link from documentation](https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps)
-------------------------------------------------------------------------------------------------------------------------------------------------
---
I solved this problem with the following two steps:
1. Add this class to an `utils.py` file:
```py
from <your-project-name> import settings
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
```
2. And in the `settings.py` file, add above middleware to the `MIDDLEWARE` list:
```py
...
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
'<path-of-utils.py>.utils.DisableCSRF',
]
...
``` |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | The answer might be inappropriate, but I hope it helps you
```
class DisableCSRFOnDebug(object):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
```
Having middleware like this helps to debug requests and to check csrf in production servers. | Before using this solution, please read [this link from documentation](https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps)
-------------------------------------------------------------------------------------------------------------------------------------------------
---
I solved this problem with the following two steps:
1. Add this class to an `utils.py` file:
```py
from <your-project-name> import settings
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
```
2. And in the `settings.py` file, add above middleware to the `MIDDLEWARE` list:
```py
...
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
'<path-of-utils.py>.utils.DisableCSRF',
]
...
``` |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | To disable CSRF for class-based views, the following worked for me.
I'm using Django 1.10 and Python 3.5.2
```
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
``` | Before using this solution, please read [this link from documentation](https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps)
-------------------------------------------------------------------------------------------------------------------------------------------------
---
I solved this problem with the following two steps:
1. Add this class to an `utils.py` file:
```py
from <your-project-name> import settings
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
```
2. And in the `settings.py` file, add above middleware to the `MIDDLEWARE` list:
```py
...
MIDDLEWARE = [
...
'django.middleware.csrf.CsrfViewMiddleware',
...
'<path-of-utils.py>.utils.DisableCSRF',
]
...
``` |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | To disable CSRF for class-based views, the following worked for me.
I'm using Django 1.10 and Python 3.5.2
```
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
``` | The problem here is that SessionAuthentication performs its own CSRF validation. That is why you get the CSRF missing error even when the CSRF Middleware is commented.
You could add @csrf\_exempt to every view, but if you want to disable CSRF and have session authentication for the whole app, you can add an extra middleware like this -
```
class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
response = self.get_response(request)
return response
```
I created this class in myapp/middle.py
Then import this middleware in Middleware in settings.py
```
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'myapp.middle.DisableCSRFMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```
That works with DRF on django 1.11 |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | If you just need some views not to use CSRF, you can use `@csrf_exempt`:
```
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
return HttpResponse('Hello world')
```
You can find more examples and other scenarios in the Django documentation:
* <https://docs.djangoproject.com/en/dev/ref/csrf/#edge-cases> | If you want disable it in Global, you can write a custom middleware, like this
```
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
```
then add this class `youappname.middlewarefilename.DisableCsrfCheck` to `MIDDLEWARE_CLASSES` lists, before `django.middleware.csrf.CsrfViewMiddleware` |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | To disable CSRF for class-based views, the following worked for me.
I'm using Django 1.10 and Python 3.5.2
```
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
def post(self, request, *args, **kwargs):
return HttpResponse('Hello world')
``` | For **Django 2**:
```
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
```
That middleware must be added to `settings.MIDDLEWARE` when appropriate (in your test settings for example).
*Note: the setting isn't not called `MIDDLEWARE_CLASSES` anymore.* |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | For **Django 2**:
```
from django.utils.deprecation import MiddlewareMixin
class DisableCSRF(MiddlewareMixin):
def process_request(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
```
That middleware must be added to `settings.MIDDLEWARE` when appropriate (in your test settings for example).
*Note: the setting isn't not called `MIDDLEWARE_CLASSES` anymore.* | CSRF can be enforced at the view level, which **can't be disabled globally**.
In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.
<https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps> |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | In `setting.py` in MIDDLEWARE you can simply remove/comment this line:
```
'django.middleware.csrf.CsrfViewMiddleware',
``` | The answer might be inappropriate, but I hope it helps you
```
class DisableCSRFOnDebug(object):
def process_request(self, request):
if settings.DEBUG:
setattr(request, '_dont_enforce_csrf_checks', True)
```
Having middleware like this helps to debug requests and to check csrf in production servers. |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | The problem here is that SessionAuthentication performs its own CSRF validation. That is why you get the CSRF missing error even when the CSRF Middleware is commented.
You could add @csrf\_exempt to every view, but if you want to disable CSRF and have session authentication for the whole app, you can add an extra middleware like this -
```
class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
response = self.get_response(request)
return response
```
I created this class in myapp/middle.py
Then import this middleware in Middleware in settings.py
```
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'myapp.middle.DisableCSRFMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```
That works with DRF on django 1.11 | CSRF can be enforced at the view level, which **can't be disabled globally**.
In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.
<https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps> |
16,458,166 | I have commented out csrf processor and middleware lines in `settings.py`:
```
122
123 TEMPLATE_CONTEXT_PROCESSORS = (
124 'django.contrib.auth.context_processors.auth',
125 # 'django.core.context_processors.csrf',
126 'django.core.context_processors.request',
127 'django.core.context_processors.static',
128 'cyathea.processors.static',
129 )
130
131 MIDDLEWARE_CLASSES = (
132 'django.middleware.common.CommonMiddleware',
133 'django.contrib.sessions.middleware.SessionMiddleware',
134 # 'django.middleware.csrf.CsrfViewMiddleware',
135 'django.contrib.auth.middleware.AuthenticationMiddleware',
136 'django.contrib.messages.middleware.MessageMiddleware',
137 'django.middleware.locale.LocaleMiddleware',
138 # Uncomment the next line for simple clickjacking protection:
139 # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
140 )
```
But when I use Ajax to send a request, Django still respond 'csrf token is incorrect or missing', and after adding X-CSRFToken to headers, the request would succeed.
What is going on here ? | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802585/"
] | The problem here is that SessionAuthentication performs its own CSRF validation. That is why you get the CSRF missing error even when the CSRF Middleware is commented.
You could add @csrf\_exempt to every view, but if you want to disable CSRF and have session authentication for the whole app, you can add an extra middleware like this -
```
class DisableCSRFMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
setattr(request, '_dont_enforce_csrf_checks', True)
response = self.get_response(request)
return response
```
I created this class in myapp/middle.py
Then import this middleware in Middleware in settings.py
```
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'myapp.middle.DisableCSRFMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
```
That works with DRF on django 1.11 | If you want disable it in Global, you can write a custom middleware, like this
```
from django.utils.deprecation import MiddlewareMixin
class DisableCsrfCheck(MiddlewareMixin):
def process_request(self, req):
attr = '_dont_enforce_csrf_checks'
if not getattr(req, attr, False):
setattr(req, attr, True)
```
then add this class `youappname.middlewarefilename.DisableCsrfCheck` to `MIDDLEWARE_CLASSES` lists, before `django.middleware.csrf.CsrfViewMiddleware` |
11,138 | In many germanic languages you change the word order if you want it to be a question.
Statement: You are tired.
Question: Are you tired?
If I put “Are” at the beginning it becomes a question.
*Sei un po' stanco?* in Italian means “Are you tired?” but it also sounds like a statement.
In Italian you cannot simply change the word order in order to make it a question. How do Italians then ask questions? By adding a question mark in texts and changing the pitch in speech?
I could write: “You are tired?” But it sounds a bit weird in English unless you were surprised that the person was tired.
Is this how you ask questions in Italian? | 2019/10/14 | [
"https://italian.stackexchange.com/questions/11138",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/-1/"
] | >
> How do Italians then ask questions? By adding a question mark in texts and changing the pitch in speech?
>
>
>
That's exactly how you do it, for questions implying a yes/no answer. | That's correct; it's explained on the [Wikipedia page on Italian grammar](https://en.wikipedia.org/wiki/Italian_grammar#Syntax):
>
> Questions are formed by a rising intonation at the end of the sentence (in written form, a question mark). There is usually no other special marker, although [wh-movement](https://en.wikipedia.org/wiki/Wh-movement) does usually occur. In general, intonation and context are important to recognize questions from affirmative statements.
>
>
> * *Davide è arrivato in ufficio.* (David has arrived at the office.)
> * *Davide è arrivato in ufficio?* ("Talking about David… did he arrived at the office?" or "Davide has arrived at the office? Really?" - depending on the intonation)
> * *Perché Davide è arrivato in ufficio?* (Why has David arrived at the office?)
> * *Perché Davide è arrivato in ufficio.* (Because David has arrived at the office.)
> * *È arrivato Davide in ufficio.* ("It was **David** who arrived at the office" or "David **arrived** at the office" - depending on the intonation)
> * *È arrivato Davide in ufficio?* (Has David arrived at the office?)
> * *È arrivato in ufficio.* (He has arrived at the office.)
> * *(Lui) è arrivato in ufficio.* (**He** has arrived at the office.)
> * *Chi è arrivato in ufficio?* (Who has arrived at the office?)
>
>
> |
632,593 | From Newton’s second law, $F=ma$, a massless object will always have zero net force. So can a massless pulley accelerate? | 2021/04/28 | [
"https://physics.stackexchange.com/questions/632593",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/297131/"
] | Yes.
As an example from life, consider a transformer. When the primary current is zero, there is no current in the secondary circuit too. All the electrons are stationary (from a classical perspective). After you have started the primary current, the magnetic field in the core will change. This leads to an electrical field in the secondary circuit and electrons moving due to an electrical force acting on them.
[](https://i.stack.imgur.com/CPxSy.jpg) | >
> Will a stationary charge be affected by changing magnetic field?
>
>
>
Yes. The force on a charge by an electro-magnetic field is called the Lorentz force, and is given by the equation
$$\vec{F} = q(\vec{E} + (\vec{v} \times \vec{B}))$$
Where
* $q$ is the charge
* $\vec{E}$ is the electric field
* $\vec{v}$ is the velocity of the charge
* $\vec{B}$ is the magnetic field
Since you have specified that the charge is stationary, the force becomes
$$\vec{F} = q\vec{E}$$
Since the question asks about an electric field induced by a changing magnetic field, the electric field $\vec{E}$ is a solution to the equations
$$\nabla \times \vec{E} = -\frac{\partial \vec{B}}{\partial t}$$
$$\nabla \cdot \vec{E} = 0$$ |
48,508,820 | I am building a system for writing code about people who take pictures of birds (the real system isn't actually about that, I use birds here to replace the business logic that I can't post). I'm having trouble keeping my code type safe while also enforcing all of the relationships I want and avoiding the code becoming super messy. Here's what I have.
There are three types of birds
```
public interface BirdType {}
public class BlueJay implements BirdType {}
public class Cardinal implements BirdType {}
public class Canary implements BirdType {}
```
For each type of bird, there's a type of camera specialized in taking pictures of that bird, and a special bird call which attracts birds of that type.
```
public interface BirdCamera<BT extends BirdType> {}
public interface BirdCall<BT extends BirdType> {}
public class BlueJayCamera implements BirdCamera<BlueJay> {}
public class CardinalCamera implements BirdCamera<Cardinal> {}
public class CanaryCamera implements BirdCamera<Canary> {}
public class BlueJayCall implements BirdCall<BlueJay> {}
public class CardinalCall implements BirdCall<Cardinal> {}
public class CanaryCall implements BirdCall<Canary> {}
```
These parts are combined in the Photographer interface, which enforces a relationship between the parts of a photographer for its implementers.
```
public interface Photographer
<BT extends BirdType,
CAM extends BirdCamera<BT>,
CAL extends BirdCall<BT>>
{
CAM getPhotographersCamera();
CAL getPhotographersBirdCall();
void examineCamera(CAM camera);
}
```
and it is implemented by three classes like this, one for each bird:
```
public class BlueJayPhotographer implements Photographer<BlueJay, BlueJayCamera, BlueJayCall> {
@Override
public BlueJayCamera getPhotographersCamera() {
//Do bluejay specific logic
return new BlueJayCamera();
}
@Override
public BlueJayCall getPhotographersBirdCall() {
//Do bluejay specific logic
return new BlueJayCall();
}
@Override
public void examineCamera(BlueJayCamera camera) {
//Do bluejay specific logic
}
}
```
One desirable thing about this is that it prevents future mistakes by other developers. Someone else can't later create
```
public class ConfusedPhotographer implements Photographer<BlueJay, CardinalCamera, CanaryCall>
```
because the constraints in Photographer prevent it.
When a class wants to use a photographer, they invoke the PhotographerProvider
```
public class PhotographerProvider {
public Photographer get(int birdCode) {
if (birdCode == 0) {
return new BlueJayPhotographer();
}
else if (birdCode == 1) {
return new CardinalPhotographer();
}
else if (birdCode == 2) {
return new CanaryPhotographer();
}
else {
throw new IllegalArgumentException("Unsupported bird code: " + birdCode);
}
}
}
```
One such class that needs to use photographers in many of its methods is the NationalPark, one of the core classes of my application. Here's an example NationalPark method:
```
public void importantMethod(PhotographerProvider photographerProvider) {
// blah blah logic goes here
int mostCommonBirdType = 1;
Photographer typicalTourist = photographerProvider.get(mostCommonBirdType);
BirdCamera cam = typicalTourist.getPhotographersCamera();
typicalTourist.examineCamera(cam);
// blah blah more logic here
}
```
The compiler doesn't like the last line of that method, and produces a warning:
Unchecked call to 'examineCamera(CAM)' as a member of raw type 'birdexample.Photographer'
I don't want this warning, but I can't find a way to fix it that doesn't cause an error someplace else... I'd also like to avoid making a gigantic mess where every class in my entire program has to be paramaterized with a bird type, camera, and call. How can I do this (short of just suppressing/ignoring the warning)? | 2018/01/29 | [
"https://Stackoverflow.com/questions/48508820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5848944/"
] | Your specific example can be done without warnings as follows:
```
Photographer<?, ?, ?> typicalTourist = photographerProvider.get(mostCommonBirdType);
foo(typicalTourist);
<BT extends BirdType,
CAM extends BirdCamera<BT>> void foo(Photographer<BT, CAM, ?> typicalTourist) {
CAM cam = typicalTourist.getPhotographersCamera();
typicalTourist.examineCamera(cam);
}
```
But I would caution about your design. Honestly, anything more than 1 type variable is pretty unwieldy. 2 is tolerable for cases like maps, but 3 is just getting a bit crazy - you end up filling half your line with the type declaration. *6* (the number you say you have in the real code) is thoroughly into the territory of hating yourself, hating your colleagues, or both.
Think carefully if you really need these generics - you might save a lot of eye strain if you can get rid of them. | In addition to [Andy's answer](https://stackoverflow.com/a/48509029/7294647), your `PhotographerProvider#get` method issues a compiler warning due to its raw return type `Photographer`. To fix that, you can use the following:
```
public class PhotographerProvider {
public Photographer<?, ?, ?> get(int birdCode) {
if (birdCode == 0) {
return new BlueJayPhotographer();
} else if (birdCode == 1) {
return new CardinalPhotographer();
} else if (birdCode == 2) {
return new CanaryPhotographer();
} else {
throw new IllegalArgumentException("Unsupported bird code: " + birdCode);
}
}
}
``` |
48,508,820 | I am building a system for writing code about people who take pictures of birds (the real system isn't actually about that, I use birds here to replace the business logic that I can't post). I'm having trouble keeping my code type safe while also enforcing all of the relationships I want and avoiding the code becoming super messy. Here's what I have.
There are three types of birds
```
public interface BirdType {}
public class BlueJay implements BirdType {}
public class Cardinal implements BirdType {}
public class Canary implements BirdType {}
```
For each type of bird, there's a type of camera specialized in taking pictures of that bird, and a special bird call which attracts birds of that type.
```
public interface BirdCamera<BT extends BirdType> {}
public interface BirdCall<BT extends BirdType> {}
public class BlueJayCamera implements BirdCamera<BlueJay> {}
public class CardinalCamera implements BirdCamera<Cardinal> {}
public class CanaryCamera implements BirdCamera<Canary> {}
public class BlueJayCall implements BirdCall<BlueJay> {}
public class CardinalCall implements BirdCall<Cardinal> {}
public class CanaryCall implements BirdCall<Canary> {}
```
These parts are combined in the Photographer interface, which enforces a relationship between the parts of a photographer for its implementers.
```
public interface Photographer
<BT extends BirdType,
CAM extends BirdCamera<BT>,
CAL extends BirdCall<BT>>
{
CAM getPhotographersCamera();
CAL getPhotographersBirdCall();
void examineCamera(CAM camera);
}
```
and it is implemented by three classes like this, one for each bird:
```
public class BlueJayPhotographer implements Photographer<BlueJay, BlueJayCamera, BlueJayCall> {
@Override
public BlueJayCamera getPhotographersCamera() {
//Do bluejay specific logic
return new BlueJayCamera();
}
@Override
public BlueJayCall getPhotographersBirdCall() {
//Do bluejay specific logic
return new BlueJayCall();
}
@Override
public void examineCamera(BlueJayCamera camera) {
//Do bluejay specific logic
}
}
```
One desirable thing about this is that it prevents future mistakes by other developers. Someone else can't later create
```
public class ConfusedPhotographer implements Photographer<BlueJay, CardinalCamera, CanaryCall>
```
because the constraints in Photographer prevent it.
When a class wants to use a photographer, they invoke the PhotographerProvider
```
public class PhotographerProvider {
public Photographer get(int birdCode) {
if (birdCode == 0) {
return new BlueJayPhotographer();
}
else if (birdCode == 1) {
return new CardinalPhotographer();
}
else if (birdCode == 2) {
return new CanaryPhotographer();
}
else {
throw new IllegalArgumentException("Unsupported bird code: " + birdCode);
}
}
}
```
One such class that needs to use photographers in many of its methods is the NationalPark, one of the core classes of my application. Here's an example NationalPark method:
```
public void importantMethod(PhotographerProvider photographerProvider) {
// blah blah logic goes here
int mostCommonBirdType = 1;
Photographer typicalTourist = photographerProvider.get(mostCommonBirdType);
BirdCamera cam = typicalTourist.getPhotographersCamera();
typicalTourist.examineCamera(cam);
// blah blah more logic here
}
```
The compiler doesn't like the last line of that method, and produces a warning:
Unchecked call to 'examineCamera(CAM)' as a member of raw type 'birdexample.Photographer'
I don't want this warning, but I can't find a way to fix it that doesn't cause an error someplace else... I'd also like to avoid making a gigantic mess where every class in my entire program has to be paramaterized with a bird type, camera, and call. How can I do this (short of just suppressing/ignoring the warning)? | 2018/01/29 | [
"https://Stackoverflow.com/questions/48508820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5848944/"
] | Your specific example can be done without warnings as follows:
```
Photographer<?, ?, ?> typicalTourist = photographerProvider.get(mostCommonBirdType);
foo(typicalTourist);
<BT extends BirdType,
CAM extends BirdCamera<BT>> void foo(Photographer<BT, CAM, ?> typicalTourist) {
CAM cam = typicalTourist.getPhotographersCamera();
typicalTourist.examineCamera(cam);
}
```
But I would caution about your design. Honestly, anything more than 1 type variable is pretty unwieldy. 2 is tolerable for cases like maps, but 3 is just getting a bit crazy - you end up filling half your line with the type declaration. *6* (the number you say you have in the real code) is thoroughly into the territory of hating yourself, hating your colleagues, or both.
Think carefully if you really need these generics - you might save a lot of eye strain if you can get rid of them. | Your method PhotographerProvider.get return a raw Photographer of unknow type of camera and birds:
```
public Photographer get(int birdCode) {
[...]
}
```
you could instead write something like
```
public <BT extends BirdType, CAM extends BirdCamera<BT>, CAL extends BirdCall<BT>> Photographer<BT, CAM, CALL> get(int birdCode) {
[...]
}
```
So you get type safety. The problem is that at least with recent version of java you could choose any BT type when calling the get method and it would be same for the compiler.
In fact all this system doesn't bring you much type safety. For example you instanciate the right type actually with an integer. And when one use a photographer he has no idea of the bird type or camera so he doen't really benefit of all of this.
The only place where it provide an added value is that a photographer of given BT type has to use a Camera and all of a given type... but you could as well do it with only BT as parametrzed type:
```
public interface Photographer<BT extends BirdType>
{
BirdCamera<BT> getPhotographersCamera();
BirdCall<BT> getPhotographersBirdCall();
void examineCamera(BirdCamera<BT> camera);
}
```
And you get method would directly get a BirdType:
```
public <BT extends BirdType> Photographer<BT> get(BT birdType) {
[...]
}
``` |
58,008,297 | I wrote a project using CMake (with ninja and Visual Studio 2017 C++ compiler), with two modules `lib_A` and `lib_B`
* `lib_B` depends one `lib_A`.
* Both `lib_B` and `lib_A` define `std::vector < size_t >`.
Finally, the compiler told me: `LNK2005 lib_A: std::vector < size_t > already defined in lib_B`
I searched answers, and they gave the solution to add link flag `/FORCE:MULTIPLE`, [page1](https://stackoverflow.com/questions/25043458/does-cmake-have-something-like-target-link-options) and [page2](https://stackoverflow.com/questions/11783932/how-do-i-add-a-linker-or-compile-flag-in-a-cmake-file).
I tried all these, but none of them work.
---
1. Use `target_link_libraries`
* with `target_link_libraries(lib_B lib_A INTERFACE "/FORCE:MULTIPLE")`
* compiler tells me `The INTERFACE, PUBLIC or PRIVATE option must appear as the second argument, just after the target name.`
* with `target_link_libraries(lib_B INTERFACE "/FORCE:MULTIPLE" lib_A )`
* compiler tells me `ninja: error: '/FORCE:MULTIPLE', needed by 'lib_B', missing and no known rule to make it`
---
2. Use `CMAKE_EXE_LINKER_FLAGS`
* with`set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} "/FORCE:MULTIPLE")`
* compile tells me `LINK : warning LNK4012: value “x64;/FORCE:MULTIPLE” is invalid, must be one of "ARM, EBC, HYBRID_X86_ARM64X64, or X86" omit this option"`
---
3. Use `set_target_properties`
with CMake code
```
get_target_property(TEMP lib_B COMPILE_FLAGS)
if(TEMP STREQUAL "TEMP-NOTFOUND")
SET(TEMP "") # Set to empty string
else()
SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
endif()
# Append our values
SET(TEMP "${TEMP} /FORCE:MULTIPLE" )
set_target_properties(lib_B PROPERTIES COMPILE_FLAGS ${TEMP} )
```
The compiler tells me `cl: command line error D8021 : invalid parameter "/FORCE:MULTIPLE"`
---
If I change `/FORCE:MULTIPLE` to `-Wl,--allow-multiple-definition`, compiler tells me similar result.
Could anyone help me?
Does add link flag with any error? | 2019/09/19 | [
"https://Stackoverflow.com/questions/58008297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287343/"
] | You can use [target\_link\_options](https://cmake.org/cmake/help/latest/command/target_link_options.html) in CMake ≥ 3.13 or [set\_target\_properties](https://cmake.org/cmake/help/latest/command/set_target_properties.html) with the `LINK_FLAGS` property before.
i.e. `target_link_options(${PROJECT_NAME} PUBLIC $<$<CXX_COMPILER_ID:MSVC>:/FORCE:MULTIPLE>)`
This also uses [generator expressions](https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html) to only apply the flag for MSVC.
But it seems like both your libraries are shared (DLL), but you are statically linking the runtime to both.
I don’t think that that’s a good idea.
Try either linking to the runtime dynamically for both libs if you want to dynamically link to them, or use the static runtime but build both libraries as static library too. | Adding the following line worked for me:
```
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /FORCE:MULTIPLE")
``` |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | To really understand the internals of the HTTP protocol you could use [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) class:
```
using (var client = new TcpClient("www.google.com", 80))
{
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.AutoFlush = true;
// Send request headers
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("Host: www.google.com:80");
writer.WriteLine("Connection: close");
writer.WriteLine();
writer.WriteLine();
// Read the response from server
Console.WriteLine(reader.ReadToEnd());
}
}
```
Another possibility is to [activate tracing](http://msdn.microsoft.com/en-us/library/ty48b824.aspx) by putting the following into your `app.config` and just use [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) to perform an HTTP request:
```
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="protocolonly">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log" />
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
```
Then you can perform an HTTP call:
```
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}
```
And finally analyze the network traffic in the generated `network.log` file. `WebClient` will also follow HTTP redirects. | Use the [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx) or [WebResponse](http://msdn.microsoft.com/en-us/library/system.net.webresponse.aspx) classes, as required.
If you need to go lower level than these provide, look at the other System.Net.Sockets.\*Client classes such as [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx). |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | Use the [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx) or [WebResponse](http://msdn.microsoft.com/en-us/library/system.net.webresponse.aspx) classes, as required.
If you need to go lower level than these provide, look at the other System.Net.Sockets.\*Client classes such as [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx). | Use [WFetch](http://www.microsoft.com/downloads/details.aspx?FamilyID=b134a806-d50e-4664-8348-da5c17129210) for the demonstration.
As for programming, [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) lets you control quite a bit about the request - again if it's for a demonstration I'd use [Wireshark](http://www.wireshark.org/) to sniff what's going over the wire when you do various tasks with the HttpWebRequest |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | To really understand the internals of the HTTP protocol you could use [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) class:
```
using (var client = new TcpClient("www.google.com", 80))
{
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.AutoFlush = true;
// Send request headers
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("Host: www.google.com:80");
writer.WriteLine("Connection: close");
writer.WriteLine();
writer.WriteLine();
// Read the response from server
Console.WriteLine(reader.ReadToEnd());
}
}
```
Another possibility is to [activate tracing](http://msdn.microsoft.com/en-us/library/ty48b824.aspx) by putting the following into your `app.config` and just use [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) to perform an HTTP request:
```
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="protocolonly">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log" />
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
```
Then you can perform an HTTP call:
```
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}
```
And finally analyze the network traffic in the generated `network.log` file. `WebClient` will also follow HTTP redirects. | Check out [`System.Net.Sockets.TcpClient`](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) if you want to write your own low level client. For HTTP GET's and POST's you can use the [`HttpWebRequest`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) and [`HttpWebResponse`](http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx) classes though.
If you are really masochistic you could go lower than `TcpClient` and implement your own `Socket`, see the [Socket class](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx). |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | Check out [`System.Net.Sockets.TcpClient`](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) if you want to write your own low level client. For HTTP GET's and POST's you can use the [`HttpWebRequest`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) and [`HttpWebResponse`](http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx) classes though.
If you are really masochistic you could go lower than `TcpClient` and implement your own `Socket`, see the [Socket class](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx). | Use [WFetch](http://www.microsoft.com/downloads/details.aspx?FamilyID=b134a806-d50e-4664-8348-da5c17129210) for the demonstration.
As for programming, [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) lets you control quite a bit about the request - again if it's for a demonstration I'd use [Wireshark](http://www.wireshark.org/) to sniff what's going over the wire when you do various tasks with the HttpWebRequest |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | To really understand the internals of the HTTP protocol you could use [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) class:
```
using (var client = new TcpClient("www.google.com", 80))
{
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.AutoFlush = true;
// Send request headers
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("Host: www.google.com:80");
writer.WriteLine("Connection: close");
writer.WriteLine();
writer.WriteLine();
// Read the response from server
Console.WriteLine(reader.ReadToEnd());
}
}
```
Another possibility is to [activate tracing](http://msdn.microsoft.com/en-us/library/ty48b824.aspx) by putting the following into your `app.config` and just use [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) to perform an HTTP request:
```
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="protocolonly">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log" />
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
```
Then you can perform an HTTP call:
```
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}
```
And finally analyze the network traffic in the generated `network.log` file. `WebClient` will also follow HTTP redirects. | In my response to this SO post [SharePoint 2007, how to check if a folder exists in a document library](https://stackoverflow.com/questions/1948552/2005855#2005855) I have included the basics of creating HttpWebRequest and reading response.
Edit: added a code example from the post above
```
System.Net.HttpWebRequest oReq;
string sUrl = "http://yoursite/sites/somesite/DocumentLibrary";
oReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl);
oReq.Method = "GET";
oReq.Credentials = System.Net.CredentialCache.DefaultCredentials;
oReq.AllowAutoRedirect = true;
//now send the request
using (System.IO.StreamWriter oRequest =
new System.IO.StreamWriter(oReq.GetRequestStream())) {
oRequest.WriteLine();
}
//and read all the response
using (System.Net.HttpWebResponse oResponse = oReq.GetResponse()){
using (System.IO.StreamReader oResponseReader =
new System.IO.StreamReader(oResponse.GetResponseStream())){
string sResponse = oResponseReader.ReadToEnd();
}
}
``` |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | In my response to this SO post [SharePoint 2007, how to check if a folder exists in a document library](https://stackoverflow.com/questions/1948552/2005855#2005855) I have included the basics of creating HttpWebRequest and reading response.
Edit: added a code example from the post above
```
System.Net.HttpWebRequest oReq;
string sUrl = "http://yoursite/sites/somesite/DocumentLibrary";
oReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl);
oReq.Method = "GET";
oReq.Credentials = System.Net.CredentialCache.DefaultCredentials;
oReq.AllowAutoRedirect = true;
//now send the request
using (System.IO.StreamWriter oRequest =
new System.IO.StreamWriter(oReq.GetRequestStream())) {
oRequest.WriteLine();
}
//and read all the response
using (System.Net.HttpWebResponse oResponse = oReq.GetResponse()){
using (System.IO.StreamReader oResponseReader =
new System.IO.StreamReader(oResponse.GetResponseStream())){
string sResponse = oResponseReader.ReadToEnd();
}
}
``` | Use [WFetch](http://www.microsoft.com/downloads/details.aspx?FamilyID=b134a806-d50e-4664-8348-da5c17129210) for the demonstration.
As for programming, [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) lets you control quite a bit about the request - again if it's for a demonstration I'd use [Wireshark](http://www.wireshark.org/) to sniff what's going over the wire when you do various tasks with the HttpWebRequest |
2,109,695 | I'd like to create my own custom HTTP requests. The WebClient class is very cool, but it creates the HTTP requests automatically. I'm thinking I need to create a network connection to the web server and pass my data over that stream, but I'm unfamiliar with the library classes that would support that kind of thing.
(Context, I'm working on some code for a web programming class that I'm teaching. I want my students to understand the basics of what's happening inside the "black box" of HTTP.) | 2010/01/21 | [
"https://Stackoverflow.com/questions/2109695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13338/"
] | To really understand the internals of the HTTP protocol you could use [TcpClient](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx) class:
```
using (var client = new TcpClient("www.google.com", 80))
{
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.AutoFlush = true;
// Send request headers
writer.WriteLine("GET / HTTP/1.1");
writer.WriteLine("Host: www.google.com:80");
writer.WriteLine("Connection: close");
writer.WriteLine();
writer.WriteLine();
// Read the response from server
Console.WriteLine(reader.ReadToEnd());
}
}
```
Another possibility is to [activate tracing](http://msdn.microsoft.com/en-us/library/ty48b824.aspx) by putting the following into your `app.config` and just use [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) to perform an HTTP request:
```
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="protocolonly">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log" />
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>
```
Then you can perform an HTTP call:
```
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
}
```
And finally analyze the network traffic in the generated `network.log` file. `WebClient` will also follow HTTP redirects. | Use [WFetch](http://www.microsoft.com/downloads/details.aspx?FamilyID=b134a806-d50e-4664-8348-da5c17129210) for the demonstration.
As for programming, [HttpWebRequest](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx) lets you control quite a bit about the request - again if it's for a demonstration I'd use [Wireshark](http://www.wireshark.org/) to sniff what's going over the wire when you do various tasks with the HttpWebRequest |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
```
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}
```
For pdflatex use:
```
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}
```
(Answer reposted from [Text appearing bold on some pages with images](https://tex.stackexchange.com/questions/60315/text-appearing-bold-on-some-pages-with-images/60316#60316), as the other thread was marked duplicate, but I think it applies here, too.) | To prime the answer pump with something else I observed: It appears to be a bug in pdflatex stemming from the handling of images with transparency; converting the PNG images to PDFs seems to fix the problem whenever it crops up. |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
```
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}
```
For pdflatex use:
```
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}
```
(Answer reposted from [Text appearing bold on some pages with images](https://tex.stackexchange.com/questions/60315/text-appearing-bold-on-some-pages-with-images/60316#60316), as the other thread was marked duplicate, but I think it applies here, too.) | Download the latest version of adobe reader 11 . it's working now
<http://get.adobe.com/reader/>
or see any other pdf readers |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I guess you are using Adobe Reader? If you use transparency in your illustrations, it seems that Adobe Reader renders text incorrectly (something like the wrong gamma correction in anti-aliasing perhaps), which makes the text look a bit too bold. It should look OK if you use other PDF readers, and it should also look OK when printed from Adobe Reader.
A simple solution is to avoid using transparency whenever possible.
You can remove transparency from existing PNG images using graphics editors like GIMP or Photoshop, or with a command-line program like [ImageMagick](http://www.imagemagick.org/). With ImageMagick, the command `convert image.png -background white -alpha off image_new.png` will remove the transparency (from <http://www.imagemagick.org/Usage/masking/#alpha_remove>). | I was also wrestling with the "PDF printing bold" issue, and had some success when I flattened transparency. But even when I followed all of the "rules" (images on layer below text, all transparent effects rasterized), the text in my color proofs was still getting inexplicably **bold**, or more accurately: the text looked like it was printed twice- registration was a bit off.
I'm using InDesign 5.5 to make a 20+ page newsletter (mixed images & text). Tried all kinds of InDesign settings, all kinds of Acrobat settings, but the one that ended up doing the trick was buried in the printer's properties dialogue: **Simulate Overprinting**. When I turned that on, my text came out exactly as intended, and there was much rejoicing.
There seems to be an odd interaction between Acrobat's print dialogue and some printer settings. For example, you'll get weirdness if you try to print "booklet" via the printer's applet (mine's a Canon C7065), but if you use Adobe Acrobat's "booklet" feature, all is well. For my newsletter to print correctly, I have to set a number of items in both dialogues, and in my case the overprint setting was a big find.
Hope that helps!
Mike Craghead |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | This may just be your PDF viewer that acting strangely. Even though PDF files are supposedly seen as you would get them, there are some differences in how it looks on screen and on paper.
Back when I was using Windows with Adobe Reader, sometimes scrolling past a page and then back it again would get rid of this "boldness". | I had this problem today and I was quite desperate.
Only way to fix this is to break your text into separate paragraphs near the areas where this issue happens.
Apparently Photoshop exports some texts twice, so you get the same text on top of itself which makes it look bold in the previews.
Sometimes it helps to just change the tracking if it's a single word. Most often it doesn't. |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I was also wrestling with the "PDF printing bold" issue, and had some success when I flattened transparency. But even when I followed all of the "rules" (images on layer below text, all transparent effects rasterized), the text in my color proofs was still getting inexplicably **bold**, or more accurately: the text looked like it was printed twice- registration was a bit off.
I'm using InDesign 5.5 to make a 20+ page newsletter (mixed images & text). Tried all kinds of InDesign settings, all kinds of Acrobat settings, but the one that ended up doing the trick was buried in the printer's properties dialogue: **Simulate Overprinting**. When I turned that on, my text came out exactly as intended, and there was much rejoicing.
There seems to be an odd interaction between Acrobat's print dialogue and some printer settings. For example, you'll get weirdness if you try to print "booklet" via the printer's applet (mine's a Canon C7065), but if you use Adobe Acrobat's "booklet" feature, all is well. For my newsletter to print correctly, I have to set a number of items in both dialogues, and in my case the overprint setting was a big find.
Hope that helps!
Mike Craghead | I had this problem today and I was quite desperate.
Only way to fix this is to break your text into separate paragraphs near the areas where this issue happens.
Apparently Photoshop exports some texts twice, so you get the same text on top of itself which makes it look bold in the previews.
Sometimes it helps to just change the tracking if it's a single word. Most often it doesn't. |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
```
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}
```
For pdflatex use:
```
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}
```
(Answer reposted from [Text appearing bold on some pages with images](https://tex.stackexchange.com/questions/60315/text-appearing-bold-on-some-pages-with-images/60316#60316), as the other thread was marked duplicate, but I think it applies here, too.) | I had this problem today and I was quite desperate.
Only way to fix this is to break your text into separate paragraphs near the areas where this issue happens.
Apparently Photoshop exports some texts twice, so you get the same text on top of itself which makes it look bold in the previews.
Sometimes it helps to just change the tracking if it's a single word. Most often it doesn't. |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I guess you are using Adobe Reader? If you use transparency in your illustrations, it seems that Adobe Reader renders text incorrectly (something like the wrong gamma correction in anti-aliasing perhaps), which makes the text look a bit too bold. It should look OK if you use other PDF readers, and it should also look OK when printed from Adobe Reader.
A simple solution is to avoid using transparency whenever possible.
You can remove transparency from existing PNG images using graphics editors like GIMP or Photoshop, or with a command-line program like [ImageMagick](http://www.imagemagick.org/). With ImageMagick, the command `convert image.png -background white -alpha off image_new.png` will remove the transparency (from <http://www.imagemagick.org/Usage/masking/#alpha_remove>). | To prime the answer pump with something else I observed: It appears to be a bug in pdflatex stemming from the handling of images with transparency; converting the PNG images to PDFs seems to fix the problem whenever it crops up. |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I guess you are using Adobe Reader? If you use transparency in your illustrations, it seems that Adobe Reader renders text incorrectly (something like the wrong gamma correction in anti-aliasing perhaps), which makes the text look a bit too bold. It should look OK if you use other PDF readers, and it should also look OK when printed from Adobe Reader.
A simple solution is to avoid using transparency whenever possible.
You can remove transparency from existing PNG images using graphics editors like GIMP or Photoshop, or with a command-line program like [ImageMagick](http://www.imagemagick.org/). With ImageMagick, the command `convert image.png -background white -alpha off image_new.png` will remove the transparency (from <http://www.imagemagick.org/Usage/masking/#alpha_remove>). | I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
```
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}
```
For pdflatex use:
```
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}
```
(Answer reposted from [Text appearing bold on some pages with images](https://tex.stackexchange.com/questions/60315/text-appearing-bold-on-some-pages-with-images/60316#60316), as the other thread was marked duplicate, but I think it applies here, too.) |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | I had such an issue when mixing pages with images with and without transparency. If you experience this in Acrobat Reader (almost all including recent versions), but not other PDF readers, the following code in the preamble might do the trick and enforce the same RGB rendering for all pages (for xelatex):
```
\AddToShipoutPicture{%
\makeatletter%
\special{pdf: put @thispage <</Group << /S /Transparency /I true /CS /DeviceRGB>> >>}%
\makeatother%
}
```
For pdflatex use:
```
\pdfpageattr {/Group << /S /Transparency /I true /CS /DeviceRGB>>}
```
(Answer reposted from [Text appearing bold on some pages with images](https://tex.stackexchange.com/questions/60315/text-appearing-bold-on-some-pages-with-images/60316#60316), as the other thread was marked duplicate, but I think it applies here, too.) | I was also wrestling with the "PDF printing bold" issue, and had some success when I flattened transparency. But even when I followed all of the "rules" (images on layer below text, all transparent effects rasterized), the text in my color proofs was still getting inexplicably **bold**, or more accurately: the text looked like it was printed twice- registration was a bit off.
I'm using InDesign 5.5 to make a 20+ page newsletter (mixed images & text). Tried all kinds of InDesign settings, all kinds of Acrobat settings, but the one that ended up doing the trick was buried in the printer's properties dialogue: **Simulate Overprinting**. When I turned that on, my text came out exactly as intended, and there was much rejoicing.
There seems to be an odd interaction between Acrobat's print dialogue and some printer settings. For example, you'll get weirdness if you try to print "booklet" via the printer's applet (mine's a Canon C7065), but if you use Adobe Acrobat's "booklet" feature, all is well. For my newsletter to print correctly, I have to set a number of items in both dialogues, and in my case the overprint setting was a big find.
Hope that helps!
Mike Craghead |
141 | When I run my LaTeX document through `pdflatex`, some of the pages (the ones where figures appear) have all the text bolded. Why, and what can I do to make it stop? | 2010/07/26 | [
"https://tex.stackexchange.com/questions/141",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/112/"
] | To prime the answer pump with something else I observed: It appears to be a bug in pdflatex stemming from the handling of images with transparency; converting the PNG images to PDFs seems to fix the problem whenever it crops up. | Download the latest version of adobe reader 11 . it's working now
<http://get.adobe.com/reader/>
or see any other pdf readers |
37,059,968 | I am currently stuck at getting a distinct set of values with value of `<NAME>` being the key.
I have the following sample XML:
```
<SAMPLE>
<FIRST>
<SUBSET>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName5</NAME>
</FILE>
</SUBSET>
</FIRST>
<SECOND>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName2</NAME>
</FILE>
<DATA>
<NAME>DataName3</NAME>
</DATA>
</SECOND>
<THIRD>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName4</NAME>
</FILE>
</THIRD>
</SAMPLE>
```
what I am trying to achieve, is to get the NAME values from both DATA and File Tags which the is following as results:
```
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName2</NAME>
<NAME>DataName3</NAME>
<NAME>DataName4</NAME>
<NAME>DataName5</NAME>
</SAMPLE>
```
Below is my code using `[(NAME=preceding::NAME)]` but it is not working..
```
<xsl:template name="Sample">
<SAMPLE>
<xsl:for-each select="((($srcFile/SAMPLE/FIRST/SUBSET)|($srcFile/SAMPLE/SECOND)|($srcFile/SAMPLE/THIRD))/(DATA | FILE))[(NAME=preceding::NAME)]">
<xsl:for-each select="NAME"><xsl:element name="{name(.)}"><xsl:value-of select="."/></xsl:element></xsl:for-each>
</xsl:for-each>
</SAMPLE>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="Sample"/>
</xsl:template>
```
the above code in the for-each section, unfortunately, only returned the following:
```
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName1</NAME>
</SAMPLE>
```
taking out `[(NAME=preceding::NAME)]`, unfortunately, would return all duplicated results.. I thought I have the filter code in the right place because I've even added the overall () before using this filter[]
Thanks in advance for all of the help/suggestions! | 2016/05/05 | [
"https://Stackoverflow.com/questions/37059968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5822164/"
] | In XSLT 2.0, this is rather trivial:
```
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<SAMPLE>
<xsl:for-each select="distinct-values(//NAME)">
<NAME>
<xsl:value-of select="." />
</NAME>
</xsl:for-each>
</SAMPLE>
</xsl:template>
</xsl:stylesheet>
``` | A simple XSLT-1.0 solution is excluding duplicates and sorting them by their lexical order. Generating an `xsl:key` of all `NAME` nodes and comparing this list again to all `NAME` nodes:
```
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" />
<xsl:key name="names" match="NAME" use="text()" />
<xsl:template match="/SAMPLE">
<SAMPLE>
<xsl:for-each select="//NAME[generate-id() = generate-id(key('names',text()))]">
<xsl:sort select="." order="ascending" />
<NAME><xsl:value-of select="." /></NAME>
</xsl:for-each>
</SAMPLE>
</xsl:template>
</xsl:stylesheet>
```
The output is:
```
<?xml version="1.0"?>
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName2</NAME>
<NAME>DataName3</NAME>
<NAME>DataName4</NAME>
<NAME>DataName5</NAME>
</SAMPLE>
``` |
37,059,968 | I am currently stuck at getting a distinct set of values with value of `<NAME>` being the key.
I have the following sample XML:
```
<SAMPLE>
<FIRST>
<SUBSET>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName5</NAME>
</FILE>
</SUBSET>
</FIRST>
<SECOND>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName2</NAME>
</FILE>
<DATA>
<NAME>DataName3</NAME>
</DATA>
</SECOND>
<THIRD>
<DATA>
<NAME>DataName1</NAME>
</DATA>
<FILE>
<NAME>DataName4</NAME>
</FILE>
</THIRD>
</SAMPLE>
```
what I am trying to achieve, is to get the NAME values from both DATA and File Tags which the is following as results:
```
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName2</NAME>
<NAME>DataName3</NAME>
<NAME>DataName4</NAME>
<NAME>DataName5</NAME>
</SAMPLE>
```
Below is my code using `[(NAME=preceding::NAME)]` but it is not working..
```
<xsl:template name="Sample">
<SAMPLE>
<xsl:for-each select="((($srcFile/SAMPLE/FIRST/SUBSET)|($srcFile/SAMPLE/SECOND)|($srcFile/SAMPLE/THIRD))/(DATA | FILE))[(NAME=preceding::NAME)]">
<xsl:for-each select="NAME"><xsl:element name="{name(.)}"><xsl:value-of select="."/></xsl:element></xsl:for-each>
</xsl:for-each>
</SAMPLE>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="Sample"/>
</xsl:template>
```
the above code in the for-each section, unfortunately, only returned the following:
```
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName1</NAME>
</SAMPLE>
```
taking out `[(NAME=preceding::NAME)]`, unfortunately, would return all duplicated results.. I thought I have the filter code in the right place because I've even added the overall () before using this filter[]
Thanks in advance for all of the help/suggestions! | 2016/05/05 | [
"https://Stackoverflow.com/questions/37059968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5822164/"
] | **I. Just use** (XSLT 2.0):
```
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vDoc" select="document('file:///C:/temp/delete/sample.xml')"/>
<xsl:template match="/*">
<xsl:for-each-group select="$vDoc/*/SECOND/SET" group-by="NAME">
<xsl:sequence select="."/>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
```
**When this transformation is applied on any source XML document** (not used), and the file `C:\temp\delete\sample.xml` (Note I have changed the value of `SAMPLE\FIRST\SET\NAME` to show that it is not copied to the result tree) **is**:
```
<SAMPLE>
<FIRST>
<SET>
<NAME>manX</NAME>
<STRING1>what</STRING1>
<STRING2>today</STRING2>
</SET>
</FIRST>
<SECOND>
<SET>
<NAME>man1</NAME>
<STRING1>what</STRING1>
<STRING2>today</STRING2>
</SET>
<SET>
<NAME>man1</NAME>
<STRING1>what</STRING1>
<STRING2>today</STRING2>
</SET>
<SET>
<NAME>man2</NAME>
<STRING1>how</STRING1>
<STRING2>tomorrow</STRING2>
</SET>
<SET>
<NAME>man3</NAME>
<STRING1>hello</STRING1>
<STRING2>yesterday</STRING2>
</SET>
</SECOND>
</SAMPLE>
```
**the wanted, correct result is produced**:
```
<SET>
<NAME>man1</NAME>
<STRING1>what</STRING1>
<STRING2>today</STRING2>
</SET>
<SET>
<NAME>man2</NAME>
<STRING1>how</STRING1>
<STRING2>tomorrow</STRING2>
</SET>
<SET>
<NAME>man3</NAME>
<STRING1>hello</STRING1>
<STRING2>yesterday</STRING2>
</SET>
```
---
**II. XSLT 1.0 solution**:
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vDoc" select="document('file:///C:/temp/delete/sample.xml')"/>
<xsl:key name="kSecondSetsByName" match="SECOND/SET" use="NAME"/>
<xsl:template match="/">
<xsl:apply-templates select="$vDoc/*/SECOND"/>
</xsl:template>
<xsl:template match="SET[generate-id()=generate-id(key('kSecondSetsByName', NAME)[1])]">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
```
---
**Explanation**:
1. Use of the standard XSLT 2.0 instruction `<xsl:for-each-group>` with the attribute `group-by`.
2. Use of the **[Muenchian method for grouping](http://www.jenitennison.com/xslt/grouping/muenchian.html)** in the XSLT 1.0 solution | A simple XSLT-1.0 solution is excluding duplicates and sorting them by their lexical order. Generating an `xsl:key` of all `NAME` nodes and comparing this list again to all `NAME` nodes:
```
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" />
<xsl:key name="names" match="NAME" use="text()" />
<xsl:template match="/SAMPLE">
<SAMPLE>
<xsl:for-each select="//NAME[generate-id() = generate-id(key('names',text()))]">
<xsl:sort select="." order="ascending" />
<NAME><xsl:value-of select="." /></NAME>
</xsl:for-each>
</SAMPLE>
</xsl:template>
</xsl:stylesheet>
```
The output is:
```
<?xml version="1.0"?>
<SAMPLE>
<NAME>DataName1</NAME>
<NAME>DataName2</NAME>
<NAME>DataName3</NAME>
<NAME>DataName4</NAME>
<NAME>DataName5</NAME>
</SAMPLE>
``` |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | The answer:
I had accidentaly referenced the assemblies from the src code folder. Which means the public tokens would have = null. I re-referenced to the assemblies in C:\Program Files\Microsoft Enterprise Library 5.0\Bin and the problem is now solved. | generate
```
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
``` |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | The answer:
I had accidentaly referenced the assemblies from the src code folder. Which means the public tokens would have = null. I re-referenced to the assemblies in C:\Program Files\Microsoft Enterprise Library 5.0\Bin and the problem is now solved. | In addition to what @Nicolas answered you can over come this problem by removing public token in app.config where ever it being used with Enterprise Library 5.0 dll |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | Enterprise library has 2 downloads ...
* Enterprise Library 5.0 - Source Code.msi
* Enterprise Library 5.0.msi
Only the second one has the signed binaries ... which is what's necessary to resolve the "manifest definition does not match the assembly reference" error
(and FYI, the second one also includes the source code if you elect to install it) | What probably you need to do is change Target framework in property of your project from ".NET Framework 4 Client Profile" to ".NET Framework 4".
When you first create a console project, VS 2010 by default creates ."NET Framework 4 Client Profile". EL 5 compiled with ".NET Framework 4" and your project has hard time to resolve EL dll(s). |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | I already saw you got the answer; however, I wanted to point out that when you open the Config tool from VS, you have the option to tell the config tool what assemblies you want to have referenced:
1. In VS2010: open the properties editor window, and select from the solution explorer the Solution file.
2. You'll see the option "Enterprise Library 5 Assembly Set, with the options to use the signed versions (Microsoft Signed) or the unsigned (EntLibV5Src)
When you fire up the config tool; it will reference the assemblies in the config file accordingly to your choice. | generate
```
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
``` |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | I already saw you got the answer; however, I wanted to point out that when you open the Config tool from VS, you have the option to tell the config tool what assemblies you want to have referenced:
1. In VS2010: open the properties editor window, and select from the solution explorer the Solution file.
2. You'll see the option "Enterprise Library 5 Assembly Set, with the options to use the signed versions (Microsoft Signed) or the unsigned (EntLibV5Src)
When you fire up the config tool; it will reference the assemblies in the config file accordingly to your choice. | What probably you need to do is change Target framework in property of your project from ".NET Framework 4 Client Profile" to ".NET Framework 4".
When you first create a console project, VS 2010 by default creates ."NET Framework 4 Client Profile". EL 5 compiled with ".NET Framework 4" and your project has hard time to resolve EL dll(s). |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | Enterprise library has 2 downloads ...
* Enterprise Library 5.0 - Source Code.msi
* Enterprise Library 5.0.msi
Only the second one has the signed binaries ... which is what's necessary to resolve the "manifest definition does not match the assembly reference" error
(and FYI, the second one also includes the source code if you elect to install it) | generate
```
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
``` |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | In addition to what @Nicolas answered you can over come this problem by removing public token in app.config where ever it being used with Enterprise Library 5.0 dll | What probably you need to do is change Target framework in property of your project from ".NET Framework 4 Client Profile" to ".NET Framework 4".
When you first create a console project, VS 2010 by default creates ."NET Framework 4 Client Profile". EL 5 compiled with ".NET Framework 4" and your project has hard time to resolve EL dll(s). |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | The answer:
I had accidentaly referenced the assemblies from the src code folder. Which means the public tokens would have = null. I re-referenced to the assemblies in C:\Program Files\Microsoft Enterprise Library 5.0\Bin and the problem is now solved. | Enterprise library has 2 downloads ...
* Enterprise Library 5.0 - Source Code.msi
* Enterprise Library 5.0.msi
Only the second one has the signed binaries ... which is what's necessary to resolve the "manifest definition does not match the assembly reference" error
(and FYI, the second one also includes the source code if you elect to install it) |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | The answer:
I had accidentaly referenced the assemblies from the src code folder. Which means the public tokens would have = null. I re-referenced to the assemblies in C:\Program Files\Microsoft Enterprise Library 5.0\Bin and the problem is now solved. | I already saw you got the answer; however, I wanted to point out that when you open the Config tool from VS, you have the option to tell the config tool what assemblies you want to have referenced:
1. In VS2010: open the properties editor window, and select from the solution explorer the Solution file.
2. You'll see the option "Enterprise Library 5 Assembly Set, with the options to use the signed versions (Microsoft Signed) or the unsigned (EntLibV5Src)
When you fire up the config tool; it will reference the assemblies in the config file accordingly to your choice. |
2,849,377 | I am running into some problems while trying to get DAAB from Enterprise library 5.0 running. I have followed the steps as per the tutorial, but am getting errors...
1) Download / install enterprise library
2) Add references to the blocks I need (common / data)
3) Imports
```
Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
```
4) Through the enterprise library config software. I open up the web.config from my site. I then click Blocks, then Add data settings... fill in my details and save / close
5) I then (thinking setup is complete) try to get an instance of the database via
```
Dim db As Database = DatabaseFactory.CreateDatabase()
```
6) I compile and receive the following error:
Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) (C:\site\web.config line 4)
Line 4 off my web.config was generated by the config tool and is:
```
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
```
Am I missing a required step? Have I done the steps in the wrong order? Have I made a mistake?
Thanks a lot for the assistance. | 2010/05/17 | [
"https://Stackoverflow.com/questions/2849377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261660/"
] | The answer:
I had accidentaly referenced the assemblies from the src code folder. Which means the public tokens would have = null. I re-referenced to the assemblies in C:\Program Files\Microsoft Enterprise Library 5.0\Bin and the problem is now solved. | What probably you need to do is change Target framework in property of your project from ".NET Framework 4 Client Profile" to ".NET Framework 4".
When you first create a console project, VS 2010 by default creates ."NET Framework 4 Client Profile". EL 5 compiled with ".NET Framework 4" and your project has hard time to resolve EL dll(s). |
69,893,773 | I'm trying to have an interface with a conditional statement.
In an interface, I know we could have something like this below to have the conditional.
```
interface exampleInterface {
a: 'A' | 'B'
}
```
This way, we could ensure the input 'a' must be either 'A' or 'B'.
I would like to populate this kind of conditional from an array like ['A', 'B']
Is there a way we can do like this below?
```
const a_list = Object.keys(config.a_list) // ['A', 'B'] I want to generate this from the config file.
interface exampleInterface {
a: oneOf(a_list)
}
```
The reason why I would like to this way is the input array is dynamic(getting information from a config file).
Any idea or suggestions helps. Thank you.
---
**Additional Information:**
I have created the array from the config file and did the below in the interface.
```
interface myInterface {
a: typeof a_list[number],
}
```
But when I tried to get the information from the config file from the user input like this below, I get the following error.
```
export default function myFunc(props: myInterface)
const [a] = useState(config.a_config[props.a].map((a) => a))
// Element implicitly has an 'any' type because the expression of type 'string' can't be used to index type.
// No index signature with a parameter of type 'string' was found on the type.
``` | 2021/11/09 | [
"https://Stackoverflow.com/questions/69893773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9644087/"
] | The solution turned out to be really simple.
```
const { Op } = require("sequelize");
```
```
let arr = []
for(let animal of animals) {
arr.push({
[Op.contains]: [animal],
});
}
abc.findAll({
where: {
animals: {
[Op.or]: arr
}
},
})
``` | `sql` solution could be something like :
```
SELECT *
FROM your_table
WHERE your_json_column :: jsonb @? '$[*].animals[*] ? (@ <@ HasAnimals)'
``` |
28,092,267 | Scenario is represented with the graph below:
```
0 -- A -- B -- C -- D
\
E -- F -- G
```
At some point, EFG become another project, and I want to completely cut the tie from 0ABCD and EFG:
```
0 -- A -- B -- C -- D
E' - F' - G'
``` | 2015/01/22 | [
"https://Stackoverflow.com/questions/28092267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1420625/"
] | You usually should use [Seq](http://www.scala-lang.org/api/current/index.html#scala.collection.Seq) as input parameter for method or class, defined for sequences in general (just general, not necessarily with generic):
```
def mySort[T](seq: Seq[T]) = ...
case class Wrapper[T](seq: Seq[T])
implicit class RichSeq[T](seq: Seq[T]) { def mySort = ...}
```
So now you can pass any sequence (like `Vector` or `List`) to `mySort`.
If you care about algorithmic complexity - you can specialize it to `IndexedSeq` (quick random element access) or `LinearSeq` (fast memory allocation). Anyway, you should prefer most top-level class if you want your function to be more [polymorphic](http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29) has on its input parameter, as `Seq` is a common interface for all sequences. If you need something even more generic - you may use `Traversable` or `Iterable`. | The principal here is the same as in a number of languages (E.g. in Java should often use List instead of ArrayList, or Map instead of HashMap). If you can deal with the more abstract concept of a Seq, you should, especially when they are parameters to methods.
2 main reasons that come to mind:
1) reuse of your code. e.g. if you have a method that takes a foo(s:Seq), it can be reused for lists and arrays.
2) the ability to change your mind easily. E.g. If you decide that List is working well, but suddenly you realise you need random access, and want to change it to an Array, if you have been defining List everywhere, you'll be forced to change it everywhere.
Note #1: there are times where you could say Iterable over Seq, if your method supports it, in which case I'd inclined to be as abstract as possible.
Note #2: Sometimes, I might be inclined to not say Seq (or be totally abstract) in my work libraries, even if I could. E.g. if I were to do something which would be highly non-performant with the wrong collection. Such as doing Random Access - even if I could write my code to work with a List, it would result in major inefficiency. |
12,379,520 | I have an audio file that plays using avaudioplayer, I want to able to play the sound on the device receiver or speaker when the audio is playing when the user presses a button. How can I do that ? Currently it just plays on whatever was selected before the audio started playing. | 2012/09/11 | [
"https://Stackoverflow.com/questions/12379520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845232/"
] | ```
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
OSStatus result = AudioSessionSetProperty( kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride );
Assert(result == kAudioSessionNoError);
``` | You can add MPVolume control ([link to documentation](http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPVolumeView_Class/Reference/Reference.html)) to your user interface and set showsVolumeSlider = NO and showsRouteButton = YES.
User will have a route button to route the audio to a device of their choice. |
12,379,520 | I have an audio file that plays using avaudioplayer, I want to able to play the sound on the device receiver or speaker when the audio is playing when the user presses a button. How can I do that ? Currently it just plays on whatever was selected before the audio started playing. | 2012/09/11 | [
"https://Stackoverflow.com/questions/12379520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845232/"
] | ```
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
OSStatus result = AudioSessionSetProperty( kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride );
Assert(result == kAudioSessionNoError);
``` | iOS 6+ version
```
NSError* error;
AVAudioSession* session = [AVAudioSession sharedInstance];
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
``` |
12,379,520 | I have an audio file that plays using avaudioplayer, I want to able to play the sound on the device receiver or speaker when the audio is playing when the user presses a button. How can I do that ? Currently it just plays on whatever was selected before the audio started playing. | 2012/09/11 | [
"https://Stackoverflow.com/questions/12379520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/845232/"
] | iOS 6+ version
```
NSError* error;
AVAudioSession* session = [AVAudioSession sharedInstance];
[session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
``` | You can add MPVolume control ([link to documentation](http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPVolumeView_Class/Reference/Reference.html)) to your user interface and set showsVolumeSlider = NO and showsRouteButton = YES.
User will have a route button to route the audio to a device of their choice. |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can do a strict comparison to the `undefined` value.
```
if (x === undefined) {
x = 0;
}
```
Naturally you'll want to be sure that `x` has been properly declared as usual.
If you have any sensitivities about the `undefined` value being plagued by really bad code (overwritten with a new value), then you can use the `void` operator to obtain a guaranteed `undefined`.You can do a strict comparison to the `undefined` value.
```
if (x === void 0) {
x = 0;
}
```
The operand to `void` doesn't matter. No matter what you give it, it'll return `undefined`.
These are all equivalent:
```
if (x === void undefined) {
x = 0;
}
if (x === void "foobar") {
x = 0;
}
if (x === void x) {
x = 0;
}
```
Ultimately if someone squashed `undefined` locally (it can't be squashed globally anymore), it's better to fix that bad code.
---
If you ever want to check for both `null` and `undefined` at the same time, and only those value, you can use `==` instead of `===`.
```
if (x == null) {
x = 0;
}
```
Now `x` will be set to `0` if it was either `null` or `undefined`, but not any other value. You can use `undefined` in the test too. It's exactly the same.
```
if (x == undefined) {
x = 0;
}
```
---
From your question, it seems a little bit like you're specifically looking for `number` elements, even `NaN`. If you want to limit it to primitive numbers including `NaN`, then use `typeof` for the test.
```
if (typeof x !== "number") {
x = 0;
}
```
However, you'll lose numeric strings and other values that can successfully be converted to a number, so it depends on what you ultimately need. | You can test using typeof (among other things):
```
if (typeof x == 'undefined') x = y;
```
Another approach is to test strict equality against undefined:
```
if (x === void 0) x = y
```
In this case we use `void 0` as a safety since `undefined` can actually be redefined. |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can do a strict comparison to the `undefined` value.
```
if (x === undefined) {
x = 0;
}
```
Naturally you'll want to be sure that `x` has been properly declared as usual.
If you have any sensitivities about the `undefined` value being plagued by really bad code (overwritten with a new value), then you can use the `void` operator to obtain a guaranteed `undefined`.You can do a strict comparison to the `undefined` value.
```
if (x === void 0) {
x = 0;
}
```
The operand to `void` doesn't matter. No matter what you give it, it'll return `undefined`.
These are all equivalent:
```
if (x === void undefined) {
x = 0;
}
if (x === void "foobar") {
x = 0;
}
if (x === void x) {
x = 0;
}
```
Ultimately if someone squashed `undefined` locally (it can't be squashed globally anymore), it's better to fix that bad code.
---
If you ever want to check for both `null` and `undefined` at the same time, and only those value, you can use `==` instead of `===`.
```
if (x == null) {
x = 0;
}
```
Now `x` will be set to `0` if it was either `null` or `undefined`, but not any other value. You can use `undefined` in the test too. It's exactly the same.
```
if (x == undefined) {
x = 0;
}
```
---
From your question, it seems a little bit like you're specifically looking for `number` elements, even `NaN`. If you want to limit it to primitive numbers including `NaN`, then use `typeof` for the test.
```
if (typeof x !== "number") {
x = 0;
}
```
However, you'll lose numeric strings and other values that can successfully be converted to a number, so it depends on what you ultimately need. | You can do this quite quickly with just a
```
x === undefined && (x = 0);
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can do a strict comparison to the `undefined` value.
```
if (x === undefined) {
x = 0;
}
```
Naturally you'll want to be sure that `x` has been properly declared as usual.
If you have any sensitivities about the `undefined` value being plagued by really bad code (overwritten with a new value), then you can use the `void` operator to obtain a guaranteed `undefined`.You can do a strict comparison to the `undefined` value.
```
if (x === void 0) {
x = 0;
}
```
The operand to `void` doesn't matter. No matter what you give it, it'll return `undefined`.
These are all equivalent:
```
if (x === void undefined) {
x = 0;
}
if (x === void "foobar") {
x = 0;
}
if (x === void x) {
x = 0;
}
```
Ultimately if someone squashed `undefined` locally (it can't be squashed globally anymore), it's better to fix that bad code.
---
If you ever want to check for both `null` and `undefined` at the same time, and only those value, you can use `==` instead of `===`.
```
if (x == null) {
x = 0;
}
```
Now `x` will be set to `0` if it was either `null` or `undefined`, but not any other value. You can use `undefined` in the test too. It's exactly the same.
```
if (x == undefined) {
x = 0;
}
```
---
From your question, it seems a little bit like you're specifically looking for `number` elements, even `NaN`. If you want to limit it to primitive numbers including `NaN`, then use `typeof` for the test.
```
if (typeof x !== "number") {
x = 0;
}
```
However, you'll lose numeric strings and other values that can successfully be converted to a number, so it depends on what you ultimately need. | For ES6 users you can simply do:
```
x ?? 0
```
`??` is a [Nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator):
>
> a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
>
>
> |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can do a strict comparison to the `undefined` value.
```
if (x === undefined) {
x = 0;
}
```
Naturally you'll want to be sure that `x` has been properly declared as usual.
If you have any sensitivities about the `undefined` value being plagued by really bad code (overwritten with a new value), then you can use the `void` operator to obtain a guaranteed `undefined`.You can do a strict comparison to the `undefined` value.
```
if (x === void 0) {
x = 0;
}
```
The operand to `void` doesn't matter. No matter what you give it, it'll return `undefined`.
These are all equivalent:
```
if (x === void undefined) {
x = 0;
}
if (x === void "foobar") {
x = 0;
}
if (x === void x) {
x = 0;
}
```
Ultimately if someone squashed `undefined` locally (it can't be squashed globally anymore), it's better to fix that bad code.
---
If you ever want to check for both `null` and `undefined` at the same time, and only those value, you can use `==` instead of `===`.
```
if (x == null) {
x = 0;
}
```
Now `x` will be set to `0` if it was either `null` or `undefined`, but not any other value. You can use `undefined` in the test too. It's exactly the same.
```
if (x == undefined) {
x = 0;
}
```
---
From your question, it seems a little bit like you're specifically looking for `number` elements, even `NaN`. If you want to limit it to primitive numbers including `NaN`, then use `typeof` for the test.
```
if (typeof x !== "number") {
x = 0;
}
```
However, you'll lose numeric strings and other values that can successfully be converted to a number, so it depends on what you ultimately need. | boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this
```js
var a;//undefined
a = ~~a
console.log(a)//0
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can test using typeof (among other things):
```
if (typeof x == 'undefined') x = y;
```
Another approach is to test strict equality against undefined:
```
if (x === void 0) x = y
```
In this case we use `void 0` as a safety since `undefined` can actually be redefined. | You can do this quite quickly with just a
```
x === undefined && (x = 0);
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | For ES6 users you can simply do:
```
x ?? 0
```
`??` is a [Nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator):
>
> a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
>
>
> | You can test using typeof (among other things):
```
if (typeof x == 'undefined') x = y;
```
Another approach is to test strict equality against undefined:
```
if (x === void 0) x = y
```
In this case we use `void 0` as a safety since `undefined` can actually be redefined. |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | You can test using typeof (among other things):
```
if (typeof x == 'undefined') x = y;
```
Another approach is to test strict equality against undefined:
```
if (x === void 0) x = y
```
In this case we use `void 0` as a safety since `undefined` can actually be redefined. | boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this
```js
var a;//undefined
a = ~~a
console.log(a)//0
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | For ES6 users you can simply do:
```
x ?? 0
```
`??` is a [Nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator):
>
> a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
>
>
> | You can do this quite quickly with just a
```
x === undefined && (x = 0);
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this
```js
var a;//undefined
a = ~~a
console.log(a)//0
``` | You can do this quite quickly with just a
```
x === undefined && (x = 0);
``` |
27,320,166 | I have a variable that gets defined by user input. I want to replace its value only if it's `undefined`. But not if it's `NaN`. How can I do it?
I tried doing `x || 0` but that also replaces `NaN` values. | 2014/12/05 | [
"https://Stackoverflow.com/questions/27320166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3312508/"
] | For ES6 users you can simply do:
```
x ?? 0
```
`??` is a [Nullish coalescing operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator):
>
> a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
>
>
> | boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this,Hello, boy. Maybe you could try this
```js
var a;//undefined
a = ~~a
console.log(a)//0
``` |
47,983 | When I cook things, such as scallop and salmon, I found that the food may be more tender if I wait till the water boils (at 100 C) and immediately turn the fire lower so that the water is not bubbling in the cook pot and maintain the fire at this level. But I noticed that at this point, there is more steam coming out of the water surface and the steam is far more visible than before.
I think I even test to see if there are in fact more steam by putting the my palm about 12 inches above the cook pot, and verified that in fact, when the fire is at high, there is less steam, but at low, there is more steam. Is there a physics principle that can explain this? | 2012/12/31 | [
"https://physics.stackexchange.com/questions/47983",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/2701/"
] | I must admit that I have never noticed this, and indeed it runs somewhat contrary to what I would expect.
It's a suggestion rather than an answer, but when the heat is high there will be a strong updraught of hot air so is it possible that the steam is being carried away from the pan before it has a chance to condense to water droplets? Indeed if the air flow is fast enough the steam might never condense because it would be diluted into the surrounding air before droplet nucleation happened.
By contrast at very low heat the air flow around the pan is slow so the water vapour has plenty of time to condense and form visible droplets. | I have been boiling water in our house for humidity at times during the cold weather. I noticed this phenomenon, but never with any food involved. I suspect it has more to do with the rapidity of which the matter is getting excited gives it less time to make the physical change. When the application of heat/energy is decreased, the fervent movement of the matter involved slows and the process of transformation is easier...the principle of dispersion lends to the water then spreading its energy to the surrounding environment in an accelerated manner vs the matter in question dealing with taking on the energy. |
47,983 | When I cook things, such as scallop and salmon, I found that the food may be more tender if I wait till the water boils (at 100 C) and immediately turn the fire lower so that the water is not bubbling in the cook pot and maintain the fire at this level. But I noticed that at this point, there is more steam coming out of the water surface and the steam is far more visible than before.
I think I even test to see if there are in fact more steam by putting the my palm about 12 inches above the cook pot, and verified that in fact, when the fire is at high, there is less steam, but at low, there is more steam. Is there a physics principle that can explain this? | 2012/12/31 | [
"https://physics.stackexchange.com/questions/47983",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/2701/"
] | I tried the experiment with a pot and 5mm of water and with a pan and 5mm of water. When it is just water steam at boiling is proportional to the fire as more bubbles form at the bottom of the pan and turn to steam.
So it must be the combined effect of food and water.
I suspect:
The surface of the scallops or salmon, if the heat is high, dries up fast and no longer evaporates, while it obstructs/absorbs the steam coming from the bottom where food touches it. In other words the food is seared immediately and less evaporative surface is exposed to air when heat is high.
When heat is low the fish does not dry up and gives off steam too, plus the fractal effect of the increased surface area, since no food is flat, must contribute to more steam at low fire.
A third effect might come from the bubble formation in the exposed surface of the liquid, since it will no longer be pure water. It might be that bubbles can be bigger and gather more steam before they burst, in the exposed to air part of the liquid, while for high heat they have too much energy and burst before accumulating steam. Again a food effect.
I will verify this supposition next time I braise salmon with teriyaki sauce. | I have been boiling water in our house for humidity at times during the cold weather. I noticed this phenomenon, but never with any food involved. I suspect it has more to do with the rapidity of which the matter is getting excited gives it less time to make the physical change. When the application of heat/energy is decreased, the fervent movement of the matter involved slows and the process of transformation is easier...the principle of dispersion lends to the water then spreading its energy to the surrounding environment in an accelerated manner vs the matter in question dealing with taking on the energy. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | [Songbird](http://getsongbird.com) with the [Tag Cloud Generator](http://addons.songbirdnest.com/addon/1642) add-on looks like it will do exactly what you are looking for. | I would certainly like to see a well implemented version of such a feature too. Until then, you can try [Media Monkey](http://www.mediamonkey.com/). Its tag editor has 5 custom fields which are straight text fields.
I did a quick experiment where I edited the Custom 1 field of the mp3 tag of one track to contain the string 'test1' and a second track to contain the string 'test1, test2'. I could then do a search of all fields for the string 'test1' and both of those tracks were selected.
This solution suffers from a couple of problems:
* You have to type previously used tags out each time, no facility to manage common tags.
* I think you need to get the 'pay' version of media monkey to be able to search just the custom fields.
Hopefully somebody will mention a better solution. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | [Songbird](http://getsongbird.com) with the [Tag Cloud Generator](http://addons.songbirdnest.com/addon/1642) add-on looks like it will do exactly what you are looking for. | Here is an approach that saves the tags to a common, but seldom-used field in your ID3 tags. This is important because the tags will be backed up with your music and usable by any media player.
Use the "grouping" field as a free-form tag field. This is a standard field, used by most media player software that is not used very often for its original purpose: grouping classical pieces. You can create auto/smart playlists in iTunes and MediaMonkey that look for tags that are space-separated. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I was thinking of this for myself some time back,
Had found the [**TaggTool**](http://www.taggtool.com/support.php).
>
> **Tagg** only stores pointers to your files and will never change or move files. Tagg does allow you to copy files but the original file is left untouched.
> When Removing Tags remember that only the pointer to the file is being removed from Tagg's database and not the physical file.
>
>
>
---
But, Lately, I find [**Locate32**](http://www.locate32.net/) is a better way for me.
The best part is -- it **allows you to create databases of specific search scopes**
(think of it as customized 'windows search index' files).
>
> **Locate32** is software which can be used to find files from your harddrives and other locations. It works like updatedb and locate commands in Unix based systems. In other words, it uses databases to store information about directory structures and uses these databases in searches. The use of these databases provides very fast searching speed. The software includes a dialog based application as well as console programs which can be used to both update and access databases. Supported operation systems are Windows 98/ME/NT4/2000/XP/Vista.
>
>
> | I agree with Andi, but I would you use the comment-field.
Je simply add ie. ;nostalgic;ballad;carmusic;whatever....
You could get more tags in the ID3-tag if you use short codes like ;Q;car;w.ever;... |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I agree with Andi, but I would you use the comment-field.
Je simply add ie. ;nostalgic;ballad;carmusic;whatever....
You could get more tags in the ID3-tag if you use short codes like ;Q;car;w.ever;... | Well, for what regards winamp: why not using any of the unused ID3 tags? I mean: you could use the "Composer" or "Publisher" fields to write whatever you want... and then find anything from within winamp. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I agree with Andi, but I would you use the comment-field.
Je simply add ie. ;nostalgic;ballad;carmusic;whatever....
You could get more tags in the ID3-tag if you use short codes like ;Q;car;w.ever;... | I would certainly like to see a well implemented version of such a feature too. Until then, you can try [Media Monkey](http://www.mediamonkey.com/). Its tag editor has 5 custom fields which are straight text fields.
I did a quick experiment where I edited the Custom 1 field of the mp3 tag of one track to contain the string 'test1' and a second track to contain the string 'test1, test2'. I could then do a search of all fields for the string 'test1' and both of those tracks were selected.
This solution suffers from a couple of problems:
* You have to type previously used tags out each time, no facility to manage common tags.
* I think you need to get the 'pay' version of media monkey to be able to search just the custom fields.
Hopefully somebody will mention a better solution. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I was thinking of this for myself some time back,
Had found the [**TaggTool**](http://www.taggtool.com/support.php).
>
> **Tagg** only stores pointers to your files and will never change or move files. Tagg does allow you to copy files but the original file is left untouched.
> When Removing Tags remember that only the pointer to the file is being removed from Tagg's database and not the physical file.
>
>
>
---
But, Lately, I find [**Locate32**](http://www.locate32.net/) is a better way for me.
The best part is -- it **allows you to create databases of specific search scopes**
(think of it as customized 'windows search index' files).
>
> **Locate32** is software which can be used to find files from your harddrives and other locations. It works like updatedb and locate commands in Unix based systems. In other words, it uses databases to store information about directory structures and uses these databases in searches. The use of these databases provides very fast searching speed. The software includes a dialog based application as well as console programs which can be used to both update and access databases. Supported operation systems are Windows 98/ME/NT4/2000/XP/Vista.
>
>
> | I'd like to find a media manager that does this correctly, the problem is either you store the tag information in the ID3 tag or you store it in an external library. If you store it in ID3 tags, it has a good possibility of getting clobbered by all the media library software out there (Winamp, iTunes, etc). If you use an external library, then, more often than not, the file path is used as the identifier, so if you rename your mp3's or sort them, then you loose the tags.
I think it would be cool if a new field was implemented in the ID3 as a standard for tags, and all media players would implement and use this field consistently.
However, as it stands now, I don't know of any software that does this. I would like to know if there was. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I was thinking of this for myself some time back,
Had found the [**TaggTool**](http://www.taggtool.com/support.php).
>
> **Tagg** only stores pointers to your files and will never change or move files. Tagg does allow you to copy files but the original file is left untouched.
> When Removing Tags remember that only the pointer to the file is being removed from Tagg's database and not the physical file.
>
>
>
---
But, Lately, I find [**Locate32**](http://www.locate32.net/) is a better way for me.
The best part is -- it **allows you to create databases of specific search scopes**
(think of it as customized 'windows search index' files).
>
> **Locate32** is software which can be used to find files from your harddrives and other locations. It works like updatedb and locate commands in Unix based systems. In other words, it uses databases to store information about directory structures and uses these databases in searches. The use of these databases provides very fast searching speed. The software includes a dialog based application as well as console programs which can be used to both update and access databases. Supported operation systems are Windows 98/ME/NT4/2000/XP/Vista.
>
>
> | Here is an approach that saves the tags to a common, but seldom-used field in your ID3 tags. This is important because the tags will be backed up with your music and usable by any media player.
Use the "grouping" field as a free-form tag field. This is a standard field, used by most media player software that is not used very often for its original purpose: grouping classical pieces. You can create auto/smart playlists in iTunes and MediaMonkey that look for tags that are space-separated. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I was thinking of this for myself some time back,
Had found the [**TaggTool**](http://www.taggtool.com/support.php).
>
> **Tagg** only stores pointers to your files and will never change or move files. Tagg does allow you to copy files but the original file is left untouched.
> When Removing Tags remember that only the pointer to the file is being removed from Tagg's database and not the physical file.
>
>
>
---
But, Lately, I find [**Locate32**](http://www.locate32.net/) is a better way for me.
The best part is -- it **allows you to create databases of specific search scopes**
(think of it as customized 'windows search index' files).
>
> **Locate32** is software which can be used to find files from your harddrives and other locations. It works like updatedb and locate commands in Unix based systems. In other words, it uses databases to store information about directory structures and uses these databases in searches. The use of these databases provides very fast searching speed. The software includes a dialog based application as well as console programs which can be used to both update and access databases. Supported operation systems are Windows 98/ME/NT4/2000/XP/Vista.
>
>
> | with [foobar2000](http://www.foobar2000.org/) you could use multiple tags in one ID3 tag (separated by ";") and show them like you want using [title formating](http://wiki.hydrogenaudio.org/index.php?title=Foobar2000:Titleformat_Reference) with %<"field">% (Default UI components: [album list](http://wiki.hydrogenaudio.org/index.php?title=Foobar2000:Titleformat_Album_List#Special_fields) / [facets](http://foobar2000.audiohq.de/foo_facets/manual) or [Columns UI](http://www.yuo.be/columns.php) components: album list panel / filter, ...) and commands like [$meta(field)](http://wiki.hydrogenaudio.org/index.php?title=Foobar2000:Titleformat_Reference#Metadata_2) (everywhere)
More info [here](http://www.hydrogenaudio.org/forums/index.php?showtopic=38866)
Note: by default only the tags: ARTIST, ALBUM ARTIST, PRODUCER, COMPOSER, PERFORMER, GENRE are configured for settings by multi-tags, but you could add yours (like MOOD, STYLE ...) in: Preferences > Advanced > Display > Properties Dialog > Multivalue Fields |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | I agree with Andi, but I would you use the comment-field.
Je simply add ie. ;nostalgic;ballad;carmusic;whatever....
You could get more tags in the ID3-tag if you use short codes like ;Q;car;w.ever;... | Here is an approach that saves the tags to a common, but seldom-used field in your ID3 tags. This is important because the tags will be backed up with your music and usable by any media player.
Use the "grouping" field as a free-form tag field. This is a standard field, used by most media player software that is not used very often for its original purpose: grouping classical pieces. You can create auto/smart playlists in iTunes and MediaMonkey that look for tags that are space-separated. |
14,739 | My problem: I have a lot of MP3s and finding the right music to listen to is difficult.
What I'd like: I'd like to be able to tag the individual files, similar to how you would tag photos on Flickr, or questions on this site. It's very difficult to search for this, since every "mp3 tagging" search ends up with ID3 taggers, which is *not* what I'm talking about. I'd imagine that this program would let you add tags (eg: `"instrumental, cowbell, party"`) and then you could easily find all your "cowbell" tracks.
Does such a program exist? And for super awesomeness, it doesn't happen to exist as a winamp plugin? | 2009/07/28 | [
"https://superuser.com/questions/14739",
"https://superuser.com",
"https://superuser.com/users/2936/"
] | [Songbird](http://getsongbird.com) with the [Tag Cloud Generator](http://addons.songbirdnest.com/addon/1642) add-on looks like it will do exactly what you are looking for. | Well, for what regards winamp: why not using any of the unused ID3 tags? I mean: you could use the "Composer" or "Publisher" fields to write whatever you want... and then find anything from within winamp. |
36,985,520 | This problem has been bugging me for the last while.. i cant seem to be able to update the stock value of the vehicle that i'm selling. I understand how to search the array and locate the model that the user is looking for but i don't understand how to update the number of that specific model vehicle that are in stock. which is going to be stock - 1 after a purchase.
I have both basic getters and setters for model and stock variables in the Vehicles superclass
Any help is appreciate!
Below is the method of purchasing a car from the driver class
```
public void purchaseCar()
{
Scanner scan = new Scanner(System.in);
String model, ans;
System.out.println("****Car Purchase Page****");
System.out.println("Enter the model of car you're looking to purchase");
model = scan.nextLine();
for (Vehicles v : list) {
if (v.getmodel().equals(model))
{
System.out.println("Is this the model you want to purchase?");
ans = scan.nextLine();
if (ans.equals("yes")) {
System.out.println("Okay! Your order is being processed");
Vehicles.setStock() = stock - 1;
}
else {
System.out.println("not working");
}
}
}
}
``` | 2016/05/02 | [
"https://Stackoverflow.com/questions/36985520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6026545/"
] | You're almost there.
Change:
```
Vehicles.setStock() = stock - 1;
```
to:
```
v.setStock(v.getStock() - 1);
```
---
As clarification, this is the same as:
```
int stock = v.getStock(); // Get the current stock value of 'v'
int newStock = stock - 1; // The new stock value after the purchase
v.setStock(newStock); // Set the new stock value
``` | You are not invoking the `Vehicles.setStock()` on the object you want to update. And in addition this method doesn't receive any parameter to update the new stock.
You should call the method on the instance you want to update passing it the new value of the stock.
Try this
```
v.setStock(v.getStock() - 1);
```
If it seems strange to you to use the `v.getStock()` to build the parameter you can create a new method within your vehicle class.
```
class Vehicles{
int stock;
public void consumeOne(){
stock = stock -1;
}
}
```
And then you can call this new method in the for statement
```
for (Vehicles v : list) {
if (v.getmodel().equals(model)){
ans = scan.nextLine();
if (ans.equals("yes")) {
v.consumeOne();
}else {
System.out.println("not working");
}
}
}
``` |
43,035,302 | Is there a way to close a window when an input element has a flag value in the side output of a DoFn? E.g. event which indicates closing of a session closes the window.
I've been reading the docs, and triggers are time based mostly. An example would be great.
Edit: Trigger.OnElementContext.forTrigger(ExecutableTrigger trigger) seems promising but ExecutableTrigger docs are pretty slim at the moment. | 2017/03/26 | [
"https://Stackoverflow.com/questions/43035302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939922/"
] | I don't think that this is available. There is only one Data Driven Trigger right now, elementCountAtLeast.
<https://cloud.google.com/dataflow/model/triggers#data-driven-triggers>
A work around for this would be to copy the sessions window function code and write a custom window function.
<https://github.com/apache/beam/blob/890bc1a23f493b042f8c2de5c042970ce5ddca96/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/windowing/Sessions.java>
In short, you keep assigning elements into the same window, until you see your terminating element. Then start creating a new window.
<https://github.com/apache/beam/blob/890bc1a23f493b042f8c2de5c042970ce5ddca96/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/windowing/Sessions.java#L60> | At present, there is no way to trigger off the content of an element, unfortunately. From the [Apache Beam Docs](https://beam.apache.org/documentation/programming-guide/#data-driven-triggers):
>
> Beam provides one data-driven trigger, `AfterPane.elementCountAtLeast()`. This trigger works on an element count; it fires after the current pane has collected at least N elements.
>
>
>
There is currently an [open ticket](https://issues.apache.org/jira/browse/BEAM-101) for more robust data-driver triggers. However (again, at present), it appears that the Beam team is filling out use-cases for data-driven triggers one at a time (i.e. element count or timestamp), as opposed to adding broad-based support for triggering off arbitrary values within an element.
An ExecutableTrigger wraps a Trigger object for execution. See [ExecutableTrigger](https://beam.apache.org/documentation/sdks/javadoc/0.2.0-incubating/org/apache/beam/sdk/util/ExecutableTrigger.html) docs. |
25,648,393 | So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure.
I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect.
However due to Django 1.7 and built in support for migrations is there a better way to do this now? | 2014/09/03 | [
"https://Stackoverflow.com/questions/25648393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848524/"
] | Another hacky alternative if the data is not big or too complicated, but still important to maintain, is to:
* Get data fixtures using [manage.py dumpdata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#dumpdata)
* Proceed to model changes and migrations properly, without relating the changes
* Global replace the fixtures from the old model and app names to the new
* Load data using [manage.py loaddata](https://docs.djangoproject.com/en/1.11/ref/django-admin/#loaddata) | **This is tested roughly, so do not forget to backup your DB!!!**
For example, there are two apps: `src_app` and `dst_app`, we want to move model `MoveMe` from `src_app` to `dst_app`.
Create empty migrations for both apps:
```
python manage.py makemigrations --empty src_app
python manage.py makemigrations --empty dst_app
```
Let's assume, that new migrations are `XXX1_src_app_new` and `XXX1_dst_app_new`, previuos top migrations are `XXX0_src_app_old` and `XXX0_dst_app_old`.
Add an operation that renames table for `MoveMe` model and renames its app\_label in ProjectState to `XXX1_dst_app_new`. Do not forget to add dependency on `XXX0_src_app_old` migration. The resulting `XXX1_dst_app_new` migration is:
```python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
# this operations is almost the same as RenameModel
# https://github.com/django/django/blob/1.7/django/db/migrations/operations/models.py#L104
class MoveModelFromOtherApp(migrations.operations.base.Operation):
def __init__(self, name, old_app_label):
self.name = name
self.old_app_label = old_app_label
def state_forwards(self, app_label, state):
# Get all of the related objects we need to repoint
apps = state.render(skip_cache=True)
model = apps.get_model(self.old_app_label, self.name)
related_objects = model._meta.get_all_related_objects()
related_m2m_objects = model._meta.get_all_related_many_to_many_objects()
# Rename the model
state.models[app_label, self.name.lower()] = state.models.pop(
(self.old_app_label, self.name.lower())
)
state.models[app_label, self.name.lower()].app_label = app_label
for model_state in state.models.values():
try:
i = model_state.bases.index("%s.%s" % (self.old_app_label, self.name.lower()))
model_state.bases = model_state.bases[:i] + ("%s.%s" % (app_label, self.name.lower()),) + model_state.bases[i+1:]
except ValueError:
pass
# Repoint the FKs and M2Ms pointing to us
for related_object in (related_objects + related_m2m_objects):
# Use the new related key for self referential related objects.
if related_object.model == model:
related_key = (app_label, self.name.lower())
else:
related_key = (
related_object.model._meta.app_label,
related_object.model._meta.object_name.lower(),
)
new_fields = []
for name, field in state.models[related_key].fields:
if name == related_object.field.name:
field = field.clone()
field.rel.to = "%s.%s" % (app_label, self.name)
new_fields.append((name, field))
state.models[related_key].fields = new_fields
def database_forwards(self, app_label, schema_editor, from_state, to_state):
old_apps = from_state.render()
new_apps = to_state.render()
old_model = old_apps.get_model(self.old_app_label, self.name)
new_model = new_apps.get_model(app_label, self.name)
if self.allowed_to_migrate(schema_editor.connection.alias, new_model):
# Move the main table
schema_editor.alter_db_table(
new_model,
old_model._meta.db_table,
new_model._meta.db_table,
)
# Alter the fields pointing to us
related_objects = old_model._meta.get_all_related_objects()
related_m2m_objects = old_model._meta.get_all_related_many_to_many_objects()
for related_object in (related_objects + related_m2m_objects):
if related_object.model == old_model:
model = new_model
related_key = (app_label, self.name.lower())
else:
model = related_object.model
related_key = (
related_object.model._meta.app_label,
related_object.model._meta.object_name.lower(),
)
to_field = new_apps.get_model(
*related_key
)._meta.get_field_by_name(related_object.field.name)[0]
schema_editor.alter_field(
model,
related_object.field,
to_field,
)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
self.old_app_label, app_label = app_label, self.old_app_label
self.database_forwards(app_label, schema_editor, from_state, to_state)
app_label, self.old_app_label = self.old_app_label, app_label
def describe(self):
return "Move %s from %s" % (self.name, self.old_app_label)
class Migration(migrations.Migration):
dependencies = [
('dst_app', 'XXX0_dst_app_old'),
('src_app', 'XXX0_src_app_old'),
]
operations = [
MoveModelFromOtherApp('MoveMe', 'src_app'),
]
```
Add dependency on `XXX1_dst_app_new` to `XXX1_src_app_new`. `XXX1_src_app_new` is no-op migration that is needed to make sure that future `src_app` migrations will be executed after `XXX1_dst_app_new`.
Move `MoveMe` from `src_app/models.py` to `dst_app/models.py`. Then run:
```
python manage.py migrate
```
That's all! |
25,648,393 | So about a year ago I started a project and like all new developers I didn't really focus too much on the structure, however now I am further along with Django it has started to appear that my project layout mainly my models are horrible in structure.
I have models mainly held in a single app and really most of these models should be in their own individual apps, I did try and resolve this and move them with south however I found it tricky and really difficult due to foreign keys ect.
However due to Django 1.7 and built in support for migrations is there a better way to do this now? | 2014/09/03 | [
"https://Stackoverflow.com/questions/25648393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2848524/"
] | You can try the following (untested):
1. move the model from `src_app` to `dest_app`
2. migrate `dest_app`; make sure the schema migration depends on the latest `src_app` migration (<https://docs.djangoproject.com/en/dev/topics/migrations/#migration-files>)
3. add a data migration to `dest_app`, that copies all data from `src_app`
4. migrate `src_app`; make sure the schema migration depends on the latest (data) migration of `dest_app` -- that is: the migration of step 3
Note that you will be *copying* the whole table, instead of *moving* it, but that way both apps don't have to touch a table that belongs to the other app, which I think is more important. | Lets say you are moving model TheModel from app\_a to app\_b.
An alternate solution is to alter the existing migrations by hand. The idea is that each time you see an operation altering TheModel in app\_a's migrations, you copy that operation to the end of app\_b's initial migration. And each time you see a reference 'app\_a.TheModel' in app\_a's migrations, you change it to 'app\_b.TheModel'.
I just did this for an existing project, where I wanted to extract a certain model to an reusable app. The procedure went smoothly. I guess things would be much harder if there were references from app\_b to app\_a. Also, I had a manually defined Meta.db\_table for my model which might have helped.
Notably you will end up with altered migration history. This doesn't matter, even if you have a database with the original migrations applied. If both the original and the rewritten migrations end up with the same database schema, then such rewrite should be OK. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.