qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
20,861,417 |
I have a HomeController with an Index.cshtml Razor view that uses an InitialChoicesViewModel with validation attributes. The Index view contains the following form:
```
@using (Html.BeginForm("CreateCharacter", "DistributePoints", FormMethod.Get))
```
This goes to a different controller (which is what I want):
```cs
public class DistributePointsController : Controller
{
public ActionResult CreateCharacter(/* my form parameters */)
// ...
}
```
How do I perform server-side validation on the form (such as checking `ModelState.IsValid`), returning my original Index view with a correct `ValidationSummary` on error? (On success I want to return the CreateCharacter view of the other controller.)
---
Based on John H's answer, I resolved this as follows:
```
@using (Html.BeginForm("CreateCharacter", "Home"))
```
HomeController:
```cs
[HttpPost]
// Only some of the model fields are posted, along with an additional name field.
public ActionResult CreateCharacter(InitialChoicesViewModel model, string name)
{
if (ModelState.IsValid)
{
return RedirectToAction("CreateCharacter", "DistributePoints",
new {name, model.Level, model.UseAdvancedPointSystem});
}
// Unsure how to post a collection - easier to reload from repository.
model.ListOfStuff = _repository.GetAll().ToList();
return View("Index", model);
}
```
I had to add a parameterless constructor to my view model, too.
|
2013/12/31
|
[
"https://Stackoverflow.com/questions/20861417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/161457/"
] |
```
[HttpPost]
public ActionResult CreateCharacter(InitialChoicesViewModel model)
{
if (ModelState.IsValid)
return RedirectToAction("SomeSuccessfulaction");
return View("~/Views/Home/Index.cshtml", model);
}
```
The `~/` denotes the relative root of your site.
The code above complies with the [Post-Redirect-Get](http://en.wikipedia.org/wiki/Post/Redirect/Get "Post-Redirect-Get") pattern, in order to prevent some types of duplicate form submission problems. It does that by redirecting to a separate action when the form submission is successful, and by returning the current view, complete with `ModelState` information, on error.
|
To check your `ModelState` just use an if statement in Controller:
```
if(ModelState.IsValid)
{
...
}
```
If there is any error add you can add an error message to the ModelState Dictionary like this:
```
ModelState.AddModelError("Somethings failed", ErrorCodeToString(e.StatusCode));
```
After that return your same View and pass it to your model
```
return View(model);
```
If you add "`@Html.ValidationSummary()`" in your View, it will get the errors from the [ModelState Dictionary](http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstate%28v=vs.118%29.aspx) and display them.But if you show values yourself maybe with different styles you can do it manually, take a look at [this question](https://stackoverflow.com/questions/1352948/how-to-get-all-errors-from-asp-net-mvc-modelstate)
And if there is no error you can return your CreateCharacter View like this, just redirect user to the appropriate action:
```
return RedirectToAction("CreateCharacter","DistributePoints");
```
|
38,530,491 |
I am trying to learn CMake, but I get a undefined reference to ... linker error
I have a directory with a subdirectory.
each of them has its own CMakeLists.txt
```
test
|----main.cpp
|----CMakeLists.txt
|----test2
|----foo.hpp
|----foo.cpp
|----CMakeLists.txt
```
the CMakeLists.txt for test is:
```
cmake_minimum_required(VERSION 3.5)
project(tests)
add_subdirectory(test2)
set(SOURCE_FILES main.cpp)
add_executable(tests ${SOURCE_FILES})
```
the CMakeLists.txt for test2 is:
```
set(test2_files
foo.cpp
foo.hpp
)
add_library(test2 ${test2_files})
```
`foo.cpp` implements a function which is defined in `foo.hpp`
for this function I am getting the undefined reference error.
What am I doing wrong? How can I get rid of this linker error
EDIT: My CMakeLists.txt now looks like this, but I still get the linker error:
```
project(tests)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories(test2)
link_directories(test2)
add_subdirectory(test)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
target_link_libraries(${PROJECT_NAME} test2)
```
I also tried it with the absolute path instead of `test2`
EDIT:
solved it it was only a typo in the CMakeLists.txt of test2.
|
2016/07/22
|
[
"https://Stackoverflow.com/questions/38530491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4735801/"
] |
Make sure that your test `CMakeLists.txt` links to the created library.
```
project(test)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories( test2 )
#here
link_directories(test2)
add_subdirectory(test2)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
#and here
target_link_libraries( ${PROJECT_NAME} test2 )
```
|
Function `add_subdirectory($dir)` does not automatically add `$dir` to include directories and link directories. To use library `test2` you should do it manually in CMakeLists.txt of `test` directory:
```
include_directories(test2/)
link_directories(test2/)
```
Then, link your executable with `test2` library to get functions definitions. Add to CMakeLists.txt of `test` directory:
```
target_link_libraries(tests test2)
```
|
57,374,604 |
I have a single-threaded multi-client program written in c.
If one client has a hideously slow network connection or is being malicious and limits their rate of send() tot he server application to something ridiculous like 1 byte/second, will select() return on the first byte received from the client (as the socket has become active) and then leave the read() call blocking while it waits for the additional 2000 bytes to be written, completely destroying the server and rendering it unreachable for the other clients; or will the select function only return when the malicious client has totally written all the bytes to some OS buffer, allowing the server to handle other clients in the meantime?
|
2019/08/06
|
[
"https://Stackoverflow.com/questions/57374604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10076563/"
] |
From [the POSIX documentation about `select`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pselect.html):
>
> A descriptor shall be considered ready for reading when a call to an input function with `O_NONBLOCK` clear would not block, whether or not the function would transfer data successfully.
>
>
>
and
>
> A descriptor shall be considered ready for writing when a call to an output function with `O_NONBLOCK` clear would not block, whether or not the function would transfer data successfully.
>
>
>
So all that is guaranteed is that a blocking socket will not block if you attempt to receive (for sockets in the read set) or send (for sockets in the write set).
The amount of bytes that you will receive or is able to send is indeterminate.
This is why receiving and sending often is done using loops and on non-blocking sockets.
Also note that this "would not block" and "whether or not the function would transfer data successfully" could mean that the receive or send calls could return immediately with errors. Or in the case of receiving, return with the value `0` which means a connection-based connection is closed by the peer.
|
How would the OS know that it has to wait for 2000 bytes to arrive? TCP is a stream, so the OS can't know after 1999 bytes that there's still a byte pending.
For UDP, the OS knows it's packet-based, and it will have the entire packet available once the last byte arrives. It can't deliver the first byte earlier, because the UDP checksum must be verified ovr the whole packet.
|
5,720 |
I've noticed that people use present perfect when emailing other people, but I'm not sure how to utilize that verb tense. Will my example below work?
>
> "To this email, **I've attached** the copies of the photos you **asked** for. Also, because you *told* me that you **didn't** get the other copies, **I've made** more copies for you. **I've also attached** them to this email."
>
>
>
Or should I use the following?
>
> "To this email, I *attached* the copies of the photos you **asked** for. Also, because you **told** me that you **didn't** get the other copies, I **made** more copies for you. I also **attached** them to this email."
>
>
>
Is there a reason why people use present perfect when emailing?
|
2013/04/24
|
[
"https://ell.stackexchange.com/questions/5720",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1319/"
] |
First one seems reasonably good and enough. Though, I believe you can also phrase 1st line as,
>
> I have, herewith, attached the copies of the photos you asked for.
>
>
>
I also don't see the need for the following phrase in the end.
>
> I've also attached them to this email.
>
>
>
Also, it's usually a good practice to make a list of the attached items to the mail in a sequence - and then perhaps add some information in front of them individually as you may see fit. For instance:
>
> Please find the following files attached herewith:
>
>
> 1. *abc.jpg* - As requested by you in the last mail
> 2. *def.jpg*, *ghi.jpg* - Copies of the earlier photos you were not able to receive
> 3. *jkl.jpg*, *mno.jpg*
>
>
>
|
Short answer: Use the Past Simple if it's clearer, and it is a bit clearer here, plus is quicker and more common.
Longer answer: The Present Perfect is usually used in three ways.
Life experience (something occurring in the subject's past):
>
> I've participated in scavenger hunts with members of the Royal Family.
>
> I've never studied Martian.
>
> I've tried to, but I only have one larynx.
>
>
>
A change or action which affects or relates to the present situation:
>
> We've sent you the insects you requested. (They're in the mail.)
>
> I've caught a cold. (Now I'm sick.)
>
> My girlfriend has broken my hip. (Now she hops.)
>
>
>
An action or state lasting up until now:
>
> We've been waiting around all day for that asteroid to hit.
>
> I've never been good at wrestling ogres.
>
>
>
In your example, while all of those Present Perfect verbs are examples of a past action having a result relevant to the matter at hand, it's a little clearer if you use Past Simple because when someone's quickly reading an email the Present Perfect may be less obvious. This is because of potential confusion with the 'life experience'.
If you write '...I've made more copies for you.' it may also be read similar to 'I've made more copies for you at times in the past.' and it's subtly more courteous to the reader to remove the confusion. Past Simple may also refer to the past but the context makes it clear here.
Both tenses are correct in this case and we have a choice of whether we want to speak as though we're emphasizing the events when they happened **or** the present situation created by them, and I prefer the Past Simple for clear communication. If this were literature, I'd probably use the Present Perfect because we really are more concerned with the resulting situation, unless I were trying to evoke a more vernacular feel.
|
5,720 |
I've noticed that people use present perfect when emailing other people, but I'm not sure how to utilize that verb tense. Will my example below work?
>
> "To this email, **I've attached** the copies of the photos you **asked** for. Also, because you *told* me that you **didn't** get the other copies, **I've made** more copies for you. **I've also attached** them to this email."
>
>
>
Or should I use the following?
>
> "To this email, I *attached* the copies of the photos you **asked** for. Also, because you **told** me that you **didn't** get the other copies, I **made** more copies for you. I also **attached** them to this email."
>
>
>
Is there a reason why people use present perfect when emailing?
|
2013/04/24
|
[
"https://ell.stackexchange.com/questions/5720",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1319/"
] |
This is probably one of those cases where British English would use the present perfect tense, while American English would use the simple past tense.
The present perfect tense is used:
* To describe how an even in the past continues to be relevant at a later time
>
> Mario has arrived home.
>
>
>
* To describe a event that started in the past and continue into the present
>
> Michelle has shopped at that store since she was a child.
>
>
>
* To describe an repeated event happened in the past
>
> She has walked downtown everyday for a year.
>
>
>
Supposing that you are talking to somebody, and you say "Mario has arrived home." you are saying that Mario is still at home, while when you say "Mario arrived home." you are not saying where Mario actually is.
In your case, you could say "I have attached the copies of the photos" since the copies of the photos are still attached to the email when you will send it. If you say "I attached the copies of the photo," the person who receives the email will understand that the copies of the photos are still attached to the email, if you don't say something different.
|
Short answer: Use the Past Simple if it's clearer, and it is a bit clearer here, plus is quicker and more common.
Longer answer: The Present Perfect is usually used in three ways.
Life experience (something occurring in the subject's past):
>
> I've participated in scavenger hunts with members of the Royal Family.
>
> I've never studied Martian.
>
> I've tried to, but I only have one larynx.
>
>
>
A change or action which affects or relates to the present situation:
>
> We've sent you the insects you requested. (They're in the mail.)
>
> I've caught a cold. (Now I'm sick.)
>
> My girlfriend has broken my hip. (Now she hops.)
>
>
>
An action or state lasting up until now:
>
> We've been waiting around all day for that asteroid to hit.
>
> I've never been good at wrestling ogres.
>
>
>
In your example, while all of those Present Perfect verbs are examples of a past action having a result relevant to the matter at hand, it's a little clearer if you use Past Simple because when someone's quickly reading an email the Present Perfect may be less obvious. This is because of potential confusion with the 'life experience'.
If you write '...I've made more copies for you.' it may also be read similar to 'I've made more copies for you at times in the past.' and it's subtly more courteous to the reader to remove the confusion. Past Simple may also refer to the past but the context makes it clear here.
Both tenses are correct in this case and we have a choice of whether we want to speak as though we're emphasizing the events when they happened **or** the present situation created by them, and I prefer the Past Simple for clear communication. If this were literature, I'd probably use the Present Perfect because we really are more concerned with the resulting situation, unless I were trying to evoke a more vernacular feel.
|
5,720 |
I've noticed that people use present perfect when emailing other people, but I'm not sure how to utilize that verb tense. Will my example below work?
>
> "To this email, **I've attached** the copies of the photos you **asked** for. Also, because you *told* me that you **didn't** get the other copies, **I've made** more copies for you. **I've also attached** them to this email."
>
>
>
Or should I use the following?
>
> "To this email, I *attached* the copies of the photos you **asked** for. Also, because you **told** me that you **didn't** get the other copies, I **made** more copies for you. I also **attached** them to this email."
>
>
>
Is there a reason why people use present perfect when emailing?
|
2013/04/24
|
[
"https://ell.stackexchange.com/questions/5720",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1319/"
] |
I think it's because the past tense sounds somewhat awkward when the author is composing the email.
We use the present perfect tense when we want to talk about unfinished actions that started in the past and continue to the present.[1](http://www.perfect-english-grammar.com/present-perfect-use.html)
Well, at the moment you are composing the email, the action is unfinished. The email is still unsent. So, when I'm proofreading my own email:
>
> I attached copies of the photos you asked for.
>
>
>
sounds off. The action isn't done; my email is still sitting in front of me.
I'll grant you, the language would sound just fine if I imagined myself as the reader, reading an already-sent email message, but it seems like *I've attached* reads better **before** the email is sent, which is perhaps why you see that form as often as you do.
Incidentally, I wouldn't be thrown off by either of the two versions you composed.
|
Short answer: Use the Past Simple if it's clearer, and it is a bit clearer here, plus is quicker and more common.
Longer answer: The Present Perfect is usually used in three ways.
Life experience (something occurring in the subject's past):
>
> I've participated in scavenger hunts with members of the Royal Family.
>
> I've never studied Martian.
>
> I've tried to, but I only have one larynx.
>
>
>
A change or action which affects or relates to the present situation:
>
> We've sent you the insects you requested. (They're in the mail.)
>
> I've caught a cold. (Now I'm sick.)
>
> My girlfriend has broken my hip. (Now she hops.)
>
>
>
An action or state lasting up until now:
>
> We've been waiting around all day for that asteroid to hit.
>
> I've never been good at wrestling ogres.
>
>
>
In your example, while all of those Present Perfect verbs are examples of a past action having a result relevant to the matter at hand, it's a little clearer if you use Past Simple because when someone's quickly reading an email the Present Perfect may be less obvious. This is because of potential confusion with the 'life experience'.
If you write '...I've made more copies for you.' it may also be read similar to 'I've made more copies for you at times in the past.' and it's subtly more courteous to the reader to remove the confusion. Past Simple may also refer to the past but the context makes it clear here.
Both tenses are correct in this case and we have a choice of whether we want to speak as though we're emphasizing the events when they happened **or** the present situation created by them, and I prefer the Past Simple for clear communication. If this were literature, I'd probably use the Present Perfect because we really are more concerned with the resulting situation, unless I were trying to evoke a more vernacular feel.
|
3,281,842 |
i need upload a file in Chrome, and need **post** some params at the same request, and need Basic Authentication.
i want use javascript AJAX to do this.
but chrome do not support sendAsBinary, how can i do this?
```
function sendMsg(status){
var user = localStorage.getObject(CURRENT_USER_KEY);
var file = $("#imageFile")[0].files[0];
var boundary = '----multipartformboundary' + (new Date).getTime();
var dashdash = '--';
var crlf = '\r\n';
/* Build RFC2388 string. */
var builder = '';
builder += dashdash;
builder += boundary;
builder += crlf;
var xhr = new XMLHttpRequest();
var upload = xhr.upload;
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
//
}
};
if(upload){
upload.onprogress = function(ev){
onprogress(ev);
};
}
/* Generate headers. [STATUS] */
builder += 'Content-Disposition: form-data; name="status"';
builder += crlf;
builder += crlf;
/* Append form data. */
builder += msg;
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Generate headers. [PIC] */
builder += 'Content-Disposition: form-data; name="pic"';
if (file.fileName) {
builder += '; filename="' + file.fileName + '"';
}
builder += crlf;
builder += 'Content-Type: '+file.type;
builder += crlf;
builder += crlf;
/* Append binary data. */
builder += file.getAsBinary(); //chrome do not support getAsBinary()
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Mark end of the request. */
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
xhr.open("POST", apiUrl.sina.upload, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Authorization', make_base_auth_header(user.userName, user.password));
xhr.sendAsBinary(builder); //chrome do not support sendAsBinary()
xhr.onload = function(event) {
/* If we got an error display it. */
if (xhr.responseText) {
console.log(xhr.responseText);
}
};
};
```
|
2010/07/19
|
[
"https://Stackoverflow.com/questions/3281842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395885/"
] |
Use `xhr.send(FormData)`. You don't need to construct the `multipart-form-data` yourself :)
See my response here:
[Javascript/HTML5 file API reading sequential files into multipart form data](https://stackoverflow.com/questions/5362747/javascript-html5-file-api-reading-sequential-files-into-multipart-form-data/6048522#6048522)
|
Use a form to submit the file upload request just like you would normally, but set the target of the form to a hidden iframe. This will not refresh the page, but will still upload the file. You can also have the server spit out some JavaScript code which, once loaded into the hidden iframe, will tell you when the file is uploaded. Here's the form:
```
<iframe name=UploadTarget style="visibility: hidden;"></iframe>
<form method=post target=MyHiddenIframe action="Upload.php" enctype="multipart/form-data">
<input type=file name=File1>
<input type=button value="Upload">
</form>
```
To post some additional params, I have found the easiest way was to append them to the form's action string:
```
Upload.php?MyVar1=value1&MyVar2=value2
```
As far as I know there's no way to read form data and file data in the same request, but you can read from the information sent through the URL.
|
3,281,842 |
i need upload a file in Chrome, and need **post** some params at the same request, and need Basic Authentication.
i want use javascript AJAX to do this.
but chrome do not support sendAsBinary, how can i do this?
```
function sendMsg(status){
var user = localStorage.getObject(CURRENT_USER_KEY);
var file = $("#imageFile")[0].files[0];
var boundary = '----multipartformboundary' + (new Date).getTime();
var dashdash = '--';
var crlf = '\r\n';
/* Build RFC2388 string. */
var builder = '';
builder += dashdash;
builder += boundary;
builder += crlf;
var xhr = new XMLHttpRequest();
var upload = xhr.upload;
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
//
}
};
if(upload){
upload.onprogress = function(ev){
onprogress(ev);
};
}
/* Generate headers. [STATUS] */
builder += 'Content-Disposition: form-data; name="status"';
builder += crlf;
builder += crlf;
/* Append form data. */
builder += msg;
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Generate headers. [PIC] */
builder += 'Content-Disposition: form-data; name="pic"';
if (file.fileName) {
builder += '; filename="' + file.fileName + '"';
}
builder += crlf;
builder += 'Content-Type: '+file.type;
builder += crlf;
builder += crlf;
/* Append binary data. */
builder += file.getAsBinary(); //chrome do not support getAsBinary()
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Mark end of the request. */
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
xhr.open("POST", apiUrl.sina.upload, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Authorization', make_base_auth_header(user.userName, user.password));
xhr.sendAsBinary(builder); //chrome do not support sendAsBinary()
xhr.onload = function(event) {
/* If we got an error display it. */
if (xhr.responseText) {
console.log(xhr.responseText);
}
};
};
```
|
2010/07/19
|
[
"https://Stackoverflow.com/questions/3281842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395885/"
] |
>
> builder += file.getAsBinary();
> //chrome do not support getAsBinary()
>
>
>
Use the `readAsBinaryString` method of the `FileReader` API. Chrome does support it.
>
> xhr.sendAsBinary(builder); //chrome do
> not support sendAsBinary()
>
>
>
Learn how to accomplish it at the following URLs:
<http://javascript0.org/wiki/Portable_sendAsBinary>
<http://code.google.com/p/chromium/issues/detail?id=35705>
|
Use a form to submit the file upload request just like you would normally, but set the target of the form to a hidden iframe. This will not refresh the page, but will still upload the file. You can also have the server spit out some JavaScript code which, once loaded into the hidden iframe, will tell you when the file is uploaded. Here's the form:
```
<iframe name=UploadTarget style="visibility: hidden;"></iframe>
<form method=post target=MyHiddenIframe action="Upload.php" enctype="multipart/form-data">
<input type=file name=File1>
<input type=button value="Upload">
</form>
```
To post some additional params, I have found the easiest way was to append them to the form's action string:
```
Upload.php?MyVar1=value1&MyVar2=value2
```
As far as I know there's no way to read form data and file data in the same request, but you can read from the information sent through the URL.
|
50,046,105 |
Below is an example for a custom web component `my-input`. I would like to bind the value attribute of my custom input component to the email attribute of a vue instance. (The example might require Chrome to support custom web components.)
=>How do I have to adapt my web component example to get the binding working?
If I replace `my-input` with a plain `input` tag, the binding works. Therefore, my syntax for the vue.js part seems to be just fine.
<https://jsfiddle.net/j5f9edjt/>
```js
new Vue({
el: '#app',
template: '#app-template',
data: {
//email data is blank initially
email: ''
}
})
```
```html
<script type="text/javascript" src="https://unpkg.com/[email protected]"></script>
<script>
class MyInput extends HTMLElement {
static get observedAttributes() {
return ['value'];
}
constructor(){
super();
this.wrappedInput=undefined;
}
connectedCallback(){
var self=this;
if(!self.wrappedInput){
var wrappedInput = document.createElement('input');
wrappedInput.type='text';
wrappedInput.onchange = ()=>this.wrappedInputChanged();
self.appendChild(wrappedInput);
self.wrappedInput = wrappedInput;
}
}
attributeChangedCallback(attr, oldValue, newValue) {
if(attr==='value'){
console.log('attribute changed ' + newValue);
if(this.wrappedInput){
this.wrappedInput.value= newValue;
}
}
}
wrappedInputChanged(){
console.log('wrapepd input changed')
var newValue = this.wrappedInput.value;
this.value = newValue;
}
get value() {
console.log('get value')
return this.getAttribute('value');
}
set value(newValue) {
this.setAttribute('value',newValue);
console.log('set value ' + newValue);
}
}
window.customElements.define('my-input', MyInput);
</script>
<div id="app"></div>
<template id="app-template">
<div>
<my-input v-model="email"></my-input>
<h1>
You entered {{email}}
</h1>
</div>
</template>
```
I tried to dispatch an extra input event but that did not help:
```
var myInput = new CustomEvent("input",
{
detail: {
message: "Hello World!",
type: 'text',
},
bubbles: true,
cancelable: true
}
);
this.dispatchEvent(myInput);
```
Where can I find the source code for the v-model directive to understand what it does?
Related question:
[How to target custom element (native web component) in vue.js?](https://stackoverflow.com/questions/49071186/how-to-target-custom-element-native-web-component-in-vue-js)
|
2018/04/26
|
[
"https://Stackoverflow.com/questions/50046105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2876079/"
] |
To make `v-model` work you need to make a wrapper component for your webcomponent. The wrapper will conform to the [requirements for using `v-model` with a component](https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components).
Alternatively, you can decompose the `v-model` into its two parts: set the `value` prop and handle `input` events. Vue doesn't seem to recognize a webcomponent as a native element as far as `v-model` goes.
```js
class MyInput extends HTMLElement {
static get observedAttributes() {
return ['value'];
}
constructor() {
super();
this.wrappedInput = undefined;
}
connectedCallback() {
var self = this;
if (!self.wrappedInput) {
var wrappedInput = document.createElement('input');
wrappedInput.type = 'text';
wrappedInput.onchange = () => this.wrappedInputChanged();
self.appendChild(wrappedInput);
self.wrappedInput = wrappedInput;
}
}
attributeChangedCallback(attr, oldValue, newValue) {
if (attr === 'value') {
console.log('attribute changed ' + newValue);
if (this.wrappedInput) {
this.wrappedInput.value = newValue;
}
}
}
wrappedInputChanged() {
var newValue = this.wrappedInput.value;
this.value = newValue;
}
get value() {
console.log('get value')
return this.getAttribute('value');
}
set value(newValue) {
this.setAttribute('value', newValue);
console.log('set value ' + newValue);
}
}
window.customElements.define('my-input', MyInput);
new Vue({
el: '#app',
template: '#app-template',
data: {
//email data is blank initially
email: ''
},
methods: {
handleInput(event) {
this.email = event.target.value;
}
},
components: {
wrappedMyInput: {
template: '#wmi-template',
props: ['value'],
methods: {
emitInput(event) {
this.$emit('input', event.target.value);
}
}
}
}
})
```
```html
<script type="text/javascript" src="https://unpkg.com/[email protected]"></script>
<div id="app"></div>
<template id="app-template">
<div>
<my-input :value="email" @input="handleInput"></my-input>
<h1>
You entered {{email}}
</h1>
<wrapped-my-input v-model="email"></wrapped-my-input>
<h1>
You entered {{email}}
</h1>
</div>
</template>
<template id="wmi-template">
<my-input :value="value" @input="emitInput"></my-input>
</template>
```
|
The `v-model` directive seems to check the type of the tag and handle them individually:
<https://github.com/vuejs/vue/blob/dev/src/platforms/web/compiler/directives/model.js>
I did not get the `v-model` to work for my custom component without extra wrappers. (I gave up on understanding how exactly my case is handled in model.js.)
As an alternative to "decomposing the binding" as suggested by Roy J.
```
<my-input :value="email" @input="email = $event.target.value"></my-input>
```
I created a custom directive `v-property`. It works both for `my-input` and `input` (as used in my original example; did not try all possible cases):
```
<my-input v-property="email"></my-input>
<input v-property="email"></my-input>
```
--
```
Vue.directive('property', {
bind: function (el, binding, vnode) {
var viewModel = vnode.context;
var propertyName = binding.expression;
el.addEventListener('input', (event)=>{
var oldValue = viewModel[propertyName];
var newValue = event.target.value;
if(newValue != oldValue){
viewModel[propertyName] = newValue;
}
});
viewModel.$watch(propertyName, ()=>{
var oldValue = el.value;
var newValue = viewModel[propertyName];
if(newValue != oldValue){
el.value = newValue;
}
});
}
});
```
<https://jsfiddle.net/7dqppqo2/>
|
45,008,526 |
I'm trying to implement an await Task.Run in my controller and then return the response.
Just curious if the response will always be got before we attempt to return it.
```
var response = await Task.Run(() => _myService.GetResponse(refno));
return Ok(response);
```
Could it attempt to return a response which hasn't been set yet?
Thanks
|
2017/07/10
|
[
"https://Stackoverflow.com/questions/45008526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115983/"
] |
One way is to manually edit the csproj file.
If you have currently referenced the NuGet package, you will have a part in the csproj file like this:
```
....
<ItemGroup>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
....
```
In this example, log4net is used. For your NuGet package, the public key token, version and so on is different.
You can no change it to:
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<Reference Include="log4net">
<HintPath>Debug\log4net.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.8\lib\net45-full\log4net.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
```
The `Condition` attribute in the `ItemGroup` element is doing the job between debug and release.
|
>
> Is it possible to do a project-reference the Nuget project (B) from the Solution (A) when building Debug. And when building Release use the Nuget package from Source?
>
>
>
**Certainly, but there are some restrictions you need to know.**
**First**, the ID of the NuGet package should different from the name of the reference project, otherwise, the reference from NuGet will replace the project reference.(For example, `TestProjectReferenceForDebug` is the name of the project reference, if you want to use project reference and NuGet package at the same time, you could not use this project to create the NuGet package directly, so I created a same project with different name to create the NuGet package "`TestNuGetForRelease`"):
[](https://i.stack.imgur.com/bQKDV.png)
**Second**, you should use `Condition` attribute in the `ItemGroup` element, otherwise, there is an ambiguous reference between '`TestProjectReferenceForDebug`' and '`TestNuGetForRelease`', so we need **add the `Condition` attribute in the `ItemGroup` element**
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<Reference Include="TestNuGetForRelease, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL" >
<HintPath>..\packages\TestNuGetForRelease.1.0.0\lib\net462\TestNuGetForRelease.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<ProjectReference Include="..\TestProjectReferenceForDebug\TestProjectReferenceForDebug.csproj">
<Project>{90424b17-2231-4d7d-997b-608115d9f4d9}</Project>
<Name>TestProjectReferenceForDebug</Name>
</ProjectReference>
</ItemGroup>
```
**Third**, after we add the `Condition` attribute in the `ItemGroup` element with `debug` and `release`, we could use project reference in `Debug` and Nuget in `Release`, however, if we use those namespace in one .cs file at same time, we need to add those two namespace, then you will get an error "The referenced component 'xxx' could not be found". That because VS could not find those two namespace only in the "Release" or "Debug" model:
[](https://i.stack.imgur.com/OpUJh.png)
**To resolve this error**, we have to annotate the namespace which in another configuration model when you change the configuration model from Debug to Release.
[](https://i.stack.imgur.com/VsrOT.gif)
|
30,591,015 |
Hey guys im new to xcode and programming
im trying out this tutorial on making a slide out menu
<https://www.youtube.com/watch?v=8EFfPT3UeWs>
I cant get it working i downloaded the finished project files found here:
<https://www.dropbox.com/s/7eku9pp06u75q6u/SlideoutMenuSwift-Full.zip?dl=0>
I cant get it to work
```
var cell = tableView.dequeueReusableCellWithIdentifier(TableArray[indexPath.row], forIndexPath: indexPath) as UITableViewCell
```
coming up with error
anyobject is not convertible to `UITableViewCell` did you mean to use "as!" to force downcast?
any help would be greatly appreciated
Im 100% it has something to do with my version of xcode so hopefully something simple
cheers
travis
|
2015/06/02
|
[
"https://Stackoverflow.com/questions/30591015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4964312/"
] |
Welcome to the magic world of programming :-)
As bjornorri writes, the syntax for `as` was changed in Swift 1.2.
If you look at the documentation for the method `dequeueReusableCellWithIdentifier` (which can be found [here](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instm/UITableView/dequeueReusableCellWithIdentifier:forIndexPath:)) you'll see that it returns `AnyObject` meaning anything really.
So...you have to cast it to a `UITableViewCell` which you do with the `as`keyword as you have already figured out.
When you cast from something more abstract to something more specific, as you do here when you try to go from `AnyObject` to `UITableViewCell`, this is known as a downcast.
The problem with a downcast is, that you cannot be sure if it'll actually work. Sure, you say that you want this object to be a `UITableViewCell` (and in this case, it will work) but there's no guarantee, maybe the original value was something else than a `UITableViewCell`.
Therefore, as of Swift 1.2, the behaviour of `as` was changed so you have to add a ! to force the downcast. This means that you tell the compiler to go ahead and just downcast the object, you know what you're doing. If it works then all is well, but if it doesn't, your app will crash.
You can read more about it here at [Ray Wenderlich](http://www.raywenderlich.com/95181/whats-new-in-swift-1-2) (which I suggest that you bookmark if you haven't already :-))
|
This is because the Swift syntax has changed since the demo was written. You can probably fix this simply by following the suggestions in the error messages Xcode provides you.
|
13,662,270 |
I have a SQL Server database that contains usage data of an application (from over 100 devices), with over 1 year of data collected (30GB database).
Inserting data into the DB is not a problem, is fast enough (for now), and is the only operation done by the clients.
There is one master table and a few child tables, but let's say I can put everything in a single table.
I need to do statistical analysis, so mostly `count(*)` filtering by date and by one or more columns. Performance is getting slow (done everything I could with indexes).
Would moving to MongoDB improve the speed? I haven't started to study it, but 99% of my operations would be (yes I know is not SQL):
```
select count(*) from table
where date between date1 and date2 and field1 = 10 and field2 = "test"
```
|
2012/12/01
|
[
"https://Stackoverflow.com/questions/13662270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1216019/"
] |
Your requirements can be easily handled by sql server.
by the use of proper indexes and other optimization techniques. these queries can be execute efficiently by SQL SERVER. for your use case a sinmple index on (date,field1,field2)
```
CREATE CLUSTERED INDEX IDX_TABLE_ID ON TABLE(id)
GO
CREATE INDEX IDX_TABLE_2 ON TABLE(date,field1,field2)
GO
```
can be sufficient for fast query execution.
**just a note:**
For archival analysis SQL server Provides data warehousing tools(SQL SERVER ANALYSIS SERVICE).
SQL SEREVER CUBE can aggregate and make analysis of huge archive data very simple.
for other sql server information : <http://ms-sql-queries.blogspot.in/>
|
If you aren't using any joins within the query then the performance of the sql server will not be affected. If you use mongodb for the same purpose then also the querying time will be about that of the sql one or a little worse.
|
246,705 |
Is it possible to set page labels in pdfs “correctly”? Pages in my latex documents are numbered 1-x. I'd like the page labels to correspond to the actual page numbers (as mentioned here: <http://pdf.editme.com/pdfua-PageLabels>).
So that the first page would be “Cover”, pages—let's say—2–5 (with toc and so on) numbered with Roman literals (i, ii, iii, etc.) and pages 6–end numbered with Arabic literals.
How do I achieve that?
|
2015/05/24
|
[
"https://tex.stackexchange.com/questions/246705",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/75475/"
] |
Package `hyperref` also adds support for the PDF page labels. It uses `\thepage` for this purpose.
The cover page can be labeled using `\thispdfpagelabel`:
```
\documentclass{report}
\usepackage{hyperref}
\begin{document}
\begin{titlepage}
\hypersetup{pageanchor=false}
\thispdfpagelabel{Cover}
\Huge Cover
\end{titlepage}
\pagenumbering{roman}
\tableofcontents
\listoffigures
\listoftables
\pagenumbering{arabic}
\chapter{Abc}
\end{document}
```
The example also disables the page label for the cover page, because it is unlikely, that it is needed (e.g., page anchors are needed for index entries). Otherwise the page anchor for the cover page (`1`) would clash with the page anchor for the first chapter page (also `1`).
If the cover pages do not print the page number, then `\thepage` can be redefined, e.g., with `Cover-` as prefix. With a unique `\thepage` the page anchor does not need to be disabled, example:
```
\documentclass{book}
\usepackage{hyperref}
\begin{document}
\begingroup
\renewcommand*{\thepage}{Cover-\arabic{page}}
\pagestyle{empty}
\Huge Cover
\cleardoublepage
\endgroup
\frontmatter
\tableofcontents
\listoffigures
\listoftables
\mainmatter
\chapter{Abc}
\end{document}
```
|
As mentioned by Heiko, just use the [`hyperref`](https://www.ctan.org/pkg/hyperref?lang=en) package.
Example:
```
\documentclass{report}
\usepackage[pdfpagelabels,hyperindex,hyperfigures]{hyperref}
\begin{document}
Hola. This is my cover page
\pdfbookmark[0]{Cover}{initialpage}
\end{document}
```
Output:

|
21,718,701 |
I am using windows 8 (not yet updated to 8.1)
The code I am using is
>
> import ctypes
>
>
> SPI\_SETDESKWALLPAPER = 20
>
>
> ctypes.windll.user32.SystemParametersInfoA(SPI\_SETDESKWALLPAPER, 0, "word.jpg", 0)
>
>
> print "hi"
>
>
>
For some reason regardless if i give it a valid image (in the same directory as program) or not, regardless of type of image (bmp, gif, jpg) the code always ends up setting my background to a black screen.
Why is this? How can it be fixed?
|
2014/02/12
|
[
"https://Stackoverflow.com/questions/21718701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180100/"
] |
Try passing `SPIF_SENDCHANGE` (which is *2*) as the last parameter. You might also need to bitwise-or it with `SPIF_UPDATEINIFILE` (which is *1*).
|
Sorry, I know this is late, but the problem is that you need to include the path. Instead of "image.jpg" do r"C:\path to file\image.jpg" Otherwise python doesn't know where to look for the image.
|
21,904 |
I'm using/learning geodjango + postgis, and I'm trying to calculate distance between 2 cities in Poland. First using WGS84/4326 I define 2 points, and then after transforming this points into spherical mercator 900913 i get distance which is about 40km too long. Which map projection should I use then? Where can I find proper srid's for different countries?
sorry for the delay, 2 cities (lat; long): Slupsk(54.465249;17.026062) and Koszalin(54.193378;16.179428)
|
2012/03/19
|
[
"https://gis.stackexchange.com/questions/21904",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/6434/"
] |
That's what picking a decent map projection is all about. I don't know your lat/long range but you can query projections relevant to a lat/long bounding box at the [EPSG Geodetic Parameter Dataset](http://www.epsg.org/). This should give some codes to test out.
EDIT: Thanks for posting your coordinates. When you just calculate a cartesian distance between these points in a Plate Carree or something similar projection, you get something like 90km which is obviously the wrong result from a wrong method.
Others have explained the 'math route' using a spherical calculation, so I took the 'tool route' and retrieved the [ETRS89](http://en.wikipedia.org/wiki/European_Terrestrial_Reference_System_1989) projection from the EPSG database based on your coordinates, measuring in this coordinate system I get about 63km, which is the considerable difference we're seeing.

|
Use latitude and longitude and the [great circle distance](http://en.wikipedia.org/wiki/Great-circle_distance), not a map projection.
|
21,904 |
I'm using/learning geodjango + postgis, and I'm trying to calculate distance between 2 cities in Poland. First using WGS84/4326 I define 2 points, and then after transforming this points into spherical mercator 900913 i get distance which is about 40km too long. Which map projection should I use then? Where can I find proper srid's for different countries?
sorry for the delay, 2 cities (lat; long): Slupsk(54.465249;17.026062) and Koszalin(54.193378;16.179428)
|
2012/03/19
|
[
"https://gis.stackexchange.com/questions/21904",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/6434/"
] |
Use latitude and longitude and the [great circle distance](http://en.wikipedia.org/wiki/Great-circle_distance), not a map projection.
|
Based on the 2 points in your comments:
```
2 cities (lat; long): Slupsk(54.465249;17.026062) and Koszalin(54.193378;16.179428)
```
I used two different approaches. The formula given in [The Aviation Formulary](http://williams.best.vwh.net/avform.htm#Example) I ended up with a distance of 63.116745 KM
I also used this tool [Calculate distance, bearing and more between Latitude/Longitude points](http://www.movable-type.co.uk/scripts/latlong.html). I ended up with an answer of 63.16 km.
Both methods use a "cue ball" earth, they do not use WGS84, or any projection.
|
21,904 |
I'm using/learning geodjango + postgis, and I'm trying to calculate distance between 2 cities in Poland. First using WGS84/4326 I define 2 points, and then after transforming this points into spherical mercator 900913 i get distance which is about 40km too long. Which map projection should I use then? Where can I find proper srid's for different countries?
sorry for the delay, 2 cities (lat; long): Slupsk(54.465249;17.026062) and Koszalin(54.193378;16.179428)
|
2012/03/19
|
[
"https://gis.stackexchange.com/questions/21904",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/6434/"
] |
That's what picking a decent map projection is all about. I don't know your lat/long range but you can query projections relevant to a lat/long bounding box at the [EPSG Geodetic Parameter Dataset](http://www.epsg.org/). This should give some codes to test out.
EDIT: Thanks for posting your coordinates. When you just calculate a cartesian distance between these points in a Plate Carree or something similar projection, you get something like 90km which is obviously the wrong result from a wrong method.
Others have explained the 'math route' using a spherical calculation, so I took the 'tool route' and retrieved the [ETRS89](http://en.wikipedia.org/wiki/European_Terrestrial_Reference_System_1989) projection from the EPSG database based on your coordinates, measuring in this coordinate system I get about 63km, which is the considerable difference we're seeing.

|
Based on the 2 points in your comments:
```
2 cities (lat; long): Slupsk(54.465249;17.026062) and Koszalin(54.193378;16.179428)
```
I used two different approaches. The formula given in [The Aviation Formulary](http://williams.best.vwh.net/avform.htm#Example) I ended up with a distance of 63.116745 KM
I also used this tool [Calculate distance, bearing and more between Latitude/Longitude points](http://www.movable-type.co.uk/scripts/latlong.html). I ended up with an answer of 63.16 km.
Both methods use a "cue ball" earth, they do not use WGS84, or any projection.
|
17,832 |
I am following climate activist Greta Thunberg's sail to N America from Europe on <https://tracker.borisherrmannracing.com/>. The model shows a cyclonic storm forming south of Nova Scotia, east of New York on August 26, 2019. The same thing can be seen on <https://earth.nullschool.net/>. I wasn't aware that this type of storm formed so far north and am wondering why this storm is forming and if this is a rare occurrence that may be related to climate change.
[](https://i.stack.imgur.com/ya8x1.jpg)
Edit to add: Here is the model of air temperature. It appears to me that the storm forms at the interface between cool air from the north and warm air from the south and that the core is warm, but perhaps someone with more expertise can weigh in.
[](https://i.stack.imgur.com/ixN6U.jpg)
|
2019/08/25
|
[
"https://earthscience.stackexchange.com/questions/17832",
"https://earthscience.stackexchange.com",
"https://earthscience.stackexchange.com/users/1242/"
] |
A cyclone is nothing more than a low-pressure system. It can surely form in the North Atlantic; in fact, most low-pressure systems that reach Europe form in the North Atlantic.
You are probably thinking about a *tropical* cyclone, which indeed cannot form that far north. Among others, a tropical cyclone needs high sea temperatures (>27 C), which are usually not present at such high latitudes.
About the present cyclone south of Nova Scotia: I think it is a cold core cyclone, as 500 hPa temperature are lower than in surroundings (which is e.g. not the case for tropical storm Dorian, which is currently east from the Lesser Antilles). Therefore, it's not a tropical cyclone but an ordinary extra-tropical cyclone, which can perfectly form at those latitudes.
|
No, it's not normal. Hurricanes and typhoons require sun-warmed seas like the Caribbean or Gulf of Mexico to form, because that's where they get their energy from. When meteorologists talk of cyclones and anticyclones, they are talking about high pressure or low pressure weather systems, not hurricanes and typhoons. Storms can form that far north, but probably not hurricanes, typhoons or cyclones, which are just different names for the same thing. When referring to the mega-storms which devastate tropical and subtropical islands, the terms hurricane (Atlantic) or typhoon (Pacific) are usually used. I don't think the weather system featured in your diagram was a hurricane.
|
57,833,624 |
I want to use !test epicchannel (epicchannel being the name of the channel , for example if I want to use !test infinite , it will create a channel named testing-infinite ) but it doesn't work. it just makes a channel named testing-test
I've tried using message.content.startsWith, but if I do that, nothing happens.
```js
const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = '!';
client.on("message", async message => {
if(message.content.startsWith === '!test') {
if(message.author.id === '560761436058550273') {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
message.guild.createChannel(`testing-${args}`).then(channel => {
channel.setTopic(`Today we will test: ${args}`)
})
}else{
if(!message.author.id === '560761436058550273') {
return;
}
}
}
});
client.login('login is here');
```
No errors, I just want it to use !test infinite to create a channel named testing-infinite
|
2019/09/07
|
[
"https://Stackoverflow.com/questions/57833624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11761104/"
] |
First check if data is not same with:
```
dd($item->item_smallest_unit_cost, $item_unit->item_unit_coast_price);
```
If is data you expected result, you need to save updated item:
```
$item = $item_unit->getItem;
$item->item_smallest_unit_cost = $item_unit->item_unit_coast_price;
$item->item_smallest_unit_selling_price = $item_unit->item_unit_selling_price;
$item->save(); // You need that
return $item;
```
This should work.
You can found more [here](https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models).
|
`$item->item_smallest_unit_cost = $item_unit->item_unit_coast_price;
$item->item_smallest_unit_selling_price = $item_unit->item_unit_selling_price;`
instead of this use following
```
$item['item_smallest_unit_cost'] = $item_unit->item_unit_coast_price;
$item['item_smallest_unit_selling_price'] = $item_unit->item_unit_selling_price;
```
also
```
return $item->get();
```
instead only
```
return $item;
```
|
11,324,295 |
I am developing small android application in which I want to find user current location.
My code structure for detecting user location looks like .
```
private void sendSMS(Context context, Intent intent)
{
final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
LocationManager locationManager;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new MyLocationListener()
);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
String loc_message = null;
if (location != null)
{
loc_message =String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(context, loc_message,Toast.LENGTH_LONG).show();
}
}
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
}
}
```
Working fine on simulator where I send coordinates from DDMS. But when I run it on device it not giving me output.On my device I keep Use GPS satellites enable. But when I tried to find user location it's not giving any output.... Need Help... Thank you.......
|
2012/07/04
|
[
"https://Stackoverflow.com/questions/11324295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861204/"
] |
Here is the skeleton of the GPS `Service` I used in my tracking application, it has been tested, and works fine I can guarantee that. I hope it will help you out.
```
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.util.Log;
public class TrackingService extends Service {
private static final String TAG = TrackingService.class.getSimpleName();
private static final long TIME_BETWEEN_UPDATES = 1000L;
private static final long MINIMUM_DISTANCE_CHANGE = 0L;
private WakeLock mWakeLock;
private LocationManager mLocationManager;
private final Timer mTimer = new Timer();
private Handler mHandler = new Handler();
private LocationListener mLocationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
// Your code here
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
private void registerLocationListener() {
if (mLocationManager == null) {
Log.e(TAG, "TrackingService: Do not have any location manager.");
return;
}
Log.d(TAG, "Preparing to register location listener w/ TrackingService...");
try {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE, mLocationListenerGps);
Log.d(TAG, "...location listener now registered w/ TrackingService @ " + TIME_BETWEEN_UPDATES);
} catch (RuntimeException e) {
Log.e(TAG, "Could not register location listener: " + e.getMessage(), e);
}
}
private void unregisterLocationListener() {
if (mLocationManager == null) {
Log.e(TAG, "TrackingService: Do not have any location manager.");
return;
}
mLocationManager.removeUpdates(mLocationListenerGps);
Log.d(TAG, "Location listener now unregistered w/ TrackingService.");
}
private TimerTask mCheckLocationListenerTask = new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "Re-registering location listener with TrackingService.");
unregisterLocationListener();
registerLocationListener();
}
});
}
};
@Override
public void onCreate() {
super.onCreate();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
registerLocationListener();
mTimer.schedule(mCheckLocationListenerTask, 1000 * 60 * 5, 1000 * 60);
acquireWakeLock();
Log.d(TAG, "Service started...");
}
@Override
public void onStart(Intent intent, int startId) {
handleStartCommand(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStartCommand(intent, startId);
return START_STICKY;
}
private void handleStartCommand(Intent intent, int startId) {
Notification notification = new Notification(R.drawable.ic_launcher,
getText(R.string.trackingservice_notification_rolling_text),
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this,
getText(R.string.trackingservice_notification_ticker_title),
getText(R.string.trackingservice_notification_ticker_text),
contentIntent);
startForeground(1, notification);
}
@Override
public void onDestroy() {
stopForeground(true);
mTimer.cancel();
mTimer.purge();
mHandler.removeCallbacksAndMessages(null);
unregisterLocationListener();
releaseWakeLock();
super.onDestroy();
Log.d(TAG, "Service stopped...");
}
private void acquireWakeLock() {
try {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm == null) {
Log.e(TAG, "TrackRecordingService: Power manager not found!");
return;
}
if (mWakeLock == null) {
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
if (mWakeLock == null) {
Log.e(TAG, "TrackRecordingService: Could not create wake lock (null).");
return;
}
}
if (!mWakeLock.isHeld()) {
mWakeLock.acquire();
if (!mWakeLock.isHeld()) {
Log.e(TAG, "TrackRecordingService: Could not acquire wake lock.");
}
}
} catch (RuntimeException e) {
Log.e(TAG, "TrackRecordingService: Caught unexpected exception: "
+ e.getMessage(), e);
}
}
/**
* Releases the wake lock if it's currently held.
*/
private void releaseWakeLock() {
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
mWakeLock = null;
}
}
}
```
And in your AndroidManifest.xml file you need
```
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
```
Just fill out the GPS location listener, Register the service in your `AndroidManifest.xml`, start the service from your activity, and enjoy.
|
Nilkash, I experienced the same problem on my Samsung Galaxy 5.
I got my problem solved because of your suggestion to change as network provider. Thanks for that Buddy . I got the solution.
"Network Provider" determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS\_COARSE\_LOCATION or android.permission.ACCESS\_FINE\_LOCATION.
But "GPS Provider" determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS\_FINE\_LOCATION.
This is the problem with device, our device does not support gps without internet it only uses location provider.
|
37,608,276 |
I'm trying to load an external OpenCL kernel and the `clCreateKernel` returns an error code: -46 `CL_INVALID_KERNEL_NAME`. The file structure is the following:
```
.
├── CMakeLists.txt
└── src
├── cl.hpp
├── GameOfLife.cpp
└── kernels
└── programs.cl
```
This is my first CMake project, thus I'm not sure the following CMake is correct:
```
cmake_minimum_required(VERSION 3.5)
project(gpgpu_gameoflife)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lOpenCL")
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/src/kernels)
# source: http://igorbarbosa.com/articles/how-to-use-opengl-freeglut-and-cmake/
#########################################################
# FIND GLUT
#########################################################
find_package(GLUT REQUIRED)
include_directories(${GLUT_INCLUDE_DIRS})
link_directories(${GLUT_LIBRARY_DIRS})
add_definitions(${GLUT_DEFINITIONS})
if(NOT GLUT_FOUND)
message(ERROR " GLUT not found!")
endif(NOT GLUT_FOUND)
#########################################################
# FIND OPENGL
#########################################################
find_package(OpenGL REQUIRED)
include_directories(${OpenGL_INCLUDE_DIRS})
link_directories(${OpenGL_LIBRARY_DIRS})
add_definitions(${OpenGL_DEFINITIONS})
if(NOT OPENGL_FOUND)
message(ERROR " OPENGL not found!")
endif(NOT OPENGL_FOUND)
set(SOURCE_FILES
src/GameOfLife.cpp
src/kernels/programs.cl
)
add_executable(gpgpu_gameoflife ${SOURCE_FILES})
target_link_libraries(gpgpu_gameoflife ${OPENGL_LIBRARIES} ${GLUT_LIBRARY})
```
For the following function call I get an empty string as a result, thus I think the kernel file is not available to be read (the kernel itself is not empty).
```
std::string sourceCode = fileToString("kernels/programs.cl");
```
...
```
std::string fileToString(const std::string &path) {
std::ifstream file(path, std::ios::in | std::ios::binary);
if (file) {
std::ostringstream contents;
contents << file.rdbuf();
file.close();
return (contents.str());
}
return "";
}
```
Could you please tell me how to create an OpenCL application using CMake that loads an external kernel? Or is this not a good practice?
Thank you!
|
2016/06/03
|
[
"https://Stackoverflow.com/questions/37608276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2286520/"
] |
Although the following line in CMake solves my problem, I'm still waiting for other answers maybe containing a better solution.
```
configure_file(src/kernels/programs.cl kernels/programs.cl COPYONLY)
```
|
you should update your path depending from where you build your program
If your project looks like this:
```
── CMakeLists.txt
└── src
| ├── cl.hpp
| ├── GameOfLife.cpp
| └── kernels
| └── programs.cl
└── build
```
and you call "make" from the build directory, the string path should look like this: "../src/kernels/programs.cl". Alternatively you can set a CMake variable with "set(PATH\_TO\_FILE "${CMAKE\_SOURCE\_DIR}/src/kernels/programs.cl") and pass it to the main args
|
412,084 |
A pointer stores/is assigned a memory address;
what about a reference variable?
it stores the actual value of an object just like any other non-pointer simple variables on Stack?
Thanks!
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/412084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36064/"
] |
A reference does contain nothing in itself. The C++ Standard even states that an implementation is not required to allocate any storage for a reference. It's really just an alias for the object or function that it references. Trying to take the value of a reference will take the value of the object or function (in that case, you get a function pointer, just like when you would try to get the value out of the function using its original name) it references, instead.
Of course, when you go on lower levels and look at the assembler code, references are just like pointers. But at the language level, they are completely different beasts. References to const, for example, can bind to temporaries, they are required to implement a copy constructor, for overloading operators and they can't be put into an array (not even if you initialize all elements of it), because references are no objects (as opposed to pointers). They are, as trivial as it may sound, reference types.
|
>
> it stores the actual value of an object just like any other non-pointer simple variables on Stack?
>
>
>
Not exactly: because you don't have **two** copies of the value (one copy in the object, and another copy in the reference to the object); instead, the reference is probably implemented as a pointer to the object.
Differences between a pointer and an object:
* reference can't be null
* reference can't be uninitialized (must be initialized when it's defined)
* reference can't be changed to reference a different object
|
412,084 |
A pointer stores/is assigned a memory address;
what about a reference variable?
it stores the actual value of an object just like any other non-pointer simple variables on Stack?
Thanks!
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/412084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36064/"
] |
A reference does contain nothing in itself. The C++ Standard even states that an implementation is not required to allocate any storage for a reference. It's really just an alias for the object or function that it references. Trying to take the value of a reference will take the value of the object or function (in that case, you get a function pointer, just like when you would try to get the value out of the function using its original name) it references, instead.
Of course, when you go on lower levels and look at the assembler code, references are just like pointers. But at the language level, they are completely different beasts. References to const, for example, can bind to temporaries, they are required to implement a copy constructor, for overloading operators and they can't be put into an array (not even if you initialize all elements of it), because references are no objects (as opposed to pointers). They are, as trivial as it may sound, reference types.
|
I'd say that it's just a pointer with a different syntax.
|
412,084 |
A pointer stores/is assigned a memory address;
what about a reference variable?
it stores the actual value of an object just like any other non-pointer simple variables on Stack?
Thanks!
|
2009/01/05
|
[
"https://Stackoverflow.com/questions/412084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36064/"
] |
A reference does contain nothing in itself. The C++ Standard even states that an implementation is not required to allocate any storage for a reference. It's really just an alias for the object or function that it references. Trying to take the value of a reference will take the value of the object or function (in that case, you get a function pointer, just like when you would try to get the value out of the function using its original name) it references, instead.
Of course, when you go on lower levels and look at the assembler code, references are just like pointers. But at the language level, they are completely different beasts. References to const, for example, can bind to temporaries, they are required to implement a copy constructor, for overloading operators and they can't be put into an array (not even if you initialize all elements of it), because references are no objects (as opposed to pointers). They are, as trivial as it may sound, reference types.
|
Internally, it's just a pointer to the object (although the standard not necessarily mandates it, all compilers implement this way). Externally, it behaves like the object itself. Think of it as a pointer with an implicit '\*' operator wherever it is used (except, of course, the declaration). It's also a const-pointer (not to be confused with a pointer-to-const), since it cannot be redirected once declared.
|
40,790,385 |
I have a strange behavior, I have developed a hybrid app with ionic, afterwards I have installed it at my mobile with this command:
[](https://i.stack.imgur.com/5Hgch.png)
everything was fine, but on my phone I cannot find this app and also cannot find this paths and the file .apk:
```
/data/local/tmp/android-debug.apk
pkg: /data/local/tmp/android-debug.apk
```
What I'm doing wrong?
|
2016/11/24
|
[
"https://Stackoverflow.com/questions/40790385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318489/"
] |
To run on device -
```
ionic run android
```
This will install application on mobile
|
1. Testing as a native app
$ ionic run android
[More about testing as a native app](https://ionicframework.com/docs/guide/testing.html)
2. To generate a release build for Android
$ cordova build --release android
[Android Publishing](https://ionicframework.com/docs/guide/publishing.html)
|
22,684 |
Card 0: **title**
```
the answer to each card is a single english word
the cards dont have to be solved in order but some cards refer back to previous answers
each card has a title which is a clue that is usually essential to the puzzle
sometimes the title has to be interpreted cleverly
good luck
```
---
Card 1: **-55**
```
WWWWWWW
WWWWWWW
WWWWW
WWWWWW
WWWWWWW
WWWWWW
WWWWWW
WWWWWWW
WWWWWWW
WWWWW
```
---
Card 2: **1+2=**
```
npwan
```
---
Card 3: **why not**
```
periphery
similarity
meander
earnest
serendipity
relief
array
gregarious
sanitary
replay
elusive
perjury
```
---
Card 4: **cardinal NEWS**
```
24 2 0 23 0 3 3 23 2 0 34
4 34 4 4 0 3 2 0 2 24 0
2 2 2 0 123 2 12 12 0 3 13
```
---
Card 5: **sewoh?**
```
_/\_
\ /
_/\_/ \_/\_
\ /
/_ _\
\ /
_/\_ _/ \_ _/\_
\ / \ / \ /
_/\_/ \_/\_/ \_/\_/ \_/\_
```
---
Card 6: **it's python**
```
''.join(card[i].ans[-i] for i in (1,2,3,4,5))
```
---
Card 7: **five by five**
```
step 1) determin. the previous answers 2 through 6 in order
(step 1 should require computer assistance)
step 2) verify that the plural is a name
step 3) shake well
```
---
***Hint***
>
> graph with 33 vertices
>
>
>
***Hint 2***
>
> 2-6 have been determined but that's not step 1. what is "determin." and why should it require computer assistance?
>
>
>
|
2015/09/29
|
[
"https://puzzling.stackexchange.com/questions/22684",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/11100/"
] |
Partial answer:
Card 1:
>
> Count the W's in each line, interpret as two-digit numbers, and subtract 55 to get `22 01 21 12 20`. With 1-26 representing A-Z, this spells `VAULT`.
>
>
>
Card 3:
>
> Take the first letters of each word without a y to get `MERGE`.
>
>
>
Card 5:
>
> The title is an anagram of "whose?". Part of the Koch snowflake is shown, so the answer to "whose?" is "Koch's". This anagrams to `SHOCK` (or `HOCKS`).
>
>
>
|
Card 6
>
> Turns/torus/tyres etc, based on f"'s answers and guessing the most likely results for t?r?s. Much less conclusive when I've read the clue properly. It looks like they may all be 5 letter words
>
>
>
Card 7
>
> **wiles** Guessing that determin. means take the determinant, and that a=1,b=2..., the determinant of the matrix is 125239. There's various groupings that could work, but Lewi (12 5 23 9) is such that adding an "s" gives a name (lewis). Mixing that up gives you wiles.
>
>
>
|
22,684 |
Card 0: **title**
```
the answer to each card is a single english word
the cards dont have to be solved in order but some cards refer back to previous answers
each card has a title which is a clue that is usually essential to the puzzle
sometimes the title has to be interpreted cleverly
good luck
```
---
Card 1: **-55**
```
WWWWWWW
WWWWWWW
WWWWW
WWWWWW
WWWWWWW
WWWWWW
WWWWWW
WWWWWWW
WWWWWWW
WWWWW
```
---
Card 2: **1+2=**
```
npwan
```
---
Card 3: **why not**
```
periphery
similarity
meander
earnest
serendipity
relief
array
gregarious
sanitary
replay
elusive
perjury
```
---
Card 4: **cardinal NEWS**
```
24 2 0 23 0 3 3 23 2 0 34
4 34 4 4 0 3 2 0 2 24 0
2 2 2 0 123 2 12 12 0 3 13
```
---
Card 5: **sewoh?**
```
_/\_
\ /
_/\_/ \_/\_
\ /
/_ _\
\ /
_/\_ _/ \_ _/\_
\ / \ / \ /
_/\_/ \_/\_/ \_/\_/ \_/\_
```
---
Card 6: **it's python**
```
''.join(card[i].ans[-i] for i in (1,2,3,4,5))
```
---
Card 7: **five by five**
```
step 1) determin. the previous answers 2 through 6 in order
(step 1 should require computer assistance)
step 2) verify that the plural is a name
step 3) shake well
```
---
***Hint***
>
> graph with 33 vertices
>
>
>
***Hint 2***
>
> 2-6 have been determined but that's not step 1. what is "determin." and why should it require computer assistance?
>
>
>
|
2015/09/29
|
[
"https://puzzling.stackexchange.com/questions/22684",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/11100/"
] |
Partial answer:
Card 1:
>
> Count the W's in each line, interpret as two-digit numbers, and subtract 55 to get `22 01 21 12 20`. With 1-26 representing A-Z, this spells `VAULT`.
>
>
>
Card 3:
>
> Take the first letters of each word without a y to get `MERGE`.
>
>
>
Card 5:
>
> The title is an anagram of "whose?". Part of the Koch snowflake is shown, so the answer to "whose?" is "Koch's". This anagrams to `SHOCK` (or `HOCKS`).
>
>
>
|
Partial answer, building on f\*'s answer to the first card.
Card 2:
>
> The card reads **1 + 2 = npwan**. 1 refers to the word on the first card, `VAULT`. The plus means to add the letters' indices (starting with `A = 0`) individually without carry, i.e. modulo 26. The resulting digits are interpreted as letters again, which yields `ROBOT`.
>
>
>
Card 4:
>
> I haven't got an answer, but I suspect that cardinal news refers to the cardinal directios so that 1 is north, 2 is east, 3 is west and 4 is south. The numbers are combinations of these directions or 0. All numbers point inwards; there are no Ns on the top (north) row and no Ss on the bottom row. But what to make of that? No idea.
>
>
>
Card 6:
>
> Using Dr Xorile's pattern matching, but taking the last letter from the first card, the second but last from the second, and so on, the pattern is `TOR?S`, which could be `TORUS`. (That would also fit in with the clue that the plural, Tori, is a name.)
>
>
>
Edit: A bit of progress!
Card 4:
>
> My assumption that `NEWS` are the cardinal directions was right, I guess. If we take the 33 numbers as points on a grid and then draw connections to neighbouring nodes in the respective directions, we get:
>
>
>
> [](https://i.stack.imgur.com/Lv9l2.png)
>
>
>
This requires some editing.
>
> The outer border is just decoration. If we remove it, the grid looks like:
>
>
>
> [](https://i.stack.imgur.com/9kAKP.png)
>
>
>
This step seems to require some imagination, but ..
>
> The forms of the **u** and the **t** leap out, but the other letters aren't as unique. The first could be **b**, **G**, **h**, **n**, **o** or **S**. The third coulod be **r** or **c** and the fourth could be an **o** or an **n**, depending on whether the borders are just borders or part of the letters. But checking for `/^[bghnos]u[rc][no]t$/i` in a (rather small) dictionary yields just `BURNT`.
>
>
>
This solution also fits nicely with ...
>
> ... my earlier assumption that the word on the sixth card is `TORUS`.
>
>
>
If the above and f'''s solutions are true, the 5×5 grid is:
>
> `ROBOT`
>
> `MERGE`
>
> `BURNT`
>
> `SHOCK`
>
> `TORUS`
>
>
>
And now, "shake well". This looks as if we need an anagram of sorts, but I haven't got a solution for that.
|
22,684 |
Card 0: **title**
```
the answer to each card is a single english word
the cards dont have to be solved in order but some cards refer back to previous answers
each card has a title which is a clue that is usually essential to the puzzle
sometimes the title has to be interpreted cleverly
good luck
```
---
Card 1: **-55**
```
WWWWWWW
WWWWWWW
WWWWW
WWWWWW
WWWWWWW
WWWWWW
WWWWWW
WWWWWWW
WWWWWWW
WWWWW
```
---
Card 2: **1+2=**
```
npwan
```
---
Card 3: **why not**
```
periphery
similarity
meander
earnest
serendipity
relief
array
gregarious
sanitary
replay
elusive
perjury
```
---
Card 4: **cardinal NEWS**
```
24 2 0 23 0 3 3 23 2 0 34
4 34 4 4 0 3 2 0 2 24 0
2 2 2 0 123 2 12 12 0 3 13
```
---
Card 5: **sewoh?**
```
_/\_
\ /
_/\_/ \_/\_
\ /
/_ _\
\ /
_/\_ _/ \_ _/\_
\ / \ / \ /
_/\_/ \_/\_/ \_/\_/ \_/\_
```
---
Card 6: **it's python**
```
''.join(card[i].ans[-i] for i in (1,2,3,4,5))
```
---
Card 7: **five by five**
```
step 1) determin. the previous answers 2 through 6 in order
(step 1 should require computer assistance)
step 2) verify that the plural is a name
step 3) shake well
```
---
***Hint***
>
> graph with 33 vertices
>
>
>
***Hint 2***
>
> 2-6 have been determined but that's not step 1. what is "determin." and why should it require computer assistance?
>
>
>
|
2015/09/29
|
[
"https://puzzling.stackexchange.com/questions/22684",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/11100/"
] |
Partial answer, building on f\*'s answer to the first card.
Card 2:
>
> The card reads **1 + 2 = npwan**. 1 refers to the word on the first card, `VAULT`. The plus means to add the letters' indices (starting with `A = 0`) individually without carry, i.e. modulo 26. The resulting digits are interpreted as letters again, which yields `ROBOT`.
>
>
>
Card 4:
>
> I haven't got an answer, but I suspect that cardinal news refers to the cardinal directios so that 1 is north, 2 is east, 3 is west and 4 is south. The numbers are combinations of these directions or 0. All numbers point inwards; there are no Ns on the top (north) row and no Ss on the bottom row. But what to make of that? No idea.
>
>
>
Card 6:
>
> Using Dr Xorile's pattern matching, but taking the last letter from the first card, the second but last from the second, and so on, the pattern is `TOR?S`, which could be `TORUS`. (That would also fit in with the clue that the plural, Tori, is a name.)
>
>
>
Edit: A bit of progress!
Card 4:
>
> My assumption that `NEWS` are the cardinal directions was right, I guess. If we take the 33 numbers as points on a grid and then draw connections to neighbouring nodes in the respective directions, we get:
>
>
>
> [](https://i.stack.imgur.com/Lv9l2.png)
>
>
>
This requires some editing.
>
> The outer border is just decoration. If we remove it, the grid looks like:
>
>
>
> [](https://i.stack.imgur.com/9kAKP.png)
>
>
>
This step seems to require some imagination, but ..
>
> The forms of the **u** and the **t** leap out, but the other letters aren't as unique. The first could be **b**, **G**, **h**, **n**, **o** or **S**. The third coulod be **r** or **c** and the fourth could be an **o** or an **n**, depending on whether the borders are just borders or part of the letters. But checking for `/^[bghnos]u[rc][no]t$/i` in a (rather small) dictionary yields just `BURNT`.
>
>
>
This solution also fits nicely with ...
>
> ... my earlier assumption that the word on the sixth card is `TORUS`.
>
>
>
If the above and f'''s solutions are true, the 5×5 grid is:
>
> `ROBOT`
>
> `MERGE`
>
> `BURNT`
>
> `SHOCK`
>
> `TORUS`
>
>
>
And now, "shake well". This looks as if we need an anagram of sorts, but I haven't got a solution for that.
|
Card 6
>
> Turns/torus/tyres etc, based on f"'s answers and guessing the most likely results for t?r?s. Much less conclusive when I've read the clue properly. It looks like they may all be 5 letter words
>
>
>
Card 7
>
> **wiles** Guessing that determin. means take the determinant, and that a=1,b=2..., the determinant of the matrix is 125239. There's various groupings that could work, but Lewi (12 5 23 9) is such that adding an "s" gives a name (lewis). Mixing that up gives you wiles.
>
>
>
|
67,954,931 |
I am making a simulation with C (for perfomance) that (currently) uses recursion and mallocs (generated in every step of the recursion). The problem is that I am not being able to free the mallocs anywhere in the code, without having the wrong final output.
The code consist of two functions and the main function:
`evolution(double initial_energy)`
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
double * evolution(double initial_energy){
double * energy_vec = malloc(sizeof(double)*50);
for(int i = 0; i <= 50; i++){
energy_vec[i] = 0;
}
int i = 0;
while(initial_energy > 1){
initial_energy /= 2;
energy_vec[i] = initial_energy;
i++;
}
return energy_vec;
}
```
here is where mallocs are generated. Then I define `recursion(double initial_energy)` that return the total number of events, being events the times that the `initial_energy` is divided by 2 until its value is less than 1.
```
double recursion(double initial_energy){
int event_counter = 0;
int j = 0;
double * Energy;
Energy = evolution(initial_energy);
while(Energy[j] > 0.0){
event_counter++;
event_counter += recursion(Energy[j]);
j++;
}
return event_counter;
}
```
and finally the `main` function, that here doesn't make much a difference to have it, but for the sake of completeness here it is
```
int main(){
int trials = 20000;
int events;
double initial_energy = 70;
for(int i = 0; i <= trials; i++){
events = recursion(initial_energy);
printf("%i) events = %i\n",i, events);
usleep(200);
}
return events;
}
```
So, is it possible for this code, to free the mallocs anywhere and have the correct result at the end? (The correct result should be 2\*\*N - 1, where N is the number of times a value greater than 1 can result from dividing `initial_energy` by 2 successivelly. For example, for this code, the correct answer would be 127 at the end of the program). I have tried defining the malloc inside the for loop in the main function, and freeing it right after I call recursion, but it doesn't hold the correct result.
I only use C ocassionally (when python performance is too slow for some sort of calculations), so I do not have the technical understanding of the language that I would like. So I am open to whatever changes in the code are necessary.
Thanks in advance!
|
2021/06/13
|
[
"https://Stackoverflow.com/questions/67954931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11056678/"
] |
You're supposed to free memory right after the last time it will be used. In your program, after the `while` loop in `recursion`, `Energy` isn't used again, so you should free it right after that (i.e., right before `return event_counter;`).
|
Joseph Sible-Reinstate Monica is correct about the question you asked. But your code can be improved in a number of areas. If you want to see the final version, you should scroll all the way to the bottom of my answer for `run_simulation`, which is a dramatically better version of your `recursion` function.
Let's start with your initial function, `evolution`. If you want to allocate memory and initialize all bytes to 0, you should use the `calloc` function rather than `malloc`. Instead of
```c
double * energy_vec = malloc(sizeof(double)*50);
for(int i = 0; i < 50; i++){ // your original i <= 50 was wrong
energy_vec[i] = 0;
}
```
you should instead do
```c
double * energy_vec = calloc(50 * sizeof(double));
```
This is usually more efficient than `malloc` + manually setting everything to 0, and it's more readable.
Second, there is no reason for `recursion` to return a `double` except. The most logical thing for `recursion` to return would be an `unsigned int`, since it will always return a nonnegative integer. This is practically a drop-in replacement; just change the return type and the type of `event_counter` to `unsigned int`, and your code will work just fine without pointlessly returning a `double`. I will make this switch - for now.
Third, a `double` can be larger than `2^50`. In the event that this happens, your `energy` array isn't going to be big enough. This is a serious problem, but it could be averted by dynamically resizing the array. A higher-level high-performance language like Rust or C++ would provide you with resizable arrays as part of the standard library, but in C, you'd have to do it by hand.
Fourth, you in fact do not need dynamic memory allocation at all because your code can be done with mathematics. You can actually get away with not having loops at all! However, to avoid using "floating point black magic", I will use loops in my answer. We first define
```c
unsigned int count_divisions(double d) {
unsigned int count;
for (count = 0; d > 1.0; d /= 2, count++);
return count;
}
```
Note that `count_divisions(d)` is exactly equal to the conceptual length of `evolution(d)`.
Now, we should note that the only properties we actually care about for our Doubles is there `count_divisions` value. It's the only thing we use. Thus, everywhere I see a `double`, I will replace it with its `count_divisions` value. The resulting code looks like this:
```c
unsigned int * evolution(unsigned int divisions){
unsigned int * Energy = malloc(divisions * sizeof(*Energy));
for(unsigned int i = 0; i < divisions; i++) {
Energy[i] = divisions - i - 1;
}
return Energy;
}
unsigned int recursion(unsigned int divisions) {
unsigned int* energy_vec = evolution(divisions);
unsigned int count = divisions;
for (unsigned int j = 0; j < divisions; j++) {
count += recursion(energy_vec[j]);
}
free(energy_vec);
return count;
}
```
Now, we're beginning to approach the answer. But notice that we actually already know what `energy_vec[j]` is for each `j`; it will be `divisions - j - 1`. So we can completely eliminate the `energy_vec` vector and get the following code:
```
unsigned int recursion(unsigned int divisions) {
unsigned int* energy_vec = evolution(divisions);
unsigned int count = divisions;
for (unsigned int j = 0; j < divisions; j++) {
count += recursion(divisions - j - 1);
}
return count;
}
```
which we can trivially rewrite as
```
unsigned int recursion(unsigned int divisions) {
unsigned int* energy_vec = evolution(divisions);
unsigned int count = 0;
for (unsigned int j = 0; j < divisions; j++) {
count += recursion(j);
}
return count + divisions;
}
```
Now, we must use a bit of cleverness to deduce a better recurrence relation for `recursion`. It turns out that it is possible to show that `recursion(0) = 0` and that `recursion(k + 1) = 2 * recursion(k) + 1`. This is because
```
recursion(k + 1)
= recursion(0) + recursion(1) + ... + recursion(k) + k + 1
= (recursion(0) + recursion(1) + ... + recursion(k - 1) + k) + recursion(k) + 1
= recursion(k) + recursion(k) + 1
= 2 * recursion(k) + 1
```
Therefore, we can easily prove by induction that `recursion(k) = 2^k - 1`.
So in fact, you're taking in the value `initial_energy` and returning `2^(ceil(log(initial_energy))) - 1`.
A final solution could thus be
```c
double run_simulation(double initial_energy) {
double power_of_two = 1;
while (initial_energy > 1) {
power_of_two *= 2;
initial_energy /= 2;
}
return power_of_two - 1;
}
```
which replaces your original `recursion` function at much less cost.
|
60,051,250 |
I've specified a custom type which takes two floats and makes them a pair (a complex number):
```
type complex = (float * float);;
let makeComplex x y = complex(x,y);;
```
The `makeComplex`function is of type `float -> float -> complex`, which is entirely correct. However, I want to create a function that takes a complex type and makes it a normal pair as well.
This is the function I've tried:
```
let complexToPair ((x,y):complex) = (x,y);;
```
But the resulting type is `float * float -> float * float`, when it should really be `complex -> float * float`. Am I using the wrong syntax for the `((x,y):complex)`part?
|
2020/02/04
|
[
"https://Stackoverflow.com/questions/60051250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11055427/"
] |
Type abbreviations do not hide or create a type distinct from their definitions. `complex` and `float * float` are still fully exchangeable, You've just given it another name.
The idiomatic way to make a distinct type in F# is to use a single-case discriminated union:
```
type complex = Complex of float * float
```
You can then write your functions using this constructor to create a value and pattern matching to deconstruct it:
```
let makeComplex x y = Complex (x,y)
let complexToPair (Complex (x, y)) = (x, y)
```
You can also hide the implementation completely from outside the module using `private`:
```
type complex = private Complex of float * float
```
Consumers would then have to use the functions you expose to create and consume values of the `complex` type.
|
If you still really want to use type abbreviation, then use type annotation, like this:
```
type complex = float * float
let complexToPair: complex -> float * float = id
```
|
60,051,250 |
I've specified a custom type which takes two floats and makes them a pair (a complex number):
```
type complex = (float * float);;
let makeComplex x y = complex(x,y);;
```
The `makeComplex`function is of type `float -> float -> complex`, which is entirely correct. However, I want to create a function that takes a complex type and makes it a normal pair as well.
This is the function I've tried:
```
let complexToPair ((x,y):complex) = (x,y);;
```
But the resulting type is `float * float -> float * float`, when it should really be `complex -> float * float`. Am I using the wrong syntax for the `((x,y):complex)`part?
|
2020/02/04
|
[
"https://Stackoverflow.com/questions/60051250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11055427/"
] |
Type abbreviations do not hide or create a type distinct from their definitions. `complex` and `float * float` are still fully exchangeable, You've just given it another name.
The idiomatic way to make a distinct type in F# is to use a single-case discriminated union:
```
type complex = Complex of float * float
```
You can then write your functions using this constructor to create a value and pattern matching to deconstruct it:
```
let makeComplex x y = Complex (x,y)
let complexToPair (Complex (x, y)) = (x, y)
```
You can also hide the implementation completely from outside the module using `private`:
```
type complex = private Complex of float * float
```
Consumers would then have to use the functions you expose to create and consume values of the `complex` type.
|
You can create a class:
```ml
type Complex(x:float, y:float) =
member t.Real = x
member t.Imaginary = y
```
Or a record:
```ml
type Complex = { Real:float; Imaginary:float }
```
These will be distinct types and also allow you to create and organize useful methods (such as arithmetic operators).
|
60,051,250 |
I've specified a custom type which takes two floats and makes them a pair (a complex number):
```
type complex = (float * float);;
let makeComplex x y = complex(x,y);;
```
The `makeComplex`function is of type `float -> float -> complex`, which is entirely correct. However, I want to create a function that takes a complex type and makes it a normal pair as well.
This is the function I've tried:
```
let complexToPair ((x,y):complex) = (x,y);;
```
But the resulting type is `float * float -> float * float`, when it should really be `complex -> float * float`. Am I using the wrong syntax for the `((x,y):complex)`part?
|
2020/02/04
|
[
"https://Stackoverflow.com/questions/60051250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11055427/"
] |
If you still really want to use type abbreviation, then use type annotation, like this:
```
type complex = float * float
let complexToPair: complex -> float * float = id
```
|
You can create a class:
```ml
type Complex(x:float, y:float) =
member t.Real = x
member t.Imaginary = y
```
Or a record:
```ml
type Complex = { Real:float; Imaginary:float }
```
These will be distinct types and also allow you to create and organize useful methods (such as arithmetic operators).
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
change your requirements.txt to this (without specifying the versions, so that pip will install latest versions)
```
asgiref
beautifulsoup4
certifi
chardet
Click
Django
idna
pytz
requests
six
soupsieve
sqlparse
urllib3
```
|
You can also look at this [question](https://stackoverflow.com/questions/24764549/upgrade-python-packages-from-requirements-txt-using-pip-command). From this question I took one of the answers which I think can solve your problem. It will not remove the package version but whenever you will install the requiremwnts.txt it will upgrade your packages to the latest versions.
`pip install pip-upgrader`
Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).
cd into your project directory, then run:
`pip-upgrade`
If the requirements are placed in a non-standard location, send them as arguments:
`pip-upgrade path/to/requirements.txt`
If you already know what package you want to upgrade, simply send them as arguments:
`pip-upgrade -p django -p celery -p dateutil`
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
you can parse the `requirements.txt` file with python itself and get your package names and split it manually like below:
```
with open("requirements.txt") as myFile:
pkgs = myFile.read()
pkgs = pkgs.splitlines()
for pkg in pkgs:
print(pkg.split('==')[0])
```
this will give you something like below:
[](https://i.stack.imgur.com/hQHf4.jpg)
|
You can also look at this [question](https://stackoverflow.com/questions/24764549/upgrade-python-packages-from-requirements-txt-using-pip-command). From this question I took one of the answers which I think can solve your problem. It will not remove the package version but whenever you will install the requiremwnts.txt it will upgrade your packages to the latest versions.
`pip install pip-upgrader`
Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).
cd into your project directory, then run:
`pip-upgrade`
If the requirements are placed in a non-standard location, send them as arguments:
`pip-upgrade path/to/requirements.txt`
If you already know what package you want to upgrade, simply send them as arguments:
`pip-upgrade -p django -p celery -p dateutil`
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
You need to change the `requirement.txt` file to remove all the version dependencies. you can parse the file for that. Or use regex.
`==\w+.+.+`
This will select all the element after symbol == including the symbol.
Replace with null empty string.
Open the requirements.txt in some editor that support regex (for example vs code).
Then use find and replace. (ctrl + f in vs code)
choose regex option. (click on `.*` in find and replace context menu in vs code)
in find put `==\w+.+.+`
in replace put nothing. (keep it empty)
then replace all.
Then `pip install requirements.txt` and you are good to go.
|
Use `sed` to remove version info from your `requirements.txt` file.
e.g.
```
sed 's/==.*$//' requirements.txt
```
will give output
```
asgiref
beautifulsoup4
certifi
chardet
Click
Django
idna
pytz
requests
six
soupsieve
sqlparse
urllib3
```
and this can be piped into `pip` to do the install
```
sed 's/==.*$//' requirements.txt | xargs pip install
```
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
Consider if you had written your app in Django 2.x a few months ago and just had `Django` as dependency listed in your `requirements.txt`. Now that Django 3 is out, installing it now would cause a major version jump from Django 2 to 3 and *potentially* break half your app. And that’s just *one* of your dependencies.
No, versions are fixed on purpose. Upgrading versions should be a conscious effort involving testing to confirm compatibility. You want to be running software in a **known good state**, not in a random unpredictable state. Version incompatibilities are not to be underestimated. pip can give you a [list of all outdated dependencies easily](https://pip.pypa.io/en/stable/user_guide/#listing-packages), and upgrading them is just another command.
Anecdote time: [openpyxl](http://openpyxl.readthedocs.io) contained a [bug in version 3.0.1](https://bitbucket.org/openpyxl/openpyxl/issues/1367/getting-rows-with-values-only-in-read-only) recently which broke an important feature in our app. Do you know why we *weren't* affected by it? Because our `requirements.txt` uses fixed versions, and I found the issue by running our unit tests while upgrading dependencies manually, and choosing to *not* upgrade openpyxl because of it. Without fixed versions, our app would have been broken for a few weeks while openpyxl 3.0.1 was the most current version.
|
You can also look at this [question](https://stackoverflow.com/questions/24764549/upgrade-python-packages-from-requirements-txt-using-pip-command). From this question I took one of the answers which I think can solve your problem. It will not remove the package version but whenever you will install the requiremwnts.txt it will upgrade your packages to the latest versions.
`pip install pip-upgrader`
Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).
cd into your project directory, then run:
`pip-upgrade`
If the requirements are placed in a non-standard location, send them as arguments:
`pip-upgrade path/to/requirements.txt`
If you already know what package you want to upgrade, simply send them as arguments:
`pip-upgrade -p django -p celery -p dateutil`
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
you can parse the `requirements.txt` file with python itself and get your package names and split it manually like below:
```
with open("requirements.txt") as myFile:
pkgs = myFile.read()
pkgs = pkgs.splitlines()
for pkg in pkgs:
print(pkg.split('==')[0])
```
this will give you something like below:
[](https://i.stack.imgur.com/hQHf4.jpg)
|
Consider if you had written your app in Django 2.x a few months ago and just had `Django` as dependency listed in your `requirements.txt`. Now that Django 3 is out, installing it now would cause a major version jump from Django 2 to 3 and *potentially* break half your app. And that’s just *one* of your dependencies.
No, versions are fixed on purpose. Upgrading versions should be a conscious effort involving testing to confirm compatibility. You want to be running software in a **known good state**, not in a random unpredictable state. Version incompatibilities are not to be underestimated. pip can give you a [list of all outdated dependencies easily](https://pip.pypa.io/en/stable/user_guide/#listing-packages), and upgrading them is just another command.
Anecdote time: [openpyxl](http://openpyxl.readthedocs.io) contained a [bug in version 3.0.1](https://bitbucket.org/openpyxl/openpyxl/issues/1367/getting-rows-with-values-only-in-read-only) recently which broke an important feature in our app. Do you know why we *weren't* affected by it? Because our `requirements.txt` uses fixed versions, and I found the issue by running our unit tests while upgrading dependencies manually, and choosing to *not* upgrade openpyxl because of it. Without fixed versions, our app would have been broken for a few weeks while openpyxl 3.0.1 was the most current version.
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
Consider if you had written your app in Django 2.x a few months ago and just had `Django` as dependency listed in your `requirements.txt`. Now that Django 3 is out, installing it now would cause a major version jump from Django 2 to 3 and *potentially* break half your app. And that’s just *one* of your dependencies.
No, versions are fixed on purpose. Upgrading versions should be a conscious effort involving testing to confirm compatibility. You want to be running software in a **known good state**, not in a random unpredictable state. Version incompatibilities are not to be underestimated. pip can give you a [list of all outdated dependencies easily](https://pip.pypa.io/en/stable/user_guide/#listing-packages), and upgrading them is just another command.
Anecdote time: [openpyxl](http://openpyxl.readthedocs.io) contained a [bug in version 3.0.1](https://bitbucket.org/openpyxl/openpyxl/issues/1367/getting-rows-with-values-only-in-read-only) recently which broke an important feature in our app. Do you know why we *weren't* affected by it? Because our `requirements.txt` uses fixed versions, and I found the issue by running our unit tests while upgrading dependencies manually, and choosing to *not* upgrade openpyxl because of it. Without fixed versions, our app would have been broken for a few weeks while openpyxl 3.0.1 was the most current version.
|
You need to change the `requirement.txt` file to remove all the version dependencies. you can parse the file for that. Or use regex.
`==\w+.+.+`
This will select all the element after symbol == including the symbol.
Replace with null empty string.
Open the requirements.txt in some editor that support regex (for example vs code).
Then use find and replace. (ctrl + f in vs code)
choose regex option. (click on `.*` in find and replace context menu in vs code)
in find put `==\w+.+.+`
in replace put nothing. (keep it empty)
then replace all.
Then `pip install requirements.txt` and you are good to go.
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
Consider if you had written your app in Django 2.x a few months ago and just had `Django` as dependency listed in your `requirements.txt`. Now that Django 3 is out, installing it now would cause a major version jump from Django 2 to 3 and *potentially* break half your app. And that’s just *one* of your dependencies.
No, versions are fixed on purpose. Upgrading versions should be a conscious effort involving testing to confirm compatibility. You want to be running software in a **known good state**, not in a random unpredictable state. Version incompatibilities are not to be underestimated. pip can give you a [list of all outdated dependencies easily](https://pip.pypa.io/en/stable/user_guide/#listing-packages), and upgrading them is just another command.
Anecdote time: [openpyxl](http://openpyxl.readthedocs.io) contained a [bug in version 3.0.1](https://bitbucket.org/openpyxl/openpyxl/issues/1367/getting-rows-with-values-only-in-read-only) recently which broke an important feature in our app. Do you know why we *weren't* affected by it? Because our `requirements.txt` uses fixed versions, and I found the issue by running our unit tests while upgrading dependencies manually, and choosing to *not* upgrade openpyxl because of it. Without fixed versions, our app would have been broken for a few weeks while openpyxl 3.0.1 was the most current version.
|
Use `sed` to remove version info from your `requirements.txt` file.
e.g.
```
sed 's/==.*$//' requirements.txt
```
will give output
```
asgiref
beautifulsoup4
certifi
chardet
Click
Django
idna
pytz
requests
six
soupsieve
sqlparse
urllib3
```
and this can be piped into `pip` to do the install
```
sed 's/==.*$//' requirements.txt | xargs pip install
```
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
You can also look at this [question](https://stackoverflow.com/questions/24764549/upgrade-python-packages-from-requirements-txt-using-pip-command). From this question I took one of the answers which I think can solve your problem. It will not remove the package version but whenever you will install the requiremwnts.txt it will upgrade your packages to the latest versions.
`pip install pip-upgrader`
Activate your virtualenv (important, because it will also install the new versions of upgraded packages in current virtualenv).
cd into your project directory, then run:
`pip-upgrade`
If the requirements are placed in a non-standard location, send them as arguments:
`pip-upgrade path/to/requirements.txt`
If you already know what package you want to upgrade, simply send them as arguments:
`pip-upgrade -p django -p celery -p dateutil`
|
Use `sed` to remove version info from your `requirements.txt` file.
e.g.
```
sed 's/==.*$//' requirements.txt
```
will give output
```
asgiref
beautifulsoup4
certifi
chardet
Click
Django
idna
pytz
requests
six
soupsieve
sqlparse
urllib3
```
and this can be piped into `pip` to do the install
```
sed 's/==.*$//' requirements.txt | xargs pip install
```
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
you can parse the `requirements.txt` file with python itself and get your package names and split it manually like below:
```
with open("requirements.txt") as myFile:
pkgs = myFile.read()
pkgs = pkgs.splitlines()
for pkg in pkgs:
print(pkg.split('==')[0])
```
this will give you something like below:
[](https://i.stack.imgur.com/hQHf4.jpg)
|
Use `sed` to remove version info from your `requirements.txt` file.
e.g.
```
sed 's/==.*$//' requirements.txt
```
will give output
```
asgiref
beautifulsoup4
certifi
chardet
Click
Django
idna
pytz
requests
six
soupsieve
sqlparse
urllib3
```
and this can be piped into `pip` to do the install
```
sed 's/==.*$//' requirements.txt | xargs pip install
```
|
59,854,453 |
Assuming that
```
outputTemp =
2×1 cell array
{122×1 string}
{220×1 string}
```
`finalOutput` is a string array (`342x1 string`).
is there any way to do the following
```
outputTemp = arrayfun(@(x)someFunc(x), someInput, 'UniformOutput', false)';
finalOutput= [outputTemp{1}; outputTemp{2}];
```
in one line?
for the minimal example, `someFunc` can be a function that provides the names of the files in folders provided in `someInput`.
|
2020/01/22
|
[
"https://Stackoverflow.com/questions/59854453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8443371/"
] |
you can parse the `requirements.txt` file with python itself and get your package names and split it manually like below:
```
with open("requirements.txt") as myFile:
pkgs = myFile.read()
pkgs = pkgs.splitlines()
for pkg in pkgs:
print(pkg.split('==')[0])
```
this will give you something like below:
[](https://i.stack.imgur.com/hQHf4.jpg)
|
You need to change the `requirement.txt` file to remove all the version dependencies. you can parse the file for that. Or use regex.
`==\w+.+.+`
This will select all the element after symbol == including the symbol.
Replace with null empty string.
Open the requirements.txt in some editor that support regex (for example vs code).
Then use find and replace. (ctrl + f in vs code)
choose regex option. (click on `.*` in find and replace context menu in vs code)
in find put `==\w+.+.+`
in replace put nothing. (keep it empty)
then replace all.
Then `pip install requirements.txt` and you are good to go.
|
3,757,350 |
I know what causes a PHP page to consistently download instead of running normally, but I have no idea why it would only sometimes download and sometimes run normally. It appears to be purely random: I just keep hitting Refresh until it stops trying to download and runs normally.
This page has a lot of jQuery/AJAX scripting running on it. Several AJAX requests are made as soon as the page loads. These are all called after the "DOM load" event, rather than when the window is ready. Does that make a difference? Could all these requests happening on the page load cause it to randomly fail to run normally?
|
2010/09/21
|
[
"https://Stackoverflow.com/questions/3757350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453464/"
] |
At the top of your php page
```
<?php
header('Content-Type: text/html');
```
Should do the trick. The problem is that the wrong MIME Type is being sent over, confusing your browser to the point that it doesn't know what do do with it so it just downloads it.
|
I've seen this happen if your script crashes the PHP interpreter. Apart from finding the cause of the crash, I'm not sure what you can do.
|
3,757,350 |
I know what causes a PHP page to consistently download instead of running normally, but I have no idea why it would only sometimes download and sometimes run normally. It appears to be purely random: I just keep hitting Refresh until it stops trying to download and runs normally.
This page has a lot of jQuery/AJAX scripting running on it. Several AJAX requests are made as soon as the page loads. These are all called after the "DOM load" event, rather than when the window is ready. Does that make a difference? Could all these requests happening on the page load cause it to randomly fail to run normally?
|
2010/09/21
|
[
"https://Stackoverflow.com/questions/3757350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453464/"
] |
At the top of your php page
```
<?php
header('Content-Type: text/html');
```
Should do the trick. The problem is that the wrong MIME Type is being sent over, confusing your browser to the point that it doesn't know what do do with it so it just downloads it.
|
Andrew Dunn said it right with
`<?php
header('Content-Type: text/html');`
But also add this to your .htaccess file
```
AddHandler application/x-httpd-php .php ..html
AddHandler x-httpd-php .php ..html
```
And then clear your browser cache before refreshing or trying to access the page again.
This problem has been bugging me for quite a long time now...
|
68,641,304 |
I have a Spring Boot application that is capturing the HTTP response content of REST requests made to the application. I am doing this for the purposes of logging and future analysis of the requests entering the system.
Currently, I have this implemented as a filter bean (per [`OncePerRequestFilter`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html)), using a [`ContentCachingResponseWrapper`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingResponseWrapper.html) to capture the content written to the output stream:
```java
@Component
public class ResponseBodyLoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
ContentCachingResponseWrapper cachingResponse =
new ContentCachingResponseWrapper(response);
try {
filterChain.doFilter(request, cachingResponse);
} finally {
byte[] responseBytes = cachingResponse.getContentInputStream().readAllBytes();
System.out.println("Response: \"" + new String(responseBytes) + "\"");
cachingResponse.copyBodyToResponse();
}
}
}
```
This works for the majority of requests to the application. One thing it does not capture, however, is the default Spring Boot error response. Rather than capturing the content of the response, it is instead returning the empty string.
**`build.gradle`**
```groovy
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
```
**Controller:**
```java
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/404")
public void throw404() {
throw new ResponseStatusException(BAD_REQUEST);
}
}
```
**HTTP response:**
```json
{
"timestamp": "2021-08-03T18:30:18.934+00:00",
"status": 400,
"error": "Bad Request",
"path": "/test/404"
}
```
**System output:**
```none
Response: ""
```
I've confirmed that if I switch from the Spring Boot default of embedded Tomcat to embedded Jetty (using `spring-boot-starter-jetty` and excluding `spring-boot-starter-tomcat`), this issue still occurs.
How can I capture the Spring Boot error response output within my application? Note that I do not *need* this to be a filter if another solution solves the problem.
|
2021/08/03
|
[
"https://Stackoverflow.com/questions/68641304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108305/"
] |
You can't do it *quite* that simply. A file is a sequence of bytes. You must first ensure that when you write all of those lines, that you write them to their *final* positions. The easiest way to do this is to "reserve" space for your line count when you first write the file. Much as you have done in your description, write the entire file, but keep "placeholder" room for the line count. For instance, if you have a maximum of 9999 lines in the file, then reserve four bytes for that count:
```
line_count=????
sam
john
gus
heisenberg
```
Once you finish writing all of the lines, then back up to the appropriate byte position in the file (bytes 11-14) with `seek(11)`, and `file.write()` the count, formatted to four characters.
I'm assuming that you already know how to write lines to a file, and how to format an integer. All you're missing is the basic logic and the `seek` method.
|
```
f.seek(0)
f.write("line_count = %s\n"%n)
f.close()
```
Where n is line count value
|
68,641,304 |
I have a Spring Boot application that is capturing the HTTP response content of REST requests made to the application. I am doing this for the purposes of logging and future analysis of the requests entering the system.
Currently, I have this implemented as a filter bean (per [`OncePerRequestFilter`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html)), using a [`ContentCachingResponseWrapper`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingResponseWrapper.html) to capture the content written to the output stream:
```java
@Component
public class ResponseBodyLoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
ContentCachingResponseWrapper cachingResponse =
new ContentCachingResponseWrapper(response);
try {
filterChain.doFilter(request, cachingResponse);
} finally {
byte[] responseBytes = cachingResponse.getContentInputStream().readAllBytes();
System.out.println("Response: \"" + new String(responseBytes) + "\"");
cachingResponse.copyBodyToResponse();
}
}
}
```
This works for the majority of requests to the application. One thing it does not capture, however, is the default Spring Boot error response. Rather than capturing the content of the response, it is instead returning the empty string.
**`build.gradle`**
```groovy
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
```
**Controller:**
```java
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/404")
public void throw404() {
throw new ResponseStatusException(BAD_REQUEST);
}
}
```
**HTTP response:**
```json
{
"timestamp": "2021-08-03T18:30:18.934+00:00",
"status": 400,
"error": "Bad Request",
"path": "/test/404"
}
```
**System output:**
```none
Response: ""
```
I've confirmed that if I switch from the Spring Boot default of embedded Tomcat to embedded Jetty (using `spring-boot-starter-jetty` and excluding `spring-boot-starter-tomcat`), this issue still occurs.
How can I capture the Spring Boot error response output within my application? Note that I do not *need* this to be a filter if another solution solves the problem.
|
2021/08/03
|
[
"https://Stackoverflow.com/questions/68641304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108305/"
] |
Here ya go!
```
text = open("textfile.txt").readlines()
counter = 0
for row in text:
counter += 1 # just snags the total amount of rows
newtext = open("textfile.txt","w")
newtext.write(f"line_count = {counter}\n\n") # This is your header xoxo
for row in text:
newtext.write(row) # put all of the original lines back
newtext.close()
```
Make sure you put in the paths to the text file but this short script will just tack on that line\_count = Number header that you wanted. Cheers!
|
```
f.seek(0)
f.write("line_count = %s\n"%n)
f.close()
```
Where n is line count value
|
68,641,304 |
I have a Spring Boot application that is capturing the HTTP response content of REST requests made to the application. I am doing this for the purposes of logging and future analysis of the requests entering the system.
Currently, I have this implemented as a filter bean (per [`OncePerRequestFilter`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html)), using a [`ContentCachingResponseWrapper`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/ContentCachingResponseWrapper.html) to capture the content written to the output stream:
```java
@Component
public class ResponseBodyLoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
ContentCachingResponseWrapper cachingResponse =
new ContentCachingResponseWrapper(response);
try {
filterChain.doFilter(request, cachingResponse);
} finally {
byte[] responseBytes = cachingResponse.getContentInputStream().readAllBytes();
System.out.println("Response: \"" + new String(responseBytes) + "\"");
cachingResponse.copyBodyToResponse();
}
}
}
```
This works for the majority of requests to the application. One thing it does not capture, however, is the default Spring Boot error response. Rather than capturing the content of the response, it is instead returning the empty string.
**`build.gradle`**
```groovy
plugins {
id 'org.springframework.boot' version '2.5.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
```
**Controller:**
```java
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/404")
public void throw404() {
throw new ResponseStatusException(BAD_REQUEST);
}
}
```
**HTTP response:**
```json
{
"timestamp": "2021-08-03T18:30:18.934+00:00",
"status": 400,
"error": "Bad Request",
"path": "/test/404"
}
```
**System output:**
```none
Response: ""
```
I've confirmed that if I switch from the Spring Boot default of embedded Tomcat to embedded Jetty (using `spring-boot-starter-jetty` and excluding `spring-boot-starter-tomcat`), this issue still occurs.
How can I capture the Spring Boot error response output within my application? Note that I do not *need* this to be a filter if another solution solves the problem.
|
2021/08/03
|
[
"https://Stackoverflow.com/questions/68641304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108305/"
] |
Here ya go!
```
text = open("textfile.txt").readlines()
counter = 0
for row in text:
counter += 1 # just snags the total amount of rows
newtext = open("textfile.txt","w")
newtext.write(f"line_count = {counter}\n\n") # This is your header xoxo
for row in text:
newtext.write(row) # put all of the original lines back
newtext.close()
```
Make sure you put in the paths to the text file but this short script will just tack on that line\_count = Number header that you wanted. Cheers!
|
You can't do it *quite* that simply. A file is a sequence of bytes. You must first ensure that when you write all of those lines, that you write them to their *final* positions. The easiest way to do this is to "reserve" space for your line count when you first write the file. Much as you have done in your description, write the entire file, but keep "placeholder" room for the line count. For instance, if you have a maximum of 9999 lines in the file, then reserve four bytes for that count:
```
line_count=????
sam
john
gus
heisenberg
```
Once you finish writing all of the lines, then back up to the appropriate byte position in the file (bytes 11-14) with `seek(11)`, and `file.write()` the count, formatted to four characters.
I'm assuming that you already know how to write lines to a file, and how to format an integer. All you're missing is the basic logic and the `seek` method.
|
2,812,144 |
let $p$ be a Pythagorean prime, and $n$ some integer. Does there necessarily exist a solution to the concurrency $n^2 \equiv (p-1) \mod p$? I've been studying this problem for the last 6 hours, and to no avail.
The first thing I did was make a table
$$1^2 + 2^2 = 5 \to n^2 \equiv 4 \mod 5 \Rightarrow n = 2,3$$
$$2^2 + 3^2 = 13 \to n^2 \equiv 12 \mod 13 \Rightarrow n = 5,8$$
$$2^2 + 5^2 = 29 \to n^2 \equiv 28 \mod 29 \Rightarrow n = 12,17$$
$$4^2 + 5^2 = 41 \to n^2 \equiv 40 \mod 41 \Rightarrow n = 9,32$$
$$5^2 + 6^2 = 61 \to n^2 \equiv 60 \mod 61 \Rightarrow n = 11,50$$
$$7^2 + 8^2 = 113 \to n^2 \equiv 112 \mod 113 \Rightarrow n = 15,98$$
$$9^2 + 10^2 = 181 \to n^2 \equiv 180 \mod 181 \Rightarrow n = 19,162$$
I also had noticed for non-Pythagorean primes, such as 3,7, and 23, there were no solutions, so that was note-worthy.
I was hoping to see a good pattern from the table, but none jumped out at me. From this point, I was trying to spot any property I could. I recognize that Pythagorean primes are of the form $4k +1$, so I tried substituting to see what I could demonstrate with algebra but I don't think it was anything significant. Is anyone aware if there will always exist a solution? If so, is there a general formula for $n$?
|
2018/06/08
|
[
"https://math.stackexchange.com/questions/2812144",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/556198/"
] |
Another way of formulating this is that $-1$ is a quadratic residue modulo $p$, which is well-known for primes $\equiv 1 \bmod 4$ - so yes it is true. There are various ways of proving this. For example you can use Wilson's theorem that $$(p-1)!\equiv -1 \bmod p$$
Now consider $q=\frac {p-1}2$
$$(p-1)!=1\cdot 2\cdot 3\dots \cdot q\cdot (q+1)\dots \cdot (p-1) \equiv1\cdot 2 \dots \cdot q\cdot (-q) \dots (-1)$$where the last half of the terms are found by deducting $p$ from the original elements. This is then $$\equiv q!\cdot (-1)^q \cdot q!=(q!)^2$$ because $q$ is even. And the $n$ you are looking for is $\equiv \pm q!$
---
To prove Wilson's theorem you can pair each element with its multiplicative inverse modulo $p$ leaving only $1$ and $-1$ unpaired.
|
Is a "pythagorean prime" a prime with $p\equiv1$ (mod $4$)? It's
a well-known theorem of number theory that the congruence $x^2\equiv-1\pmod p$ has a solution for an odd prime $p$ iff $p\equiv1\pmod 4$.
|
67,155,497 |
Below is the table from which I need to create conditionalize view.
[](https://i.stack.imgur.com/Nzmgj.png)
and I am getting one flag from different table. So based on the flag values i.e. if flag=1 then I need to display actual column values from table, and if flag=0 then show all column values as null values.
I know we can handle it using CASE statement but here, in may case column count is very big so need to handle it in better way.
|
2021/04/19
|
[
"https://Stackoverflow.com/questions/67155497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1704622/"
] |
There's always the comma operator, although it doesn't make the code any more readable
```
return void_function(), 0;
```
|
Well, you can always (ab)use preprocessor macros:
```
#define CALL_AND_RETURN(x) {x; return 0;}
[...]
CALL_AND_RETURN(void_function());
```
I don't think this is a good idea, though, since it doesn't gain you much and it makes your code harder for other people to understand.
|
67,155,497 |
Below is the table from which I need to create conditionalize view.
[](https://i.stack.imgur.com/Nzmgj.png)
and I am getting one flag from different table. So based on the flag values i.e. if flag=1 then I need to display actual column values from table, and if flag=0 then show all column values as null values.
I know we can handle it using CASE statement but here, in may case column count is very big so need to handle it in better way.
|
2021/04/19
|
[
"https://Stackoverflow.com/questions/67155497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1704622/"
] |
There's always the comma operator, although it doesn't make the code any more readable
```
return void_function(), 0;
```
|
Create a lambda that calls void\_function() and returns 0, then from the my\_function() you can return that invoked lambda.
|
41,880,973 |
Mandar has graciously written this code for me from this Q/A [in r, how to assess the two vectors based on other vectors](https://stackoverflow.com/questions/41817623/in-r-how-to-assess-the-two-vectors-based-on-other-vectors)
```
names(df) <- c("a","b","c","d")
df_backup <- df
df$newcol <- NA
used <- c()
for (i in seq(1,length(df$a),1)){
print("######## Separator ########")
print(paste("searching right match that fits criteria for ",df$a[i],"in column 'a'",sep=""))
valuea <- df[i,1]
orderx <- order(abs(df$b-valuea))
index=1
while (is.na(df$newcol[i])) {
j=orderx[index]
if (df$b[j] %in% used){
print(paste("passing ",df$b[j], "as it has already been used",sep=""))
index=index+1
next
} else {
indexb <- j
valueb <- df$b[indexb]
print(paste("trying ",valueb,sep=""))
if (df$c[i] != df$d[indexb]) {
df$newcol[i] <- df$b[indexb]
print(paste("using ",valueb,sep=""))
used <- c(used,df$b[indexb])
} else {
df$newcol[i] <- NA
print(paste("cant use ",valueb,"as the column c (related to index in a) and d (related to index in b) values are matching",sep=""))
}
index=index+1
}
}
}
```
this is what my data look like
```
a b c d
12.9722051 297.9117268 1 1
69.64816997 298.1908749 2 2
318.8794557 169.0386352 3 3
326.1762208 169.3201391 4 4
137.5400592 336.6595313 5 5
358.0600171 94.70890334 6 6
258.9282428 94.77530919 7 7
98.57513917 290.1983195 8 8
98.46303072 290.4078981 9 9
17.2276417 344.383796 10 10
316.6442074 148.786547 11 11
310.7370168 153.3287735 12 12
237.3270752 107.8397117 13 13
250.6538555 108.0570571 14 14
337.0954288 180.6311769 15 15
137.0336521 1.0294907 16 16
301.2277242 185.2062845 17 17
332.935301 185.9792236 18 18
340.841266 220.4043846 19 19
```
the values in column a and b are compass bearings. currently, the formula looks at a value in column a and compares it to all values in column b and finds the closest one. but what i realized i need it to do is look at a value in column b, but not only find the nearest value based on absolute difference, but also take into account that it is a compass bearing. for example: for the value in column a of 358.0600171 the current formula would return a value from column b of 344.383796, which is ~14 degrees away from 358.060171; however, the actual closest bearing value from column b should be 1.0294907 which is only 3 degrees away from 358.0600171. i would like to incorporate a function that that accounts for this compass bearing issue into the current formula: which does all my other needed evaluation, filtering, and column creation.
There a similar query here([Finding the closest difference between 2 degrees of a compass - Javascript](https://stackoverflow.com/questions/24392062/finding-the-closest-difference-between-2-degrees-of-a-compass-javascript)), but I need assistance on whether the function will work in R, and how to incorporate it into the existing formula.
|
2017/01/26
|
[
"https://Stackoverflow.com/questions/41880973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7422511/"
] |
we can find the nearest compass bearings like this:
```
nearest = function(i,df){
diff = abs(df[i, 1] - df[, 2])
diff = pmin(diff, 360-diff)
which.min(diff)
}
df$nearest_b = sapply(1:NROW(df), nearest, df[1:2])
df$nearest_a = sapply(1:NROW(df), nearest, df[2:1])
# a b nearest_b nearest_a
# 1 12.97221 297.911727 16 17
# 2 69.64817 298.190875 6 17
# 3 318.87946 169.038635 5 5
# 4 326.17622 169.320139 5 5
# 5 137.54006 336.659531 11 15
# 6 358.06002 94.708903 16 9
# 7 258.92824 94.775309 8 9
# 8 98.57514 290.198320 7 17
# 9 98.46303 290.407898 7 17
# 10 17.22764 344.383796 16 19
# 11 316.64421 148.786547 2 5
# 12 310.73702 153.328774 2 5
# 13 237.32708 107.839712 19 8
# 14 250.65386 108.057057 19 8
# 15 337.09543 180.631177 5 5
# 16 137.03365 1.029491 11 6
# 17 301.22772 185.206285 2 5
# 18 332.93530 185.979224 5 5
# 19 340.84127 220.404385 10 13
```
**The data**
```
df = read.table(text =
"a b c d
12.9722051 297.9117268 1 1
69.64816997 298.1908749 2 2
318.8794557 169.0386352 3 3
326.1762208 169.3201391 4 4
137.5400592 336.6595313 5 5
358.0600171 94.70890334 6 6
258.9282428 94.77530919 7 7
98.57513917 290.1983195 8 8
98.46303072 290.4078981 9 9
17.2276417 344.383796 10 10
316.6442074 148.786547 11 11
310.7370168 153.3287735 12 12
237.3270752 107.8397117 13 13
250.6538555 108.0570571 14 14
337.0954288 180.6311769 15 15
137.0336521 1.0294907 16 16
301.2277242 185.2062845 17 17
332.935301 185.9792236 18 18
340.841266 220.4043846 19 19",
header = T)[,1:2]
```
|
The geosphere package has a few functions that incorporate distance between spherical points.
<ftp://cran.r-project.org/pub/R/web/packages/geosphere/geosphere.pdf>
I'm not sure it will be what you're looking for - you may have to figure out how the compass bearings in your data translate to the inputs you need.
I notice the problem you're having is that it treats absolute distance as numerical difference, not accounting for the fact that you should be resetting to 0 at 360. You might be able to account for this by writing a function that stipulates to sum (difference between the co-ordinate and 360) and (other co-ordinate).
Eg:
- c1 is the input co-ordinate
- c2 is the co-ordinate you're comparing it to
`if c1 - c2 > 180 { (360 - c1) + c2 }`
I don't fully understand what you're trying to do so not sure if this is right but hope it helps.
|
41,880,973 |
Mandar has graciously written this code for me from this Q/A [in r, how to assess the two vectors based on other vectors](https://stackoverflow.com/questions/41817623/in-r-how-to-assess-the-two-vectors-based-on-other-vectors)
```
names(df) <- c("a","b","c","d")
df_backup <- df
df$newcol <- NA
used <- c()
for (i in seq(1,length(df$a),1)){
print("######## Separator ########")
print(paste("searching right match that fits criteria for ",df$a[i],"in column 'a'",sep=""))
valuea <- df[i,1]
orderx <- order(abs(df$b-valuea))
index=1
while (is.na(df$newcol[i])) {
j=orderx[index]
if (df$b[j] %in% used){
print(paste("passing ",df$b[j], "as it has already been used",sep=""))
index=index+1
next
} else {
indexb <- j
valueb <- df$b[indexb]
print(paste("trying ",valueb,sep=""))
if (df$c[i] != df$d[indexb]) {
df$newcol[i] <- df$b[indexb]
print(paste("using ",valueb,sep=""))
used <- c(used,df$b[indexb])
} else {
df$newcol[i] <- NA
print(paste("cant use ",valueb,"as the column c (related to index in a) and d (related to index in b) values are matching",sep=""))
}
index=index+1
}
}
}
```
this is what my data look like
```
a b c d
12.9722051 297.9117268 1 1
69.64816997 298.1908749 2 2
318.8794557 169.0386352 3 3
326.1762208 169.3201391 4 4
137.5400592 336.6595313 5 5
358.0600171 94.70890334 6 6
258.9282428 94.77530919 7 7
98.57513917 290.1983195 8 8
98.46303072 290.4078981 9 9
17.2276417 344.383796 10 10
316.6442074 148.786547 11 11
310.7370168 153.3287735 12 12
237.3270752 107.8397117 13 13
250.6538555 108.0570571 14 14
337.0954288 180.6311769 15 15
137.0336521 1.0294907 16 16
301.2277242 185.2062845 17 17
332.935301 185.9792236 18 18
340.841266 220.4043846 19 19
```
the values in column a and b are compass bearings. currently, the formula looks at a value in column a and compares it to all values in column b and finds the closest one. but what i realized i need it to do is look at a value in column b, but not only find the nearest value based on absolute difference, but also take into account that it is a compass bearing. for example: for the value in column a of 358.0600171 the current formula would return a value from column b of 344.383796, which is ~14 degrees away from 358.060171; however, the actual closest bearing value from column b should be 1.0294907 which is only 3 degrees away from 358.0600171. i would like to incorporate a function that that accounts for this compass bearing issue into the current formula: which does all my other needed evaluation, filtering, and column creation.
There a similar query here([Finding the closest difference between 2 degrees of a compass - Javascript](https://stackoverflow.com/questions/24392062/finding-the-closest-difference-between-2-degrees-of-a-compass-javascript)), but I need assistance on whether the function will work in R, and how to incorporate it into the existing formula.
|
2017/01/26
|
[
"https://Stackoverflow.com/questions/41880973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7422511/"
] |
we can find the nearest compass bearings like this:
```
nearest = function(i,df){
diff = abs(df[i, 1] - df[, 2])
diff = pmin(diff, 360-diff)
which.min(diff)
}
df$nearest_b = sapply(1:NROW(df), nearest, df[1:2])
df$nearest_a = sapply(1:NROW(df), nearest, df[2:1])
# a b nearest_b nearest_a
# 1 12.97221 297.911727 16 17
# 2 69.64817 298.190875 6 17
# 3 318.87946 169.038635 5 5
# 4 326.17622 169.320139 5 5
# 5 137.54006 336.659531 11 15
# 6 358.06002 94.708903 16 9
# 7 258.92824 94.775309 8 9
# 8 98.57514 290.198320 7 17
# 9 98.46303 290.407898 7 17
# 10 17.22764 344.383796 16 19
# 11 316.64421 148.786547 2 5
# 12 310.73702 153.328774 2 5
# 13 237.32708 107.839712 19 8
# 14 250.65386 108.057057 19 8
# 15 337.09543 180.631177 5 5
# 16 137.03365 1.029491 11 6
# 17 301.22772 185.206285 2 5
# 18 332.93530 185.979224 5 5
# 19 340.84127 220.404385 10 13
```
**The data**
```
df = read.table(text =
"a b c d
12.9722051 297.9117268 1 1
69.64816997 298.1908749 2 2
318.8794557 169.0386352 3 3
326.1762208 169.3201391 4 4
137.5400592 336.6595313 5 5
358.0600171 94.70890334 6 6
258.9282428 94.77530919 7 7
98.57513917 290.1983195 8 8
98.46303072 290.4078981 9 9
17.2276417 344.383796 10 10
316.6442074 148.786547 11 11
310.7370168 153.3287735 12 12
237.3270752 107.8397117 13 13
250.6538555 108.0570571 14 14
337.0954288 180.6311769 15 15
137.0336521 1.0294907 16 16
301.2277242 185.2062845 17 17
332.935301 185.9792236 18 18
340.841266 220.4043846 19 19",
header = T)[,1:2]
```
|
Check this code :
Just changed how orderx is defined with ifelse
Now if the abs difference between angles is > 180, then use the 360-difference (which is lower value); otherwise if the difference is already <=180 use the smaller difference itself
```
setwd("~/Desktop/")
df <- read.table("trial.txt",header=T,sep="\t")
names(df) <- c("a","B","C","D")
df_backup <- df
df$newcol <- NA
used <- c()
for (i in seq(1,length(df$a),1)){
print("######## Separator ########")
print(paste("searching right match that fits criteria for ",df$a[i],"in column 'a'",sep=""))
valueA <- df[i,1]
# orderx <- order(abs(df$B-valueA))
orderx <- order(ifelse(360-abs(df$B-valueA) > 180, abs(df$B-valueA) ,360-abs(df$B-valueA)))
index=1
while (is.na(df$newcol[i])) {
j=orderx[index]
if (df$B[j] %in% used){
print(paste("passing ",df$B[j], "as it has already been used",sep=""))
index=index+1
next
} else {
indexB <- j
valueB <- df$B[indexB]
print(paste("trying ",valueB,sep=""))
if (df$C[i] != df$D[indexB]) {
df$newcol[i] <- df$B[indexB]
print(paste("using ",valueB,sep=""))
used <- c(used,df$B[indexB])
} else {
df$newcol[i] <- NA
print(paste("cant use ",valueB,"as the column C (related to index in A) and D (related to index in B) values are matching",sep=""))
}
index=index+1
}
}
}
```
|
14,641,361 |
I need to map ntext column of a table using the mapping by code feature in NHibernate 3.2, so that it doesn't get truncated to 4000 characters.
What do I neet to change in the following example? "Notes" is the property which has ntext type in sql table:
Property(emp => emp.Notes);
Note: Please don't mix it with fluent NHibernate or hbm file mapping.
|
2013/02/01
|
[
"https://Stackoverflow.com/questions/14641361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741507/"
] |
Maybe you can try this, which should also work for nvarchar(max) columns :
```
Property(emp => emp.Notes, m => m.Type(NHibernateUtil.StringClob));
```
Hope this will help
|
Try:
```
Property(emp => emp.Notes, mapinfo => mapinfo.Lenth(someHighValue));
```
If the length provided is larger than what can fit in a varchar, NHibernate will switch to a different character type.
|
14,641,361 |
I need to map ntext column of a table using the mapping by code feature in NHibernate 3.2, so that it doesn't get truncated to 4000 characters.
What do I neet to change in the following example? "Notes" is the property which has ntext type in sql table:
Property(emp => emp.Notes);
Note: Please don't mix it with fluent NHibernate or hbm file mapping.
|
2013/02/01
|
[
"https://Stackoverflow.com/questions/14641361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741507/"
] |
So, I solved the problem as following:
>
> Property(emp => emp.Notes, map => map.Column(col =>
> col.SqlType("ntext")));
>
>
>
Actually, all what we need to do is: tell the NHibernate mapper the actual type of the column in sql. :)
The solution comes from [here](http://devio.wordpress.com/2012/02/24/mssql-legacy-data-types-in-nhibernate-mapping-bycode-conformist/) as pointed by [jbl](https://stackoverflow.com/users/1236044/jbl).
|
Try:
```
Property(emp => emp.Notes, mapinfo => mapinfo.Lenth(someHighValue));
```
If the length provided is larger than what can fit in a varchar, NHibernate will switch to a different character type.
|
14,641,361 |
I need to map ntext column of a table using the mapping by code feature in NHibernate 3.2, so that it doesn't get truncated to 4000 characters.
What do I neet to change in the following example? "Notes" is the property which has ntext type in sql table:
Property(emp => emp.Notes);
Note: Please don't mix it with fluent NHibernate or hbm file mapping.
|
2013/02/01
|
[
"https://Stackoverflow.com/questions/14641361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/741507/"
] |
So, I solved the problem as following:
>
> Property(emp => emp.Notes, map => map.Column(col =>
> col.SqlType("ntext")));
>
>
>
Actually, all what we need to do is: tell the NHibernate mapper the actual type of the column in sql. :)
The solution comes from [here](http://devio.wordpress.com/2012/02/24/mssql-legacy-data-types-in-nhibernate-mapping-bycode-conformist/) as pointed by [jbl](https://stackoverflow.com/users/1236044/jbl).
|
Maybe you can try this, which should also work for nvarchar(max) columns :
```
Property(emp => emp.Notes, m => m.Type(NHibernateUtil.StringClob));
```
Hope this will help
|
4,577,981 |
I'm reading the [Wikipedia article](https://en.m.wikipedia.org/wiki/Analytic_continuation) on analytic continuation and I got stuck in the last step of the worked example. How to get the following result? $$\sum\_{n=0}^{\infty}(-1)^n{n\choose k}(a-1)^{n-k}=(-1)^ka^{-k-1}$$
Obviously the sum starts from $n=k$ because ${n\choose k}=0$ for all $k>n$. I have tried by calculating some first terms of the sum and using the identity $${n\choose k}={n-1\choose k-1}+{n-1\choose k}$$ to see if there would be a useful pattern but I have had no success. Could someone tell how to arrive to the rhs from the lhs? This [question](https://math.stackexchange.com/questions/3395306/steps-to-solve-integral-in-analytic-continuation-problem) is about the same exmple and there is no answer to the op's comment. So here is the comment as a proper question.
EDIT: I had a typo on the lhs: it's actually $(-1)^n$ instead of $(-1)^k$.
Thanks to Mike Earnest's answer suggesting Newton's Binomial Theorem I calculated $$(x+1)^{-n}=\sum\_{i=0}^{\infty}{-n\choose i}x^i.$$ By simplifying the binomial coefficients $$\frac{-n(-n-1)(-n-2)...(-n-i+1)}{i!}=(-1)^i\frac{n(n+1)(n+2)...(n+i-1)}{i!}=(-1)^i\frac{n+i-1}{i!(n-1)}=(-1)^i{n-1 +i\choose i}=(-1)^i{n-1+i\choose n-1}$$
and then choosing $x=(a-1)$ gives: $$\sum\_{n=k}^{\infty}(-1)^n{n\choose k}(a-1)^{n-k}=a^{-k-1}.$$ So I'm only missing the $(-1)^k$. Where can that be found?
|
2022/11/16
|
[
"https://math.stackexchange.com/questions/4577981",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/762068/"
] |
>
> We obtain
> \begin{align\*}
> \color{blue}{\sum\_{n=0}^{\infty}}&\color{blue}{(-1)^n{n\choose k}(a-1)^{n-k}}\\
> &=\sum\_{n=k}^{\infty}(-1)^n\binom{n}{k}(a-1)^{n-k}\tag{1}\\
> &=\sum\_{n=0}^{\infty}(-1)^{n+k}\binom{n+k}{k}(a-1)^{n}\tag{2}\\
> &=(-1)^k\sum\_{n=0}^{\infty}\binom{-k-1}{n}(a-1)^{n}\tag{3}\\
> &=(-1)^k(1+(a-1))^{-k-1}\tag{4}\\
> &\,\,\color{blue}{=(-1)^ka^{-k-1}}
> \end{align\*}
> and the claim follows.
>
>
>
**Comment:**
* In (1) we start with index $n=k$ since $\binom{n}{k}=0$ if $n<k$.
* In (2) we shift the index to start with $n=0$ again.
* In (3) we use the binomial identities $\binom{p}{q}=\binom{p}{p-q}$ and $\binom{-p}{q}=\binom{p+q-1}{q}(-1)^q$. We get
\begin{align\*}
\binom{n+k}{k}=\binom{n+k}{n}=\binom{-(n+k)+n-1}{n}(-1)^n=\binom{-k-1}{n}(-1)^n
\end{align\*}
* In (4) we use the *[binomial series expansion](https://en.wikipedia.org/wiki/Binomial_series)*.
|
You need to use this general fact:
$$
\sum\_{n= 0}^\infty \binom nkx^n = \frac{x^k}{(1-x)^{k+1}}\qquad (|x|<1)
$$
In your case, you want $x=a-1$.
To prove this, let $S\_k=\sum\_{n\ge 0}\binom nkx^k$. Using Pascal's identity, $\binom nk=\binom{n-1}{k-1}+\binom {n-1}k$, you can split this into two sums, and derive the equation
$$
S\_k = xS\_{k-1}+xS\_k,
$$
which, combined with the base case $S\_0=(1-x)^{-1}$, quickly leads to a proof by induction that $S\_k=x^k(1-x)^{-(k+1)}$.
This also follows from Newton's binomial theorem:
$$
\sum\_{n\ge 0}\binom n{n-k}x^n
=\sum\_{n\ge 0}(-1)^{n-k}\binom{-(k+1)}{n-k}x^n
=x^k\sum\_{n\ge 0}\binom{-(k+1)}{n-k}(-x)^{n-k}=x^k(1-x)^{-(k+1)}
$$
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I agree with ShreevatsaR, if you don't make the helper function top-level (or worse, put it in the export list), than it doesn't matter what its name is.
I tend to call helper functions `f` and `g`.
```
reverse :: [a] -> [a]
reverse = f []
where
f ys [] = xs
f ys (x:xs) = f (x:ys) xs
```
I just use this naming scheme for small functions (otherwise I don't know what the `f` refers to). Then again, why would you ever write big functions?
However, if you do want to export your 'helper' function because it might be useful to others, I would call it:
```
reverseAccumulator
```
Like Haskell's `zip` and `zipWith`.
But I wouldn't call those 'helper' functions, `zipWith` is just a generic function and `zip` is the default implementation (probably the one thats used the most).
|
I use `aux` or `foo_aux` (for main function `foo`), and nest the definition so it's not externally visible.
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I tend to add "\_recurse" to the end. So "reverse\_recurse". Not sure where I got that from. I like leaving the base case function simple as you have in your example. It tends to be the "public" function and the fact that it uses a helper function to perform the iteration is irrelevant to the caller. In javascript I sometimes go so far as to hide the iterative function via a closure, to make it really clear it is not to be called directly.
|
setup and execute
example:
```
function whateverSetup() { ... }
function whateverExecute() { ... }
```
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I agree with ShreevatsaR, if you don't make the helper function top-level (or worse, put it in the export list), than it doesn't matter what its name is.
I tend to call helper functions `f` and `g`.
```
reverse :: [a] -> [a]
reverse = f []
where
f ys [] = xs
f ys (x:xs) = f (x:ys) xs
```
I just use this naming scheme for small functions (otherwise I don't know what the `f` refers to). Then again, why would you ever write big functions?
However, if you do want to export your 'helper' function because it might be useful to others, I would call it:
```
reverseAccumulator
```
Like Haskell's `zip` and `zipWith`.
But I wouldn't call those 'helper' functions, `zipWith` is just a generic function and `zip` is the default implementation (probably the one thats used the most).
|
setup and execute
example:
```
function whateverSetup() { ... }
function whateverExecute() { ... }
```
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
You can call the helper function anything you want, and it won't matter as long as you don't put the helper function in the "global" namespace. Simply adding a "prime" seems a common practice. :) E.g., in Haskell,
```
reverse :: [a] -> [a]
reverse = reverse' []
where reverse' :: [a] -> [a] -> [a]
reverse' result [] = result
reverse' result (x:xs) = reverse' (x:result) xs
```
|
I also agree with ShreevatsaR, in this example I would make the helper a private function.
For other cases where I need helper functions to be visible in the whole module, but not exported, I tend to prefix functions with '\_'. Sure, there is the explicit exports statement but during development I tend to export all functions to ease interactive exploration, e.g. in ghci. Later on I add the list of exported functions and the underbar makes it easy to remember whether I intended a function to be local or not.
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I also agree with ShreevatsaR, in this example I would make the helper a private function.
For other cases where I need helper functions to be visible in the whole module, but not exported, I tend to prefix functions with '\_'. Sure, there is the explicit exports statement but during development I tend to export all functions to ease interactive exploration, e.g. in ghci. Later on I add the list of exported functions and the underbar makes it easy to remember whether I intended a function to be local or not.
|
setup and execute
example:
```
function whateverSetup() { ... }
function whateverExecute() { ... }
```
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I always use do\_, like "do\_compute" with "compute". I find it quite descriptive as it is effectively the part of the function that performs the action, whereas the "compute" that gets called needs to have a simple descriptive name for the outside world.
|
I also agree with ShreevatsaR, in this example I would make the helper a private function.
For other cases where I need helper functions to be visible in the whole module, but not exported, I tend to prefix functions with '\_'. Sure, there is the explicit exports statement but during development I tend to export all functions to ease interactive exploration, e.g. in ghci. Later on I add the list of exported functions and the underbar makes it easy to remember whether I intended a function to be local or not.
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I tend to add "\_recurse" to the end. So "reverse\_recurse". Not sure where I got that from. I like leaving the base case function simple as you have in your example. It tends to be the "public" function and the fact that it uses a helper function to perform the iteration is irrelevant to the caller. In javascript I sometimes go so far as to hide the iterative function via a closure, to make it really clear it is not to be called directly.
|
I also agree with ShreevatsaR, in this example I would make the helper a private function.
For other cases where I need helper functions to be visible in the whole module, but not exported, I tend to prefix functions with '\_'. Sure, there is the explicit exports statement but during development I tend to export all functions to ease interactive exploration, e.g. in ghci. Later on I add the list of exported functions and the underbar makes it easy to remember whether I intended a function to be local or not.
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I agree with ShreevatsaR, if you don't make the helper function top-level (or worse, put it in the export list), than it doesn't matter what its name is.
I tend to call helper functions `f` and `g`.
```
reverse :: [a] -> [a]
reverse = f []
where
f ys [] = xs
f ys (x:xs) = f (x:ys) xs
```
I just use this naming scheme for small functions (otherwise I don't know what the `f` refers to). Then again, why would you ever write big functions?
However, if you do want to export your 'helper' function because it might be useful to others, I would call it:
```
reverseAccumulator
```
Like Haskell's `zip` and `zipWith`.
But I wouldn't call those 'helper' functions, `zipWith` is just a generic function and `zip` is the default implementation (probably the one thats used the most).
|
I also agree with ShreevatsaR, in this example I would make the helper a private function.
For other cases where I need helper functions to be visible in the whole module, but not exported, I tend to prefix functions with '\_'. Sure, there is the explicit exports statement but during development I tend to export all functions to ease interactive exploration, e.g. in ghci. Later on I add the list of exported functions and the underbar makes it easy to remember whether I intended a function to be local or not.
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
I use `aux` or `foo_aux` (for main function `foo`), and nest the definition so it's not externally visible.
|
setup and execute
example:
```
function whateverSetup() { ... }
function whateverExecute() { ... }
```
|
418,120 |
In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.
```
reverse :: [a] -> [a]
reverse = reverse_helper []
reverse_helper :: [a] -> [a] -> [a]
reverse_helper result [] = result
reverse_helper result (x:xs) = reverse_helper (x:result) xs
```
"reverse\_helper" isn't really a good, descriptive name. However, "reverse\_recursive\_part" is just awkward.
What naming convention would you use for helper functions like this?
|
2009/01/06
|
[
"https://Stackoverflow.com/questions/418120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32998/"
] |
You can call the helper function anything you want, and it won't matter as long as you don't put the helper function in the "global" namespace. Simply adding a "prime" seems a common practice. :) E.g., in Haskell,
```
reverse :: [a] -> [a]
reverse = reverse' []
where reverse' :: [a] -> [a] -> [a]
reverse' result [] = result
reverse' result (x:xs) = reverse' (x:result) xs
```
|
I always use do\_, like "do\_compute" with "compute". I find it quite descriptive as it is effectively the part of the function that performs the action, whereas the "compute" that gets called needs to have a simple descriptive name for the outside world.
|
8,861,015 |
s it possible to remove cancel button or
override cancel button function from
local notification view?If yes then how we can achieve this
|
2012/01/14
|
[
"https://Stackoverflow.com/questions/8861015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1125018/"
] |
Have you [checked](http://www.java.com/en/download/testjava.jsp) that the [Java plugin](http://support.mozilla.org/en-US/kb/Using%20the%20Java%20plugin%20with%20Firefox) is working in Firefox?
Edit:
Apparently, FF [requires](http://www.java.com/en/download/faq/firefox_newplugin.xml) Java 6 Update 10 (or above) to work.
|
I had made these changes and after that it was working fine for me after searching a lot.
Go to
* Control panel
* Java Control Panel
* Java Tab View
* IN run time parameters add this line
```none
-Djava.net.preferIPv4Stack=true
```
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Get yourself subversion, mercurial, git, cvs, anything is a vast improvement over zip files. You can generally get free plugins for VS as well although they aren't necessary.
|
I've used Mercurial which has a plugin for VS2010 that can be found here:
<http://visualhg.codeplex.com/>
But, as GIT does also, you can use it via command line.
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Get yourself subversion, mercurial, git, cvs, anything is a vast improvement over zip files. You can generally get free plugins for VS as well although they aren't necessary.
|
Since you're working with VS2010 I suggest you start working with [**TFS2010 Basic**](https://devblogs.microsoft.com/bharry/tfs-2010-for-sourcesafe-users/).
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Get yourself subversion, mercurial, git, cvs, anything is a vast improvement over zip files. You can generally get free plugins for VS as well although they aren't necessary.
|
SVN would be perfect for you!!
I use Visual Studio 2010 as well, and there's a great open source plugin for working with SVN - [AnkhSVN](http://ankhsvn.open.collab.net/)
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Anything would be better then zip files.
For personal projects I would start with Git or SVN. Both are free and have addons for VS.
|
I've used Mercurial which has a plugin for VS2010 that can be found here:
<http://visualhg.codeplex.com/>
But, as GIT does also, you can use it via command line.
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Anything would be better then zip files.
For personal projects I would start with Git or SVN. Both are free and have addons for VS.
|
Since you're working with VS2010 I suggest you start working with [**TFS2010 Basic**](https://devblogs.microsoft.com/bharry/tfs-2010-for-sourcesafe-users/).
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
Anything would be better then zip files.
For personal projects I would start with Git or SVN. Both are free and have addons for VS.
|
SVN would be perfect for you!!
I use Visual Studio 2010 as well, and there's a great open source plugin for working with SVN - [AnkhSVN](http://ankhsvn.open.collab.net/)
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
I've used Mercurial which has a plugin for VS2010 that can be found here:
<http://visualhg.codeplex.com/>
But, as GIT does also, you can use it via command line.
|
Since you're working with VS2010 I suggest you start working with [**TFS2010 Basic**](https://devblogs.microsoft.com/bharry/tfs-2010-for-sourcesafe-users/).
|
3,316,120 |
I am a sole developer currently backing up my source code to .zip files on an external drive. Is it worthwhile for me to start looking at code repositories? What's the simplest, cheapest option for me? (ie. There is no need for lots of fancy features as the repository is just as a backup and not for sharing with a team).
... Forgot to mention. I use Visual Studio 2010 only.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3316120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384141/"
] |
SVN would be perfect for you!!
I use Visual Studio 2010 as well, and there's a great open source plugin for working with SVN - [AnkhSVN](http://ankhsvn.open.collab.net/)
|
Since you're working with VS2010 I suggest you start working with [**TFS2010 Basic**](https://devblogs.microsoft.com/bharry/tfs-2010-for-sourcesafe-users/).
|
20,979,456 |
I'm trying to make a website with links rotating around a circle. (Something like this) <http://i.imgur.com/i9DzASw.jpg?1> with the different images and texts leading to different urls. The image is one unified image that also rotates as the user scrolls. Is there anyway I can do this? Also is there a way to make the page height infinite so that the user never gets to the bottom of the page as they scroll? Thanks!
Here's the jsfiddle and the code that allows for the rotation of the image.
<http://jsfiddle.net/kDSqB/135/>
```
var $cog = $('#cog'),
$body = $(document.body),
bodyHeight = $body.height();
$(window).scroll(function () {
$cog.css({
'transform': 'rotate(' + ($body.scrollTop() / bodyHeight * 30000) + 'deg)'
});
});
```
|
2014/01/07
|
[
"https://Stackoverflow.com/questions/20979456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3170382/"
] |
Ok, finally I had found the problem !!!
Encoding of PDO is the problem...
Just adjusted driver options and all works good!
```
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')
```
Thanks guys anyway!
|
how about whitelisting? ie allow only valid characters
regex\_replace `[^-_.@a-zA-Z]` with `''`
|
20,979,456 |
I'm trying to make a website with links rotating around a circle. (Something like this) <http://i.imgur.com/i9DzASw.jpg?1> with the different images and texts leading to different urls. The image is one unified image that also rotates as the user scrolls. Is there anyway I can do this? Also is there a way to make the page height infinite so that the user never gets to the bottom of the page as they scroll? Thanks!
Here's the jsfiddle and the code that allows for the rotation of the image.
<http://jsfiddle.net/kDSqB/135/>
```
var $cog = $('#cog'),
$body = $(document.body),
bodyHeight = $body.height();
$(window).scroll(function () {
$cog.css({
'transform': 'rotate(' + ($body.scrollTop() / bodyHeight * 30000) + 'deg)'
});
});
```
|
2014/01/07
|
[
"https://Stackoverflow.com/questions/20979456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3170382/"
] |
how about whitelisting? ie allow only valid characters
regex\_replace `[^-_.@a-zA-Z]` with `''`
|
Found that on MySQL checking against CHAR(160) does not work.For UTF-8 NBSP the below worked for me:
```
REPLACE(the_field, UNHEX('C2A0'), ' ').
```
Solution provided on similar stack overflow question [Whitespace in a database field is not removed by trim()](https://stackoverflow.com/a/44262935)
|
20,979,456 |
I'm trying to make a website with links rotating around a circle. (Something like this) <http://i.imgur.com/i9DzASw.jpg?1> with the different images and texts leading to different urls. The image is one unified image that also rotates as the user scrolls. Is there anyway I can do this? Also is there a way to make the page height infinite so that the user never gets to the bottom of the page as they scroll? Thanks!
Here's the jsfiddle and the code that allows for the rotation of the image.
<http://jsfiddle.net/kDSqB/135/>
```
var $cog = $('#cog'),
$body = $(document.body),
bodyHeight = $body.height();
$(window).scroll(function () {
$cog.css({
'transform': 'rotate(' + ($body.scrollTop() / bodyHeight * 30000) + 'deg)'
});
});
```
|
2014/01/07
|
[
"https://Stackoverflow.com/questions/20979456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3170382/"
] |
Ok, finally I had found the problem !!!
Encoding of PDO is the problem...
Just adjusted driver options and all works good!
```
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'')
```
Thanks guys anyway!
|
Found that on MySQL checking against CHAR(160) does not work.For UTF-8 NBSP the below worked for me:
```
REPLACE(the_field, UNHEX('C2A0'), ' ').
```
Solution provided on similar stack overflow question [Whitespace in a database field is not removed by trim()](https://stackoverflow.com/a/44262935)
|
44,556,536 |
I have a web app where the client side is developed in Javascript. I have already enabled Azure AD login for my app by configuring it at portal.azure.com. Then, every time when this app loads, users are required to log in, if they have not.
I would like to have some Javascript in my client side so the app knows the user name. Here is the code I have.
```
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.11/js/adal.min.js"></script>
<script type="text/javascript">
var authContext = new AuthenticationContext({
clientId: 'xxxx-xxx-xxxx',
postLogoutRedirectUri: window.location
});
var user = authContext.getCachedUser();
if (user) {
window.alert("Signed in as " + user.userName);
} else{
window.alert("Failed to get the user information");
}
</script>
```
However, the variable *user* is always null. Can anybody help?
|
2017/06/15
|
[
"https://Stackoverflow.com/questions/44556536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8163283/"
] |
That seems you are using "Authentication / Authorization" feature of azure app service and the identity provide is azure ad . If you want to access the tokens from a client (like JavaScript in a browser), or if you want to get a richer set of information about the logged in user, you can also send an authenticated GET request to the `/.auth/me` endpoint. Javascript code below to get user claims is for your reference:
```
<script type="text/javascript">
$(document).ready(function ()
{
$.get("https://xxxxxx.azurewebsites.net/.auth/me", function (data, status) {
for (var key in data[0]["user_claims"]) {
var obj = data[0]["user_claims"][key];
alert(obj["typ"]); //claim type in user_claims
alert(obj["val"]) //claim value in user_claims
}
});
});
</script>
```
|
Thanks, Yan. That pretty solves my problem, only with little revision to your code. My situation is that I need to retrieve the user name first before generating the later part of my app. So, I removed the outer wrapper *$(document).ready(function(){}*. Correct me if I am wrong. Probably this out wrapper is telling this chunk of code to run after the entire app is loaded. Then, the final code is like this:
```
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$.get("https://xxxxx.azurewebsites.net/.auth/me", function (data) {
labeler = data[0]['user_id'];
window.alert("You logged in as " + data[0]['user_id']);
});
</script>
```
|
64,690,799 |
i`m using Vue and wanna use async/await to give a sequence for my function A and B
```
result is false by default
mounted() {
this.A();
this.B();
}
async A() {
this.result = await this.$api...
}
async B() {
if(this.result) let data = await this.$another1 api...
else let data = await this.$another2 api...
}
```
i assume that after function A call api and return a value of 'result' then, function B do his job.
However, sometimes api in function B called 'another2 api' before 'this.result' get his value even if result is 'true' after function A receive a value from $api
[](https://i.stack.imgur.com/3nIF3.png)
this is normal action which i expect
[](https://i.stack.imgur.com/6RLg3.png)
this is an error which was found sometimes when i refresh a page.
How can i solve this problem?
|
2020/11/05
|
[
"https://Stackoverflow.com/questions/64690799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13531705/"
] |
If you are coding in SwiftUI 2 you can convert your Color to UIColor and use getRed method to get the red, green, blue and alpha components. Once you have the components you can convert the values to hexa string:
---
```
extension Color {
var uiColor: UIColor { .init(self) }
typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
var rgba: RGBA? {
var (r, g, b, a): RGBA = (0, 0, 0, 0)
return uiColor.getRed(&r, green: &g, blue: &b, alpha: &a) ? (r, g, b, a) : nil
}
var hexaRGB: String? {
guard let (red, green, blue, _) = rgba else { return nil }
return String(format: "#%02x%02x%02x",
Int(red * 255),
Int(green * 255),
Int(blue * 255))
}
var hexaRGBA: String? {
guard let (red, green, blue, alpha) = rgba else { return nil }
return String(format: "#%02x%02x%02x%02x",
Int(red * 255),
Int(green * 255),
Int(blue * 255),
Int(alpha * 255))
}
}
```
---
```
Color.purple.hexaRGB // "#af52de"
Color.purple.hexaRGBA // "#af52deff"
if let (red, green, blue, alpha) = Color.purple.rgba {
red // 0.686274528503418
green // 0.321568638086319
blue // 0.8705882430076599
alpha // 1
}
```
|
Isn't it good to use it like this?
```
import UIKit
extension UIColor {
convenience init(hex:Int, alpha: CGFloat = 1.0) {
self.init(
red: CGFloat((hex & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hex & 0x00FF00) >> 8) / 255.0,
blue: CGFloat((hex & 0x0000FF) >> 0) / 255.0,
alpha: alpha
)
}
}
```
|
31,632,824 |
I know there are many threads already on 'spark streaming connection refused' issues. But most of these are in Linux or at least pointing to HDFS. I am running this on my local laptop with Windows.
I am running a very simple basic Spark streaming standalone application, just to see how the streaming works. Not doing anything complex here:-
```
import org.apache.spark.streaming.Seconds
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.SparkConf
object MyStream
{
def main(args:Array[String])
{
val sc = new StreamingContext(new SparkConf(),Seconds(10))
val mystreamRDD = sc.socketTextStream("localhost",7777)
mystreamRDD.print()
sc.start()
sc.awaitTermination()
}
}
```
I am getting the following error:-
```none
2015-07-25 18:13:07 INFO ReceiverSupervisorImpl:59 - Starting receiver
2015-07-25 18:13:07 INFO ReceiverSupervisorImpl:59 - Called receiver onStart
2015-07-25 18:13:07 INFO SocketReceiver:59 - Connecting to localhost:7777
2015-07-25 18:13:07 INFO ReceiverTracker:59 - Registered receiver for stream 0 from 192.168.19.1:11300
2015-07-25 18:13:08 WARN ReceiverSupervisorImpl:92 - Restarting receiver with delay 2000 ms: Error connecting to localhost:7777
java.net.ConnectException: Connection refused
```
I have tried using different port numbers, but it doesn't help. So it keeps retrying in loop and keeps on getting same error. Does anyone have an idea?
|
2015/07/26
|
[
"https://Stackoverflow.com/questions/31632824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5057753/"
] |
Within the code for `socketTextStream`, Spark creates an instance of `SocketInputDStream` which uses `java.net.Socket` <https://github.com/apache/spark/blob/master/streaming/src/main/scala/org/apache/spark/streaming/dstream/SocketInputDStream.scala#L73>
`java.net.Socket` is a client socket, which means it is expecting there to be a server already running at the address and port you specify. Unless you have some service running a server on port 7777 of your local machine, the error you are seeing is as expected.
To see what I mean, try the following (you may not need to set `master` or `appName` in your environment).
```
import org.apache.spark.streaming.Seconds
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.SparkConf
object MyStream
{
def main(args:Array[String])
{
val sc = new StreamingContext(new SparkConf().setMaster("local").setAppName("socketstream"),Seconds(10))
val mystreamRDD = sc.socketTextStream("bbc.co.uk",80)
mystreamRDD.print()
sc.start()
sc.awaitTermination()
}
}
```
This doesn't return any content because the app doesn't speak HTTP to the bbc website but it does not get a connection refused exception.
To run a local server when on linux, I would use netcat with a simple command such as
```
cat data.txt | ncat -l -p 7777
```
I'm not sure what your best approach is in Windows. You could write another application which listens as a server on that port and sends some data.
|
Make sure to start the netcat or the port connection before you run the program.
nc -lk 8080
|
113,595 |
Is there any ranking as to the usefulness or rarity of some of the offered quest rewards? Yes, I know that its possible to just run through the content multiple times and get all of them - but I don't want to do that yet, my furthest char is Act 2 Normal ;)
What considerations should I think of, for e.g. when choosing between `Added Lightning Damage` and `Weapon Elemental Damage` for a Templar? Are there general 'rules of thumb' to keep in mind?
|
2013/04/10
|
[
"https://gaming.stackexchange.com/questions/113595",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/25150/"
] |
If you get offered 2 or more gems that you actually need for your character then pick the one that's harder to find and more expensive to buy from other players. Of course you should also check which gems you'll be getting from quests in the near future in case one of those gems will appear as reward again. [Check them here.](http://en.pathofexilewiki.com/wiki/Quest_Rewards)
If you don't get any gems you need for your character then you can:
* Pick the one you might need for your other character, if you have one or plan on making one
* Pick the one that sells for the most to other players
In case you get bad gems as reward which you don't need, and other people don't want to buy then just pick either one and delete it
Do note that there aren't that many quest reward gems that are actually worth something. Since they can be obtained from quests their prices are low to nonexistent.
|
For reference to anyone coming to this question post-2.0.0 update of the game, most, if not all, gems that are quest rewards can subsequently be bought from vendors.
|
25,934,325 |
I have an App Engine application which uses Google Cloud SQL, and from a page in my application I am doing some database operation; whenever this page is accessed, it is not able to perform all database operations. When I go to the console, all I see is `/_ah/queue/__deferred__`.
I am able to run the application without any issues on localhost so code has no errors, however, there is an issue with the Cloud SQL after deploying it.
**Note :** I have not used queues anywhere in my code.
*What is the actual cause for* `/_ah/queue/__deferred__` *to appear in App Engine logs?*
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25934325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3776061/"
] |
I had a similar issue. I've found that that in one of my filters was opening session for each incomming connection:
```
httpRequest.getSession(true);
//or the one below - both opens a valid HTTP Session
httpRequest.getSession();
```
and my *appengine-web.xml* was configured to store session asynchronously
```
<sessions-enabled>true</sessions-enabled>
<async-session-persistence enabled="true"/>
```
This has resulted in creating a lot of tasks in default queue and each one of them tried to store an empty session. To avoid this, make sure that you are opening session only for proper requests. Either by fixing filter or changing filter *url-patterns* in your *web.xml*
|
Unless you specified a queue name, all deferred tasks go into the "default" Task Queue. From there, you can rerun and if you are on local dev server (debug mode) you can step through the code.
|
80,720 |
I am using a Postgres DB to implement a scheduling of jobs for a large number of computers/processes. To make the story short, every job has its id, all scheduling is implemented with three tabes: all jobs, currently running jobs, and already completed jobs.
The key functionality of the scheduling is to (1) request a job and (2) inform DB about a completed job. Requesting a job takes any id from the job list, which is not in the running table and not in the completed table:
```
insert into piper.jobs_running
select x.fid from (
SELECT fid FROM piper.jobs
except
select fid from piper.jobs_running
except
select fid from piper.jobs_completed
) as x limit 1
returning(fid)
```
Completing the job removes it from the running list and inserts it into the completed list. Since it is not concurrency-specific I ommit the SQL commands (it takes something from tens of minutes to a couple of hours to finish a job.)
It came as a nasty surpirse to me, that two processes runing exactly the same query above (pretty much requesting the job at the same time) may get the same job id (fid). The only possible explanation that I am comming up is that Postgres is not rely ACID conform. Comments?
**Additional information:** I set the transactions to be serializable (in *postgresql.conf* `set default_transaction_isolation = 'serializable'`). Now the DBMS fails the transactions in case the isolation is not fullfilled. is it possible to force Postgres to restart them automatically?
|
2014/10/21
|
[
"https://dba.stackexchange.com/questions/80720",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/28367/"
] |
Specific issues with the query
------------------------------
PostgreSQL defaults to `READ COMMITTED` isolation, and it looks like you're not using anything different. In `READ COMMITTED` each statement gets its own snapshot. It cannot see uncommitted changes from other transactions; it's as if they simply haven't happened.
Now, imagine you run this simultaneously in three sessions, on a setup with three entries in `jobs`, zero in `jobs_running` and zero in `jobs_completed`:
```
insert into piper.jobs_running
select x.fid from (
SELECT fid FROM piper.jobs
except
select fid from piper.jobs_running
except
select fid from piper.jobs_completed
) as x limit 1
returning(fid)
```
Each run will select the three jobs in `jobs`. Because their snapshots were all taken before any of them committed a change, or even created the uncommitted row, \*all of them will find zero rows in `jobs_running` and `jobs_completed`.
So they all claim a job. Probably *the same job*, because even though there's no `ORDER BY`, the scan order will be the same.
Locking
-------
Row locking crosses transnational boundaries, and lets you communicate between transactions to enforce ordering. So you might think this would solve your problem, but it won't.
If you take a `FOR UPDATE` lock on the `row` entry, so the row is locked exclusively, the lock is held until the transaction commits or rolls back. So you'd think that then the next transaction would get a different row, or if it tried to get the same row it'd wait for the lock to release, see that there was now an entry in `jobs_running`, and skip the row. You'd be wrong.
What'll happen is that you'll lock all rows. One transaction will successfully get the locks on all rows. The other transactions, which will do the same index or sequential scan, will generally try to lock the rows in the same order, get stuck on the first lock attempt, and wait for the first transaction to roll back or commit. If you're unlucky, they might start locking different sets of rows and deadlock against each other instead, causing a deadlock abort, but usually you're just getting no useful concurrency.
Worse though, the first transaction picks one of the rows it locked, inserts a row into `jobs_running` and commits, releasing the locks. Another transaction is then able to continue, and locks all the rows.... but *it doesn't get a new snapshot of the database state* (the snapshot gets taken at statement start), so \*it can't see that you inserted a row into `jobs_running`. Thus, it grabs the same job, inserts a row for that job into `jobs_running`, and commits.
Condition re-checks
-------------------
PostgreSQL has a quirky feature not included in most databases where, if a transaction blocks on a lock, it re-checks that the selected row still matches the lock condition when it gets the lock after the first transaction commits.
That's why the example in <https://stackoverflow.com/questions/11532550/atomic-update-select-in-postgres> works - it relies on qualifier re-checks in `WHERE` clauses after reclaiming a lock.
The use of locking forces everything to run serially, so in practice you might as well have a single connection doing the work.
Isolation, ACID, and reality
----------------------------
Transaction isolation in PostgreSQL is not the perfect ideal where transactions run concurrently, but their effects are the same as if they were executed serially.
The only real world database that would deliver perfect isolation would be one that exclusively locks every table when a write transaction first accesses it, so in practice transactions can only be concurrent access if it's to different parts of the DB. Nobody wants to use such a database in situations where concurrency is desirable or useful.
All real world implementations are compromises.
`READ COMMITTED` default
------------------------
PostgreSQL's default is [`READ COMMITTED` isolation, a well-defined isolation level that *permits* non-repeatable and phantom reads](http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Read_committed), as [discussed in the PostgreSQL manual on transaction isolation](http://www.postgresql.org/docs/current/static/transaction-iso.html).
`SERIALIZABLE` isolation
------------------------
You can request stricter [`SERIALIZABLE` isolation](http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Serializable) on a per-transaction basis or as a per-user, per-database or (not recommended) global default. This provides much stronger guarantees, though still not perfect, at the cost of forcibly rolling back transactions if they interact in ways that couldn't happen if they had run serially.
Because your concurrent queries will always try to grab the first job, no matter how many jobs there are, all but one will abort with serialization failures. So in practice you don't get any useful concurrency and might as well have a single connection handing out jobs to workers.
(Note that prior to PostgreSQL 9.1 `SERIALIZABLE` offered much weaker guarantees and would not detect quite a lot of cases where transactions were interdependent.)
Auto-re-run `SERIALIZABLE`
--------------------------
PostgreSQL does *not* auto-re-run `SERIALIZABLE` transactions that abort due to serialization failures. There are cases where this would be quite useful, but other cases where doing so would be completely wrong and dangerous - especially where read/modify/write cycles via the application are involved. At this time there is no support for automatically rerunning transactions on serialization failures. The application is expected to retry.
Don't write a DIY queuing system
--------------------------------
It looks like what you're trying to do is write a queuing system. Consider not doing that. Writing a robust, reliable and correct queueing system is hard, and there are a few good ones already available that you could adopt. You have to handle things like crash-safety, what happens when someone takes a task then fails to complete it, race conditions around completion just as you give up on the task handler completing it, etc. There are lots of subtle concurrency problems. Don't try to DIY.
9.5 and `SKIP LOCKED`
---------------------
PostgreSQL 9.5, still in development, adds a feature that makes queuing quite a bit easier.
It lets you say that if when you `SELECT ... FOR UPDATE`, if a row is locked, you should ignore it and carry on to find the next not-locked row. This is very useful when combined with a `LIMIT` as it makes it possible to say "find me the first row someone else isn't already trying to claim". So it becomes very simple to write queuing that grabs jobs safely and concurrently.
Until that feature is available I strongly suggest that you stick to single connection queue management, or use a well-tested task queue system.
|
The answer from craig-ringer fully answers the question. For the sake of completeness, I add up the following trivial code to solve the issue using locks:
```
create or replace function f_requestJob(
jobs text,
jobs_running text,
jobs_completed text
)
returns bigint as
$$
declare
sql varchar;
c bigint;
begin
execute 'LOCK TABLE ' || jobs || ' IN ACCESS EXCLUSIVE MODE';
execute 'LOCK TABLE ' || jobs_running || ' IN ACCESS EXCLUSIVE MODE';
execute 'LOCK TABLE ' || jobs_completed || ' IN ACCESS EXCLUSIVE MODE';
sql := '
insert into ' || jobs_running || '
select x.fid
from (
SELECT fid FROM ' || jobs || '
except
select fid from ' || jobs_running || '
except
select fid from ' || jobs_completed || '
) as x limit 1
returning(fid)';
execute sql into c;
return c; --may be a null value
end;
$$ language plpgsql;
```
|
8,499 |
It seems on Friday night that various people rise at various times towards the end of השכיבנו (and before beginning ושמרו). When is the actual proper moment to rise? (Sources, please.)
|
2011/06/26
|
[
"https://judaism.stackexchange.com/questions/8499",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/128/"
] |
In the Nusach Edot HaMizrach...
>
> הַשְׁכִּיבֵנוּ אָבִינוּ לְשָׁלום,
> וְהַעֲמִידֵנוּ מַלְכֵּנוּ לְחַיִּים
> טובִים וּלְשָׁלום, וּפְרושׂ עָלֵינוּ
> סֻכַּת שְׁלומֶךָ וְתַקְּנֵנוּ
> מַלְכֵּנוּ בְּעֵצָה טובָה
> מִלְּפָנֶיךָ, וְהושִׁיעֵנוּ מְהֵרָה
> לְמַעַן שְׁמֶךָ וְהָגֵן בַּעֲדֵנוּ. <>
> וּפְרושׂ עָלֵינוּ וְעַל יְרוּשָׁלַיִם
> עִירָךְ סֻכַּת רַחֲמִים וְשָׁלום.
> בָּרוּךְ אַתָּה ה' הַפּורֵשׂ סֻכַּת
> שָׁלום עָלֵינוּ וְעַל כָּל עַמּו
> יִשְׂרָאֵל וְעַל יְרוּשָׁלַיִם אָמֵן:
>
>
>
Right where I put the <> marker is where you rise and accept the extra Neshamah of Shabbat. (You accept the extra Nefesh at the end of Lecha Dodi, and the extra Ruach at Barechu)
(Ben Ish Hai Parshat Vayera #3, Kaf HaHayyim 267:11.)
On Yom Tov it appears that one stands at the beginning of Kaddish, just as one does on weeknights. Even Sepharadim are not required to stand for Kaddish in general, the halacha is that at Arvit, one stands for Shemoneh Esreh at the kaddish immediately preceding Shemoneh Esreh.
|
Chabad stands before "Ufros aleinu" (See Hayom Yom, [2nd Day of Sivan](http://www.chabad.org/library/article_cdo/aid/5783/jewish/Sivan-2-46th-day-of-the-omer.htm)). It does not give a reason, but see [here](http://www.chabad.org/kabbalah/article_cdo/aid/1490225/jewish/Day-6.htm), where it quotes S'fardi prayer books as follows:
>
> after Boi Kalah on Friday night: Think that the extra Nefesh has descended in to you. After Barchu, it tells us to think that the extra Ruach has entered, and after Ufros Aleinu, the extra Neshama.
>
>
>
If that is the case, this could be the reason why we stand by Ufros Aleinu, to welcome or give respect to the extra Neshama level of the soul ([the 3rd level of the soul](http://www.askmoses.com/en/article/192,2108428/Levels-of-Soul-Consciousness.html)).
Also, some Nuschaot say "Ufros aleinu" twice in the prayer (like [here](https://judaism.stackexchange.com/questions/8499/when-to-stand-friday-night-by-haskiveinu/8503#8503) or [here](http://siddur.org/transliterations/friday-night-sabbath-services/shabbat-maariv-shema#hashk)), but the Chabad Siddur only [has it once](http://chabadlibrarybooks.com/pdfpager.aspx?req=32581&st=&pgnum=138).
|
46,799,467 |
Trying to find a regex for a string containing only numbers and single spaces (but no spaces at beginning and end) such as this:
"1 2 3 -4" --> Accept
" 1 2 3 -4 " --> Not accept
So far been using this:
```
^\S+[-?\d ]*\b$
```
However this still accepts the string for:
"1 2 --3" which should not be accepted due to a double negative and a double space.
Note that the numbers can be any integer.
Any help?
Thank you
|
2017/10/17
|
[
"https://Stackoverflow.com/questions/46799467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4371769/"
] |
This will work:
```
^-?\d+(?:[ ]-?\d+)*$
```
Note that
* the `+` quantifier is applied only to the `\d` expressions.
* I put the required single-space separator into a character class for clarity; it could equivalently be expressed without
* the anchors aren't really necessary if you are going to use `Matcher.matches()` to match single-line strings.
|
Try this:
```
^\S+( (-?)[\d]+)+\b$
```
or even better:
```
^\S+( ((-?)\d+))+\b$|^\d$
```
in order to match single digits also
Edit (see comments):
This should be an even better version (removes that leading \S)
```
^\d( (-?)[\d]+)*\b$
```
|
46,799,467 |
Trying to find a regex for a string containing only numbers and single spaces (but no spaces at beginning and end) such as this:
"1 2 3 -4" --> Accept
" 1 2 3 -4 " --> Not accept
So far been using this:
```
^\S+[-?\d ]*\b$
```
However this still accepts the string for:
"1 2 --3" which should not be accepted due to a double negative and a double space.
Note that the numbers can be any integer.
Any help?
Thank you
|
2017/10/17
|
[
"https://Stackoverflow.com/questions/46799467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4371769/"
] |
Code
----
```
^(?:-?\d+ )*(?:-?\d+)+$
```
Explanation
-----------
* `^` Assert position at beginning of the line
* `(?:-?\d+ )*` Match the following any number of times
+ `-?\d+` Match zero or one of the `-` character, followed by one or more digits, followed by a space character
* `(?:-?\d+)+` Match zero or one of the `-` character, followed by one or more digits
* `$` Assert position at the end of the line
|
Try this:
```
^\S+( (-?)[\d]+)+\b$
```
or even better:
```
^\S+( ((-?)\d+))+\b$|^\d$
```
in order to match single digits also
Edit (see comments):
This should be an even better version (removes that leading \S)
```
^\d( (-?)[\d]+)*\b$
```
|
46,799,467 |
Trying to find a regex for a string containing only numbers and single spaces (but no spaces at beginning and end) such as this:
"1 2 3 -4" --> Accept
" 1 2 3 -4 " --> Not accept
So far been using this:
```
^\S+[-?\d ]*\b$
```
However this still accepts the string for:
"1 2 --3" which should not be accepted due to a double negative and a double space.
Note that the numbers can be any integer.
Any help?
Thank you
|
2017/10/17
|
[
"https://Stackoverflow.com/questions/46799467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4371769/"
] |
Code
----
```
^(?:-?\d+ )*(?:-?\d+)+$
```
Explanation
-----------
* `^` Assert position at beginning of the line
* `(?:-?\d+ )*` Match the following any number of times
+ `-?\d+` Match zero or one of the `-` character, followed by one or more digits, followed by a space character
* `(?:-?\d+)+` Match zero or one of the `-` character, followed by one or more digits
* `$` Assert position at the end of the line
|
This will work:
```
^-?\d+(?:[ ]-?\d+)*$
```
Note that
* the `+` quantifier is applied only to the `\d` expressions.
* I put the required single-space separator into a character class for clarity; it could equivalently be expressed without
* the anchors aren't really necessary if you are going to use `Matcher.matches()` to match single-line strings.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[CJam](https://sourceforge.net/p/cjam), 29 bytes
------------------------------------------------
```
qN/{)\z}h]2/{~W%+}%eeSf.*W%N*
```
[Try it online!](https://tio.run/nexus/cjam#@1/op1@tGVNVmxFrpF9dF66qXauamhqcpqcVruqn9f@/oZGxnr0il4mpmT2QMrewVFRUBAA "CJam – TIO Nexus")
### Explanation
Instead of extracting the diagonals, we peel off layers from the end, alternating left and right. Consider the following input:
```
GFDB
EEDB
CCCB
AAAA
```
If we write out the diagonals as required by the challenge, we get:
```
G
EEF
CCCDD
AAAABBB
```
Note that this is simply (from bottom to top), the bottom-most row, concatenated with the right-most column. This definition also works if the input is rectangular.
```
{ e# Run this loop while there are still lines left in the input.
) e# Pull off the bottom-most row.
\ e# Swap with the remaining rows.
z e# Transpose the grid so that the next iteration pulls off the last
e# column instead. However, it should be noted that transposing
e# effectively reverses the column, so the second half of each output
e# line will be the wrong way around. We'll fix that later.
}h e# When the loop is done, we'll have all the individual layers on the
e# stack from bottom to top, alternating between horizontal and vertical
e# layers. There will be an empty string on top.
] e# Wrap all those strings in a list.
2/ e# Split into pairs. There may or may not be a trailing single-element
e# list with the empty string.
{ e# Map this block over each pair...
~ e# Dump the pair on the stack.
W% e# Reverse the second element.
+ e# Append to first element.
e# If there was a trailing single-element list, this will simply
e# add the empty string to the previous pair, which just removes
e# the empty string.
}%
ee e# Enumerate the list, which pairs each string (now containing both halves)
e# of an output line from bottom to top) with its index.
Sf.* e# Turn those indices X into strings of X spaces, to get the correct
e# indentation.
W% e# Reverse the list of strings so the longest line ends up on the bottom.
```
|
Python 3, 247 bytes
===================
```
def a(s):
s=s.split('\n')
for i,l in enumerate(s):r=len(s)-i-1;s[i]=' '*r+l+' '*(len(s)-r-1)
print(*[''.join(i) for i in list(zip(*[''.join(a).rstrip([::-1].ljust(min(len(s),len(s[0])))for a in zip(*[list(i)for i in s])]))[::-1]],sep='\n')`
```
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[Jelly](https://github.com/DennisMitchell/jelly), 15 or 14 bytes
================================================================
```
L’⁶x;\Ṛ;"µZUZṚY
```
[Try it online!](https://tio.run/nexus/jelly#@@/zqGHmo8ZtFdYxD3fOslY6tDUqNArIivz//7@SoZGxnr2iko6SiamZPZhhbmGpqKioBAA "Jelly – TIO Nexus")
This is an algorithm that doesn't use Jelly's built-in for diagonals. Doing that might make it shorter; I might well try that next.
Here's how the algorithm works. Let's start with this input:
```
["abc",
"def",
"ghi"]
```
We start off with `L’⁶x;\`. `L’` gives us the length of the input minus 1 (in this case, 2). Then `⁶x` gives us a string of spaces of that length (`" "` in this case); and `;\` gives us the cumulative results when concatenating it (a triangle of spaces). We then reverse the triangle and concatenate it to the left side of the original (`;"` concatenates corresponding elements of lists, `µ` forcibly causes a break in the parsing and thus uses the original input as the second list by default), giving us this:
```
[" abc",
" def",
"ghi"]
```
This is almost the solution we want, but we need to move the elements downwards to be flush with the last string. That's a matter of transposing (`Z`), reversing inside each line (`U`), transposing again (`Z`), and reversing the lines (`Ṛ`):
```
[" abc",
" def",
"ghi"]
```
transpose
```
[" g",
" dh",
"aei",
"bf",
"c"]
```
reverse within rows
```
["g ",
"hd ",
"iea",
"fb",
"c"]
```
transpose
```
["ghifc",
" deb",
" a"]
```
reverse the rows
```
[" a",
" deb",
"ghifc"]
```
Finally, `Y` joins on newlines. It's unclear to me whether or not this is required to comply with the specification (which allows input as a list of strings, but doesn't say the same about output), so the exact byte count depends on whether it's included or omitted.
|
Octave, 57 bytes
================
```octave
@(A){B=spdiags(A),C=B>0,D=' '(C+1),D(sort(C))=B(C),D}{5}
```
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[Jelly](https://github.com/DennisMitchell/jelly), 11 or 10 bytes
================================================================
```
ZŒDṙLUz⁶ṚUY
```
[Try it online!](https://tio.run/nexus/jelly#@x91dJLLw50zfUKrHjVue7hzVmjk////lRKTklNSlXSU0tIzMrOAdHZObl6@EgA "Jelly – TIO Nexus")
A fairly different algorithm from my other solution; this one uses a builtin to get at the diagonals, rather than doing things manually.
Explanation:
```
ZŒDṙLUz⁶ṚUY
Z transpose
ŒD diagonals, main diagonal first
L number of lines in the original array
ṙ rotate list (i.e. placing the short diagonal first)
U reverse inside lines
z⁶ transpose, padding with spaces
ṚU rotate matrix 180 degrees
Y (possibly unnecessary) join on newlines
```
The diagonals come out in possibly the worst possible orientation (requiring repeated transpositions, reversals, and rotations), and in the wrong order (Jelly outputs the main diagonal first, so we have to move some diagonals from the end to the start to get them in order). However, this still comes out shorter than my other Jelly solution.
|
[Jelly](https://github.com/DennisMitchell/jelly), 15 or 14 bytes
================================================================
```
L’⁶x;\Ṛ;"µZUZṚY
```
[Try it online!](https://tio.run/nexus/jelly#@@/zqGHmo8ZtFdYxD3fOslY6tDUqNArIivz//7@SoZGxnr2iko6SiamZPZhhbmGpqKioBAA "Jelly – TIO Nexus")
This is an algorithm that doesn't use Jelly's built-in for diagonals. Doing that might make it shorter; I might well try that next.
Here's how the algorithm works. Let's start with this input:
```
["abc",
"def",
"ghi"]
```
We start off with `L’⁶x;\`. `L’` gives us the length of the input minus 1 (in this case, 2). Then `⁶x` gives us a string of spaces of that length (`" "` in this case); and `;\` gives us the cumulative results when concatenating it (a triangle of spaces). We then reverse the triangle and concatenate it to the left side of the original (`;"` concatenates corresponding elements of lists, `µ` forcibly causes a break in the parsing and thus uses the original input as the second list by default), giving us this:
```
[" abc",
" def",
"ghi"]
```
This is almost the solution we want, but we need to move the elements downwards to be flush with the last string. That's a matter of transposing (`Z`), reversing inside each line (`U`), transposing again (`Z`), and reversing the lines (`Ṛ`):
```
[" abc",
" def",
"ghi"]
```
transpose
```
[" g",
" dh",
"aei",
"bf",
"c"]
```
reverse within rows
```
["g ",
"hd ",
"iea",
"fb",
"c"]
```
transpose
```
["ghifc",
" deb",
" a"]
```
reverse the rows
```
[" a",
" deb",
"ghifc"]
```
Finally, `Y` joins on newlines. It's unclear to me whether or not this is required to comply with the specification (which allows input as a list of strings, but doesn't say the same about output), so the exact byte count depends on whether it's included or omitted.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[CJam](https://sourceforge.net/p/cjam), 29 bytes
------------------------------------------------
```
qN/{)\z}h]2/{~W%+}%eeSf.*W%N*
```
[Try it online!](https://tio.run/nexus/cjam#@1/op1@tGVNVmxFrpF9dF66qXauamhqcpqcVruqn9f@/oZGxnr0il4mpmT2QMrewVFRUBAA "CJam – TIO Nexus")
### Explanation
Instead of extracting the diagonals, we peel off layers from the end, alternating left and right. Consider the following input:
```
GFDB
EEDB
CCCB
AAAA
```
If we write out the diagonals as required by the challenge, we get:
```
G
EEF
CCCDD
AAAABBB
```
Note that this is simply (from bottom to top), the bottom-most row, concatenated with the right-most column. This definition also works if the input is rectangular.
```
{ e# Run this loop while there are still lines left in the input.
) e# Pull off the bottom-most row.
\ e# Swap with the remaining rows.
z e# Transpose the grid so that the next iteration pulls off the last
e# column instead. However, it should be noted that transposing
e# effectively reverses the column, so the second half of each output
e# line will be the wrong way around. We'll fix that later.
}h e# When the loop is done, we'll have all the individual layers on the
e# stack from bottom to top, alternating between horizontal and vertical
e# layers. There will be an empty string on top.
] e# Wrap all those strings in a list.
2/ e# Split into pairs. There may or may not be a trailing single-element
e# list with the empty string.
{ e# Map this block over each pair...
~ e# Dump the pair on the stack.
W% e# Reverse the second element.
+ e# Append to first element.
e# If there was a trailing single-element list, this will simply
e# add the empty string to the previous pair, which just removes
e# the empty string.
}%
ee e# Enumerate the list, which pairs each string (now containing both halves)
e# of an output line from bottom to top) with its index.
Sf.* e# Turn those indices X into strings of X spaces, to get the correct
e# indentation.
W% e# Reverse the list of strings so the longest line ends up on the bottom.
```
|
Clojure, 194 bytes
------------------
Implemented the hard way by grouping characters to `G` and then generating lines.
```
#(let[n(count %)m(count(% 0))G(group-by first(for[i(range n)j(range m)][(min(- n i)(- m j))((% i)j)]))](apply str(flatten(for[k(reverse(sort(keys G)))][(repeat(dec k)" ")(map last(G k))"\n"]))))
```
Takes input as a `vec` of `vec`s like `[[\a \b \c \d] [\1 \2 \3 \4] [\W \X \Y \Z]]`. Example:
```
(def f #( ... ))
(print (str "\n" (f (mapv vec(re-seq #".+" "abcd\n1234\nWXYZ")))))
ab
c123
d4WXYZ
```
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[J](http://jsoftware.com/), 12 bytes
------------------------------------
```
|./.&.|:&.|.
```
Defines an anonymous verb.
[Try it online!](https://tio.run/nexus/j#@5@mYGulUKOnr6emV2MFxHr/S0AixgomCioK6olJySmGRsYm4RGRUepcqckZ@QrqnnkFpSVQTglUzL@0BCGYplDyHwA "J – TIO Nexus")
Explanation
-----------
```
|./.&.|:&.|.
|. Reversed
/. anti-diagonals
&. under
|: transpose
&. under
|. reversal
```
In J, `u &. v` (read: `u` under `v`) means "v, then u, then inverse of v".
Reversal and transpose are self-inverses, so the program really means "reverse, transpose, extract reversed anti-diagonals, transpose, reverse".
With example input:
```
abcd
1234
WXYZ
```
Reverse:
```
WXYZ
1234
abcd
```
Transpose:
```
W1a
X2b
Y3c
Z4d
```
Extract reversed anti-diagonals (and pad with spaces):
```
W
X1
Y2a
Z3b
4c
d
```
Transpose:
```
WXYZ4d
123c
ab
```
Reverse:
```
ab
123c
WXYZ4d
```
|
Clojure, 194 bytes
------------------
Implemented the hard way by grouping characters to `G` and then generating lines.
```
#(let[n(count %)m(count(% 0))G(group-by first(for[i(range n)j(range m)][(min(- n i)(- m j))((% i)j)]))](apply str(flatten(for[k(reverse(sort(keys G)))][(repeat(dec k)" ")(map last(G k))"\n"]))))
```
Takes input as a `vec` of `vec`s like `[[\a \b \c \d] [\1 \2 \3 \4] [\W \X \Y \Z]]`. Example:
```
(def f #( ... ))
(print (str "\n" (f (mapv vec(re-seq #".+" "abcd\n1234\nWXYZ")))))
ab
c123
d4WXYZ
```
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[CJam](https://sourceforge.net/p/cjam), 29 bytes
------------------------------------------------
```
qN/{)\z}h]2/{~W%+}%eeSf.*W%N*
```
[Try it online!](https://tio.run/nexus/cjam#@1/op1@tGVNVmxFrpF9dF66qXauamhqcpqcVruqn9f@/oZGxnr0il4mpmT2QMrewVFRUBAA "CJam – TIO Nexus")
### Explanation
Instead of extracting the diagonals, we peel off layers from the end, alternating left and right. Consider the following input:
```
GFDB
EEDB
CCCB
AAAA
```
If we write out the diagonals as required by the challenge, we get:
```
G
EEF
CCCDD
AAAABBB
```
Note that this is simply (from bottom to top), the bottom-most row, concatenated with the right-most column. This definition also works if the input is rectangular.
```
{ e# Run this loop while there are still lines left in the input.
) e# Pull off the bottom-most row.
\ e# Swap with the remaining rows.
z e# Transpose the grid so that the next iteration pulls off the last
e# column instead. However, it should be noted that transposing
e# effectively reverses the column, so the second half of each output
e# line will be the wrong way around. We'll fix that later.
}h e# When the loop is done, we'll have all the individual layers on the
e# stack from bottom to top, alternating between horizontal and vertical
e# layers. There will be an empty string on top.
] e# Wrap all those strings in a list.
2/ e# Split into pairs. There may or may not be a trailing single-element
e# list with the empty string.
{ e# Map this block over each pair...
~ e# Dump the pair on the stack.
W% e# Reverse the second element.
+ e# Append to first element.
e# If there was a trailing single-element list, this will simply
e# add the empty string to the previous pair, which just removes
e# the empty string.
}%
ee e# Enumerate the list, which pairs each string (now containing both halves)
e# of an output line from bottom to top) with its index.
Sf.* e# Turn those indices X into strings of X spaces, to get the correct
e# indentation.
W% e# Reverse the list of strings so the longest line ends up on the bottom.
```
|
JavaScript (ES6), 140 bytes
---------------------------
```
a=>[...Array(m=(h=a.length)<(w=a[0].length)?h:w)].map((_,i)=>[...Array(h+w-1)].map((_,j)=>(a[x=i+h-m-(++j>w&&j-w)]||``)[x+j-h]||` `).join``)
```
Takes input and output as arrays of strings. Also accepts a two-dimensional character array input, and save 7 bytes if a two-dimensional character array output is acceptable. Explanation: The height of the result `m` is the minimum of the height `h` and width `w` of the original array, while the width is simply one less than the sum of the height and width of the original array. The source row for the characters on the main portion of the result come directly from the appropriate row of the original array, counting up from the bottom, while on the extra portion of the result the source row moves up one row for each additional column. The source column for both halves of the result turns out to be equal to the destination column moved one column left for each source row above the bottom.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
JavaScript, ~~116~~ 101 bytes
=============================
```js
f=(s,r='$&',l='',z=s.replace(/.$|\n?(?!.*\n)..+/gm,x=>(l=x+l,'')))=>l?f(z,r+' ')+l.replace(/\n?/,r):l
G.onclick=()=>O.textContent=f(I.value);
```
```html
<textarea id=I style=height:100px>/\/\
\/ /
/ /\
\/\/</textarea><button id=G>Go</button><pre id=O></pre>
```
I just wanted to use this regex pattern `/.$|\n?(?!.*\n)..+/gm` idea. (<https://regex101.com/r/mjMz9i/2>)
JavaScript regex flavour is disappointing, I had to use `(?!.*\n)` because it doesn't have `\Z` implemented, and somehow I didn't get to use `\0`.
* 15 bytes off thanks @Neil.
|
Python 2, 150 bytes
===================
```py
def f(l):w=len(l[0]);h=len(l);J=''.join;R=range;print'\n'.join(map(J,zip(*['%%-%ds'%h%J(l[h+~i][j-i]for i in R(h)if-w<i-j<1)for j in R(h-~w)]))[::-1])
```
Takes input as list of strings.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[J](http://jsoftware.com/), 12 bytes
------------------------------------
```
|./.&.|:&.|.
```
Defines an anonymous verb.
[Try it online!](https://tio.run/nexus/j#@5@mYGulUKOnr6emV2MFxHr/S0AixgomCioK6olJySmGRsYm4RGRUepcqckZ@QrqnnkFpSVQTglUzL@0BCGYplDyHwA "J – TIO Nexus")
Explanation
-----------
```
|./.&.|:&.|.
|. Reversed
/. anti-diagonals
&. under
|: transpose
&. under
|. reversal
```
In J, `u &. v` (read: `u` under `v`) means "v, then u, then inverse of v".
Reversal and transpose are self-inverses, so the program really means "reverse, transpose, extract reversed anti-diagonals, transpose, reverse".
With example input:
```
abcd
1234
WXYZ
```
Reverse:
```
WXYZ
1234
abcd
```
Transpose:
```
W1a
X2b
Y3c
Z4d
```
Extract reversed anti-diagonals (and pad with spaces):
```
W
X1
Y2a
Z3b
4c
d
```
Transpose:
```
WXYZ4d
123c
ab
```
Reverse:
```
ab
123c
WXYZ4d
```
|
JavaScript (ES6), 140 bytes
---------------------------
```
a=>[...Array(m=(h=a.length)<(w=a[0].length)?h:w)].map((_,i)=>[...Array(h+w-1)].map((_,j)=>(a[x=i+h-m-(++j>w&&j-w)]||``)[x+j-h]||` `).join``)
```
Takes input and output as arrays of strings. Also accepts a two-dimensional character array input, and save 7 bytes if a two-dimensional character array output is acceptable. Explanation: The height of the result `m` is the minimum of the height `h` and width `w` of the original array, while the width is simply one less than the sum of the height and width of the original array. The source row for the characters on the main portion of the result come directly from the appropriate row of the original array, counting up from the bottom, while on the extra portion of the result the source row moves up one row for each additional column. The source column for both halves of the result turns out to be equal to the destination column moved one column left for each source row above the bottom.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
JavaScript, ~~116~~ 101 bytes
=============================
```js
f=(s,r='$&',l='',z=s.replace(/.$|\n?(?!.*\n)..+/gm,x=>(l=x+l,'')))=>l?f(z,r+' ')+l.replace(/\n?/,r):l
G.onclick=()=>O.textContent=f(I.value);
```
```html
<textarea id=I style=height:100px>/\/\
\/ /
/ /\
\/\/</textarea><button id=G>Go</button><pre id=O></pre>
```
I just wanted to use this regex pattern `/.$|\n?(?!.*\n)..+/gm` idea. (<https://regex101.com/r/mjMz9i/2>)
JavaScript regex flavour is disappointing, I had to use `(?!.*\n)` because it doesn't have `\Z` implemented, and somehow I didn't get to use `\0`.
* 15 bytes off thanks @Neil.
|
JavaScript (ES6), 140 bytes
---------------------------
```
a=>[...Array(m=(h=a.length)<(w=a[0].length)?h:w)].map((_,i)=>[...Array(h+w-1)].map((_,j)=>(a[x=i+h-m-(++j>w&&j-w)]||``)[x+j-h]||` `).join``)
```
Takes input and output as arrays of strings. Also accepts a two-dimensional character array input, and save 7 bytes if a two-dimensional character array output is acceptable. Explanation: The height of the result `m` is the minimum of the height `h` and width `w` of the original array, while the width is simply one less than the sum of the height and width of the original array. The source row for the characters on the main portion of the result come directly from the appropriate row of the original array, counting up from the bottom, while on the extra portion of the result the source row moves up one row for each additional column. The source column for both halves of the result turns out to be equal to the destination column moved one column left for each source row above the bottom.
|
104,748 |
Given a rectangular grid of text, line up the diagonals that go from the upper-left to the bottom-right into columns such that the lowest-rightmost characters of all diagonals are on a level. Use spaces for indentation.
For example, if the input grid of text is
```
abcd
1234
WXYZ
```
then you'd line up the diagonals `W`, `1X`, `a2Y`, `b3z`, `c4`, and `d` in columns giving this output:
```
ab
123c
WXYZ4d
```
Note that the lowest-rightmost characters of all diagonals, `WXYZ4d`, are at the same level.
Details
=======
* The input grid of text will be at minimum 1×1 in size and all lines will be the same length.
* You may take the input grid as a multiline string or as a list of single line strings.
* The input grid will only contains [printable ASCII characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (includes space).
* The output may optionally have one trailing newline but there should be no other empty lines.
* The lines of the output may optionally have trailing spaces but should not have unnecessary leading spaces.
Other Examples
==============
Empty lines separate examples. Each input is directly followed by its output.
```
123
456
789
1
452
78963
123.?!
456??!
789!!!
123.
456???
789!!!!!
**@
@
**
@ @
/\/\
\/ /
/ /\
\/\/
/
\/\
/ / /
\/\/\/\
12
34
56
78
90
7531
908642
Code
Code
G
O
L
F
FLOG
~
~
```
Scoring
=======
The shortest code in bytes wins.
|
2016/12/27
|
[
"https://codegolf.stackexchange.com/questions/104748",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/26997/"
] |
[Jelly](https://github.com/DennisMitchell/jelly), 11 or 10 bytes
================================================================
```
ZŒDṙLUz⁶ṚUY
```
[Try it online!](https://tio.run/nexus/jelly#@x91dJLLw50zfUKrHjVue7hzVmjk////lRKTklNSlXSU0tIzMrOAdHZObl6@EgA "Jelly – TIO Nexus")
A fairly different algorithm from my other solution; this one uses a builtin to get at the diagonals, rather than doing things manually.
Explanation:
```
ZŒDṙLUz⁶ṚUY
Z transpose
ŒD diagonals, main diagonal first
L number of lines in the original array
ṙ rotate list (i.e. placing the short diagonal first)
U reverse inside lines
z⁶ transpose, padding with spaces
ṚU rotate matrix 180 degrees
Y (possibly unnecessary) join on newlines
```
The diagonals come out in possibly the worst possible orientation (requiring repeated transpositions, reversals, and rotations), and in the wrong order (Jelly outputs the main diagonal first, so we have to move some diagonals from the end to the start to get them in order). However, this still comes out shorter than my other Jelly solution.
|
Pyth, 16 bytes
==============
```
j_.t_M.Tm+*;l=tQ
```
### [Big Pyth](https://github.com/isaacg1/pyth/blob/master/big-pyth.py):
```
join-on-newline
reverse transpose-and-fill-with-spaces reverse func-map transpose-justified
map
plus
times innermost-var
length assign tail input
implicit-innermost-var
implicit-input
```
Since people say golfing languages are hard to read, I've designed Big Pyth, which is both easily readable and easily translatable to Pyth. The linked file translates an input stream of Big Pyth to Pyth. Each whitespace-separated Big Pyth token corresponds to a Pyth token, either a character or a `.` followed by a character. The exceptions are the `implicit` tokens, which are implicit in the Pyth code.
I want to see how good an explanatory format Big Pyth is, so I'm not going to give any other explanation. Ask me if you want something explained, however.
|
33,679,480 |
I am trying to insert div with iframe before HTML comment (it is the only unique element at this position).
So I have comment like: `<!-- Comment -->` and I would like to insert code like this before the comment:
```
<div id="test">
<noscript>
<iframe src="https://test.net" frameborder="0" scrolling="no" width="742" height="92"></iframe>
</noscript>
</div>
```
I tried methods like .append() and prepend(), but without success.
The result should be:
```
<div id="test">
<noscript>
<iframe src="https://test.net" frameborder="0" scrolling="no" width="742" height="92"></iframe>
</noscript>
</div>
<!-- Comment -->
```
Many thanks for any help!
|
2015/11/12
|
[
"https://Stackoverflow.com/questions/33679480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4940705/"
] |
You can do this in many ways, one of them is the following:
```
template <typename E, typename Enable = void>
struct get_a_int_val {
static const int value = 42;
};
template <typename E>
struct get_a_int_val<E, typename std::enable_if<std::is_same<decltype(E::a),
decltype(E::a)>::value, void>::type>{
static const int value = static_cast<int>(E::a);
};
```
[**LIVE DEMO**](http://coliru.stacked-crooked.com/a/7f7b1705aec30451)
|
You may create a traits for that:
```
template <typename E>
std::false_type has_a_impl(...);
template <typename E> auto has_a_impl(int) -> decltype(E::a, std::true_type{});
template <typename E>
using has_a = decltype(has_a_impl<E>(0));
```
And then use it in SFINAE:
```
template <typename E>
std::enable_if_t<has_a<E>::value, int>
get_a_int_val() { return static_cast<int>(E::a); }
template <typename E>
std::enable_if_t<!has_a<E>::value, int>
get_a_int_val() { return 42; }
```
[Demo](https://ideone.com/6eq8ML)
|
70,501,845 |
I am trying to set the values of several cells in the same row of a cell that I am changing.
IF the value in AJ2 is True then the range AK2:AX2 should also be true.If I change AJ2 to false, then I should be able to uncheck any of the values in the range and they would then be false. I 'sort of' have this logic working. IF I have AJ2 checked and uncheck AK2, when I uncheck AJ2 it rechecks AK2.
I also need this to happen on all rows if I change the value in the column of AJ for their rows. not just row 2. I am fairly new to working with sheets and could use some help.
```
function onEdit(e) {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getRange("AJ2");
var range =ss.getRange("AK2:AX2")
var activeCell = ss.getActiveCell();
if(activeCell.getColumn() == 36&&ss.getActiveSheet().getName()=="MasterData") {
if (Cell = "TRUE")
range.setValue("TRUE")}
}
```
|
2021/12/28
|
[
"https://Stackoverflow.com/questions/70501845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17777132/"
] |
Try this
```
function onEdit(e) {
const sheet = e.source.getActiveSheet();
const cell = e.range;
// AJ = column 36 (master column)
if(sheet.getName() == "MasterData" && cell.getColumn()==36 && cell.isChecked()){
sheet.getRange(cell.getRow(),37,1,14).setValue('TRUE')
}
// individual columns : 37 (AK) to 50 (AX)
if(sheet.getName() == "MasterData" && cell.getColumn()>=37 && cell.getColumn()<=50 && !cell.isChecked()){
sheet.getRange(cell.getRow(),36,1,1).setValue('FALSE')
}
}
```
explanation
===========
when a box is checked in column 36 (AJ = 'master column'), all the boxes of the same row between 37 to 50 (AK to AX) will be checked
when an individual box is unchecked between column 37 to 50 (AK to AX) the master box of the same row will be also unchecked
reference
=========
[onEdit trigger](https://developers.google.com/apps-script/guides/triggers#onedite)
|
The [onEdit(e) simple trigger](https://developers.google.com/apps-script/guides/triggers) returns an [event object](https://developers.google.com/apps-script/guides/triggers/events).
The event object contains the information about the spreadsheet that was edited, which you use instead of the "SpreadsheetApp.getActiveSpreadsheet()"
To access the information in the event object, you need to use the 'e':
```
function onEdit(e) {
//the sheet that was edited
var sheet = e.source.getActiveSheet();
//the cell that was edited
var cell = sheet.getActiveCell();
//the row number of the cell that was edited
var row = cell.getRow();
//the column number of the cell that was edited
var column = cell.getColumn();
```
From there, proceed as you normally would with sheets and ranges.
To update multiple cells at once, you can set the range with [getRange(row, column, numRows, numColumns)](https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow,-column,-numrows,-numcolumns) and then [setValues(values)](https://developers.google.com/apps-script/reference/spreadsheet/range#setValues(Object)). Note that it's setValues(), not setValue().
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.