qid
int64 1
74.6M
| question
stringlengths 45
24.2k
| date
stringlengths 10
10
| metadata
stringlengths 101
178
| response_j
stringlengths 32
23.2k
| response_k
stringlengths 21
13.2k
|
---|---|---|---|---|---|
4,701,114 | Is there a way to tell the split command to save the resultant files in a particular location? | 2011/01/15 | ['https://Stackoverflow.com/questions/4701114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50329/'] | How about:
```
$ split -b 10 input.txt xxx/split-file
```
or
```
$ split -b 10 input.txt /tmp/split-file
```
Just include the output directory in the prefix specification. Keep in mind that the directory must be created beforehand. | This is the MacOS X (BSD) version of split, and includes some features of `csplit`:
>
> split [-a suffix\_length] [-b byte\_count[k|m]] [-l line\_count] [-p pattern] [file [name]]
>
>
>
The `name` specifies the prefix to the file name - the default is `x`, effectively `./x`.
So, you do:
```
split bigfile /lots/of/little/files/here
```
### POSIX
The POSIX definition of [`split`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/split.html) gives the synopses:
>
>
> ```
> split [-l line_count] [-a suffix_length] [file [name]]
>
> split -b n[k|m] [-a suffix_length] [file [name]]
>
> ```
>
>
(The web site has a repeated typo - no space between `file` and `[name]`.) |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | I typically vote on answers I like right after reading them but usually read several of the answers. | I typically read most answers before voting. |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | I typically read most answers before voting. | I typically vote on answers I like right after reading them and often don't read further answers. |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | I typically read most answers before voting. | **Other** (vote before reading, never vote, ...)
Please explain in comments. |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | I typically vote on answers I like right after reading them but usually read several of the answers. | I typically vote on answers I like right after reading them and often don't read further answers. |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | I typically vote on answers I like right after reading them but usually read several of the answers. | **Other** (vote before reading, never vote, ...)
Please explain in comments. |
4,427 | Motivated by these questions:
[Case Study: First Answer Bias](https://academia.meta.stackexchange.com/q/4414/19607) and [Are upvotes skewed towards the first answer to a question?](https://academia.meta.stackexchange.com/q/3826/19607)
I propose a biased (biased towards people who use the meta site) study of AcademiaSE users to see how much of an upvote biases the first answer to a question gets (the "fastest gun in the west" problem) from "non-random" Academia users. To wit,
>
> For questions you read which have multiple answers, do you typically vote on an answer before reading other answers? (Answer by up-voting answers below. At least for this question, please read the answers first and upvote at least one.)
>
>
> | 2019/02/10 | ['https://academia.meta.stackexchange.com/questions/4427', 'https://academia.meta.stackexchange.com', 'https://academia.meta.stackexchange.com/users/19607/'] | **Other** (vote before reading, never vote, ...)
Please explain in comments. | I typically vote on answers I like right after reading them and often don't read further answers. |
40,375,015 | My scenario is like this : I have some texts and image inside the Container. Both of them display correctly with different screen sizes.
However, it doesn't display to my expected result when I view it in Desktop.
[![enter image description here](https://i.stack.imgur.com/kPGhO.jpg)](https://i.stack.imgur.com/kPGhO.jpg)
**What I want to achieve is something similar to screenshot(Responsive). Anyone know how to do that?**
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<style>
p.solid {border-style: solid;}
</style>
<body>
<div class="container">
<p class="solid">A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.A solid border.</p>
<p align="center"><img class="img-responsive" src="img/20161014_220509_073.jpg" /> </p>
</div>
</body>
</html>
``` | 2016/11/02 | ['https://Stackoverflow.com/questions/40375015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6521417/'] | You appear to be running on a corporate network that is **sending web traffic through a proxy** (`pfSense proxy`).
The error is showing a **private IP address** (`192.168.0.46`), which means the request never made it to the Internet.
You should chat with your network administrators and determine why it is listed in a group called `Bloack_Sites` (presumably, 'Blocked sites'?). | Since the address is address: 192.168.0.46
and the client name is address: 192.168.0.46
Then the target group is undefined: Bloack\_Sites not recognized.
Target group: Block\_Sites |
78,924 | As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the "Share" option grayed out. | 2011/11/13 | ['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/'] | I just did a test, created a new folder */new* and gave it permissions 777. When right clicking on it, Ubuntu One options were greyed out. Also tried creating a shortcut in ~/ dir, but no luck either.
In short: No, you can't
======================= | There are unsupported ways which will work. Think mount points under ~/
Using a bind mount as described above to a folder under ~/ you can sync any folder on your computer with Ubuntu One.
I sync folders on a separate partition with Ubuntu One this way.
Like I said, this is not really supported, but it does work |
78,924 | As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the "Share" option grayed out. | 2011/11/13 | ['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/'] | You could try using a `mount --bind command`. Something like
```
mount --bind /path/to/folder /home/username/folder_to_sync
```
This should make the contents of `/path/to/folder` available in both places.
Ubuntu-one doesn't support symlinks, but it might support binding mounts. If it does work, you can add a line to `/etc/fstab`
```
/path/to/folder /home/username/folder_to_sync none bind 0 0
```
That way it will always mount on boot. | I just did a test, created a new folder */new* and gave it permissions 777. When right clicking on it, Ubuntu One options were greyed out. Also tried creating a shortcut in ~/ dir, but no luck either.
In short: No, you can't
======================= |
78,924 | As the title suggests, I can't figure out a way to share a folder outside my home folder using Ubuntu One. When browsing to my work partition using Nautilus, every folder has the "Share" option grayed out. | 2011/11/13 | ['https://askubuntu.com/questions/78924', 'https://askubuntu.com', 'https://askubuntu.com/users/39959/'] | You could try using a `mount --bind command`. Something like
```
mount --bind /path/to/folder /home/username/folder_to_sync
```
This should make the contents of `/path/to/folder` available in both places.
Ubuntu-one doesn't support symlinks, but it might support binding mounts. If it does work, you can add a line to `/etc/fstab`
```
/path/to/folder /home/username/folder_to_sync none bind 0 0
```
That way it will always mount on boot. | There are unsupported ways which will work. Think mount points under ~/
Using a bind mount as described above to a folder under ~/ you can sync any folder on your computer with Ubuntu One.
I sync folders on a separate partition with Ubuntu One this way.
Like I said, this is not really supported, but it does work |
70,277,178 | How to take an number input from user and split it's digits and use each digit separately
*For example*
If user enters '''4568'''
The code should split 4568 into 4,5,6,8 | 2021/12/08 | ['https://Stackoverflow.com/questions/70277178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17627014/'] | Use a list comprehension over the user input.
```py
values = [int(i) for i in input()]
```
Note that this code doesn't handles cases where user puts non-digits characters in his input. To deal with this case, you would prefer to write :
```py
values = [int(i) for i in input() if i.isdigit()]
``` | Convert it to string, iterate to string and get each character as an integer.
```
# Input from the user
inp = input()
digits=[]
for c in str(inp):
try:
digit=int(c)
# Populate the list with the last digit obtained
digits.append(digit)
except:
# I'm assuming you don't need to worry about any other non integer character
pass
```
Or in one line, **BUT pay attention that if any non integer character is present into the input, the map fails**:
```
inp = 1234
digits = list(map(int, list(str(inp)))
```
Where `list(str(inp))` splits the string-converted input in the list of its characters, `map` applies the transformation to integer to each element of the latter list, eventually the conversion to list return your desired array
EDIT: I was writing the code while the comment were being written. I've now integrated the direct `int` suggestion to map function
EDIT2: a nitpicky edit to allow for an actual user input instead of a test variable. This does not change the substance at all. |
70,277,178 | How to take an number input from user and split it's digits and use each digit separately
*For example*
If user enters '''4568'''
The code should split 4568 into 4,5,6,8 | 2021/12/08 | ['https://Stackoverflow.com/questions/70277178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17627014/'] | You could `map` it to `int`, and convert the `map` to `list`.
```
digits = list(map(int, input()))
```
If you want to make sure only numbers are accepted add a `filter` to the `input`
```
digits = list(map(int, filter(lambda c: c.isdigit(), input())))
``` | Convert it to string, iterate to string and get each character as an integer.
```
# Input from the user
inp = input()
digits=[]
for c in str(inp):
try:
digit=int(c)
# Populate the list with the last digit obtained
digits.append(digit)
except:
# I'm assuming you don't need to worry about any other non integer character
pass
```
Or in one line, **BUT pay attention that if any non integer character is present into the input, the map fails**:
```
inp = 1234
digits = list(map(int, list(str(inp)))
```
Where `list(str(inp))` splits the string-converted input in the list of its characters, `map` applies the transformation to integer to each element of the latter list, eventually the conversion to list return your desired array
EDIT: I was writing the code while the comment were being written. I've now integrated the direct `int` suggestion to map function
EDIT2: a nitpicky edit to allow for an actual user input instead of a test variable. This does not change the substance at all. |
1,116 | In English and other Germanic languages, noun compounds are formed simply by “appending” the nouns in a certain order. For example, phrases like this are very common:
>
> electricity price comparison service
>
>
>
In Portuguese, Spanish and probably other Romance languages, this kind of compounding has to be done with the aid of prepositions. The translation of the phrase above to Portuguese is:
>
> serviço *de* comparação *de* preços *de* eletricidade
>
>
>
What determines how noun compounds are formed in a language? Is there something like a parameter (as in the principles and parameters theory) that explains this?
I'm focusing only on "open" compounds (not idiomatic ones) formed exclusively by nouns. As Molly mentioned, this might be related to the Adj/N word order in the language. This hypothesis is quite reasonable, since in the Germanic languages the head in these compounds comes at the end, whereas in Romance languages, they come at the beginning, matching the Adj/N word order.
But even if this correlation does hold cross-linguistically, how does it relate to the need for prepositions? Maybe prepositions help avoiding ambiguities when the adjectives are postnominal? Could it be related to processing preferences? | 2011/12/06 | ['https://linguistics.stackexchange.com/questions/1116', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/22/'] | Compound words are really complex, even if we limit it to noun-noun compounds.
It looks like you're concerned with "open" compound nouns, not "closed" or hyphenated or [idiomatic](http://www.sciencedirect.com/science/article/pii/0024384168900521) compound nouns [like these](http://www.rickwalton.com/curricul/compound.htm) (what a list! right? corpus alert!). So -
The syntactic definition of a compound noun is when the rule N -> N N can be recursively applied. Anything with more than two nouns is ambiguous in structure. ((coffee mug) holder) vs. (coffee (mug holder)) or whatever.
Most languages are more predictable than English when it comes to "headedness" or left/right branching of closed noun compounds; Downing's conclusion to ["On the Creation and Use of English Compound Nouns"](http://www.jstor.org/pss/412913) is basically that the relationship is unpredictable from the semantics of the two words.
My instinct (very scientific!) is that the concatenation vs. use of prepositions for noun-noun compounds is predictable by typology. My guess is that the form of compound nouns is correlated to [the Adj/N word order](http://wals.info/chapter/87) tendency of a language. Of course, this isn't really an answer, but I think the answer you're looking for is too big. It's sort of like asking why a language is SVO or SOV. | Just thinking out aloud, but might it be related to the case systems in Germanic vs. Romance languages?
>
> electricity price comparison service
>
>
>
...is a shortened form of:
>
> service for the comparison of prices for electricity
>
>
>
This is the same as your Portuguese translation, where the prepositions act as case licensors. However, in Germanic languages, the case system is/was richer and the prepositions disappear (because they're redundant). In particular, "of" can be seen as a genitive licensor:
>
> (service for the comparison) of (prices for electricity)
>
>
> (prices for electricity)'s (service for the[ir] comparison)
>
>
>
Similarly, "for" is a dative licensor:
>
> (electricity prices)'s (comparison service)
>
>
>
Dropping the genitive "'s" morpheme doesn't seem like a huge stretch of the imagination and serves brevity:
>
> electricity price comparison service
>
>
> |
9,458,285 | I've been actively using the revealing module pattern for years but there's a few things I'd like to understand deeper. From what I understand potential benefits of self-executing functions are anoymimty & self-execution, both of which don't seem necessary/utilised in this particular pattern. The other thing I don't understand is, what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function, self-executing functions seem to be a very a unique construct in JS, isn't it strange that we can just assign a properties values to a self-executing code block?
```
var myObj = {
prop1, "prop1value",
SocialMedia: (function () {
function Init() {
}
return {
Init: Init
}
})()
}
``` | 2012/02/26 | ['https://Stackoverflow.com/questions/9458285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314963/'] | >
> Why do we use self-executing functions in the revealing module pattern?
>
>
>
JavaScript has first-class functions and lacks block-scoping, so functions are used to introduce new scopes.
>
> what in the below scenario makes its possible to wrap function Init inside the SocialMedia function(), i.e an embedded function
> ... isn't it strange that we can just assign a properties values to a self-executing code block?
>
>
>
In JavaScript, a function is just an object that responds to the `()` and `new` operators.
Like other objects, you can use it when you define it, or store it in a variable or property for later use.
>
> self-executing functions seem to be a very a unique construct in JS
>
>
>
This isn't unique to JavaScript. All languages that have [first class functions](http://en.wikipedia.org/wiki/First-class_function) have this property, for example:
* Lisp,
* OCaml,
* Scala,
* Go,
* C# (via delegates),
* C (via fn ptrs),
* Python,
* Perl (via `&`),
* Ruby,
* Lua
In recent language development, first-class functions are the norm rather than the rule. Un-statically-typed languages just make it easier because there's no overhead in the type system syntax and no [variance](http://en.wikipedia.org/wiki/Variance_%28computer_science%29#Need_for_covariant_argument_types.3F) issues.
Even Java might be jumping on the bandwagon with [Lambdas slated for Java 8](http://openjdk.java.net/projects/lambda/).
In many of those other languages, immediately called functions aren't that useful though. Most other languages are [block-scoped](http://en.wikipedia.org/wiki/Scope_%28computer_science%29#Block_scope_within_a_function) so if you want to keep your variables separate, you just use a `{...}` block. In JavaScript though, `var` is scoped to the smallest containing `function` or Program, so `function`s are the easiest way to introduce a new scope.
[Ruby](http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/) makes very little distinction between blocks and functions so could be considered similar to JS in this respect. | Self-executing functions are used to introduce new scopes, see also Mike Samuels answer.
There are two reasons for that:
* avoid polluting the global scope
* use of closures, i.e. "exporting" a function from an extra scope
Of course you can stack scopes, but usually you won't create that big modules where you have to avoid polluting your local module scope :-)
Also, the self-executing function in your example is useless, as it's totally equivalent to
```
var myObj = {
prop1: "prop1value",
SocialMedia: {
Init: function Init() {
}
}
}
``` |
15,773,588 | I'm trying to write text in `Canvas`. As I need to show the soft keyboard to write text, I added an `EditText` to my Activity with 0 width. I also implemented a TextWatcher to get the text entered into the `EditText`. With this trick, I can show the soft keyboard whenever I like with this code :
```
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(myEditText, InputMethodManager.SHOW_IMPLICIT);
```
Like this I'm able to know what the user is writing and to write the text inside my `Canvas`.
Now... this becomes tricky when the user would like to stop writing (or let say, anchor the text in the canvas definitely). What I thought is that he could press 'Enter'. So I tried to implement some way to catch the key events. Without any success so far.
Here is my actual code. This method is called when I would like to start writing. 'edit' is an `EditText`.
```
public void handleUp(final Paint myPaint) {
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
edit.addTextChangedListener(new Watcher());
edit.setImeOptions(EditorInfo.IME_ACTION_GO);
edit.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
Log.d("MyApp", "key pressed");
Paint localPaint = new Paint();
mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint);
return false;
}
});
edit.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d("MyApp", "key pressed");
if (keyCode == KeyEvent.ACTION_DOWN) {
Paint localPaint = new Paint();
mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint);
return true;
}
return false;
}
});
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
}
```
When I debug my app I never reach check points that I have put on my `Log()` and can't see any message in my Logs neither. I have seen many posts on StackOverFlow where this kind of implementation is used by I can't figure out why it fails here.
Thank you | 2013/04/02 | ['https://Stackoverflow.com/questions/15773588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1685143/'] | Taken from the documentation:
```
public void setOnKeyListener (View.OnKeyListener l)
Added in API level 1
Register a callback to be invoked when a hardware key is pressed in this view. Key presses in software input methods will generally not trigger the methods of this listener.
```
So you should look for another listener.
My best guess would be to use this:
```
public void setOnEditorActionListener (TextView.OnEditorActionListener l)
Added in API level 3
Set a special listener to be called when an action is performed on the text view. This will be called when the enter key is pressed, or when an action supplied to the IME is selected by the user. Setting this means that the normal hard key event will not insert a newline into the text view, even if it is multi-line; holding down the ALT modifier will, however, allow the user to insert a newline character.
```
But none of the methods I could see in the documentation mentioned anything about soft key input. | Okay so finally the reason nothing worked was because my `EditText` had a width of 0. When I put width and height to 1. Setting visibility to `View.INVISIBLE` doesn't work in this case.
By the way, the three Listener (OnEditorActionListener, OnKeyListener and Overriding dispatchKeyEvent) get the callbacks. But I'll use `OnEditorActionListener` because it's the only one getting only one callback. The two others get several callbacks which is problematic. |
15,773,588 | I'm trying to write text in `Canvas`. As I need to show the soft keyboard to write text, I added an `EditText` to my Activity with 0 width. I also implemented a TextWatcher to get the text entered into the `EditText`. With this trick, I can show the soft keyboard whenever I like with this code :
```
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(myEditText, InputMethodManager.SHOW_IMPLICIT);
```
Like this I'm able to know what the user is writing and to write the text inside my `Canvas`.
Now... this becomes tricky when the user would like to stop writing (or let say, anchor the text in the canvas definitely). What I thought is that he could press 'Enter'. So I tried to implement some way to catch the key events. Without any success so far.
Here is my actual code. This method is called when I would like to start writing. 'edit' is an `EditText`.
```
public void handleUp(final Paint myPaint) {
edit.setFocusable(true);
edit.setFocusableInTouchMode(true);
edit.requestFocus();
edit.addTextChangedListener(new Watcher());
edit.setImeOptions(EditorInfo.IME_ACTION_GO);
edit.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
Log.d("MyApp", "key pressed");
Paint localPaint = new Paint();
mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint);
return false;
}
});
edit.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d("MyApp", "key pressed");
if (keyCode == KeyEvent.ACTION_DOWN) {
Paint localPaint = new Paint();
mCanvas.drawText(edit.getText().toString(), mX, mY, localPaint);
return true;
}
return false;
}
});
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
}
```
When I debug my app I never reach check points that I have put on my `Log()` and can't see any message in my Logs neither. I have seen many posts on StackOverFlow where this kind of implementation is used by I can't figure out why it fails here.
Thank you | 2013/04/02 | ['https://Stackoverflow.com/questions/15773588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1685143/'] | You override the dispatchKeyEvent to get the Enter key
```
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
// Do whatever you want
}
return super.dispatchKeyEvent(event);
}
``` | Okay so finally the reason nothing worked was because my `EditText` had a width of 0. When I put width and height to 1. Setting visibility to `View.INVISIBLE` doesn't work in this case.
By the way, the three Listener (OnEditorActionListener, OnKeyListener and Overriding dispatchKeyEvent) get the callbacks. But I'll use `OnEditorActionListener` because it's the only one getting only one callback. The two others get several callbacks which is problematic. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | Give the empty element a different class (say `someHiddenElement`) when you are generating the content. Then add `someHiddenElement { display: none }` to your style sheet. | At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | You can do the trick with the CSS3 pseudo-class :empty
```
.someElement
{
// your standard style
}
.someElement:empty
{
display:none;
}
```
Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine... | I can't think of a CSS only way to do that.
I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | You can do the trick with the CSS3 pseudo-class :empty
```
.someElement
{
// your standard style
}
.someElement:empty
{
display:none;
}
```
Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine... | ```
<style>
.someElement{padding-top: 5px; display:table;}
</style>
<div class="someElement">With padded content</div>
<div class="someElement"><!-- shouldn't render since it has no content --></div>
```
Adding display:table; should do the trick. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | Give the element an `id` attribute. You can then use Javascript to check it's innerHTML property once the page has loaded. If innerHTML has a length of zero, then you can set it's display property to none. [This page](http://www.tizag.com/javascriptT/javascript-innerHTML.php) might help if you don't know your javascript.
This is still a mucky way to play. If you know the element shouldn't be rendered before you serve the page it would be better to omit it altogether. If you don't want to omit the element, just hide it, then force it into hiding; `style="display: none"` | Don't use padding on container, use margin on content. Than when there is no content, container remains invisible. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | If it's *necessary* to have the `div.someElement` in the HTML, the best CSS/HTML way to do that would be to add an extra `div` around the added content that has the padding property
```
.someElement > div{padding-top:5px;}
<div class="someElement"><div>Content</div></div>
```
Otherwise, do as Pekka says, or take a look at having javascript do it for you. | At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | If it's *necessary* to have the `div.someElement` in the HTML, the best CSS/HTML way to do that would be to add an extra `div` around the added content that has the padding property
```
.someElement > div{padding-top:5px;}
<div class="someElement"><div>Content</div></div>
```
Otherwise, do as Pekka says, or take a look at having javascript do it for you. | Don't use padding on container, use margin on content. Than when there is no content, container remains invisible. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | You can do the trick with the CSS3 pseudo-class :empty
```
.someElement
{
// your standard style
}
.someElement:empty
{
display:none;
}
```
Sadly Internet explorer doesn't support that feauture yet. For all the other browsers it shall do just fine... | Give the empty element a different class (say `someHiddenElement`) when you are generating the content. Then add `someHiddenElement { display: none }` to your style sheet. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | ```
<style>
.someElement{padding-top: 5px; display:table;}
</style>
<div class="someElement">With padded content</div>
<div class="someElement"><!-- shouldn't render since it has no content --></div>
```
Adding display:table; should do the trick. | I can't think of a CSS only way to do that.
I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | ```
<style>
.someElement{padding-top: 5px; display:table;}
</style>
<div class="someElement">With padded content</div>
<div class="someElement"><!-- shouldn't render since it has no content --></div>
```
Adding display:table; should do the trick. | Don't use padding on container, use margin on content. Than when there is no content, container remains invisible. |
1,992,827 | I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query? | 2010/01/02 | ['https://Stackoverflow.com/questions/1992827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107922/'] | I can't think of a CSS only way to do that.
I would try to decide whether the element is rendered at the time I know whether there will be any content in it. That is probably the cleanest solution. | At the point where you populate the optional `div`, if there is no text to put in it, try changing the CSS `display` property to `none.` According to [this source](http://webdesign.about.com/od/css/f/blfaqhidden.htm) (and others), `display: none` removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code. |
20,354,862 | Even If I choose only one branch in git extensions it still shows me something like this. Why are there additional vertical lines? As I found out, red one is branch in my local repo, why is there a separate blue line with tags, why aren't they on red line?
Edit: and what are these circles and rectangles mean?
![enter image description here](https://i.stack.imgur.com/qUCLM.png) | 2013/12/03 | ['https://Stackoverflow.com/questions/20354862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260894/'] | A git branch is basically a name that points to a commit, but the commit it points to is updated whenever a new commit is added to the branch.
Git is an acyclic directed graph. Each git commit has a) an optional [tree object](http://www.gitguys.com/topics/git-object-tree/), b) an optional parent commit (or two or more parents if it's a merge commit), and c) Commit metadata (committer name, email, commit message, etc.). This means that a branch, which in implementation is just a special auto-updated pointer to a commit, represents the entire subgraph accessible by traversing from that commit along its parents, and their parents, etc. In a history with no merges you will get what you expect; a single straight line of commits. In a history with merges you will see what you have here, multiple paths expanding outward (and merging inwards when a commit started two separate branches which were later merged together. | And for your edit:
The circles represent revisions in the history.
The squares represent a revision which is referenced by one ore more branches. |
19,142 | I have a new LCD for my HTC phone, but unfortunately it's not press-fit or screw on like some older phones. I have to re-glue it back. What domestic glues (not superglue as I've heard it cracks when dry) could I use to put my LCD screen back onto my phone please? I was thinking a more glutenous glue like vinyl repair or heated glue? Thanks | 2018/09/05 | ['https://lifehacks.stackexchange.com/questions/19142', 'https://lifehacks.stackexchange.com', 'https://lifehacks.stackexchange.com/users/25469/'] | Replacement screens, event rebuilds, may come with an adhesive strip already attached. This is also how these screens were mounted in the first place.
If that is not the case we may use double-sided adhesive tape (AKA double-sided sticky tape, mounting tape, carpet tape) that we cut into the desired dimensions.
Before we attach the replacement we have to carfully remove **all** remnants of the original tape. | If you're mounting a screen assembly (protective glass/touch sensitive digitiser/LCD display) onto a phone chassis, a double sided sticky foam as Takkat recommends - surprised it didn't come with the display/wasn't already attached but may be available separately, computer cut for your exact phone dimensions
If you mean glueing a protective glass onto a digitiser or digitiser onto an LCD (depending how your phone screen stack is constructed) there's a specific glue for it, referred to as LOCA, optically clear (and indeed forms a vital part of the vibrancy of the display) - it is set using UV light after being applied
Both these items are available on the likes of amazon and eBay. Your local mobile phone repair place should also be able to advise and supply |
15,594,289 | I am trying to display some images in a ListView and have not been successful. I am using WPF MVVM and the ListView is a holdover from simply displaying suits and rank data. (See my previous post: [MVVM in WPF - How to alert ViewModel of changes in Model... or should I?](https://stackoverflow.com/questions/15439841/mvvm-in-wpf-how-to-alert-viewmodel-of-changes-in-model-or-should-i) if you are interested!) That is, I could use something other than ListView (if that is the advice) but I would still like to know how to do it with ListView, assuming it's doable. My property I'm binding to in the ViewModel is:
```
public ObservableCollection<Image> PlayerCardImages{
get{
ObservableCollection<Image> results = new ObservableCollection<Image>();
foreach (CardModel card in PlayerCards)
{
Image img = new Image();
BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
// TODO: Pick card based on suit/rank. Just get 1 image working now
bi3.UriSource = new Uri("diamond-1.png", UriKind.Relative);
bi3.EndInit();
img.Stretch = Stretch.Fill;
img.Source = bi3;
results.Add(img);
}
return results;
}
}
```
In my **XAML** code I'm using:
```
<Window.Resources>
<DataTemplate x:Key="ImageCell">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding PlayerCardImages}" Width="200" Height="200" Stretch="Fill" ToolTip="Add tooltip"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel Orientation="Vertical">
<Label Content="Player Cards"/>
<ListView Name="lvwTitles" ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True"
SelectionMode="Single" ItemTemplate="{StaticResource ImageCell}" Height="59">
</ListView>
</StackPanel>
```
This idea was shamelessly stolen from: [WPF - bind images horizontally to ListView](https://stackoverflow.com/questions/10457872/wpf-bind-images-horizontally-to-listview) However, it doesn't even appear to databind as evidenced by my breakpoint in PlayerCardImages not being hit.
I also tried the following XAML with somewhat better luck:
```
<StackPanel Orientation="Vertical">
<Label Content="Player Cards"/>
<ListView
AlternationCount="2"
DataContext="{StaticResource PlayerCardsGroups }"
ItemsSource="{Binding}"
>
<ListView.GroupStyle>
<StaticResourceExtension
ResourceKey="CardGroupStyle"
/>
</ListView.GroupStyle>
<ListView.View>
<GridView>
<GridViewColumn>
<Image Height="50" Width="40"></Image>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
<Window.Resources>
<CollectionViewSource x:Key="PlayerCardsGroups"
Source="{Binding Path=PlayerCardImages}">
</CollectionViewSource>
<GroupStyle x:Key="CardGroupStyle">
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock
x:Name="txt"
Background="{StaticResource Brush_HeaderBackground}"
FontWeight="Bold"
Foreground="White"
Margin="1"
Padding="4,2,0,2"
Text="Cards"
/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
<Style x:Key="CardItemStyle" TargetType="{x:Type ListViewItem}">
<!--
Stretch the content of each cell so that we can
right-align text in the Total Sales column.
-->
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<!--
Bind the IsSelected property of a ListViewItem to the
IsSelected property of a CustomerViewModel object.
-->
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="ItemsControl.AlternationIndex" Value="1" />
<Condition Property="IsSelected" Value="False" />
<Condition Property="IsMouseOver" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Background" Value="#EEEEEEEE" />
</MultiTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
```
this code definitely goes through databinding - my breakpoint is hit at the beginning of the program and whenever items are added to the collection. But no images is displayed. Rather than torture you with more XAML that does not work, perhaps I could ask someone to point me to some code/examples/docs that show how to bind a list of Images to a ListView (or another control if you really feel that ListView is inappropriate). Notice that my collection is the stuff I'm binding to. I notice that with many examples, they are binding to a subproperty. I.e. they may have a collection of albums and for each album they bind to it's property image (see: [Showing items as images in a WPF ListView](https://stackoverflow.com/questions/2570568/showing-items-as-images-in-a-wpf-listview)).
Any ideas or help would be much appreciated.
-Dave
**Additional info.**
Based on suggestions by Clemens, I now have this code for PlayerCardImages:
```
public ObservableCollection<ImageSource> PlayerCardImages
{
get
{
var results = new ObservableCollection<ImageSource>();
//if (PlayerCards.Count == 0)
// return results;
//else
//{
// results.Add(new BitmapImage(new Uri(@"Images\\" + "diamond-1.png", UriKind.Relative)));
//}
foreach (var card in PlayerCards)
{
results.Add(new BitmapImage(new Uri(@"Images\\" + GetCardFileName(card), UriKind.Relative)));
}
return results;
}
```
I used the exact XAML he suggested. It almost works. I say "almost" because I noticed strange behavior whereby sometimes 1 card would show and sometimes not (I never got 2 cards). All the getting cards from files and binding seems to be working and I tracked down what I think is key to the last remaining bug (and it's BIZARRE). If in the debugger, I examine results, and further open up results[0] in the debugger, I get that card displayed! I actually have to open up [0] (you see info about height, width, etc.) for this to work. Furthermore if I open up [1], I get that card displayed instead. Why would opening up the debugger info have any effect? For those of you who might ask, what happens if you open up both cards in the debugger... that doesn't work. I get a operation timed out exception. I will say that perhaps my image files are big. 10Kbytes to 30 Kbytes. Is that the problem? I'm guessing not, and that it's a subtle problem with reading in the images or binding. What is going on? Thanks, Dave | 2013/03/24 | ['https://Stackoverflow.com/questions/15594289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286641/'] | First, you should not use Image controls in your ViewModel. You already have an Image control in the DateTemplate of your view. You want to bind the `Source` property of this Image conntrol, and the source property of this binding can't be another Image.
Instead your ViewModel would either use [`ImageSource`](http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx) (or a derived class like [`BitmapImage`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx)) as image type, like this:
```
public ObservableCollection<ImageSource> PlayerCardImages
{
get
{
var results = new ObservableCollection<ImageSource>();
foreach (var card in PlayerCards)
{
results.Add(new BitmapImage(new Uri(card.ImageUrl)));
}
return results;
}
}
```
Or simply the image URIs or paths, as there is an automatic conversion from `string` to `ImageSource` built into WPF:
```
public ObservableCollection<string> PlayerCardImages
{
get
{
var results = new ObservableCollection<string>();
foreach (var card in PlayerCards)
{
results.Add(card.ImageUrl);
}
return results;
}
}
```
You would now bind your Listbox's `ItemsSource` property to the `PlayerCardGames` collection, and in the DataTemplate you bind directly to the collection item. The ListView's DataContext has to be set to an instance of the object that defines the `PlayerCardGames` property.
```
<ListView ItemsSource="{Binding PlayerCardGames}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
```
---
UPDATE: As there seems to be a problem with loading the image files, you may try the following method. It loads images synchronously and you are able to step through with the debugger.
```
public static ImageSource LoadImage(string fileName)
{
var image = new BitmapImage();
using (var stream = new FileStream(fileName, FileMode.Open))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
return image;
}
```
You can use this method in your `PlayerCardGames` property getter like this:
```
foreach (var card in PlayerCards)
{
results.Add(LoadImage(@"Images\\" + GetCardFileName(card)));
}
``` | I didn't really try to reproduce your problem, but I will if this is not solving it:
In your first xaml block, I think you mixed up the bindings. This would be how I expect it, ItemsSource to the ObservableCollection of Images, Image source to the Image.
```
<Image Source="{Binding}" ... />
<ListView Name="lvwTitles" ItemsSource="{Binding PlayerCardImages}" ... />
```
In your second block, you omitted the Source binding altogether:
```
<Image Source="{Binding}" Height="50" Width="40" />
``` |
14,950,314 | UPDATE 1
========
I did some more debugging and found that the constructor is run from the main UI thread but the handleMessage(Message) method is run on the Thread I created, which completely contradicts my understanding of Handlers.
Problem
=======
I've been working on Android for a while now and I've run into an issue that doesn't seem to be documented. I'm not doing anything special with my code. I can't seem to get my application to create any UI elements such as Alert Dialogs and Toast messages from a Handler's handleMessage method.
Additionally, I get a "Thread has not called Looper.prepare()" exception. However, I believe that I shouldn't even need to call Looper.prepare() since I'm not creating a Handler inside of the Thread object. I'm calling the constructor in the main UI thread and then passing it to the new Thread's constructor.
What I Expect
-------------
I should see a Toast message as well as an Alert Dialog.
What Actually Happens
---------------------
Nothing. I've run the debugger on the application and I find that the JVM does launch the Thread. The run method is called and the message is dispatched. The handler handles the method and I run through all the methods of creating the AlertDialog as well as the Toast message but nothing ever shows up.
I've run this application on my Emulator running 4.2, my friend's Samsung Galaxy S3 running 4.0.4, and my own Droid X2 running 2.3.5.
Flow of the Program
===================
1. I create a Handler on the UI thread.
2. I create and start a Thread that will dispatch a message to the Handler.
3. The handler will handle the message
Source Code
===========
<http://pastebin.com/cRfaW7b0>
```
package com.nguyenmp.ErrorTest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Init the UI
setContentView(R.layout.main);
//Create a new handler, passing it the current activity context
final Handler handler = new MyHandler(MyActivity.this);
//Bind a listener to the button on the UI
View view = findViewById(R.id.button);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Start a new thread that will send a message to that handler
new MyThread(handler).start();
}
});
}
private class MyThread extends Thread {
private final Handler mHandler;
MyThread(Handler handler) {
mHandler = handler;
}
@Override
public void run() {
//Dispatch message to UI thread asynchronously
Looper.prepare();
mHandler.dispatchMessage(mHandler.obtainMessage());
}
}
private class MyHandler extends Handler {
private final Context mContext;
MyHandler(Context context) {
mContext = context;
}
@Override
public void handleMessage(Message msg) {
//Show that we got the message
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("HelloWorld");
builder.setMessage("It worked!");
builder.show();
//Another variant of showing that we got the message
Toast.makeText(mContext, "Message Received", Toast.LENGTH_SHORT).show();
System.out.println("Yeah");
}
}
}
``` | 2013/02/19 | ['https://Stackoverflow.com/questions/14950314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/783338/'] | You should use <http://developer.android.com/reference/android/os/Handler.html#sendMessage(android.os.Message)>
to send the message that will be later processed by handleMessage. | The problem was that I was calling dispatchMessage(Message) which is executed imediately on the current thread. I should have been using sendMessage(Message) which would enqueue the given Message to the original thread's message queue that created the Handler in the first place. |
63,394,559 | I have POJO attribute as below,
```
@Column(name = "timeStamp")
private LocalDateTime timeStamp;
```
This attribute coming from a service, and need to retain the format. I am streaming input from Kafka and need to store in Cassandra.
I'm creating table using datastax API,
```
CreateTable createTable = SchemaBuilder.createTable("sample31", "contactNew")
.ifNotExists()
.withColumn("timeStamp", DataTypes.TIMESTAMP);
```
When my job execution, am facing the below exception,
```
Codec not found for requested operation: [timestamp <-> java.time.LocalDateTime]
```
I tried with different data type such as `DataTypes.DURATION` , `DataTypes.DATE` not working. | 2020/08/13 | ['https://Stackoverflow.com/questions/63394559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2182920/'] | For Java driver 3.x you need to use a separate package - so-called "Optional codecs" by including an additional dependency:
```xml
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-extras</artifactId>
<version>driver-version</version>
</dependency>
```
For `LocalDateTime` from Java 8 there is a `LocalDateTimeCodec` ([doc](https://docs.datastax.com/en/developer/java-driver/3.8/manual/custom_codecs/extras/#jdk-8)) that should be registered when you created a cluster object, like this:
```java
import com.datastax.driver.extras.codecs.jdk8.LocalDateTimeCodec;
cluster.getConfiguration().getCodecRegistry()
.register(LocalDateTimeCodec.instance);
```
There is similar codecs for Java driver 4.x, starting with driver 4.8. Also just register necessary codec as [described in documentation](https://docs.datastax.com/en/developer/java-driver/4.8/manual/core/custom_codecs/#mapping-cql-timestamps-to-local-date-time). But the easiest way is to register all necessary codecs at the session build time with something like this:
```java
CqlSession session = CqlSession.builder().addTypeCodecs()....build();
``` | Just convert it to Instant and it will be mapped automatically:
```
message.getLocalDateTime().toInstant(ZoneOffset.UTC)
``` |
48,798,101 | What I want to do is save one y dataframe for each file in the loop below.Right now, I only have the last one.
```
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
for (file in myfiles){
y <- some code
}
```
y has 26 observations of 2 variables.
Sorry if this is not a working example. My data is too big even if taking samples. Any help is much appreciated. | 2018/02/14 | ['https://Stackoverflow.com/questions/48798101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7747528/'] | `df <- do.call("rbind",lapply(list.files(pattern = "*.csv"),read.csv, header = TRUE))`
Here is an [example](https://stat.ethz.ch/pipermail/r-help/2003-April/032077.html). | If I understand well, you want to save `y` as a `csv`? You could do something like this:
```
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
## Adding a counter to be incremented in the loop
counter <- 1
for (file in myfiles){
y <- some code
## writing the csv
write.csv(y, file = paste0("my_csv_", counter, ".csv")
## Increment the counter
counter <- counter + 1
}
```
Or do you want to save `y` as a variable containing all your data.frames? In this case, you can do something like this:
```
temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.csv)
## Adding a counter to be incremented in the loop
counter <- 1
## Create an empty list y
for (file in myfiles){
y[[counter]] <- some code
## Increment the counter
counter <- counter + 1
}
``` |
25,582,291 | I am trying to call a stored procedure using entity framework 6. I get an error on the output message.
>
> A first chance exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll
>
>
>
```
using (var context = new PartnerPortalEntities2())
{
var outputParameter = new ObjectParameter("result", typeof(string));
var spresults = context.assignRoles_CreateAccountAndContacts(user.Id, role, user.AccountId, user.AccountName, user.ContactId, user.FirstName, user.LastName, outputParameter);
// Control never comes after the above line
if(spresults.Equals("1"))
{
//Do something
}
else
{
// Do something
}
}
```
When i do a debug, The control goes to line where the stored procedure is called after which we get the above error on the output window and the debugger stops, it never gets into the if statements.
I have run the stored procedure on SQLserver and it works fine there. Any thoughts what could be the error. I have built the context by generating the code from database. | 2014/08/30 | ['https://Stackoverflow.com/questions/25582291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193247/'] | As suggested by @Shoe, i had embeded the call to stored procedure with in a try catch block which caught the exception and showed the exact error.
It turned out to be that i was not passing the exact variable as the output parameter. Changed result to results as the variable defined in stored procedure was results
```
var outputParameter = new ObjectParameter("result", typeof(string));
``` | I just had the same error and I managed to fix it!
This error could be a result of other reasons, but the reason for this error was that the SQL server was not configured to accept transport from my debugging station- I had to configure the IP of my computer in the Sql server settings and then it worked perfectly.
Hope it helps. |
19,600,123 | I have created a timeline card with a custom menu item. I would like to get a callback when the user has selected that menu item.
```
// Create a menu item for the card
var mnuActivate = new MenuItem() {
Action = "CUSTOM",
RemoveWhenSelected = new bool?(true),
Id = ACCEPT_ID,
Values = new List<MenuValue>() {
new MenuValue() {
State="DEFAULT",
DisplayName="Activate",
},
new MenuValue() {
State="PENDING",
DisplayName="Activating..."
},
new MenuValue() {
State="CONFIRMED",
DisplayName="Activated"
}
}
}
// Create a new card for the user's timeline
var item = new TimelineItem() {
Html = html,
Notification = new NotificationConfig() { Level = "DEFAULT" },
MenuItems = new List<MenuItem>() { mnuActivate }
};
var card = this._service.Timeline.Insert(item).Fetch();
```
I then subscribe to all timeline events and provide an https callback URL
```
// Create a new subscription
var subscription = new Subscription()
{
Collection = "timeline",
Operation = new List(),
CallbackUrl = "<https://mypubliclyavailableserver.com/notify>"
};
this._service.Subscriptions.Insert(subscription).Fetch();
// Retrieve a list of subscriptions to make sure it is there.
var mySubcriptions = this._service.Subscriptions.List().Fetch();
if (mySubcriptions != null && mySubcriptions.Items != null && mySubcriptions.Items.Count == 1)
{
Console.WriteLine("Subscription created successfully.");
}
```
So the subscription is created without any issues as far as I can tell. But after interacting with the card, I never get a callback. What am I missing?
Things I have tried:
1. Populating Ids on the subscription obj, timeline card, and menuItem
2. Subscribing before creating the card instead of after
3. Adding the userId as the UserToken on the subscription object
4. Calling my callback URL directly to ensure that it is listening
JSON Response from GET /mirror/v1/subscriptions:
```
{
"kind": "mirror#subscriptionsList",
"items": [
{
"kind": "mirror#subscription",
"id": "timeline",
"updated": "2013-10-28T15:19:19.404Z",
"collection": "timeline",
"callbackUrl": "https://mypubliclyavailableserver.com/notify"
}
]
}
``` | 2013/10/25 | ['https://Stackoverflow.com/questions/19600123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281336/'] | The main thing you need to keep in mind is [endianness](http://en.wikipedia.org/wiki/Endianness). That is, the order the bytes are interpreted in is different on different platforms.
For example, your Intel CPU might interpret the byte string `0x01 0x00` to be the number 1, but someone else's PowerPC would interpret that string of bytes to be the number 256.
When building a network protocol, it's important to keep issues like this in mind. (you might look at something like [Google Protocol Buffers](https://code.google.com/p/protobuf/), which was designed to address this concern)
Since you're only talking about two bytes, you should also take a look at the `htons()` macro. This converts a 2-byte value from *host order* to *network order*. (network order is *big endian*, whereas host order is often *little endian*, but on big endian platforms `htons()` can simply be defined as a no-op.) If you want to send 4-byte (32-bit) values, you should also take a look at the `htonl()` macro. `htons` stands for *host to network short*, and will convert your 16-byte value to an equivalent *network order* 16-bit value (if you are on an Intel CPU, that means it will return a version of the 16-bit integer with the bytes swapped). When you have incoming bytes, your code should use the `ntohs` (and `ntohl`, for 32-bit values) macro to convert the incoming data from network byte order back to host order. | Also, you'd obviously want to send both bytes using a single socket write operation. Don't write one byte and then write the other using two writes as that could end up being very inefficient over the wire. That is, don't write uint8\_t[0] followed by uint8\_t[1]. Writing &uint16\_t will avoid that situation. |
41,422,231 | I am developing an app with input field, and for pattern using angular js ui-mask.
**HTML**
```
<input type="tel" class="input-field " data-ng-model="registrationField.debitcard" ui-mask="9999 9999 9999 9999" placeholder="Enter ATM/Debit Card Number" ui-mask-placeholder ui-mask-placeholder-char="space" id="debitCardFld" ui-options="{clearOnBlur: false}"/>
```
1. With `type="text"` the code works fine.
2. But when we use `type="password"`, on `focus` of the field, the **spaces** in `pattern` is also masked.
Only when the user types, it has to mask the characters.
Is there any way to achieve it?
Ref: <https://github.com/angular-ui/ui-mask> | 2017/01/02 | ['https://Stackoverflow.com/questions/41422231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2979319/'] | You can use conditional aggregation for this:
```
SELECT column1,
column2
FROM your_table t
GROUP BY column1,
column2
HAVING COUNT(CASE WHEN source = 'a' THEN 1 END) = 0;
``` | You can achieve the desired result using below query:
SELECT DISTINCT COLUMN1, COLUMN2
FROM TABLE1
WHERE Source <> 'a' |
36,939,625 | I'm looking for a way to evaluate price expressions stored in database in Postgres 9.1+
I tried code below from answer in
[How to evaluate expression in select statement in Postgres](https://stackoverflow.com/questions/26063328/how-to-evaluate-expression-in-select-statement-in-postgres)
but got error
```
ERROR: missing FROM-clause entry for table "product"
LINE 1: select product.price*0.95
```
how to fix ?
Maybe it is possible to pass customer and product current row as eval parameters and to use them in eval expresion ?
```
create or replace function eval( sql text ) returns text as $$
declare
as_txt text;
begin
execute 'select ' || sql into as_txt ;
return as_txt ;
end;
$$ language plpgsql;
create table customer
( id int primary key,
priceexpression text );
insert into customer values (1, 'product.price*0.95'),(2,'cost+12.0' );
create table product
( id char(20) primary key,
price numeric(12,4),
cost numeric(12,4) );
insert into product values ('PRODUCT1', 120, 80),('PRODUCT2', 310.5, 290);
select
customer.id as customer,
product.id as product,
eval(priceexpression) as price
from customer,product
``` | 2016/04/29 | ['https://Stackoverflow.com/questions/36939625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742402/'] | *Serg* is basically right. **Your *dyna-SQL* is executed "on its own"** so it needs to be a valid SQL statement (**having "to know" all involved tables**). I [updated my answer in the referred thread](https://stackoverflow.com/a/36909941/1915920) to reflect this.
But to properly cite it in here your example should be something like (actually you should **use the 2nd `eval( sql text, keys text[], vals text[] )` variant!**):
```
eval(
'select '||c.price_expression||' from product where id=:pid',
'{"{cost}",:pid}',
array[ p.cost, p.id ]
) as cust_cost
```
This should be more straight forward, robust and modular than *Serg*s suggestions. | Just add the table name somwhere. May be
```
insert into customer values (1, 'product.price*0.95 FROM product'),(2,'cost+12.0 FROM product' );
```
or may be
```
execute 'select ' || sql || ' FROM product' into as_txt ;
```
at your choice.
Hope this `priceexpression` is not exposed to users but only to restricted number of admins, because it's dangerous sql injection security hole. |
14,249,367 | below is a terminal session illustrating the problem:
```
$ pip install scrappy --user
Requirement already satisfied (use --upgrade to upgrade): scrappy in /home/louist/Documents/Python/Scrappy
Downloading/unpacking guessit (from scrappy)
Downloading guessit-0.5.3.tar.gz (45Kb): 45Kb downloaded
Running setup.py egg_info for package guessit
Downloading/unpacking tvdb-api (from scrappy)
Downloading tvdb_api-1.8.2.tar.gz
Running setup.py egg_info for package tvdb-api
Downloading/unpacking hachoir-metadata (from scrappy)
Downloading hachoir-metadata-1.3.3.tar.gz (52Kb): 52Kb downloaded
Running setup.py egg_info for package hachoir-metadata
Warning: unable to recompile dialog.ui to dialog_ui.py using pyuic4
(use command "-c egg_info --egg-base pip-egg-info --disable-qt" to disable this warning)
Downloading/unpacking hachoir-core (from scrappy)
Downloading hachoir-core-1.3.3.tar.gz (91Kb): 91Kb downloaded
Running setup.py egg_info for package hachoir-core
Downloading/unpacking hachoir-parser (from scrappy)
Downloading hachoir-parser-1.3.4.tar.gz (359Kb): 359Kb downloaded
Running setup.py egg_info for package hachoir-parser
warning: no files found matching 'metadata_csv.py'
Installing collected packages: guessit, tvdb-api, hachoir-metadata, hachoir-core, hachoir-parser
Running setup.py install for guessit
Running setup.py install for tvdb-api
Running setup.py install for hachoir-metadata
Warning: unable to recompile dialog.ui to dialog_ui.py using pyuic4
(use command "-c install --single-version-externally-managed --record /tmp/pip-3OxvBD-record/install-record.txt --install-headers /home/louist/.virtualenvs/test/include/site/python2.7 --user --disable-qt" to disable this warning)
changing mode of build/scripts-2.7/hachoir-metadata from 664 to 775
changing mode of build/scripts-2.7/hachoir-metadata-gtk from 664 to 775
changing mode of build/scripts-2.7/hachoir-metadata-qt from 664 to 775
deleting hachoir_metadata.egg-info/requires.txt
changing mode of /home/louist/.local/bin/hachoir-metadata to 775
changing mode of /home/louist/.local/bin/hachoir-metadata-gtk to 775
changing mode of /home/louist/.local/bin/hachoir-metadata-qt to 775
Running setup.py install for hachoir-core
Running setup.py install for hachoir-parser
deleting hachoir_parser.egg-info/requires.txt
warning: no files found matching 'metadata_csv.py'
Successfully installed guessit tvdb-api hachoir-metadata hachoir-core hachoir-parser
Cleaning up...
(test)louist@ltpc:~/Documents/Python/Scrappy$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import scrappy.core as scrappy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "scrappy/core.py", line 10, in <module>
import guessit
ImportError: No module named guessit
```
In a nutshell, I did the following:
1. start a virtualenv with `mkvirtualenv test`
2. try to install the package i'm developing via `pip install scrappy --user`
3. start python terminal and then try to import `scrappy.core`
Here is my setup.py file:
```
#!/usr/bin/env python
from setuptools import setup
setup(
name='Scrappy',
version="0.2.7 alpha",
author='Louis Thibault',
author_email='[email protected]',
packages=['scrappy'],
include_package_data=True,
install_requires=['guessit', 'tvdb_api', 'hachoir-metadata', 'hachoir-core', 'hachoir-parser'],
url='https://github.com/louist87/scrappy',
license='GPL 3.0',
description='Rename video files based on information scraped from thetvdb.com',
keywords=["TVDB", "thetvdb", "rename", "broadcatching", "media"],
long_description=open('README.rst').read()
)
```
Any ideas as to what's going on? | 2013/01/10 | ['https://Stackoverflow.com/questions/14249367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1156707/'] | By default new virtualenv doesn't include packages installed outside of it (created without `--system-site-packages` option). Therefore your `test` virtualenv doesn't see packages installed to `~/.local` (due to `--user` option).
Either create virtualenv with --system-site-packages option or don't use --user while installing within activated virtualenv. | I had a similar issue, it was a distros problem
When i installed using the following -
```
sudo apt-get install python-scrapy
```
from command line it work. Do make sure you update your repository before hitting the above command to get a current version |
444,376 | **Duplicate of: [In Python, how do I get the path and name of the file that is currently executing?](https://stackoverflow.com/questions/50499/in-python-how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing)**
I would like to find out the path to the currently executing script.
I have tried os.getcwd() but that only returns the directory I ran the script from not the actual directory the script is stored. | 2009/01/14 | ['https://Stackoverflow.com/questions/444376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32933/'] | In Python, `__file__` identifies the current Python file. Thus:
```
print "I'm inside Python file %s" % __file__
```
will print the current Python file. Note that this works in imported Python modules, as well as scripts. | How about using sys.path[0]
You can do something like
'print os.path.join(sys.path[0], sys.argv[0])'
<https://docs.python.org/library/sys.html> |
19,517,707 | I'd like to sort a `List` on element *counts* of `IGrouping`s.
And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects.
**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first.
**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with). | 2013/10/22 | ['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/'] | Almost no operation in .NET clones an object. Neither deeply nor shallowly. LINQ also does not clone the elements it processes. Therefore, a simple LINQ query will work:
```
var oldList = ...;
var newList = (from x in oldList
group x by something into g
orderby g.Count()
from x in g //flatten the groups
select x).ToList();
```
This code copies *references* to the original objects. If you believe otherwise, you are probably misinterpreting what you are seeing. | Well, this is embarrassing.
My mistake was indeed based on a misunderstanding:
```
class Item
{
internal string Value { get; set; }
internal string Qux { get; set; }
internal string Quux { get; set; }
}
var query = from i in list
group i by new { i.Value, i.Qux } into g // Note: no Quux, no primary key, just what's necessary
orderby g.Count() descending, g.Key.Value
select new { // [1]
Value = g.Key.Value,
Qux = g.Key.Qux,
// Quux?
}
```
My bad assumption was that the selection at [1] was acting on individual records, much like SQL. Well, hopefully I can save someone who had the same assumption: it is not.
It seems obvious now, but the selection acts on individual groups, and hence here a new object would be created for each group, not for each element.
My second mistake was in focusing on the key, wondering how one would "pass" other properties without using it. I was also worried that we seemed to be required to make shallow copies of our objects. Again this is based on the fact that we were clueless as to how the `IGrouping` is behaving: since we didn't know we were selecting on the groups, we couldn't even create new objects for each element from the select.
The solution is definitely not impressive:
```
var query = from i in list
group i by new { i.Value, i.Qux } into g
orderby g.Count() descending, g.Key.Value
select g;
foreach (var group in query)
{
foreach (var item in group)
Console.WriteLine("{0} {1} {2} [Original object? {3}]",
item.Value,
item.Qux,
item.Quux,
list.Contains(item));
Console.WriteLine("-");
}
```
Output:
```
AAA Foo ... [Original object? True]
AAA Foo ... [Original object? True]
AAA Foo ... [Original object? True]
-
BBB Foo ... [Original object? True]
BBB Foo ... [Original object? True]
-
AAA Bar ... [Original object? True]
-
CCC Foo ... [Original object? True]
-
DDD Foo ... [Original object? True]
-
DDD Bar ... [Original object? True]
-
EEE Foo ... [Original object? True]
```
Indeed the `IGrouping` elements are the original elements. From there we can create a new list without any issue.
**Update:** I flatten the result set outside of the query mainly to be able to write the group separator to the console for demonstration purposes, but see Tim's and usr's answers to flatten inside the query using `SelectMany` (and equivalent Linq syntax).
Needless to say, this was another classic case of "we're in too much of a hurry, let's read some examples here and there and that'll be it", where the proper approach would have been to spend a little bit of time learning the fundamentals. Linq is not SQL.
My apologies for the time you may have wasted trying to clear the confusion. Hopefully someone else in a hurry might benefit from these mistakes now. |
19,517,707 | I'd like to sort a `List` on element *counts* of `IGrouping`s.
And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects.
**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first.
**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with). | 2013/10/22 | ['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/'] | ```
var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
.SelectMany(x => x).ToList();
``` | Almost no operation in .NET clones an object. Neither deeply nor shallowly. LINQ also does not clone the elements it processes. Therefore, a simple LINQ query will work:
```
var oldList = ...;
var newList = (from x in oldList
group x by something into g
orderby g.Count()
from x in g //flatten the groups
select x).ToList();
```
This code copies *references* to the original objects. If you believe otherwise, you are probably misinterpreting what you are seeing. |
19,517,707 | I'd like to sort a `List` on element *counts* of `IGrouping`s.
And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects.
**Specifically:** We have an entity with many properties, and a list of objects of this type. We'd like to **(1)** group the objects by certain properties (name, address, ...) then **(2)** count the number of elements in each group. Finally we'd like to **(3)** reorder the list based on these counts by placing the elements that are part of the larger groups first.
**Note:** Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by `IGrouping`. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with). | 2013/10/22 | ['https://Stackoverflow.com/questions/19517707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266481/'] | ```
var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
.SelectMany(x => x).ToList();
``` | Well, this is embarrassing.
My mistake was indeed based on a misunderstanding:
```
class Item
{
internal string Value { get; set; }
internal string Qux { get; set; }
internal string Quux { get; set; }
}
var query = from i in list
group i by new { i.Value, i.Qux } into g // Note: no Quux, no primary key, just what's necessary
orderby g.Count() descending, g.Key.Value
select new { // [1]
Value = g.Key.Value,
Qux = g.Key.Qux,
// Quux?
}
```
My bad assumption was that the selection at [1] was acting on individual records, much like SQL. Well, hopefully I can save someone who had the same assumption: it is not.
It seems obvious now, but the selection acts on individual groups, and hence here a new object would be created for each group, not for each element.
My second mistake was in focusing on the key, wondering how one would "pass" other properties without using it. I was also worried that we seemed to be required to make shallow copies of our objects. Again this is based on the fact that we were clueless as to how the `IGrouping` is behaving: since we didn't know we were selecting on the groups, we couldn't even create new objects for each element from the select.
The solution is definitely not impressive:
```
var query = from i in list
group i by new { i.Value, i.Qux } into g
orderby g.Count() descending, g.Key.Value
select g;
foreach (var group in query)
{
foreach (var item in group)
Console.WriteLine("{0} {1} {2} [Original object? {3}]",
item.Value,
item.Qux,
item.Quux,
list.Contains(item));
Console.WriteLine("-");
}
```
Output:
```
AAA Foo ... [Original object? True]
AAA Foo ... [Original object? True]
AAA Foo ... [Original object? True]
-
BBB Foo ... [Original object? True]
BBB Foo ... [Original object? True]
-
AAA Bar ... [Original object? True]
-
CCC Foo ... [Original object? True]
-
DDD Foo ... [Original object? True]
-
DDD Bar ... [Original object? True]
-
EEE Foo ... [Original object? True]
```
Indeed the `IGrouping` elements are the original elements. From there we can create a new list without any issue.
**Update:** I flatten the result set outside of the query mainly to be able to write the group separator to the console for demonstration purposes, but see Tim's and usr's answers to flatten inside the query using `SelectMany` (and equivalent Linq syntax).
Needless to say, this was another classic case of "we're in too much of a hurry, let's read some examples here and there and that'll be it", where the proper approach would have been to spend a little bit of time learning the fundamentals. Linq is not SQL.
My apologies for the time you may have wasted trying to clear the confusion. Hopefully someone else in a hurry might benefit from these mistakes now. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too.
Of course it looks like you have decided to use Advanced Installer. Good luck. | We have chosen WiX too. Mind you that you will still need to know all about Windows Installer mechanisms. WiX is version control friendly and very transparent
If you need custom actions and would like to write that in a .NET language then go for the CustomActionAttribute approach. You can write setup dialogs using WinForms.
This site is also a very good source [InstallSite.org](http://www.installsite.org/) |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too.
Of course it looks like you have decided to use Advanced Installer. Good luck. | Since you mention Visual Studio and .net, I'm assuming you are deploying to Windows based servers, but even still you might want to take a look at [fabric](http://www.nongnu.org/fab/). It is a python based deployment tool. You can write and launch scripts to deploy and setup your servers, web services, etc.. The only thing is I'm not sure how well it plays with Windows as the target server. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | WiX is your friend here.
<http://wix.sourceforge.net/>
WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there.
There are a number of blogs that are relevant to WiX out there. Check out:
<http://www.joyofsetup.com/>
<http://robmensching.com/blog/> | There are three things I don't like about InstallShield:
1. It seems overly complex
2. There is no way (to my knowledge) of generating from the command line, you always have to use the GUI, which is a hindrance for automated builds.
3. It seems to add an excessive amount of overhead.
I've used [NSIS](http://nsis.sourceforge.net/) a fair bit, which is open source. Whereas InstallShield has almost a too high level a view of things, NSIS is almost a too low level. You have to write the code to poke the registry entries in for uninstalling via Add/Remove programs for instance. You will be able to get the job done, and have full control of exactly what it will do, though, and it will package into a very compact single executable.
I have no experience with [InnoSetup](http://www.jrsoftware.org/isinfo.php) or [WiX](http://wix.sourceforge.net/) - either of them may steer a course between the two extremes of InstallShield and NSIS. Both are freely available and worth a look as well. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use. | WiX is your friend here.
<http://wix.sourceforge.net/>
WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there.
There are a number of blogs that are relevant to WiX out there. Check out:
<http://www.joyofsetup.com/>
<http://robmensching.com/blog/> |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too.
Of course it looks like you have decided to use Advanced Installer. Good luck. | There are three things I don't like about InstallShield:
1. It seems overly complex
2. There is no way (to my knowledge) of generating from the command line, you always have to use the GUI, which is a hindrance for automated builds.
3. It seems to add an excessive amount of overhead.
I've used [NSIS](http://nsis.sourceforge.net/) a fair bit, which is open source. Whereas InstallShield has almost a too high level a view of things, NSIS is almost a too low level. You have to write the code to poke the registry entries in for uninstalling via Add/Remove programs for instance. You will be able to get the job done, and have full control of exactly what it will do, though, and it will package into a very compact single executable.
I have no experience with [InnoSetup](http://www.jrsoftware.org/isinfo.php) or [WiX](http://wix.sourceforge.net/) - either of them may steer a course between the two extremes of InstallShield and NSIS. Both are freely available and worth a look as well. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use. | I have used [Installshield](http://www.acresso.com/products/is/installshield-overview.htm), [NSIS](http://nsis.sourceforge.net/), Visual Studio and [WiX](http://wix.sourceforge.net/). Installshield always produced a bloated installer for me and costs alot. Visual Studio can be limited in some of the things that it can do, but overall it is pretty good. NSIS is definately a nice little install system since I have use it for a few products (one that has been downloaded and installed about 750k times) but when I was using it it did not follow the MSI rules. WiX is great and provides you with alot of functionality as well but is script based but there are GUIs for it now too.
Of course it looks like you have decided to use Advanced Installer. Good luck. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use. | If you want to or have to adhere to the MSI standard installs for the Windows platform, I'd second Martin Peck's recommendation for WiX. It's basically the same technology the VS-setup projects and Installshield use - with all its pros and cons.
If you do **not** need to be on the MSI train, you could also look at simpler alternatives - my favourite here would be [InnoSetup](http://www.jrsoftware.org/isinfo.php). It's free, it's totally easy to use, it's open source (Pascal/Delphi), it can install your apps in a fraction of a second, it JUST WORKS! :)
Marc |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use. | We have chosen WiX too. Mind you that you will still need to know all about Windows Installer mechanisms. WiX is version control friendly and very transparent
If you need custom actions and would like to write that in a .NET language then go for the CustomActionAttribute approach. You can write setup dialogs using WinForms.
This site is also a very good source [InstallSite.org](http://www.installsite.org/) |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | After reading these answers we ended up deciding to use Advanced Installer, it has the advantage of adhering to the MSI standards and also of being quite simple to use. | Since you mention Visual Studio and .net, I'm assuming you are deploying to Windows based servers, but even still you might want to take a look at [fabric](http://www.nongnu.org/fab/). It is a python based deployment tool. You can write and launch scripts to deploy and setup your servers, web services, etc.. The only thing is I'm not sure how well it plays with Windows as the target server. |
806,400 | We have a project with several applications including web applications, web services, windows services and windows applications. We also have prerequisites like SQL Server Express, .NET 2.0 and others. We don't have much user interaction during the setup but we want to add more intelligence to it.
We are currently using Visual Studio to generate the integrated setup for all this. But we continuously struggle with it to make it work like we want.
We want to change our setup tool into something simpler and flexible enough.
We are also looking for a better solution for the upgrader, that must run upgrade sql scripts on the deployed system. Maybe this could be integrated with the setup.
We are thinking about using InstallShield, but some say that it brings a lot of complexity. What do you think is the best tool for this job?
Thanks! | 2009/04/30 | ['https://Stackoverflow.com/questions/806400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44547/'] | WiX is your friend here.
<http://wix.sourceforge.net/>
WiX is an incredibly flexible setup technology, xml driven and with a lot of tools and knowledge out there.
There are a number of blogs that are relevant to WiX out there. Check out:
<http://www.joyofsetup.com/>
<http://robmensching.com/blog/> | If you want to or have to adhere to the MSI standard installs for the Windows platform, I'd second Martin Peck's recommendation for WiX. It's basically the same technology the VS-setup projects and Installshield use - with all its pros and cons.
If you do **not** need to be on the MSI train, you could also look at simpler alternatives - my favourite here would be [InnoSetup](http://www.jrsoftware.org/isinfo.php). It's free, it's totally easy to use, it's open source (Pascal/Delphi), it can install your apps in a fraction of a second, it JUST WORKS! :)
Marc |
56,685,913 | I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help.
I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired.
```
import pandas.io.sql as psql
from datetime import datetime
import xlwt
import numpy
date = datetime.strftime(datetime.now(), '%m.%d.%Y')
cnxn = pyodbc.connect(
driver='{SQL Server}',
Server='atlmktsql06',
Database='Repository',
trusted_connection='yes')
cursor = cnxn.cursor()
sql = ("""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'""")
df = psql.read_sql_query(sql, cnxn)
cnxn.close()
psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce')
a = df.head(60)
print(a)
print(df.dtypes)
df.to_excel(r'C:\PythonCode\Testing.xls')
```
The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again! | 2019/06/20 | ['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/'] | One option is to use the base R function `setNames`
```
aggregate_mtcars <- mtcars_copy[, setNames(.(sum(carb)), new_col)]
```
Or you could use `data.table::setnames`
```
aggregate_mtcars <- setnames(mtcars_copy[, .(sum(carb))], new_col)
``` | I think what you want is to simply make a copy when doing case 1.
```
aggregate_mtcars <- copy(mtcars_copy)[, eval(new_col) := sum(carb)]
```
That retains `mtcars_copy` as a separate dataset to the new `aggregate_metcars`, without the new columns. |
56,685,913 | I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help.
I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired.
```
import pandas.io.sql as psql
from datetime import datetime
import xlwt
import numpy
date = datetime.strftime(datetime.now(), '%m.%d.%Y')
cnxn = pyodbc.connect(
driver='{SQL Server}',
Server='atlmktsql06',
Database='Repository',
trusted_connection='yes')
cursor = cnxn.cursor()
sql = ("""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'""")
df = psql.read_sql_query(sql, cnxn)
cnxn.close()
psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce')
a = df.head(60)
print(a)
print(df.dtypes)
df.to_excel(r'C:\PythonCode\Testing.xls')
```
The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again! | 2019/06/20 | ['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/'] | I think what you want is to simply make a copy when doing case 1.
```
aggregate_mtcars <- copy(mtcars_copy)[, eval(new_col) := sum(carb)]
```
That retains `mtcars_copy` as a separate dataset to the new `aggregate_metcars`, without the new columns. | The reason is because case 2 uses `data.frame` way to create column in a data frame (as a new list).
There is hidden parameter in data.table : `with` that handles the way the object is returned. It can be a data.table or a vector.
>
> ?data.table :
>
> By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset.
>
>
> When j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is not necessary anymore to select columns dynamically. Note that x[, cols] is equivalent to x[, ..cols] and to x[, cols, with=FALSE] and to x[, .SD, .SDcols=cols].
>
>
>
```r
# Case 2 :
aggregate_mtcars<-mtcars_copy[,(get(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,eval(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,c(eval(new_col)=sum(carb))] # Error
mtcars_copy[, new_col, with = FALSE ] # gives a data.table
mtcars_copy[, eval(new_col), with = FALSE ] # this works and create a data.table
mtcars_copy[, eval(new_col), with = TRUE ] # the default that is used here with error
mtcars_copy[, get(new_col), with = TRUE ] # works and gives a vector
# Case 2 solution : affecting values the data.frame way
mtcars_copy[, eval(new_col) ] <- sum(mtcars_copy$carb) # or any vector
mtcars_copy[[eval(new_col)]] <- sum(mtcars_copy$carb) # or any vector
``` |
56,685,913 | I am pulling data out of a SQL server using pyodbc. The issue is I need to pull data from a certain date frame, however; the date comes across in both an incorrect data type and format. Float64 and 90502(5/02/09 is what I would like.) I am very new to python and far from really even being very good at this and would appreciate any help.
I have tried converting to string, and then strptime but it tells me that the data is in the wrong format. I have also tried the included code, however it does not seem to do what I would like for it to do, as the data still reads as float64, and does not output as desired.
```
import pandas.io.sql as psql
from datetime import datetime
import xlwt
import numpy
date = datetime.strftime(datetime.now(), '%m.%d.%Y')
cnxn = pyodbc.connect(
driver='{SQL Server}',
Server='atlmktsql06',
Database='Repository',
trusted_connection='yes')
cursor = cnxn.cursor()
sql = ("""select * FROM dbo.tblAS400_Vcresrv WHERE VRRESV='CCVNQ'""")
df = psql.read_sql_query(sql, cnxn)
cnxn.close()
psql.to_datetime(psql.Series(['VRIN']).astype(str), infer_datetime_format=True, errors='coerce')
a = df.head(60)
print(a)
print(df.dtypes)
df.to_excel(r'C:\PythonCode\Testing.xls')
```
The end result as stated above would be for the data to convert to date, and also read appropriately so I can use the sql statement in python to pull by timeframe. Currently, VRIN = Float64 and reads as 90502 and I want VRIN = Date 5/02/09. Thank you again! | 2019/06/20 | ['https://Stackoverflow.com/questions/56685913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8112192/'] | One option is to use the base R function `setNames`
```
aggregate_mtcars <- mtcars_copy[, setNames(.(sum(carb)), new_col)]
```
Or you could use `data.table::setnames`
```
aggregate_mtcars <- setnames(mtcars_copy[, .(sum(carb))], new_col)
``` | The reason is because case 2 uses `data.frame` way to create column in a data frame (as a new list).
There is hidden parameter in data.table : `with` that handles the way the object is returned. It can be a data.table or a vector.
>
> ?data.table :
>
> By default with=TRUE and j is evaluated within the frame of x; column names can be used as variables. In case of overlapping variables names inside dataset and in parent scope you can use double dot prefix ..cols to explicitly refer to 'cols variable parent scope and not from your dataset.
>
>
> When j is a character vector of column names, a numeric vector of column positions to select or of the form startcol:endcol, and the value returned is always a data.table. with=FALSE is not necessary anymore to select columns dynamically. Note that x[, cols] is equivalent to x[, ..cols] and to x[, cols, with=FALSE] and to x[, .SD, .SDcols=cols].
>
>
>
```r
# Case 2 :
aggregate_mtcars<-mtcars_copy[,(get(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,eval(new_col)=sum(carb))] # error
aggregate_mtcars<-mtcars_copy[,c(eval(new_col)=sum(carb))] # Error
mtcars_copy[, new_col, with = FALSE ] # gives a data.table
mtcars_copy[, eval(new_col), with = FALSE ] # this works and create a data.table
mtcars_copy[, eval(new_col), with = TRUE ] # the default that is used here with error
mtcars_copy[, get(new_col), with = TRUE ] # works and gives a vector
# Case 2 solution : affecting values the data.frame way
mtcars_copy[, eval(new_col) ] <- sum(mtcars_copy$carb) # or any vector
mtcars_copy[[eval(new_col)]] <- sum(mtcars_copy$carb) # or any vector
``` |
26,974,838 | I want to run Python on 3Dsmax 2014. I saw the website and know 3Dsmax 2014 can use the Python script . But when I try with example from the website, it does not work. Maybe lack of some software or anything else.
I used this code in "MAXscript Listener":
```
python.Execute "print 'hello'"
```
And result was:
```
-- Unknown property: "execute" in undefined
```
So , someone can guide me how to use the Execute ?
Thanks everyone ! | 2014/11/17 | ['https://Stackoverflow.com/questions/26974838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4261541/'] | You would need the Extension 1 (Subscription Advantage Pack) to be able to run python scripts like that. | You need to load python first. Try this:
```
python.init()
python.execute "print 'Hello World'"
``` |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | as Varundroid mentioned in his answer,
```
String userAgent = System.getProperty("http.agent");
```
is better way to do it for Android 2.1 and above.
====================
From android source code.
```
public static String getDefaultUserAgent() {
StringBuilder result = new StringBuilder(64);
result.append("Dalvik/");
result.append(System.getProperty("java.vm.version")); // such as 1.1.0
result.append(" (Linux; U; Android ");
String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
result.append(version.length() > 0 ? version : "1.0");
// add the model for the release build
if ("REL".equals(Build.VERSION.CODENAME)) {
String model = Build.MODEL;
if (model.length() > 0) {
result.append("; ");
result.append(model);
}
}
String id = Build.ID; // "MASTER" or "M4-rc20"
if (id.length() > 0) {
result.append(" Build/");
result.append(id);
}
result.append(")");
return result.toString();
}
``` | **Edit: See Prakash's answer, which is better for 2.1+.**
Try <http://developer.android.com/reference/android/webkit/WebSettings.html#getUserAgentString>
Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do:
```
String userAgent = new WebView(this).getSettings().getUserAgentString();
```
Alternatively, you can use the JavaScript method `navigator.getUserAgent()`. |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | **Edit: See Prakash's answer, which is better for 2.1+.**
Try <http://developer.android.com/reference/android/webkit/WebSettings.html#getUserAgentString>
Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do:
```
String userAgent = new WebView(this).getSettings().getUserAgentString();
```
Alternatively, you can use the JavaScript method `navigator.getUserAgent()`. | When you use web view to access the user-agent, make sure you run the
`new WebView(this).getSettings().getUserAgentString();`
on the UI thread.
If you want access the user agent on background thread.
use
`System.getProperty("http.agent")`
To check whether a user-agent is valid or not use this
<https://deviceatlas.com/device-data/user-agent-tester> |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | **Edit: See Prakash's answer, which is better for 2.1+.**
Try <http://developer.android.com/reference/android/webkit/WebSettings.html#getUserAgentString>
Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do:
```
String userAgent = new WebView(this).getSettings().getUserAgentString();
```
Alternatively, you can use the JavaScript method `navigator.getUserAgent()`. | An alternative
```
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = WebSettings.getDefaultUserAgent(context);
}
``` |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | as Varundroid mentioned in his answer,
```
String userAgent = System.getProperty("http.agent");
```
is better way to do it for Android 2.1 and above.
====================
From android source code.
```
public static String getDefaultUserAgent() {
StringBuilder result = new StringBuilder(64);
result.append("Dalvik/");
result.append(System.getProperty("java.vm.version")); // such as 1.1.0
result.append(" (Linux; U; Android ");
String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
result.append(version.length() > 0 ? version : "1.0");
// add the model for the release build
if ("REL".equals(Build.VERSION.CODENAME)) {
String model = Build.MODEL;
if (model.length() > 0) {
result.append("; ");
result.append(model);
}
}
String id = Build.ID; // "MASTER" or "M4-rc20"
if (id.length() > 0) {
result.append(" Build/");
result.append(id);
}
result.append(")");
return result.toString();
}
``` | When you use web view to access the user-agent, make sure you run the
`new WebView(this).getSettings().getUserAgentString();`
on the UI thread.
If you want access the user agent on background thread.
use
`System.getProperty("http.agent")`
To check whether a user-agent is valid or not use this
<https://deviceatlas.com/device-data/user-agent-tester> |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | as Varundroid mentioned in his answer,
```
String userAgent = System.getProperty("http.agent");
```
is better way to do it for Android 2.1 and above.
====================
From android source code.
```
public static String getDefaultUserAgent() {
StringBuilder result = new StringBuilder(64);
result.append("Dalvik/");
result.append(System.getProperty("java.vm.version")); // such as 1.1.0
result.append(" (Linux; U; Android ");
String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
result.append(version.length() > 0 ? version : "1.0");
// add the model for the release build
if ("REL".equals(Build.VERSION.CODENAME)) {
String model = Build.MODEL;
if (model.length() > 0) {
result.append("; ");
result.append(model);
}
}
String id = Build.ID; // "MASTER" or "M4-rc20"
if (id.length() > 0) {
result.append(" Build/");
result.append(id);
}
result.append(")");
return result.toString();
}
``` | An alternative
```
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = WebSettings.getDefaultUserAgent(context);
}
``` |
6,824,604 | How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib | 2011/07/26 | ['https://Stackoverflow.com/questions/6824604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530993/'] | When you use web view to access the user-agent, make sure you run the
`new WebView(this).getSettings().getUserAgentString();`
on the UI thread.
If you want access the user agent on background thread.
use
`System.getProperty("http.agent")`
To check whether a user-agent is valid or not use this
<https://deviceatlas.com/device-data/user-agent-tester> | An alternative
```
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = WebSettings.getDefaultUserAgent(context);
}
``` |
19,532,982 | I tried to give `@Column(name = "message")` only for the field, but it didn't work.
I have a Bean class, that contains 10 fields but i want to insert only 2 fields using HIBERNATE ANNOTATION..?
How can i omit rest of the fields??
I am getting full Query:
```
insert into message (circle, day, destNumber, encryptedBody, hour, interfaceType, location, message) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
```
Instead i want only:
insert into message (message,msgId) values(?,?) | 2013/10/23 | ['https://Stackoverflow.com/questions/19532982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2888996/'] | According to the [documentation](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-property), you need to annotate the properties that you **don't** want to be persisted as `@Transient`:
```
@Entity
public class Message implements Serializable {
Long id;
int circle;
int day;
String message
//...
@Id
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
// Will not be persisted
@Transient
public int getCircle() { return circle; }
public void setCircle(int circle) { this.circle = circle; }
// Will not be persisted
@Transient
public int getDay() { return day; }
public void setDay(int day) { this.day = day; }
// Will be persisted
public string getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
//...
}
```
If you need the `Id` to be auto-generated, you should annotate it with [`@GeneratedValue`](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-id-generator):
```
@Id
@GeneratedValue
@Column(name = "msgId")
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
```
The `@GeneratedValue` annotation has many parameters that help you define how the identifier should be generated. For example, if it will be generated by the database (identity column) you should use `@GeneratedValue(strategy=GenerationType.IDENTITY)`. [This](http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#d5e2487) section of the documentation lists all of the generation strategies.
Please read the documentation carefully. You'll find the answer to almost all of your questions in the documentation. Refer to the links that I've provided. | For the MsgId issue
1.Make sure that your MsgId field is set to Primary key and auto increment
2.add these annotations for MsgId
>
> @Id
>
>
> @GeneratedValue(strategy=GenerationType.AUTO)
>
>
> public Long getMsgId() {
>
>
> return id;
>
>
> }
>
>
> |
19,532,982 | I tried to give `@Column(name = "message")` only for the field, but it didn't work.
I have a Bean class, that contains 10 fields but i want to insert only 2 fields using HIBERNATE ANNOTATION..?
How can i omit rest of the fields??
I am getting full Query:
```
insert into message (circle, day, destNumber, encryptedBody, hour, interfaceType, location, message) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
```
Instead i want only:
insert into message (message,msgId) values(?,?) | 2013/10/23 | ['https://Stackoverflow.com/questions/19532982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2888996/'] | >
> Use Dynamic insert or dynamic-update
>
>
>
The dynamic-insert attribute tells Hibernate whether to include null properties in the SQL INSERT statement.
To update only modified values Use dynamic-update option
If dynamic-update set to true, then hibernate excludes unmodified properties in the Hibernate’s SQL update statement.
>
> @Entity
>
>
> @Table(name = "table")
>
>
> @org.hibernate.annotations.Entity(
> dynamicUpdate = true)
>
>
> public class Sample implements java.io.Serializable { // }
>
>
>
[Example for dynamic insert](http://www.mkyong.com/hibernate/hibernate-dynamic-insert-attribute-example/)
[Example for dynamic update](http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/) | For the MsgId issue
1.Make sure that your MsgId field is set to Primary key and auto increment
2.add these annotations for MsgId
>
> @Id
>
>
> @GeneratedValue(strategy=GenerationType.AUTO)
>
>
> public Long getMsgId() {
>
>
> return id;
>
>
> }
>
>
> |
47,113,078 | I have a matrix `A` of size 13472x1537. This matrix contains values smaller than 1. In my case I seek for a solution to satisfy the following condition:
If a column contains a value smaller than 1, replace all other values in the same column with `NaN`.
I was able to implement a code that could replace these values (smaller than 1) with the previous value (or any value). However, I am looking for a solution that changes every value in the column to `NaN` no matter whether later (or previous) values are greater than 1.
I have `i=1537`; `t=13472`
```
for i = 1:size(A,2)
I = A(1,i);
for t= 2:size(A,1)
if A(t,i) <= 1
A(t,i) = I;
else
I = A(t,i);
end
end
end
``` | 2017/11/04 | ['https://Stackoverflow.com/questions/47113078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7758301/'] | A version, which gets rid of the loop would look like this:
```
A = randn(5)+2; % Random example
[row,col] = find(A<1);
A(:,col) = NaN;
```
If you would want to keep the values smaller than 1 in the matrix a solution could look something like this:
```
A = randn(5)+2; % Random example
[row,col,ind] = find(A<1);
b = A(ind)
A(:,col) = NaN;
A(ind) = b;
``` | That would be like the following
```
for i = 1:size(A,2)
if ~isempty(find(A(:,i) <= 1))
A(:,i)=nan(size(A,1),1);
end
end
``` |
14,108,373 | I am developing an application in swing which has 5 tabs with following 5 operations on an image :No Operation ,Color Convert ,Affine Transform ,Convolve and Look Up.
Here is the code :
```
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.LookupTable;
import java.awt.image.ShortLookupTable;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class ImageProcessing extends JFrame{
BufferedImage source;
public static void main(String args[])
{
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e1){e1.printStackTrace();}
SwingUtilities.invokeLater(new Runnable(){public void run(){new ImageProcessing();}});
}
public ImageProcessing() {
// TODO Auto-generated constructor stub
super("Image Processing");
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try
{
source=ImageIO.read(new File("src/abc.jpg"));
}catch(IOException e){System.out.println("Exception Here :"+e);}
JTabbedPane jtp=new JTabbedPane();
buildNoOpTab(jtp);
buildAffineTransformOpTab(jtp);
buildColorConvertOpTab(jtp);
buildConvolveOpTab(jtp);
buildLookUpOpTab(jtp);
//buildRescaleOpTab(jtp);
add(jtp);
setVisible(true);
}
private void buildNoOpTab(JTabbedPane jtp)
{
jtp.add("No Op",new JLabel(new ImageIcon(source)));
}
private void buildAffineTransformOpTab(JTabbedPane jtp)
{
BufferedImage dst;
AffineTransform transform=AffineTransform.getScaleInstance(0.5, 0.5);
AffineTransformOp op=new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
dst=op.filter(source, null);
jtp.add("AffineTransform",new JLabel(new ImageIcon(dst)));
}
private void buildColorConvertOpTab(JTabbedPane jtp)
{
BufferedImage dst = null;
ColorSpace clr=ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op=new ColorConvertOp(clr,null);
dst=op.filter(source,dst);
jtp.add("Color Convert",new JLabel(new ImageIcon(dst)));
}
private void buildConvolveOpTab(JTabbedPane jtp) {
BufferedImage dst = null;
float sharpen[] = new float[] {
0.0f, -1.0f, 0.0f,
-1.0f, 5.0f, -1.0f,
0.0f, -1.0f, 0.0f
};
Kernel kernel = new Kernel(3, 3, sharpen);
ConvolveOp op = new ConvolveOp(kernel);
dst = op.filter(source, null);
jtp.add("Convolve", new JLabel(new ImageIcon(dst)));
}
private void buildLookUpOpTab(JTabbedPane jtp)
{
BufferedImage dst=null;
short[] data=new short[256];
for(int i=0;i<256;i++)
data[i]=(short)(255-i);
LookupTable lkp=new ShortLookupTable(0,data);
LookupOp op=new LookupOp(lkp,null);
dst=op.filter(source, null);
jtp.add("Look Up",new JLabel(new ImageIcon(dst)));
}
}
```
There is some problem in the buildLookUpOpTab as removing this method application works fine.
Here is the exception which I am getting:
```
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Number of color/alpha components should be 3 but length of bits array is 1
at java.awt.image.ColorModel.<init>(ColorModel.java:336)
at java.awt.image.ComponentColorModel.<init>(ComponentColorModel.java:273)
at java.awt.image.LookupOp.createCompatibleDestImage(LookupOp.java:413)
at java.awt.image.LookupOp.filter(LookupOp.java:153)
at ImageProcessing.buildLookUpOpTab(ImageProcessing.java:108)
at ImageProcessing.<init>(ImageProcessing.java:49)
at ImageProcessing$1.run(ImageProcessing.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
```
Can anyone tell me what is the problem in that method? | 2013/01/01 | ['https://Stackoverflow.com/questions/14108373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1460665/'] | The `LookupOp.filter` method says that:
*Performs a lookup operation on a BufferedImage. If the color model in the source image is not the same as that in the destination image, the pixels will be converted in the destination. If the destination image is null, a BufferedImage will be created with an appropriate ColorModel. **An IllegalArgumentException might be thrown if the number of arrays in the LookupTable does not meet the restrictions stated in the class comment above, or if the source image has an IndexColorModel.***
Since you are filtering a `BufferedImage` created from using `ImageIO.read`, the color model that the image will have will definitely not be IndexColorModel, since `JPEGImageReader` (which actually created the BufferdImage from the file) does not support `IndexColorModel` - in the olden days, JPEGs used the `DirectColorModel`
Have a look at the answer on this thread on how to read a JPEG file and use a different color model:
[Unable to read JPEG image using ImageIO.read(File file)](https://stackoverflow.com/questions/2408613/problem-reading-jpeg-image-using-imageio-readfile-file) | You need to remove alpha channel from your image before using any filter on it. To make your code working, change:
```
try
{
source=ImageIO.read(new File("src/abc.jpg"));
} catch(IOException e){System.out.println("Exception Here :"+e);}
```
with this:
```
try
{
BufferedImage src = ImageIO.read(new File("abc.jpg"));
int w = src.getWidth();
int h = src.getHeight();
source = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Raster raster = src.getRaster().createChild(0, 0, w, h, 0, 0,
new int[] {0, 1, 2});
source.setData(raster);
}catch(IOException e){System.out.println("Exception Here :"+e);}
```
The above code creates a new buffered image in `RGB` mode and set the `RGB` data of original image to new buffered image ignoring the `alpha` values. But in case your original image contains completely transparent spots then it will become black spots in new buffered image. |
17,284,128 | It just occured to me I do not know how to best handle cases like these were I am retrieving an object from the disk, in this case I know it only is supposed to be of type `NSDictionary`. But it´s not good coding practice to make assumptions so... is the norm to do a check on which class it is and then convert it to Dictionary?
If so, would I first retrieve the file in an `NSData` class and then ask if it is a `NSDictionary` class?
```
NSString *destinationString = [NSString stringWithFormat:@"%@/%@",dataPath,filename];
NSDictionary *file = [[NSDictionary alloc]initWithContentsOfFile:destinationString];
if (file) {
return YES;
}
return NO;
}
``` | 2013/06/24 | ['https://Stackoverflow.com/questions/17284128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526334/'] | You don't know how `initWithContentsOfFile` is implemented. Chances are that it checks the start of the file to see if it matches a dictionary and bails early if it doesn't (returning `nil`). It might be much more efficient than getting the data first.
As per the docs for `initWithContentsOfFile`, the method checks the type of data contained in the file and won't return a 'bad' or 'wrong' object to you so you can be sure that a non-nil object is good.
Whether your code needs to try creating an array and then a dictionary is a different matter. | Implementing persistence in the way you describe is quite fragile. Any little change can break your persistence solution and introduce unexpected errors. If you need light weight persistence, you may take a look at [Mantle from Github](https://github.com/github/Mantle). Mantle allows you to build a typed serializable model that you can easily save into a file and read it back. Additionally, it supports versioning that is utmost important if you have to evolve your model over time. |
17,284,128 | It just occured to me I do not know how to best handle cases like these were I am retrieving an object from the disk, in this case I know it only is supposed to be of type `NSDictionary`. But it´s not good coding practice to make assumptions so... is the norm to do a check on which class it is and then convert it to Dictionary?
If so, would I first retrieve the file in an `NSData` class and then ask if it is a `NSDictionary` class?
```
NSString *destinationString = [NSString stringWithFormat:@"%@/%@",dataPath,filename];
NSDictionary *file = [[NSDictionary alloc]initWithContentsOfFile:destinationString];
if (file) {
return YES;
}
return NO;
}
``` | 2013/06/24 | ['https://Stackoverflow.com/questions/17284128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526334/'] | You don't know how `initWithContentsOfFile` is implemented. Chances are that it checks the start of the file to see if it matches a dictionary and bails early if it doesn't (returning `nil`). It might be much more efficient than getting the data first.
As per the docs for `initWithContentsOfFile`, the method checks the type of data contained in the file and won't return a 'bad' or 'wrong' object to you so you can be sure that a non-nil object is good.
Whether your code needs to try creating an array and then a dictionary is a different matter. | Persist first class models that make sense to your application. Implement `NSCoding`and use `NSKeyedArchiver` and `NSKeyedUnarchiver`. Or as @allprog suggests, go with Mantle, this is effectively what they're doing, they just make it less boilerplate code for you. |
7,603 | If my interpretation is correct, Kant argued in the Critique of pure reason and Prolegomena that:
>
> The existence of an external world guarantees that we can intuit, conceive, etc internally.
>
>
>
This argument bears that "transcendental" essence in it.
Now my question is:
Does the Brain-in-a-Vat thought experiment undermines Kant's transcendental argument above? in what way?
I have read [this entry in the SEP](http://plato.stanford.edu/entries/realism-sem-challenge/), but it doesn't get me any further for the question I had. | 2013/07/18 | ['https://philosophy.stackexchange.com/questions/7603', 'https://philosophy.stackexchange.com', 'https://philosophy.stackexchange.com/users/1671/'] | >
> The existence of an external world guarantees that we can intuit,
> conceive, etc internally. Does the Brain-in-a-Vat thought experiment
> undermines Kant's transcendental argument above?
>
>
>
I think your central question is “Does external exist, and we conceive internally, if we are a brain in the vat?
Answer: If we apply the Occam's razor the question is pointless.The maps are not the territory.
Suppose a Bizarre Brain, BB, that is, the computer of the "brain in the vat" skepticism, the brain of the Descartes' devil that deceives us, a permanently dreaming brain, or the solipsistic brain that create the "universe" for itself or for us. If the BB makes her mind the object of scientific study, it will find that it behaves with the same complexity as the universe described by a Common Sense Brain, CSB. Thus what CSB calls "the universe", the BB calls "one's own mind." Understood this way, the distinction between CSB and BB collapses and amounts to different ways of describing the same thing: a massively complex process that causes all the BB's experiences. Presumably having made the case that the BB scientist is actually a CSB scientist, the BB applies Occam's Razor, and suggests to the BB scientist to prefer the CSB's standard external “reality” over something like a BB's "reality". This is because the standard "reality" fits all the data available to the scientist, and on the skeptic's hypothesis is impossible to find differences, rendering superfluous the other more complicated possibilities.
Unobservables such as atomic particles, the force of gravity, and the quantum physics, are useful representation models. "The brain in the Vat" skepticism and the solipsism are interpretations or models too. Any language which provide a practical way of thinking and make sense about natural laws, a common mind-independent world, must provide a way of expressing common true inductive inferences about this world, or a description that relates representation to prediction. What varies are the models and interpretations, but if they are to be true, what they predict does not change. There is no more an objective basis for choosing one theory/representation over another than there is for preferring the Fahrenheit to the Celsius scale for temperature ascriptions. In an interpretation, it is prediction that remains invariant between different, but equally adequate, theories or representations.
If too many of speakers utterances are false, then the link between what speakers say and the world is severed; and the enterprise of interpretation each other halts. Too much error in statements about the world is not an option if speakers are going to translate each other. Therefore prediction is objective in the sense that most of what speakers say about the world are truths about the world. This is an assumption an translator makes because the only path into the world speakers share are the events in the world that cause them to hold those sentences true. Models translation need essentially inter-subjectivity.The maps are not the territory. It is pointless to say "the mountain is disobeying the map".
Central ideas of David Deutsch and David Davidson | Kant was reacting to two positions - the wholly idealistic philosophy of Berkeley - which is a very rough equivalent to the 'brain in a vat' thought experiment which is more akin to classical solipsism - in which everything is mind and objective reality disappears, and the radical scepticism of Hume which totally undermined the basis for empirical science - essentially the idea of causality.
The phenomenal world as we know it and sense it immediately is structured by the the intuition giving it space & time to be presented to the intellectual & reasoning faculties of the mind - the understanding. (Think of a photograph, it is actually flat, but the mind projects an illusion of space; think of reading a novel, we give the illusion of time to the protagonists in it, a (narrative) time that is entirely separate from the flow of time we are as we are reading it).
The world in-itself (noumena) is never accessible - but it exists - otherwise we won't see its representation as phenomena.
So Kant finds a middle ground where mind & intuition meet reality and each is immanent in the other. This allows science to happen, as it must; and leaves solipsism still fighting a lost battle. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | In my case I ran the following on a Pi 4 model B
```
vcgencmd get_camera
supported=1 detected=1
raspistill -w 3280 -h 2464 -n -t 2000 -o test.png
mmal: mmal_vc_component_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates
make: *** [makefile:27: raspistill] Error 70
```
It turned out to be the camera. The standard camera works! | This error occurs when you use I/O during camera recording operation.
I faced the same issue on using used I/O while recording.
So you can either add before recording or after not in between. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | This error will appear when the RPi Camera is "On" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process.
One solution is to try to stop the Camera stream before the Snapshot and then restart it after. | This error occurs when you use I/O during camera recording operation.
I faced the same issue on using used I/O while recording.
So you can either add before recording or after not in between. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | Stop any other processes using the camera (e.g.raspimjpeg)
```
$ ps -aux
```
// locate the process pid and kill it using the pid number (e.g. 764)
```
$ sudo kill 764
```
Note: You might have more than one process running so be sure to kill them all before trying again. | I use a Raspberry Pi 4 Model B and I had faced the same issue.
My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | Stop any other processes using the camera (e.g.raspimjpeg)
```
$ ps -aux
```
// locate the process pid and kill it using the pid number (e.g. 764)
```
$ sudo kill 764
```
Note: You might have more than one process running so be sure to kill them all before trying again. | This error occurs when you use I/O during camera recording operation.
I faced the same issue on using used I/O while recording.
So you can either add before recording or after not in between. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | finally i can solve this problem after a lot of hours troubleshooting.
I already share it in my YouTube (<https://youtu.be/on8UlkRvLok>)
This problem only occur in camera raspberry pi V2.1 (IMX219) from **Element14**. But in camera raspberry pi V2.1 from **OKdo**, i don't get this error
So, the solution when error
"mmal: mmal\_vc\_component\_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates"
You **need some initialization** with a works camera (me camera from **OKdo**).
So, the step is
1. Plug your works camera to Raspberry Pi (me using Raspberry Pi 4B)
2. Turn on your Raspberry Pi
3. check "vcgencmd get\_camera" to make sure your hardware is detected the camera
4. capture image using "raspistill -v" and camera will capture the image
5. Then replace the works camera with ENOSPC Error Camera (from **Element14**)
6. then try to capture the image "raspistill -v" and the ENOSPC Error will not occur
**Notes:**
* But, after the ENOSPC Error Camera works, and then you restart/shutdown the raspberry pi, the error will occur again :(
OS Raspberry Pi 4 Model B (4GB)
* Linux raspberrypi 5.10.60-v7l+ #1449 SMP Wed Aug 25 15:00:44 BST 2021 armv7l GNU/Linux | This error occurs when you use I/O during camera recording operation.
I faced the same issue on using used I/O while recording.
So you can either add before recording or after not in between. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | Stop any other processes using the camera (e.g.raspimjpeg)
```
$ ps -aux
```
// locate the process pid and kill it using the pid number (e.g. 764)
```
$ sudo kill 764
```
Note: You might have more than one process running so be sure to kill them all before trying again. | finally i can solve this problem after a lot of hours troubleshooting.
I already share it in my YouTube (<https://youtu.be/on8UlkRvLok>)
This problem only occur in camera raspberry pi V2.1 (IMX219) from **Element14**. But in camera raspberry pi V2.1 from **OKdo**, i don't get this error
So, the solution when error
"mmal: mmal\_vc\_component\_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates"
You **need some initialization** with a works camera (me camera from **OKdo**).
So, the step is
1. Plug your works camera to Raspberry Pi (me using Raspberry Pi 4B)
2. Turn on your Raspberry Pi
3. check "vcgencmd get\_camera" to make sure your hardware is detected the camera
4. capture image using "raspistill -v" and camera will capture the image
5. Then replace the works camera with ENOSPC Error Camera (from **Element14**)
6. then try to capture the image "raspistill -v" and the ENOSPC Error will not occur
**Notes:**
* But, after the ENOSPC Error Camera works, and then you restart/shutdown the raspberry pi, the error will occur again :(
OS Raspberry Pi 4 Model B (4GB)
* Linux raspberrypi 5.10.60-v7l+ #1449 SMP Wed Aug 25 15:00:44 BST 2021 armv7l GNU/Linux |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | In my case I ran the following on a Pi 4 model B
```
vcgencmd get_camera
supported=1 detected=1
raspistill -w 3280 -h 2464 -n -t 2000 -o test.png
mmal: mmal_vc_component_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates
make: *** [makefile:27: raspistill] Error 70
```
It turned out to be the camera. The standard camera works! | I use a Raspberry Pi 4 Model B and I had faced the same issue.
My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | This error will appear when the RPi Camera is "On" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process.
One solution is to try to stop the Camera stream before the Snapshot and then restart it after. | I use a Raspberry Pi 4 Model B and I had faced the same issue.
My solution was to **set the GPU Memory from 128 to 256** in the Raspberry Pi Configuration. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | Stop any other processes using the camera (e.g.raspimjpeg)
```
$ ps -aux
```
// locate the process pid and kill it using the pid number (e.g. 764)
```
$ sudo kill 764
```
Note: You might have more than one process running so be sure to kill them all before trying again. | This error will appear when the RPi Camera is "On" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process.
One solution is to try to stop the Camera stream before the Snapshot and then restart it after. |
29,314,841 | I want to use Raspberry PI's system command `raspistill`to take images in a c program, the program line is: `system("raspistill -q 5 -vf -hf -o pic1.jpg -t 1 -th 0:0:0");`
However, when I run the program sometimes error occurs,
it shows that:
>
> mmal\_vc\_component\_enable- failed to enable component- ENOSPC
> mmal- camera component couldn't be enabled
> mmal- main- Failed to create camera component
> mmal- Failed to run camera app. Please check for firmware updatesckquote
>
>
>
And I have tried to add some parameters into /boot/config.txt:
>
> gpu\_mem=128 start\_file=start\_x.elf fixup\_file=fixup\_x.dat
>
> disable\_camera\_led=1 cam\_lwm=16 cam\_hwm=32 cam\_offline\_start=16
>
>
>
However the error still always occurs sometimes (sometimes ok). I really want to solve this problem in order to continue my project. What should I do? | 2015/03/28 | ['https://Stackoverflow.com/questions/29314841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4407689/'] | In my case I ran the following on a Pi 4 model B
```
vcgencmd get_camera
supported=1 detected=1
raspistill -w 3280 -h 2464 -n -t 2000 -o test.png
mmal: mmal_vc_component_enable: failed to enable component: ENOSPC
mmal: camera component couldn't be enabled
mmal: main: Failed to create camera component
mmal: Failed to run camera app. Please check for firmware updates
make: *** [makefile:27: raspistill] Error 70
```
It turned out to be the camera. The standard camera works! | This error will appear when the RPi Camera is "On" and is streaming. The component: ENOSPC cannot start unless the RPi Camera is not streaming or being used by another process.
One solution is to try to stop the Camera stream before the Snapshot and then restart it after. |
35,521,868 | I cannot change the color of this SVG Image: <http://uxrepo.com/download/pause-by-iconic/000000>
Here's the SVG's code:
```
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" height="1000" width="705">
<path d="M18 946.5l0 -893l223 0l0 893l-223 0zm446 0l0 -893l224 0l0 893l-224 0z" fill="#000000"/>
</svg>
```
I want the color to be white using the following but it doesn't change anything:
```
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" height="1000" width="705">
<path d="M18 946.5l0 -893l223 0l0 893l-223 0zm446 0l0 -893l224 0l0 893l-224 0z" fill="#FFFFFFFF"/>
</svg>
```
What's the problem?
I am editing the SVG's code using this site: <https://petercollingridge.appspot.com/svg-editor/> | 2016/02/20 | ['https://Stackoverflow.com/questions/35521868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/'] | Try using this:
```
let selectedTube = "circle"
let headers = ["cache-control": "no-cache",]
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
``` | I'm not quite sure what your problem is. The following code works just fine in a playground. I would suspect the problem lies within your custom `JSON` function:
```
import Foundation
let selectedTube = "Circle"
let url = NSURL(string: "https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304")
if let jsonData = NSData(contentsOfURL: url!) {
let readableJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers)
NSLog("the URL: \(readableJSON)")
} else {
print("Cannot read data.")
}
``` |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales. | You can also reconfigure the locales package using `dpkg-reconfigure locales`. |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales. | **Which locales are installed on my machine?**
You can check which locales are generated and configured on your system using the locale command:
* **`locale`** ... list the current locale configuration
* **`locale -a`** ... lists all all locales that were generated on your system
* **`locale -a -v`** ... list all locales and show useful additional information (such as
directory names that contain the locale information data files)
The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories.
-
**Supported locales**
All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map.
I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line:
```
en_US UTF-8
```
-
**Error messages**
If error messages are displayed when issuing the locale command, e.g.
```
locale: Cannot set LC_ALL to default locale: No such file or directory
```
make sure the file **`/etc/default/locale`** exists and has proper content, such as:
```
LANG="en_US"
LANGUAGE="en_US:en"
```
-
**Get rid of unneeded locale data - Step by step**
Now we know all the necessary details to get started with cleaning up our system's locale information:
1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line)
2. Create and edit **`/etc/default/locale`** (see above for an example)
3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`**
4. Re-generate new locales: **`locale-gen`**
That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected.
-
**Reference:**
<https://www.linuxquestions.org/questions/blog/bittner-195120/remove-unwanted-locales-on-ubuntu-debian-3281/> |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales. | **Note:** Some of the commands below require root privileges, consider the use of `sudo`.
### Basic info
According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files.
>
> `/etc/locale.gen`
>
>
> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built.
>
>
> `/var/lib/locales/supported.d/`
>
>
> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades.
>
>
>
Locales are compiled (generated) into a single file.
>
> `/usr/lib/locale/locale-archive`
>
>
> Usual default locale archive location.
>
>
>
Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale).
### Checking locales and the locale
To list available (known) locales, run any of the following commands (with minor output differences).
```bash
locale -a
localectl list-locales
```
To check the (already) generated locales, run the following command.
```bash
localedef --list-archive
```
To check the currently used locale, run any of the following commands (with minor output differences).
```bash
locale
localectl
```
### Setting and generating (new) locales
Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required.
```bash
nano /etc/locale.gen # uncomment desired lines (locales)
locale-gen
```
This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not.
Alternatively, the command
```bash
locale-gen <locale>
```
will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one.
Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux.
### Removing locales
When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge <locale>` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered.
To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`.
To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/<code>` depends on the package `language-pack-<code>-base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following.
```bash
apt-mark language-pack-<code>-base
```
To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html).
**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the ["immutable (i)" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance:
```bash
cd /var/lib/locales/supported.d/
rm <code> && touch <code> # <code> has been emptied
lsattr <code> # regular attributes
chattr +i <code> # adding (+) immutable
lsattr <code> # checking attributes
```
### Setting the locale
Setting and generating locales does not set the system locale. Any of the following commands achieves this.
```bash
echo LANG=<code> | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu)
localectl set-locale LANG=<code>
``` |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | I think you can do this by editing `/var/lib/locales/supported.d/local` and removing that locale. Then run `locale-gen` to regenerate the compiled locales. | I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html)
For Debian based Systems, should it be available by
```bash
apt-get install localepurge
```
From the Manpage:
>
> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run.
>
>
>
>
> You have to define the locale diretory names you want to keep from
> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all.
>
>
>
>
> The contents of following directories will be affected from removals:
>
>
>
```
- /usr/share/doc/kde/HTML
- /usr/share/gnome/help
- /usr/share/locale
- /usr/share/man
- /usr/share/omf
- /usr/share/tcltk
- /usr/share/cups/{templates,locale,doc-root}
- /usr/share/calendar
- /usr/share/aptitude
- /usr/share/help/<domain>/HELP_CONTENT(files&dirs)
- /usr/share/vim/vim*/lang
```
>
> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command:
>
>
>
```
dpkg-reconfigure localepurge
```
Conclusion:
This Script will take care of any unwanted locales at the moment and in the future. |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | You can also reconfigure the locales package using `dpkg-reconfigure locales`. | **Note:** Some of the commands below require root privileges, consider the use of `sudo`.
### Basic info
According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files.
>
> `/etc/locale.gen`
>
>
> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built.
>
>
> `/var/lib/locales/supported.d/`
>
>
> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades.
>
>
>
Locales are compiled (generated) into a single file.
>
> `/usr/lib/locale/locale-archive`
>
>
> Usual default locale archive location.
>
>
>
Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale).
### Checking locales and the locale
To list available (known) locales, run any of the following commands (with minor output differences).
```bash
locale -a
localectl list-locales
```
To check the (already) generated locales, run the following command.
```bash
localedef --list-archive
```
To check the currently used locale, run any of the following commands (with minor output differences).
```bash
locale
localectl
```
### Setting and generating (new) locales
Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required.
```bash
nano /etc/locale.gen # uncomment desired lines (locales)
locale-gen
```
This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not.
Alternatively, the command
```bash
locale-gen <locale>
```
will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one.
Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux.
### Removing locales
When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge <locale>` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered.
To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`.
To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/<code>` depends on the package `language-pack-<code>-base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following.
```bash
apt-mark language-pack-<code>-base
```
To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html).
**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the ["immutable (i)" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance:
```bash
cd /var/lib/locales/supported.d/
rm <code> && touch <code> # <code> has been emptied
lsattr <code> # regular attributes
chattr +i <code> # adding (+) immutable
lsattr <code> # checking attributes
```
### Setting the locale
Setting and generating locales does not set the system locale. Any of the following commands achieves this.
```bash
echo LANG=<code> | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu)
localectl set-locale LANG=<code>
``` |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | You can also reconfigure the locales package using `dpkg-reconfigure locales`. | I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html)
For Debian based Systems, should it be available by
```bash
apt-get install localepurge
```
From the Manpage:
>
> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run.
>
>
>
>
> You have to define the locale diretory names you want to keep from
> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all.
>
>
>
>
> The contents of following directories will be affected from removals:
>
>
>
```
- /usr/share/doc/kde/HTML
- /usr/share/gnome/help
- /usr/share/locale
- /usr/share/man
- /usr/share/omf
- /usr/share/tcltk
- /usr/share/cups/{templates,locale,doc-root}
- /usr/share/calendar
- /usr/share/aptitude
- /usr/share/help/<domain>/HELP_CONTENT(files&dirs)
- /usr/share/vim/vim*/lang
```
>
> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command:
>
>
>
```
dpkg-reconfigure localepurge
```
Conclusion:
This Script will take care of any unwanted locales at the moment and in the future. |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | **Which locales are installed on my machine?**
You can check which locales are generated and configured on your system using the locale command:
* **`locale`** ... list the current locale configuration
* **`locale -a`** ... lists all all locales that were generated on your system
* **`locale -a -v`** ... list all locales and show useful additional information (such as
directory names that contain the locale information data files)
The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories.
-
**Supported locales**
All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map.
I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line:
```
en_US UTF-8
```
-
**Error messages**
If error messages are displayed when issuing the locale command, e.g.
```
locale: Cannot set LC_ALL to default locale: No such file or directory
```
make sure the file **`/etc/default/locale`** exists and has proper content, such as:
```
LANG="en_US"
LANGUAGE="en_US:en"
```
-
**Get rid of unneeded locale data - Step by step**
Now we know all the necessary details to get started with cleaning up our system's locale information:
1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line)
2. Create and edit **`/etc/default/locale`** (see above for an example)
3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`**
4. Re-generate new locales: **`locale-gen`**
That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected.
-
**Reference:**
<https://www.linuxquestions.org/questions/blog/bittner-195120/remove-unwanted-locales-on-ubuntu-debian-3281/> | **Note:** Some of the commands below require root privileges, consider the use of `sudo`.
### Basic info
According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files.
>
> `/etc/locale.gen`
>
>
> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built.
>
>
> `/var/lib/locales/supported.d/`
>
>
> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades.
>
>
>
Locales are compiled (generated) into a single file.
>
> `/usr/lib/locale/locale-archive`
>
>
> Usual default locale archive location.
>
>
>
Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale).
### Checking locales and the locale
To list available (known) locales, run any of the following commands (with minor output differences).
```bash
locale -a
localectl list-locales
```
To check the (already) generated locales, run the following command.
```bash
localedef --list-archive
```
To check the currently used locale, run any of the following commands (with minor output differences).
```bash
locale
localectl
```
### Setting and generating (new) locales
Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required.
```bash
nano /etc/locale.gen # uncomment desired lines (locales)
locale-gen
```
This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not.
Alternatively, the command
```bash
locale-gen <locale>
```
will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one.
Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux.
### Removing locales
When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge <locale>` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered.
To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`.
To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/<code>` depends on the package `language-pack-<code>-base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following.
```bash
apt-mark language-pack-<code>-base
```
To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html).
**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the ["immutable (i)" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance:
```bash
cd /var/lib/locales/supported.d/
rm <code> && touch <code> # <code> has been emptied
lsattr <code> # regular attributes
chattr +i <code> # adding (+) immutable
lsattr <code> # checking attributes
```
### Setting the locale
Setting and generating locales does not set the system locale. Any of the following commands achieves this.
```bash
echo LANG=<code> | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu)
localectl set-locale LANG=<code>
``` |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | **Which locales are installed on my machine?**
You can check which locales are generated and configured on your system using the locale command:
* **`locale`** ... list the current locale configuration
* **`locale -a`** ... lists all all locales that were generated on your system
* **`locale -a -v`** ... list all locales and show useful additional information (such as
directory names that contain the locale information data files)
The last command from above makes you see that all generated locales are located in **`/usr/lib/locale/`**, and you may remove any of them if unneeded. Each pack of locale information is a directory containing text files and other directories.
-
**Supported locales**
All locales that you want your system to support are listed in the text files in **`/var/lib/locales/supported.d/`**. These files have two columns, language tag and character map.
I want my system to know US-English only, so I have only one file there, called **`en`**, which contains just a single line:
```
en_US UTF-8
```
-
**Error messages**
If error messages are displayed when issuing the locale command, e.g.
```
locale: Cannot set LC_ALL to default locale: No such file or directory
```
make sure the file **`/etc/default/locale`** exists and has proper content, such as:
```
LANG="en_US"
LANGUAGE="en_US:en"
```
-
**Get rid of unneeded locale data - Step by step**
Now we know all the necessary details to get started with cleaning up our system's locale information:
1. Edit the locale file(s) in **`/var/lib/locales/supported.d/`**, and remove all unneeded locales (one locale per line)
2. Create and edit **`/etc/default/locale`** (see above for an example)
3. Delete all generated locale data: **`rm -rfv /usr/lib/locale/*`**
4. Re-generate new locales: **`locale-gen`**
That's all! Reboot your machine to make your changes take effect. Then run one or more of the locale command examples from above to ensure yourself that the result is as expected.
-
**Reference:**
<https://www.linuxquestions.org/questions/blog/bittner-195120/remove-unwanted-locales-on-ubuntu-debian-3281/> | I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html)
For Debian based Systems, should it be available by
```bash
apt-get install localepurge
```
From the Manpage:
>
> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run.
>
>
>
>
> You have to define the locale diretory names you want to keep from
> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all.
>
>
>
>
> The contents of following directories will be affected from removals:
>
>
>
```
- /usr/share/doc/kde/HTML
- /usr/share/gnome/help
- /usr/share/locale
- /usr/share/man
- /usr/share/omf
- /usr/share/tcltk
- /usr/share/cups/{templates,locale,doc-root}
- /usr/share/calendar
- /usr/share/aptitude
- /usr/share/help/<domain>/HELP_CONTENT(files&dirs)
- /usr/share/vim/vim*/lang
```
>
> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command:
>
>
>
```
dpkg-reconfigure localepurge
```
Conclusion:
This Script will take care of any unwanted locales at the moment and in the future. |
394,610 | I accidentally add a locale, e.g. sudo locale-gen zh\_TW
e.g. locale -a
```
zh_TW
```
But how to remove it? | 2012/06/01 | ['https://serverfault.com/questions/394610', 'https://serverfault.com', 'https://serverfault.com/users/50774/'] | **Note:** Some of the commands below require root privileges, consider the use of `sudo`.
### Basic info
According to [`man locale-gen`](http://manpages.ubuntu.com/manpages/jammy/man8/locale-gen.8.html), locales are set in several files.
>
> `/etc/locale.gen`
>
>
> The main configuration file, which has a simple format: every line that is not empty and does not begin with a # is treated as a locale definition that is to be built.
>
>
> `/var/lib/locales/supported.d/`
>
>
> A directory containing locale.gen snippets provided by language-pack packages. Do not edit these manually, they will be overwritten on package upgrades.
>
>
>
Locales are compiled (generated) into a single file.
>
> `/usr/lib/locale/locale-archive`
>
>
> Usual default locale archive location.
>
>
>
Comprehensive details on locales at the [Arch Wiki](https://wiki.archlinux.org/index.php/locale).
### Checking locales and the locale
To list available (known) locales, run any of the following commands (with minor output differences).
```bash
locale -a
localectl list-locales
```
To check the (already) generated locales, run the following command.
```bash
localedef --list-archive
```
To check the currently used locale, run any of the following commands (with minor output differences).
```bash
locale
localectl
```
### Setting and generating (new) locales
Locales are typically set by uncommenting lines in `/etc/locale.gen`, after which running `locale-gen` is required.
```bash
nano /etc/locale.gen # uncomment desired lines (locales)
locale-gen
```
This will compile (generate) locales into `/usr/lib/locale/locale-archive` for each uncommented line in `/etc/locale.gen` and under `/var/lib/locales/supported.d/`, whether they were previously compiled or not.
Alternatively, the command
```bash
locale-gen <locale>
```
will uncomment the corresponding line in `locale-gen` while generating the desired locale and only this one.
Note: The implementation of `locale-gen` is distro dependent. For instance, the command above is valid in Ubuntu/Debian but not in ArchLinux.
### Removing locales
When issuing `locale-gen`, the compiled archive is erased and all locales in `/etc/locale.gen` and under `/usr/lib/locale/locale-archive` are regenerated anew. The command `locale-gen --purge <locale>` doesn't do what the modifier suggests but the opposite: It removes all compiled locales except those indicated. To make sure only specific locales are generated when `locale-gen` is issued or and update is performed both `/etc/locale.gen` and `/usr/lib/locale/locale-archive` must be considered.
To remove locales in `/etc/locale.gen`, simply comment the desired lines and regenerate the locales using `locale-gen`.
To remove locales under `/var/lib/locales/supported.d/` is trickier. Since any file `/var/lib/locales/supported.d/<code>` depends on the package `language-pack-<code>-base`, any change on the former will be restored when the latter is updated. To solve this, simply hold the packages that update files under `/var/lib/locales/supported.d/`. The command that achieves this in Ubuntu/Debian is the following.
```bash
apt-mark language-pack-<code>-base
```
To update a held package, you must [unmark](https://manpages.ubuntu.com/manpages/jammy/man8/apt-mark.8.html) it or simply [`--ignore-hold`](https://manpages.ubuntu.com/manpages/jammy/man8/apt-get.8.html).
**Workaround.** A more intrusive but general solution that prevents changes under `/var/lib/locales/supported.d/` is to set files in it with the ["immutable (i)" attribute](http://manpages.ubuntu.com/manpages/jammy/man1/chattr.1.html). So instead of removing files, empty them. For instance:
```bash
cd /var/lib/locales/supported.d/
rm <code> && touch <code> # <code> has been emptied
lsattr <code> # regular attributes
chattr +i <code> # adding (+) immutable
lsattr <code> # checking attributes
```
### Setting the locale
Setting and generating locales does not set the system locale. Any of the following commands achieves this.
```bash
echo LANG=<code> | sudo tee /etc/locale.conf # reboot (might be ignored in Ubuntu)
localectl set-locale LANG=<code>
``` | I am unsure why the most Distributions and Users are unaware from [localepurge](https://manpages.ubuntu.com/manpages/kinetic/en/man8/localepurge.8.html)
For Debian based Systems, should it be available by
```bash
apt-get install localepurge
```
From the Manpage:
>
> localepurge is a small script to recover disk space wasted for unneeded locale files and localized man pages. It will be automagically invoked by dpkg upon completion of any apt installation run.
>
>
>
>
> You have to define the locale diretory names you want to keep from
> removal after each apt installation run in the /etc/locale.nopurge configuration file. Unless localepurge has been adequately configured, the system's localization files won't be touched at all.
>
>
>
>
> The contents of following directories will be affected from removals:
>
>
>
```
- /usr/share/doc/kde/HTML
- /usr/share/gnome/help
- /usr/share/locale
- /usr/share/man
- /usr/share/omf
- /usr/share/tcltk
- /usr/share/cups/{templates,locale,doc-root}
- /usr/share/calendar
- /usr/share/aptitude
- /usr/share/help/<domain>/HELP_CONTENT(files&dirs)
- /usr/share/vim/vim*/lang
```
>
> The localization files you actually need and which you want to be preserved on your system can be easily configured by running the following command:
>
>
>
```
dpkg-reconfigure localepurge
```
Conclusion:
This Script will take care of any unwanted locales at the moment and in the future. |
70,755,860 | I have done until now to create a button and inside a tag button I have created another div with class background to give same property for animation effects when click on button.
But I am not sure if in this way is regular syntax for HTML to put another div into tag button in my case?
I AM SHARING MY CODE:
```css
button {
height: 73px;
min-width: 198px;
border-radius: 5px;
background-color: $gold;
border-color: $gold;
position: relative;
overflow: hidden;
display: inline-block;
font-size: 1.313rem;
color: black;
z-index: 2;
line-height: 30.24px;
font-weight: bold;
text-transform: uppercase;
}
.background {
width: 0;
height: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-image: linear-gradient(#000000, #000000);
transition: .5s;
z-index: -1;
border-radius: 50%;
}
button:hover {
color: $gold;
}
button:hover .background {
width: 500%;
height: 500%;
}
```
```html
<button class='btn'>
<div class="background"></div>Contact
</button>
```
But when I Click on button we want background color display as circle and not as eclipse in the center on button. Exactly by the Figma[enter link description here](https://www.figma.com/proto/kwnH9NnM6eZO9eGAjEpEaG/Passport-Site-(Copy)?node-id=10%3A185&scaling=min-zoom&page-id=0%3A1&starting-point-node-id=10%3A185)
or code pene: [enter link description here](https://codepen.io/liamj/pen/vvdRdR) | 2022/01/18 | ['https://Stackoverflow.com/questions/70755860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15796964/'] | The issue in your approach is that you are setting the background `width` and `height` to 1:1 proportions. This would make circle for a square button. For you to create circle you need to make it proportional to the width and height of your button. For example:
```css
button {
height: 73px;
min-width: 198px;
border-radius: 5px;
background-color: $gold;
border-color: $gold;
position: relative;
overflow: hidden;
display: inline-block;
font-size: 1.313rem;
color: black;
z-index: 2;
line-height: 30.24px;
font-weight: bold;
text-transform: uppercase;
}
.background {
width: 0;
height: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-image: linear-gradient(#000000, #000000);
transition: .5s;
z-index: -1;
border-radius: 50%;
}
button:hover {
color: $gold;
}
button:hover .background {
width: 150%;
height: 406%;
}
```
```html
<button class='btn'>
<span class="background"></span>Contact
</button>
```
To get the proportional width you can use in your case (198/73)\*height. So if you choose for your height to be 130% you should have width of 353%. The higher % the faster your animation will be, so keep that in mind. | ```
button:hover .background {
width: 120%;
height: 300%;
}
``` |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | In python, the `auth` is being passed in the header.
You have to do a http post request, passing both the header and the body.
This is a working code:
```
func test() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | [`requests.post`](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) sends an HTTP POST request, encoding key/value pairs as `application/x-www-form-urlencoded`. You need to do the same.
* convert the set of key-value pairs into `application/x-www-form-urlencoded` as per [How to escape the HTTP params in Swift](https://stackoverflow.com/questions/27148100/how-to-escape-the-http-params-in-swift)
* compose the request using the resulting string for data & send it as per [iOS : http Post using swift](https://stackoverflow.com/questions/30596114/ios-http-post-using-swift) |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15:
```
func sendEmail() {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = "https://api:[email protected]/v3/YOUR_DOMAIN/messages?"
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + "from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)")! as URL)
// POST and report back with any errors and response codes
request.httpMethod = "POST"
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | [`requests.post`](http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests) sends an HTTP POST request, encoding key/value pairs as `application/x-www-form-urlencoded`. You need to do the same.
* convert the set of key-value pairs into `application/x-www-form-urlencoded` as per [How to escape the HTTP params in Swift](https://stackoverflow.com/questions/27148100/how-to-escape-the-http-params-in-swift)
* compose the request using the resulting string for data & send it as per [iOS : http Post using swift](https://stackoverflow.com/questions/30596114/ios-http-post-using-swift) |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | In python, the `auth` is being passed in the header.
You have to do a http post request, passing both the header and the body.
This is a working code:
```
func test() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | I spent hours trying to get the selected answer working, but to no avail.
Although I was finally able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
```
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
```
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
```
https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?
```
Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution! |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | In python, the `auth` is being passed in the header.
You have to do a http post request, passing both the header and the body.
This is a working code:
```
func test() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | Swift 3 answer:
```
func test() {
let session = URLSession.shared
var request = URLRequest(url: URL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.httpMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.httpBody = data.data(using: .ascii)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | In python, the `auth` is being passed in the header.
You have to do a http post request, passing both the header and the body.
This is a working code:
```
func test() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15:
```
func sendEmail() {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = "https://api:[email protected]/v3/YOUR_DOMAIN/messages?"
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + "from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)")! as URL)
// POST and report back with any errors and response codes
request.httpMethod = "POST"
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15:
```
func sendEmail() {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = "https://api:[email protected]/v3/YOUR_DOMAIN/messages?"
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + "from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)")! as URL)
// POST and report back with any errors and response codes
request.httpMethod = "POST"
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | I spent hours trying to get the selected answer working, but to no avail.
Although I was finally able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
```
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler@<my domain>.com%3E&to=reservations@<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
```
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
```
https://API:key-<my key>@api.mailgun.net/v3/<my domain>.com/messages?
```
Hope this offers a solution to anyone else having issues with MailGun and wanting to avoid a 3rd party solution! |
33,325,137 | **Problem**
I would like to use the [MailGun](https://documentation.mailgun.com/quickstart-sending.html#how-to-start-sending-email) service to send emails from a pure Swift app.
**Research So Far**
As I understand it, [there are two methods to send an email](https://documentation.mailgun.com/quickstart-sending.html#send-via-smtp) via MailGun. One is to email MailGun with the emails, and MailGun will redirect it (See *Send via SMTP*). That will, as I understand it, not work, as iOS cannot programatically automatically send mail, and must use [methods that require user intervention](http://www.ioscreator.com/tutorials/send-email-tutorial-ios8-swift). As such, I should use the API directly. As I understand it, I need to open a URL to do this, and so I should use some form of `NSURLSession`, as per [this SO answer](https://stackoverflow.com/questions/24016142/how-to-make-an-http-request-in-swift)
**Code**
MailGun provides documentation for Python, which is as follows:
```
def send_simple_message():
return requests.post(
"https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages",
auth=("api", "key-(Personal info)"),
data={"from": "Excited User <(Personal info)>",
"to": ["[email protected]", "(Personal info)"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"})
```
with (Personal info) being substituted for keys/information/emails.
**Question**
How do I do that in Swift?
Thanks! | 2015/10/25 | ['https://Stackoverflow.com/questions/33325137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3892545/'] | people are getting 400 or 401 errors because none of the other answers construct the url correctly. here is some code that works in swift 5 and iOS15:
```
func sendEmail() {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = "https://api:[email protected]/v3/YOUR_DOMAIN/messages?"
let emailRecipient = "[email protected]"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: mailgunAPIPath + "from=USER@YOUR_DOMAIN&to=\(emailRecipient)&subject=A%20New%20Test%21&text=\(emailMessage)")! as URL)
// POST and report back with any errors and response codes
request.httpMethod = "POST"
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` | Swift 3 answer:
```
func test() {
let session = URLSession.shared
var request = URLRequest(url: URL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.httpMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [[email protected],(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.httpBody = data.data(using: .ascii)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
``` |
2,428,907 | $$\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=\lim\_{u\to0}\frac{\sin^2(u)}{\left(\dfrac u3\right)^2}=9\left(\lim\_{u\to0}\frac{\sin u}u\right)^2.$$
>
> A bit of confusion on the little steps that are missing. 1. Why does $\sin(x)$ go away. It is because $\cos(0)=1$? 2. How does the change of variable work, completely lost?
>
>
> | 2017/09/14 | ['https://math.stackexchange.com/questions/2428907', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/418493/'] | Hint:$$\quad{\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=\\\lim\_{x\to0}\frac{\sin(3x)}{x}.\lim\_{x\to0}\frac{\sin(3x)}{x}.\lim\_{x\to0}\frac{1}{\cos x}=\\
\lim\_{x\to0}\color{red} {3}\frac{\sin(3x)}{\color{red} {3}x}.\lim\_{x\to0}\color{red} {3}\frac{\sin(3x)}{\color{red} {3}x}.\lim\_{x\to0}\frac{1}{\cos x}=\\
\color{red} {9}\underbrace{\lim\_{x\to0}\frac{\sin(3x)}{\color{red} {3}x}}\_{1}.\underbrace{\lim\_{x\to0}\frac{\sin(3x)}{\color{red} {3}x}}\_{1}.\lim\_{x\to0}\frac{1}{\cos x}=\\9.1.1.\lim\_{x\to0}\frac{1}{\cos x}=9.1.1.1}$$ | $$\lim\_{x\to0}\frac{\sin^2(3x)}{x^2\cos x}=3^2\left(\lim\_{x\to0}\dfrac{\sin3x}{3x}\right)^2\cdot\dfrac1{\lim\_{x\to0}\cos x}=?$$ |
846,695 | Is $\delta \_{mn}=1$ when $m\neq n$, and $\delta \_{mm}=0$?
I am not very good at Math. So would you give me the answer and explanation please? | 2014/06/25 | ['https://math.stackexchange.com/questions/846695', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135962/'] | You got it. [For example, this.](http://www.wolframalpha.com/input/?i=sin%20300) What is your worry? | $$\cos^2\theta + \sin^2\theta = 1^2$$
$$r^2(\cos^2\theta + \sin^2\theta) = r^2(1^2)$$
$$(r\cos\theta)^2 + (r\sin\theta)^2 = r^2$$
$$x^2+y^2 = r^2$$
Draw a circle of radius 2. For what values of $\theta$ would the y-coordinate of the circle $x^2+y^2=2^2$ intersect the line $y = -\sqrt{3}$?
![enter image description here](https://i.stack.imgur.com/j0ivq.png)
Hint #2
What does $x$ equal? What is the distance between $(-x, -\sqrt{3})$ and $(x,-\sqrt{3})$? |
26,900,359 | Currently i am designing WPF application using MahApps.Metro style UI.
Tile control which provided by MahApps can not showing icon in center of tile
I saw example in MahApps website where it could show image as tile background, but I couldn't figure out how to show icon instead of image (icon such as IE logo, people logo, maps logo, etc)
I appreciated if someone can show me how to do this
Thank you | 2014/11/13 | ['https://Stackoverflow.com/questions/26900359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3540114/'] | i figure it out
use icons.xaml as resource, and add rectangle control inside tile, here is the example on how to show character inside tile control
```
<Controls:Tile x:Name="mahTileExit" Background="Green" Foreground="Yellow" Title="Exit" Width="100" Height="100" TiltFactor ="4" Margin="936,404,0,0" VerticalAlignment="Top" HorizontalAlignment="Left">
<Rectangle Fill="White" Height="45" Width="45">
<Rectangle.OpacityMask>
<VisualBrush Visual="{StaticResource appbar_door_leave}" Stretch="Fill" />
</Rectangle.OpacityMask>
</Rectangle>
</Controls:Tile>
```
thank you if anyone notice about this, hope can help to contribute | You can use [FontAwesome.Wpf](https://github.com/charri/Font-Awesome-WPF/blob/master/README-WPF.md) which has more icons and requires less code.
```
<Controls:Tile Width="300" Height="150" Grid.Column="0" Grid.Row="1" Title="Hello!">
<Grid Width="50" Height="50">
<fa:ImageAwesome Icon="Flag" Foreground="#FFFFFF"/>
</Grid>
</Controls:Tile>
```
Don't forget to call the namespace
```
xmlns:fa="http://schemas.fontawesome.io/icons/"
``` |