qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
313,161 | In other words, is there a website where I can find a simple list of all the packages that apt-get install searches through, along with descriptions of what each package does?
When I run apt-get update, I see that my computer hits <http://security.ubuntu.com> and finds something called oneiric-updates. Is there a human-friendly version of this website? | 2013/06/27 | [
"https://askubuntu.com/questions/313161",
"https://askubuntu.com",
"https://askubuntu.com/users/170549/"
] | You can find all the packages depending on the build installed here:
[Ubuntu Packages Search](http://packages.ubuntu.com/)
But Oneiric Ocelot is the Codename for 11.10, so it is probably just downloading the security updates for your version. I wouldn't be worried about anything.
EDIT: After looking here: [Ubuntu oneiric-updates](https://launchpad.net/ubuntu/+milestone/oneiric-updates). It possibly looks like a pack of drivers but I may be mistaken | Depends on what you mean by "human-friendly"
You can browse here:
<http://packages.ubuntu.com/> |
313,161 | In other words, is there a website where I can find a simple list of all the packages that apt-get install searches through, along with descriptions of what each package does?
When I run apt-get update, I see that my computer hits <http://security.ubuntu.com> and finds something called oneiric-updates. Is there a human-friendly version of this website? | 2013/06/27 | [
"https://askubuntu.com/questions/313161",
"https://askubuntu.com",
"https://askubuntu.com/users/170549/"
] | You can find all the packages depending on the build installed here:
[Ubuntu Packages Search](http://packages.ubuntu.com/)
But Oneiric Ocelot is the Codename for 11.10, so it is probably just downloading the security updates for your version. I wouldn't be worried about anything.
EDIT: After looking here: [Ubuntu oneiric-updates](https://launchpad.net/ubuntu/+milestone/oneiric-updates). It possibly looks like a pack of drivers but I may be mistaken | I guess what you are looking for is software manager.
It has GUI and categorized package lists. It is in your ubuntu by default. Try may be. |
54,235,317 | I'm having trouble with the `contentInset` property. I have a `UITableView`, with dynamic cell sizes (AutoLayout). I'm setting the `contentInset` property to leave some space above the top of the content. But I'm getting the following result:
[](https://i.stack.imgur.com/0VZbq.png)
The content is in blue, the content inset in purple. When the table view first appears, it is in the left situation. I can scroll to get to the right situation, that is working, but I would like the table view to appears directly as in the right illustration — which I thought would be the default behavior.
How can I achieve that? | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3780788/"
] | Not sure if it's the best way but I fixed it by adding:
```
tableView.contentOffset.y = -70
```
after the line:
```
tableView.contentInset = UIEdgeInsets(top: 70, left: 0, bottom: 50, right: 0)
``` | This is how it can be fixed easily from the Storyboard:
Table View > Size Inspector > Content Insets: Never |
54,235,317 | I'm having trouble with the `contentInset` property. I have a `UITableView`, with dynamic cell sizes (AutoLayout). I'm setting the `contentInset` property to leave some space above the top of the content. But I'm getting the following result:
[](https://i.stack.imgur.com/0VZbq.png)
The content is in blue, the content inset in purple. When the table view first appears, it is in the left situation. I can scroll to get to the right situation, that is working, but I would like the table view to appears directly as in the right illustration — which I thought would be the default behavior.
How can I achieve that? | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3780788/"
] | you can scroll programmatically when the view loads.
```
tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: false)
``` | This is how it can be fixed easily from the Storyboard:
Table View > Size Inspector > Content Insets: Never |
54,235,317 | I'm having trouble with the `contentInset` property. I have a `UITableView`, with dynamic cell sizes (AutoLayout). I'm setting the `contentInset` property to leave some space above the top of the content. But I'm getting the following result:
[](https://i.stack.imgur.com/0VZbq.png)
The content is in blue, the content inset in purple. When the table view first appears, it is in the left situation. I can scroll to get to the right situation, that is working, but I would like the table view to appears directly as in the right illustration — which I thought would be the default behavior.
How can I achieve that? | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3780788/"
] | Not sure if it's the best way but I fixed it by adding:
```
tableView.contentOffset.y = -70
```
after the line:
```
tableView.contentInset = UIEdgeInsets(top: 70, left: 0, bottom: 50, right: 0)
``` | You provide an UIEdgeInset object,
```
UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
```
The top property shows the distance from top of content to top border of the area. |
54,235,317 | I'm having trouble with the `contentInset` property. I have a `UITableView`, with dynamic cell sizes (AutoLayout). I'm setting the `contentInset` property to leave some space above the top of the content. But I'm getting the following result:
[](https://i.stack.imgur.com/0VZbq.png)
The content is in blue, the content inset in purple. When the table view first appears, it is in the left situation. I can scroll to get to the right situation, that is working, but I would like the table view to appears directly as in the right illustration — which I thought would be the default behavior.
How can I achieve that? | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3780788/"
] | you can scroll programmatically when the view loads.
```
tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: false)
``` | You provide an UIEdgeInset object,
```
UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)
```
The top property shows the distance from top of content to top border of the area. |
54,235,317 | I'm having trouble with the `contentInset` property. I have a `UITableView`, with dynamic cell sizes (AutoLayout). I'm setting the `contentInset` property to leave some space above the top of the content. But I'm getting the following result:
[](https://i.stack.imgur.com/0VZbq.png)
The content is in blue, the content inset in purple. When the table view first appears, it is in the left situation. I can scroll to get to the right situation, that is working, but I would like the table view to appears directly as in the right illustration — which I thought would be the default behavior.
How can I achieve that? | 2019/01/17 | [
"https://Stackoverflow.com/questions/54235317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3780788/"
] | Not sure if it's the best way but I fixed it by adding:
```
tableView.contentOffset.y = -70
```
after the line:
```
tableView.contentInset = UIEdgeInsets(top: 70, left: 0, bottom: 50, right: 0)
``` | you can scroll programmatically when the view loads.
```
tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: false)
``` |
47,389,508 | I have searched on Google and here on SO before posting this question.
I have found several solution to my problem, but none of them fits my needs.
Here is my code: [Plunker](https://plnkr.co/edit/Vb0y4ZCLKyiXlClXuhBk)
```
<div *ngIf="description.length > 200" class="ui mini compact buttons expand">
<button class="ui button" (click)="showMore($event)">Show more</button>
</div>
```
The "show more" button appears only if text length exceeds 200 characters.
As you can see it seems to be a nice solution.
```
showMore(event: any) {
$(event.target).text((i, text) => { return text === "Show more" ? "Show less" : "Show more"; });
$(event.target).parent().prev().find('.detail-value').toggleClass('text-ellipsis');
}
```
Anyway I could have a text that is not 200 characters long and that doesn't fit the SPAN element, then it has the ellipsis but the "show more" button doesn't appear.
[](https://i.stack.imgur.com/s7KaG.png)
How can I make my solution work in any case? Do you know a workaround or a best solution to solve that? | 2017/11/20 | [
"https://Stackoverflow.com/questions/47389508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2516399/"
] | Edit with a possible solution:
```
//our root app component
import {Component, NgModule, VERSION, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ElementRef,ViewChild} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div class="ui segment detail-container" (window:resize)="checkOverflow(span)">
<span class="title-container" role="heading">User details</span>
<div class="detail-group">
<div class="detail-element">
<span class="detail-label">Name</span>
<span class="detail-value">John</span>
</div>
<div class="detail-element">
<span class="detail-label">Surname</span>
<span class="detail-value">Smith</span>
</div>
</div>
<div class="detail-group">
<div class="detail-element">
<span class="detail-label">Description</span>
<span #span class="detail-value text-ellipsis">{{description}}</span>
</div>
<div class="ui mini compact buttons expand">
<button *ngIf="checkOverflow(span) && showMoreFlag" class="ui button" (click)="showMore($event)">Show more</button>
<button *ngIf="!showMoreFlag" class="ui button" (click)="showMore($event)">Show less</button>
</div>
</div>
</div>
`,
styleUrls: ['src/app.css']
})
export class App implements OnInit {
description: string = 'Lorem ipsum dolor sit a ';
showMoreFlag:boolean = true;
constructor() {
}
ngOnInit(): void {
this.overflowOcurs = this.checkOverflow(this.el.nativeElement);
}
showMore(event: any) {
this.showMoreFlag = !this.showMoreFlag;
$(event.target).parent().prev().find('.detail-value').toggleClass('text-ellipsis');
}
checkOverflow (element) {
if (element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth) {
return true;
} else {
return false;
}
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
```
Plunker working properly:
<https://plnkr.co/edit/HCd6ds5RBYvlcmUtdvKr> | I Recommend using the "ng2-truncate".
With this component, you can truncate your codes with length or word count or something else.
I hope this component help you.
[Plunker](https://embed.plnkr.co/d3JiQCw756OEjS0HkVuY)
[npm](https://www.npmjs.com/package/ng2-truncate) |
68,533,939 | I'm very new to python and need some help. I'm not sure if my question is the right terminology but I cant figure it out. I've tried .format f-string but I cant get it to work. The codes purpose is to ask a user to fill in a story. Edit: Forgot to Add character input. Forgot to add issue. Fixed Ty kind stranger!
This is the code
```
#Purpose: Ask a user to fill in a story
def main():
character = input("What do you want your character name to be?")
setting = input("Where do you want your story to take place?")
time = input("What year does the story take place?")
meaning = input("What is character doing?")
meaningTwo = input("What is the meaning for the characters actions?")
print(f"For character name you input {character}. For setting you said {setting}. For the year
you said {time}. Your character is {meaning}. The meaning for the characters actions is
{meaningTwo}.")
question = input("Is this correct (yes or no)")
if(question == "yes"):
print("Alright here is your story:")
print("Unfinished Story")
else:
print("Ok Goodbye")
main()
``` | 2021/07/26 | [
"https://Stackoverflow.com/questions/68533939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16530818/"
] | There is additional information on initialization strategies in the [paper](https://www.sciencedirect.com/science/article/abs/pii/S0098135415001179):
>
> Safdarnejad, S.M., Hedengren, J.D., Lewis, N.R., Haseltine, E.,
> Initialization Strategies for Optimization of Dynamic Systems,
> Computers and Chemical Engineering, Vol. 78, pp. 39-50, DOI:
> 10.1016/j.compchemeng.2015.04.016.
>
>
>
Here are a couple things to try:
* Start with a very small time step such as `m.time = np.linspace(0,1e-3,2)` to verify a successful solution.
* Switch to `m.options.IMODE=4` and `m.options.COLDSTART=2`. This also produces an infeasible solution in the first block.
* Eliminate divide-by-zero by rearranging the equations such as `x.dt()==1/y` to `y*x.dt()==1`.
* The value of `I` is undefined in the script.
* Try setting a lower bound of zero for all variables, especially those that shouldn't physically be negative.
* Try removing other non-physical bounds (upper bounds of 2.7?) to see if the problem becomes feasible.
```py
from gekko import GEKKO
import numpy as np
# Define constants and parameters of the system
# Will be updated in the future to work as variables or changing parameters
T = 298.0 # [K] Temperature of the cell
Iapp = 1.7 # [A] Single value for now
tMax = 3600 # [s] Simulation time
I = Iapp
# Physical constants
F = 9.64853399e4 # [sA/mol = C/mol] Faraday constant
R = 8.314462175 # [J/(K*mol)] Gas constant
NA = 6.0221412927e23 # [1/mol] Avogadro number
e = 1.60217656535e-19 # [C] Electron charge
ne = 4.0 # [] Electron number per reaction
ns8 = 8.0 # [] Number of sulfur atoms in the polysulfide
ns4 = 4.0 # [] Number of sulfur atoms in the polysulfide
ns2 = 2.0 # [] Number of sulfur atoms in the polysulfide
ns = 1.0 # [] Number of sulfur atoms in the polysulfide
Mm = 32.0 # [g/mol] Molecular mass of Sulfur
# Cell parameters
Eh0 = 2.195 # [V] Reference open circuit potential of high plateau (H)
El0 = 2.35 # [V] Reference OCP of low plateau (L)
ih0 = 0.96 # [A/m^2] Exchange current density in H
il0 = ih0/2 # [A/m^2] Echange current density in L
Ar = 0.96 # [m^2] Active reaction area of the cell
ms = 2.7 # [g] Mass of active sulfur on the cell
velyt = 0.0114 # [L] Electrolyte volume in the cell
fh = ns4**2*Mm*velyt/ns8 # [gL/mol] Dimensionality factor H
fl = ns**2*ns2*Mm**2*velyt**2/ns4 # [[g^2 L^2/mol]] Dimensionality factor L
# Precipitation and shuttle parameters
Vol = 0.0114e-3 # [m^3] Cell volume
RhoS = 2.0e6 # [g/m^3] Density of precipitated sulfur
Ksp = 0.0001 # [g] Saturation mass of sulfur in electrolyte
kp = 100.0 # [1/s] Precipitation/dissolution rate constant
ks = 0.0002 # [1/s] Shuttle rate constant
# REAL INITIAL (t = 0s) for discharge
S80 = 2.67300000000000 # [g] S80
S40 = 0.0128002860955374 # [g] S40
S20 = 4.33210229104915e-06 # [g] S20
S0 = 1.63210229104915e-06 # [g] S0
Sp0 = 2.70000000000000e-06 # [g] Sp0
Ih0 = 1.70000000000000 # [A] Ih0
Il0 = 0.00000 # [A] Il0
V0 = 2.40000000000000 # [V] V0
ETAh0 = -0.0102460242980059 # [V] ETAh0
ETAl0 = 0.00000 # [V] Etal0
Eh0 = 2.4102460242980059 # [V] Eh0
El0 = 2.40000000000000 # [V] El0
# Setup Gekko model
Model0D = GEKKO(remote=False) # create GEKKO model
Model0D.time = np.linspace(0,1e-3,2) #tMax,tMax)
# Define the variables of the problem
S8 = Model0D.Var(value=S80)
S4 = Model0D.Var(value=S40)
S2 = Model0D.Var(value=S20)
S = Model0D.Var(value=S0)
Sp = Model0D.Var(value=Sp0)
Ih = Model0D.Var(value=Ih0)
Il = Model0D.Var(value=Il0)
V = Model0D.Var(value=V0)
ETAh = Model0D.Var(value=ETAh0)
ETAl = Model0D.Var(value=ETAl0)
Eh = Model0D.Var(value=Eh0)
El = Model0D.Var(value=El0)
# Define all the equations of the system (DAE)
Model0D.Equation(S8.dt() == - Ih*(ns8*Mm)/(ne*F) - ks*S8)
Model0D.Equation(S4.dt() == Ih*(ns8*Mm)/(ne*F) + ks*S8 - Il*(ns4*Mm)/(ne*F))
Model0D.Equation(S2.dt() == Il*(ns2*Mm)/(ne*F))
Model0D.Equation(S.dt() == 2.0*Il*(ns*Mm)/(ne*F) - Sp*(kp/(Vol*RhoS))*(S-Ksp))
Model0D.Equation(Sp.dt() == Sp*(kp/(Vol*RhoS))*(S-Ksp))
Model0D.Equation(I == Ih + Il)
Model0D.Equation(Ih == 2.0*ih0*Ar*Model0D.sinh(ne*F*ETAh/(2.0*R*T)))
Model0D.Equation(Il == 2.0*il0*Ar*Model0D.sinh(ne*F*ETAl/(2.0*R*T)))
Model0D.Equation(ETAh == V - Eh)
Model0D.Equation(ETAl == V - El)
Model0D.Equation(Eh == Eh0 + (R*T/(4.0*F))*Model0D.log(fh*S8/S4**2.0))
Model0D.Equation(El == El0 + (R*T/(4.0*F))*Model0D.log(fl*S4/(S2*S**2.0)))
# Set model options
Model0D.options.IMODE = 4 # Set model type (simulation -> 4-simultaneous 7-sequential)
Model0D.options.COLDSTART=2
Model0D.options.SOLVER=1
# Solve model
Model0D.open_folder()
Model0D.solve(disp=True)
```
This didn't make the problem feasible but may help with the search. The `infeasibilities.txt` file can also help. It is available when solving with `remote=False` in the run directory `m.path` or by opening the run directory with `m.open_folder()` (before the `m.solve()` command). It is more readable if the variables are named such as `x = m.Var(name='x')`. | I have tried to use this model as a subject to learn the GEKKO ().
I advise on using `I=Model0D.intermediate()` instead of;
```
Model0D.Equation(ETAh == V - Eh)
Model0D.Equation(ETAl == V - El)
```
Also the time step are very large, creating unstable solution. |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | I think the best and simplest way for you is that you have a view for creating `Form` and at the bottom of it put a `fieldset` to assign `FormFields` to it.
For the fieldset, you should have two partial views: One for create and another for edit. The partial view for creating should be something like this:
```
@model myPrj.Models.Form_FormFieldInfo
@{
var index = Guid.NewGuid().ToString();
string ln = (string)ViewBag.ListName;
string hn = ln + ".Index";
}
<tr>
<td>
<input type="hidden" name="@hn" value="@index" />
@Html.LabelFor(model => model.FormFieldID)
</td>
<td>
@Html.DropDownList(ln + "[" + index + "].FormFieldID",
new SelectList(new myPrj.Models.DbContext().FormFields, "ID", "FieldName"))
</td>
<td>
<input type="button" onclick="$(this).parent().parent().remove();"
value="Remove" />
</td>
</tr>
```
By calling this partial view in the create place view ajaxly, you can render some elements for each tag. Each line of elements contains a label, a DropDownList containing tags, and a remove button to simply remove the created elements.
In the create place view, you have a bare table which will contain those elements you create through the partial view:
```
<fieldset>
<legend>Form and FormFields</legend>
@Html.ValidationMessageFor(model => model.FormFields)</label>
<table id="tblFields"></table>
<input type="button" id="btnAddTag" value="Add new Field"/>
<img id="imgSpinnerl" src="~/Images/indicator-blue.gif" style="display:none;" />
</fieldset>
```
and you have the following script to create a line of elements for each tag:
```
$(document).ready(function () {
$("#btnAddField").click(function () {
$.ajax({
url: "/Controller/GetFormFieldRow/FormFields",
type: 'GET', dataType: 'json',
success: function (data, textStatus, jqXHR) {
$("#tblFields").append(jqXHR.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#tblFields").append(jqXHR.responseText);
},
beforeSend: function () { $("#imgSpinnerl").show(); },
complete: function () { $("#imgSpinnerl").hide(); }
});
});
});
```
The action method `GetFormFieldRow` is like the following:
```
public PartialViewResult GetFormFieldRow(string id = "")
{
ViewBag.ListName = id;
return PartialView("_FormFieldPartial");
}
```
and your done for the create... The whole solution for your question has many codes for views, partial views, controllers, ajax calls and model binding. I tried to just show you the way because I really can't to post all of them in this answer.
[Here](http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/) is the full info and how-to.
Hope that this answer be useful and lead the way for you. | The problem is that your partial view needs to use:
```
@model Form //Instead of FormField
```
and then inside of the partial view you must use model => model.**FormField**.x
```
<div class="editor-label">
@Html.LabelFor(model => model.FormField.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormField.Name)
@Html.ValidationMessageFor(model => model.FormField.Name)
</div>
```
This only works for one-to-one relationships (or so I read in this thread: [Here](https://stackoverflow.com/questions/16447616/mvc-4-add-update-list-in-a-partial-view)). It also does not matter if you have @Html.Form inside of the partial view.
After making those changes I had no problem getting all of the posted data back to the controller.
**EDIT:** I've run into problems with this as anyone would soon figure out.
The better way to do this (that I've seen) is instead use an EditorTemplate. This way the editor stays independent of the Parent, and you can add a *Form* on any page, not simply a page where you are also adding a FormField.
You would then replace
```
@Html.Partial("view")
```
with
```
@Html.EditorFor()
```
Basically, I've found out that it's far better to use an @Html.EditorFor instead of a partial view when doing editing (It is called a view - not an editor). |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | You can use @Html.RenderPartial(\_CreateFormField.cshtml) htlper method inside your parent cshtml page.
For mode info, <http://msdn.microsoft.com/en-us/library/dd492962(v=vs.118).aspx>
I am providing an pseudo code example,
```
@Foreach(childModel in model.FormFields)
{
@Html.RenderPartial("childView.cshtml","Name", childModel)
}
```
Please try it in proper c# syntactical way and you will get your partial views rendered for each collection item. | The problem is that your partial view needs to use:
```
@model Form //Instead of FormField
```
and then inside of the partial view you must use model => model.**FormField**.x
```
<div class="editor-label">
@Html.LabelFor(model => model.FormField.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormField.Name)
@Html.ValidationMessageFor(model => model.FormField.Name)
</div>
```
This only works for one-to-one relationships (or so I read in this thread: [Here](https://stackoverflow.com/questions/16447616/mvc-4-add-update-list-in-a-partial-view)). It also does not matter if you have @Html.Form inside of the partial view.
After making those changes I had no problem getting all of the posted data back to the controller.
**EDIT:** I've run into problems with this as anyone would soon figure out.
The better way to do this (that I've seen) is instead use an EditorTemplate. This way the editor stays independent of the Parent, and you can add a *Form* on any page, not simply a page where you are also adding a FormField.
You would then replace
```
@Html.Partial("view")
```
with
```
@Html.EditorFor()
```
Basically, I've found out that it's far better to use an @Html.EditorFor instead of a partial view when doing editing (It is called a view - not an editor). |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | I think the best and simplest way for you is that you have a view for creating `Form` and at the bottom of it put a `fieldset` to assign `FormFields` to it.
For the fieldset, you should have two partial views: One for create and another for edit. The partial view for creating should be something like this:
```
@model myPrj.Models.Form_FormFieldInfo
@{
var index = Guid.NewGuid().ToString();
string ln = (string)ViewBag.ListName;
string hn = ln + ".Index";
}
<tr>
<td>
<input type="hidden" name="@hn" value="@index" />
@Html.LabelFor(model => model.FormFieldID)
</td>
<td>
@Html.DropDownList(ln + "[" + index + "].FormFieldID",
new SelectList(new myPrj.Models.DbContext().FormFields, "ID", "FieldName"))
</td>
<td>
<input type="button" onclick="$(this).parent().parent().remove();"
value="Remove" />
</td>
</tr>
```
By calling this partial view in the create place view ajaxly, you can render some elements for each tag. Each line of elements contains a label, a DropDownList containing tags, and a remove button to simply remove the created elements.
In the create place view, you have a bare table which will contain those elements you create through the partial view:
```
<fieldset>
<legend>Form and FormFields</legend>
@Html.ValidationMessageFor(model => model.FormFields)</label>
<table id="tblFields"></table>
<input type="button" id="btnAddTag" value="Add new Field"/>
<img id="imgSpinnerl" src="~/Images/indicator-blue.gif" style="display:none;" />
</fieldset>
```
and you have the following script to create a line of elements for each tag:
```
$(document).ready(function () {
$("#btnAddField").click(function () {
$.ajax({
url: "/Controller/GetFormFieldRow/FormFields",
type: 'GET', dataType: 'json',
success: function (data, textStatus, jqXHR) {
$("#tblFields").append(jqXHR.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#tblFields").append(jqXHR.responseText);
},
beforeSend: function () { $("#imgSpinnerl").show(); },
complete: function () { $("#imgSpinnerl").hide(); }
});
});
});
```
The action method `GetFormFieldRow` is like the following:
```
public PartialViewResult GetFormFieldRow(string id = "")
{
ViewBag.ListName = id;
return PartialView("_FormFieldPartial");
}
```
and your done for the create... The whole solution for your question has many codes for views, partial views, controllers, ajax calls and model binding. I tried to just show you the way because I really can't to post all of them in this answer.
[Here](http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/) is the full info and how-to.
Hope that this answer be useful and lead the way for you. | If you want to use grid based layout you may want to try [Kendo UI grid](http://demos.telerik.com/kendo-ui/grid/detailtemplate) |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | I think the best and simplest way for you is that you have a view for creating `Form` and at the bottom of it put a `fieldset` to assign `FormFields` to it.
For the fieldset, you should have two partial views: One for create and another for edit. The partial view for creating should be something like this:
```
@model myPrj.Models.Form_FormFieldInfo
@{
var index = Guid.NewGuid().ToString();
string ln = (string)ViewBag.ListName;
string hn = ln + ".Index";
}
<tr>
<td>
<input type="hidden" name="@hn" value="@index" />
@Html.LabelFor(model => model.FormFieldID)
</td>
<td>
@Html.DropDownList(ln + "[" + index + "].FormFieldID",
new SelectList(new myPrj.Models.DbContext().FormFields, "ID", "FieldName"))
</td>
<td>
<input type="button" onclick="$(this).parent().parent().remove();"
value="Remove" />
</td>
</tr>
```
By calling this partial view in the create place view ajaxly, you can render some elements for each tag. Each line of elements contains a label, a DropDownList containing tags, and a remove button to simply remove the created elements.
In the create place view, you have a bare table which will contain those elements you create through the partial view:
```
<fieldset>
<legend>Form and FormFields</legend>
@Html.ValidationMessageFor(model => model.FormFields)</label>
<table id="tblFields"></table>
<input type="button" id="btnAddTag" value="Add new Field"/>
<img id="imgSpinnerl" src="~/Images/indicator-blue.gif" style="display:none;" />
</fieldset>
```
and you have the following script to create a line of elements for each tag:
```
$(document).ready(function () {
$("#btnAddField").click(function () {
$.ajax({
url: "/Controller/GetFormFieldRow/FormFields",
type: 'GET', dataType: 'json',
success: function (data, textStatus, jqXHR) {
$("#tblFields").append(jqXHR.responseText);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#tblFields").append(jqXHR.responseText);
},
beforeSend: function () { $("#imgSpinnerl").show(); },
complete: function () { $("#imgSpinnerl").hide(); }
});
});
});
```
The action method `GetFormFieldRow` is like the following:
```
public PartialViewResult GetFormFieldRow(string id = "")
{
ViewBag.ListName = id;
return PartialView("_FormFieldPartial");
}
```
and your done for the create... The whole solution for your question has many codes for views, partial views, controllers, ajax calls and model binding. I tried to just show you the way because I really can't to post all of them in this answer.
[Here](http://ivanz.com/2011/06/16/editing-variable-length-reorderable-collections-in-asp-net-mvc-part-1/) is the full info and how-to.
Hope that this answer be useful and lead the way for you. | Use jQueryto add FormField on click of button.
Similar I've used it as follows
```
<div class="accomp-multi-field-wrapper">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>FormId</th>
<th>Remove</th>
</tr>
</thead>
<tbody class="accomp-multi-fields">
<tr class="multi-field">
<td> <input name="FormFields[0].Name" type="text" value=""></td>
<td> <input name="FormFields[0].FormId" type="text" value=""></td>
<td> <button type="button" class="remove-field">X</button></td>
</tr>
</tbody>
<tr>
<th><button type="button" class="add-field btn btn-xs btn-primary addclr"><i class="fa fa-plus"></i> Add field</button> </th>
</tr>
</table>
</div>
```
and jQuery is as follows for adding field and removing
```
<script>
$('.accomp-multi-field-wrapper').each(function () {
var $wrapper = $('.accomp-multi-fields', this);
$(".add-field", $(this)).click(function (e) {
var $len = $('.multi-field', $wrapper).length;
$('.multi-field:first-child', $wrapper).clone(false, true).appendTo($wrapper).find('select,input,span').val('').each(function () {
$(this).attr('name', $(this).attr('name').replace('\[0\]', '\[' + $len + '\]'));
});
$(document).on("click",'.multi-field .remove-field', function () {
if ($('.multi-field', $wrapper).length > 1) {
$(this).closest('tr').remove();
//
$('.multi-field', $wrapper).each(function (indx) {
$(this).find('input,select,span').each(function () {
$(this).attr('name', $(this).attr('name').replace(/\d+/g, indx));
})
})
}
});
</script>
```
Hope so this is going to help you. |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | You can use @Html.RenderPartial(\_CreateFormField.cshtml) htlper method inside your parent cshtml page.
For mode info, <http://msdn.microsoft.com/en-us/library/dd492962(v=vs.118).aspx>
I am providing an pseudo code example,
```
@Foreach(childModel in model.FormFields)
{
@Html.RenderPartial("childView.cshtml","Name", childModel)
}
```
Please try it in proper c# syntactical way and you will get your partial views rendered for each collection item. | If you want to use grid based layout you may want to try [Kendo UI grid](http://demos.telerik.com/kendo-ui/grid/detailtemplate) |
14,548,727 | My MVC application has a classic parent-child (master-detail) relations.
I want to have a single page that create both the new parent and the children on the same page. I have added an action the returns a partial view that and adds the child HTML to the parent’s view, but I don’t know how to associate the newly created child in the action to the original parent (in other word, how to I add the new child entity to the collection of these entities in the parent entity).
I guess that when I submit the form the action should get the parent entity with the newly created children in its collection.
So to make things short, what should be the code of the action that creates the child entity and how is the child added to its parent collection?
I have read a lot of posts here (and other sites) and couldn’t find an example.
The application uses MVC 4 and Entity Framework 5.
Code sample (I removed some of the code the keep it simple).
The model is Form (parent) and FormField (child) entities.
```
public partial class Form
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<FormField> FormFields { get; set; }
}
public partial class FormField
{
public int ID { get; set; }
public string Name { get; set; }
public int FormID { get; set; }
}
```
The following partial view (\_CreateFormField.cshtml) creates new FormField (child).
```
@model FormField
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>FormField</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FormID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FormID)
@Html.ValidationMessageFor(model => model.FormID)
</div>
</fieldset>
}
```
And the following view (Create.cshtml) is the one the creates the Form.
```
@model Form
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Form</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div>
@Html.ActionLink(
"Add Field",
"CreateFormField",
new { id = -1},
new { @class = "form-field" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
<div id="CreateFormField"></div>
@section Scripts {
<script>
$(function () {
$('.form-field').on('click', function (e) {
$.get($(this).prop('href'), function (response) {
$('#CreateFormField').append(response)
});
e.preventDefault();
});
});
</script>
@Scripts.Render("~/bundles/jqueryval")
}
```
The following actions handle the creation in the FormController.
```
[HttpPost]
public ActionResult Create(Form form)
{
if (ModelState.IsValid)
{
db.Forms.Add(form);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
public ActionResult CreateFormField(string id = null)
{
// I guess something is missing here.
return PartialView("_CreateFormField", new FormField());
}
```
Thanks in advance,
Sharon. | 2013/01/27 | [
"https://Stackoverflow.com/questions/14548727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2015251/"
] | You can use @Html.RenderPartial(\_CreateFormField.cshtml) htlper method inside your parent cshtml page.
For mode info, <http://msdn.microsoft.com/en-us/library/dd492962(v=vs.118).aspx>
I am providing an pseudo code example,
```
@Foreach(childModel in model.FormFields)
{
@Html.RenderPartial("childView.cshtml","Name", childModel)
}
```
Please try it in proper c# syntactical way and you will get your partial views rendered for each collection item. | Use jQueryto add FormField on click of button.
Similar I've used it as follows
```
<div class="accomp-multi-field-wrapper">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>FormId</th>
<th>Remove</th>
</tr>
</thead>
<tbody class="accomp-multi-fields">
<tr class="multi-field">
<td> <input name="FormFields[0].Name" type="text" value=""></td>
<td> <input name="FormFields[0].FormId" type="text" value=""></td>
<td> <button type="button" class="remove-field">X</button></td>
</tr>
</tbody>
<tr>
<th><button type="button" class="add-field btn btn-xs btn-primary addclr"><i class="fa fa-plus"></i> Add field</button> </th>
</tr>
</table>
</div>
```
and jQuery is as follows for adding field and removing
```
<script>
$('.accomp-multi-field-wrapper').each(function () {
var $wrapper = $('.accomp-multi-fields', this);
$(".add-field", $(this)).click(function (e) {
var $len = $('.multi-field', $wrapper).length;
$('.multi-field:first-child', $wrapper).clone(false, true).appendTo($wrapper).find('select,input,span').val('').each(function () {
$(this).attr('name', $(this).attr('name').replace('\[0\]', '\[' + $len + '\]'));
});
$(document).on("click",'.multi-field .remove-field', function () {
if ($('.multi-field', $wrapper).length > 1) {
$(this).closest('tr').remove();
//
$('.multi-field', $wrapper).each(function (indx) {
$(this).find('input,select,span').each(function () {
$(this).attr('name', $(this).attr('name').replace(/\d+/g, indx));
})
})
}
});
</script>
```
Hope so this is going to help you. |
195,770 | I need to build up a sentence saying like this "She has no false pride like other actresses, she replies to every message sent by her fans". I need to emphasize that she has no false pride like other actresses. Much appreciated if someone can build a better sentence than mine. thanks. | 2014/09/10 | [
"https://english.stackexchange.com/questions/195770",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/93075/"
] | Celebrities are sometimes
[egotistical](http://www.thefreedictionary.com/egotistical): characteristic of those having an *inflated idea of their own importance*; A *conceited*, boastful person.
[conceited](http://www.thefreedictionary.com/conceited): having a high or exaggerated opinion of oneself or one's accomplishments; *vain*
or [smug](http://www.thefreedictionary.com/smug): contentedly confident of one's ability, superiority, or correctness; complacent.
or [snobbish](http://www.thefreedictionary.com/snobbish) - befitting or characteristic of those who incline to social exclusiveness and who rebuff the advances of people considered inferior
(TFD) | I think [conceit](http://www.thefreedictionary.com/Conceit) or vanity, may convey the idea:
>
> * a high, often exaggerated, opinion of oneself or one's accomplishments, [vanity](http://www.thefreedictionary.com/vanity).
>
>
>
Source: /www.thefreedictionary.com |
195,770 | I need to build up a sentence saying like this "She has no false pride like other actresses, she replies to every message sent by her fans". I need to emphasize that she has no false pride like other actresses. Much appreciated if someone can build a better sentence than mine. thanks. | 2014/09/10 | [
"https://english.stackexchange.com/questions/195770",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/93075/"
] | Celebrities are sometimes
[egotistical](http://www.thefreedictionary.com/egotistical): characteristic of those having an *inflated idea of their own importance*; A *conceited*, boastful person.
[conceited](http://www.thefreedictionary.com/conceited): having a high or exaggerated opinion of oneself or one's accomplishments; *vain*
or [smug](http://www.thefreedictionary.com/smug): contentedly confident of one's ability, superiority, or correctness; complacent.
or [snobbish](http://www.thefreedictionary.com/snobbish) - befitting or characteristic of those who incline to social exclusiveness and who rebuff the advances of people considered inferior
(TFD) | **hubris** - defined by Google dictionary as: excessive pride or self-confidence, and in Greek tragedy an excessive pride toward or defiance of the gods, leading to nemesis.
So there is a hint with this word that such pride will lead to a humilating fall in time. |
60,448 | I have a multi-class classification problem. It performs quite well but on the least represented classes it doesn't. Indeed, here is the distribution :
[](https://i.stack.imgur.com/YXUYI.png)
And here are the classification results of my former classification (I took the numbers off the labels):
[](https://i.stack.imgur.com/aB4Tj.png).
Therefore I tried to improve classificationby downsampling the marjority classes
```
import os
from sklearn.utils import resample
# rebalance data
#df = resample_data(df)
if True:
count_class_A, count_class_B,count_class_C, count_class_D,count_class_E, count_class_F, count_class_G = df.grade.value_counts()
count_df = df.shape[0]
class_dict = {"A": count_class_A,"B" :count_class_B,"C": count_class_C,"D": count_class_D,"E": count_class_E, "F": count_class_F, "G": count_class_G}
counts = [count_class_A, count_class_B,count_class_C, count_class_D,count_class_E, count_class_F, count_class_G]
median = statistics.median(counts)
for key in class_dict:
if class_dict[key]>median:
print(key)
df[df.grade == key] = df[df.grade == key].sample(int(count_df/7), replace = False)
#replace=False, # sample without replacement
#n_samples=int(count_df/7), # to match minority class
#random_state=123)
# Divide the data set into training and test sets
x_train, x_test, y_train, y_test = split_data(df, APPLICANT_NUMERIC + CREDIT_NUMERIC,
APPLICANT_CATEGORICAL,
TARGET,
test_size = 0.2,
#row_limit = os.environ.get("sample"))
row_limit = 552160)
```
However it the results where catastrophic. The model accuracy and the model loss looked to have some issues :
[](https://i.stack.imgur.com/v7sXg.png)
And everything was classified in "A" on the test set. | 2019/09/19 | [
"https://datascience.stackexchange.com/questions/60448",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/41692/"
] | Going according to your problem, you should set the NaN values to 0. It follows logically as the number of minutes spent with the nurse or doctor will be zero if the patient hasn't visited them yet. And yes as you said filling with mean is not correct as it would not represent the problem correctly.
Also, if you fill the NaN values with big number such as 9999 they might be treated as outliers which is not the case. Hence, purely thinking from a logical point of view you should replace them with 0. But I also suggest you to run trial experiments with some other values such as large values. Machine Learning is a lot about hyperparameter tuning and in this case how you replace your NaN values behaves like a hyperparameter! | This is a feature engineering problem. That patients have not been visited yet is valuable informationen but also clearly not on the same scale as minutes until visit.
Create a new categorical variable 1=visited and 0=not visited.
Additionally instead of imputation try using a model that can cope with NA like randomforest or XGB. |
17,111,247 | I need to retrieve a number version from database to add this as dll version.
I can add manually this version each time I publish, but I'll like to run this in an automatic process.
So, is it possible at compile time to execute a SQL or any operation to get this number ?
Thanks for your help. | 2013/06/14 | [
"https://Stackoverflow.com/questions/17111247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/255673/"
] | You could write a small simple application (command line) that looks up the version or build number and replaces it in the appropriate file.
Then you could add it as a pre-build event to your Visual Studio project. | ```
is it possible at compile time to execute a SQL or any operation
to get this number
```
No you cannot call SQL at compile time. Compiling is purely for creating MSIL (dll or exe) to be executed later by the CLR. All work is performed by the JIT compiler of the CLR (which is at runtime). No work can be done at compile time.
However, you could add a pre build event (that would happen before the compilation), which gets data and writes it into a config file. The app can read the version number from here.
 |
36,894,357 | I'm trying to map a column name dynamically in Dataweave using the contents of a flow variable. The static version of what I'm trying to achieve looks something like:
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01.INPUTA
})
```
Now the part that I need to be dynamic is `INPUTA` - I need the `A` to be derived from a flow variable that is set prior to the Dataweave component. I've tried something like:
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01.INPUT#flowVars['varName']
})
```
But I'm getting a `com.mulesoft.weave.grammar.InvalidNamespacePrefixException` error.
Is this possible to achieve in Dataweave? Can't seem to find any relevant docs describing how. | 2016/04/27 | [
"https://Stackoverflow.com/questions/36894357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3327896/"
] | Use it like below. Note the parenthesis around key which is very important because () tells DataWeave to first execute script inside it and then use the result as the value for outside expression.
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01[('INPUT' ++ flowVars.varName)]
})
```
Let me know that doesn't work.
I see your key name is COLUMNA, you can also append varName to key by using (). | Try to access flowVar just like MEL way: `#[flowVars.varName]`, donot prefix with `payload01` |
36,894,357 | I'm trying to map a column name dynamically in Dataweave using the contents of a flow variable. The static version of what I'm trying to achieve looks something like:
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01.INPUTA
})
```
Now the part that I need to be dynamic is `INPUTA` - I need the `A` to be derived from a flow variable that is set prior to the Dataweave component. I've tried something like:
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01.INPUT#flowVars['varName']
})
```
But I'm getting a `com.mulesoft.weave.grammar.InvalidNamespacePrefixException` error.
Is this possible to achieve in Dataweave? Can't seem to find any relevant docs describing how. | 2016/04/27 | [
"https://Stackoverflow.com/questions/36894357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3327896/"
] | Use it like below. Note the parenthesis around key which is very important because () tells DataWeave to first execute script inside it and then use the result as the value for outside expression.
```
payload map ((payload01 , indexOfPayload01) -> {
COLUMNA: payload01[('INPUT' ++ flowVars.varName)]
})
```
Let me know that doesn't work.
I see your key name is COLUMNA, you can also append varName to key by using (). | From Dataweave you have to access the flowvars or session vars as given below.
flowVars.varName
sessionVars.varName
You can use various Dataweave operators to form final field names or value.
Understanding Dataweave Operators is crucial to to make best use of Dataweave component. Please go through the link below for a understanding of Dataweave operators.
<https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators> |
325,407 | Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.
hopefully the example below helps
say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.
i return an array of persons back
my code snippet will be something like
```
dim v = from p in persons.. select p.fname,p.lname
```
i now have an anonymous type from system.collections.generic.ineumerable(of t)
to bind this to a grid i would have to iterate and add to an array
e.g.
```
dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
```
i dont want to do the iteration continually as i might have different objects
i would like a function which does something like below:
```
function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
```
hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.
many thanks in advance as any and all pointers/help will be VASTLY appreciated.
regards
azad | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Your question is a little unclear, so I'm not sure how much my answers will help, but here goes...
* [An anonymous type has method scope](http://msdn.microsoft.com/en-us/library/bb397696.aspx) so you cannot return it from a function, at least not in a strongly-typed manner. [You can cast to `object` and then back to a re-creation of your anonymous type](http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx), but you'd be better off declaring a simple class with some [automatic properties](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx).
* To convert an `IEnumerable` to an array, just call `ToArray()`
* However, you can `DataBind` to an `IEnumerable` directly, no need to convert it to an array
* If the data you are dealing with can have different fields then you might be best off creating a `DataTable` and binding that to your DataGrid. | I'm not sure that you can easily pass anonymous objects as parameters, anymore than you can have them as return values.
I say easily, because:
* <http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx>
* <http://blog.decarufel.net/2007/11/passing-anonymous-to-and-from-methods.html>
*[Try the code formatting option on your question (the " button in the editor), it would make it easier to read the parts of your question which are code snippets.]* |
325,407 | Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.
hopefully the example below helps
say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.
i return an array of persons back
my code snippet will be something like
```
dim v = from p in persons.. select p.fname,p.lname
```
i now have an anonymous type from system.collections.generic.ineumerable(of t)
to bind this to a grid i would have to iterate and add to an array
e.g.
```
dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
```
i dont want to do the iteration continually as i might have different objects
i would like a function which does something like below:
```
function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
```
hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.
many thanks in advance as any and all pointers/help will be VASTLY appreciated.
regards
azad | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You'd just call [ToArray](http://msdn.microsoft.com/en-us/library/bb298736.aspx). Sure, the type is anonymous... but because of type inference, you don't have to say the type's name.
From the example code:
```
packages _
.Select(Function(pkg) pkg.Company) _
.ToArray()
```
Company happens to be string, but there's no reason it couldn't be anything else. | Your question is a little unclear, so I'm not sure how much my answers will help, but here goes...
* [An anonymous type has method scope](http://msdn.microsoft.com/en-us/library/bb397696.aspx) so you cannot return it from a function, at least not in a strongly-typed manner. [You can cast to `object` and then back to a re-creation of your anonymous type](http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx), but you'd be better off declaring a simple class with some [automatic properties](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx).
* To convert an `IEnumerable` to an array, just call `ToArray()`
* However, you can `DataBind` to an `IEnumerable` directly, no need to convert it to an array
* If the data you are dealing with can have different fields then you might be best off creating a `DataTable` and binding that to your DataGrid. |
325,407 | Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.
hopefully the example below helps
say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.
i return an array of persons back
my code snippet will be something like
```
dim v = from p in persons.. select p.fname,p.lname
```
i now have an anonymous type from system.collections.generic.ineumerable(of t)
to bind this to a grid i would have to iterate and add to an array
e.g.
```
dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
```
i dont want to do the iteration continually as i might have different objects
i would like a function which does something like below:
```
function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
```
hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.
many thanks in advance as any and all pointers/help will be VASTLY appreciated.
regards
azad | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can bind a grid directly to the array of anonymous types. Here's an example:
```
var qry = from a in Enumerable.Range(0, 100)
select new { SomeField1 = a, SomeField2 = a * 2, SomeField3 = a * 3 };
object[] objs = qry.ToArray();
dataGridView1.DataSource = objs;
```
Note also the call to ToArray, which eliminates the need for a loop. I also assign it to a type of object[] to demonstrate that you could pass that around as its type if you want. | Your question is a little unclear, so I'm not sure how much my answers will help, but here goes...
* [An anonymous type has method scope](http://msdn.microsoft.com/en-us/library/bb397696.aspx) so you cannot return it from a function, at least not in a strongly-typed manner. [You can cast to `object` and then back to a re-creation of your anonymous type](http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx), but you'd be better off declaring a simple class with some [automatic properties](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx).
* To convert an `IEnumerable` to an array, just call `ToArray()`
* However, you can `DataBind` to an `IEnumerable` directly, no need to convert it to an array
* If the data you are dealing with can have different fields then you might be best off creating a `DataTable` and binding that to your DataGrid. |
325,407 | Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.
hopefully the example below helps
say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.
i return an array of persons back
my code snippet will be something like
```
dim v = from p in persons.. select p.fname,p.lname
```
i now have an anonymous type from system.collections.generic.ineumerable(of t)
to bind this to a grid i would have to iterate and add to an array
e.g.
```
dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
```
i dont want to do the iteration continually as i might have different objects
i would like a function which does something like below:
```
function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
```
hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.
many thanks in advance as any and all pointers/help will be VASTLY appreciated.
regards
azad | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You'd just call [ToArray](http://msdn.microsoft.com/en-us/library/bb298736.aspx). Sure, the type is anonymous... but because of type inference, you don't have to say the type's name.
From the example code:
```
packages _
.Select(Function(pkg) pkg.Company) _
.ToArray()
```
Company happens to be string, but there's no reason it couldn't be anything else. | I'm not sure that you can easily pass anonymous objects as parameters, anymore than you can have them as return values.
I say easily, because:
* <http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx>
* <http://blog.decarufel.net/2007/11/passing-anonymous-to-and-from-methods.html>
*[Try the code formatting option on your question (the " button in the editor), it would make it easier to read the parts of your question which are code snippets.]* |
325,407 | Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.
hopefully the example below helps
say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.
i return an array of persons back
my code snippet will be something like
```
dim v = from p in persons.. select p.fname,p.lname
```
i now have an anonymous type from system.collections.generic.ineumerable(of t)
to bind this to a grid i would have to iterate and add to an array
e.g.
```
dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
```
i dont want to do the iteration continually as i might have different objects
i would like a function which does something like below:
```
function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
```
hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.
many thanks in advance as any and all pointers/help will be VASTLY appreciated.
regards
azad | 2008/11/28 | [
"https://Stackoverflow.com/questions/325407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can bind a grid directly to the array of anonymous types. Here's an example:
```
var qry = from a in Enumerable.Range(0, 100)
select new { SomeField1 = a, SomeField2 = a * 2, SomeField3 = a * 3 };
object[] objs = qry.ToArray();
dataGridView1.DataSource = objs;
```
Note also the call to ToArray, which eliminates the need for a loop. I also assign it to a type of object[] to demonstrate that you could pass that around as its type if you want. | I'm not sure that you can easily pass anonymous objects as parameters, anymore than you can have them as return values.
I say easily, because:
* <http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx>
* <http://blog.decarufel.net/2007/11/passing-anonymous-to-and-from-methods.html>
*[Try the code formatting option on your question (the " button in the editor), it would make it easier to read the parts of your question which are code snippets.]* |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | We **sketch** a proof. For my comfort, I will use $a$ and $b$ instead of $x$ and $y$. Sorry! So we show that every $n\ge (a-1)(b-1)$ is representable in the form $au + bv$ with $u$ and $v$ being nonnegative integers.
**1.** Because $a$ and $b$ are relatively prime, there exist integers $x\_0,y\_0$ (not necessarily both $\ge 0$) such that $ax\_0+by\_0=1$. Thus (multiplying through by $n$) we find that there exist integers $x\_1,y\_1$ such that $ax\_1+by\_1=n$.
**2.** Infinitely many solutions of the equation $ax+by=n$ are given by $x=x\_1-tb$, $y=y\_1+ta$, where $t$ ranges over the integers. (Actually these are all solutions, but we won't need this.)
**3.** Let $t$ be the **smallest** positive integer such that $y\_1+ta\ge 0$. We show that $x\_1-tb\ge 0$. We have
$$a(x\_1-tb)+b(y\_1+ta)=n \ge (a-1)(b-1),$$
thus
$$a(x\_1-tb) \ge (a-1)(b-1) - b(y\_1+ta).$$
But $y\_1+ta\le a-1$, else we could decrement $t$.
Thus
$$a(x\_1-tb)\ge (a-1)(b-1)-b(a-1) = -(a-1) > -a,$$
and therefore $x\_1-tb> -1$, so that $x\_1-tb \geq 0$ (since $x\_1-tb \in \mathbb{Z}$). So we have produced the required non-negative solution. | Let me show another proof of this elementary problem (in terms of $a$ and $b$ as constants and $x$, $y$ as variables).
Let $i$ be the least (non-negative) residue of $y$ modulo $a$. Then one can rewrite the form $ax+by$ as $ax+b(i+az)=bi+a(x+bz)$. Given $0 \leq i \leq a-1$, we obtain the sequence $bi+an$, $n\geq 0$, of integers, which can be represented by the form (and only elements of these sequences possess this property).
Suppose that $a$ and $b$ are coprime positive integers. It follows from the extended Euclidean algorithm that $b$ is an invertible element of $\mathbb{Z}/a\mathbb{Z}$. Therefore, the multiplication by $b$ is an automorphism of the ring $\mathbb{Z}/a\mathbb{Z}$. Thus, all $bi$'s are distinct modulo $a$, i.e. two different sequences contain no common elements.
Note that the smallest element of each of these sequence is less than or equal to $b(a-1)$, i.e. they "begin" not later than this "moment". Obviously, any integer $N \geq b(a-1)$ appears in exactly one of those sequence. Moreover, the sequence that corresponds to $b(a-1)+m$, $0<m \leq a-1$, contains $b(a-1)+m-a \geq b(a-2)$, since it begins not later than $b(a-2)$. Thus, any integer $N \geq b(a-1) + 1 - a = (a-1)(b-1)$ can be represented by the form.
It suffices to see that $ax+by=(a-1)(b-1)-1$ has no non-negative solutions. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | This problem is similar to the "coin problem", where you need to find the smallest integer from which every integer can be obtained with a linear combination of the values of your coins with positive coefficients.
For your problem with 2 numbers (aka 2 coin values), a solution can be found here : <http://www.cut-the-knot.org/blue/Sylvester.shtml#solution> | Let me show another proof of this elementary problem (in terms of $a$ and $b$ as constants and $x$, $y$ as variables).
Let $i$ be the least (non-negative) residue of $y$ modulo $a$. Then one can rewrite the form $ax+by$ as $ax+b(i+az)=bi+a(x+bz)$. Given $0 \leq i \leq a-1$, we obtain the sequence $bi+an$, $n\geq 0$, of integers, which can be represented by the form (and only elements of these sequences possess this property).
Suppose that $a$ and $b$ are coprime positive integers. It follows from the extended Euclidean algorithm that $b$ is an invertible element of $\mathbb{Z}/a\mathbb{Z}$. Therefore, the multiplication by $b$ is an automorphism of the ring $\mathbb{Z}/a\mathbb{Z}$. Thus, all $bi$'s are distinct modulo $a$, i.e. two different sequences contain no common elements.
Note that the smallest element of each of these sequence is less than or equal to $b(a-1)$, i.e. they "begin" not later than this "moment". Obviously, any integer $N \geq b(a-1)$ appears in exactly one of those sequence. Moreover, the sequence that corresponds to $b(a-1)+m$, $0<m \leq a-1$, contains $b(a-1)+m-a \geq b(a-2)$, since it begins not later than $b(a-2)$. Thus, any integer $N \geq b(a-1) + 1 - a = (a-1)(b-1)$ can be represented by the form.
It suffices to see that $ax+by=(a-1)(b-1)-1$ has no non-negative solutions. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | **Key Idea** $ $ In the plane $\,\mathbb R^2,\,$ a line $\rm\,a\,x+b\,y = c\,$ of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ is in the first quadrant, i.e. $\,\rm y\_0 \ge 0\,.$ We can use an analogous "normalized" point test to check if a discrete line $\rm\,m\,x + n\,y = k\,$ has points in the first quadrant.
**Hint** $\ $ Normalize $\rm\,k = m\, x + n\, y\,$ so $\rm\,0 \le x < n\,$
by adding a multiple of $\rm\,(-n,m)\,$ to $\rm\,(x,y)$
**Lemma** $\rm\ \ k = m\ x + n\ y\,$ for some integers $\rm\,x,\,y \ge 0\,$
$\iff$ its normalization has $\rm\,y \ge 0.$
**Proof** $\ (\Rightarrow)\ $ If $\rm\ x,\, y \ge 0\,$ normalizing adds $\rm\,(-n,m)\,$ zero or more times, preserving $\rm\,y \ge 0\,.\,$
$(\Leftarrow)\ \,$ If the normalized rep has $\rm\ y < 0,\,$ then $\rm\,k\,$ has no representation with $\rm\, x,\,y \ge 0\,\, $ since to shift so that $\rm\,y > 0\,$
we must add $\rm\,(-n,m)\,$ at least once, which forces $\rm\,x < 0,\,$ by $\rm\,0\le x < n.\ \ \ $ **QED**
To solve the OP, note that since $\rm\, k = m\ x + n\ y\, $ is increasing in both $\rm\,x\,$ and $\rm\,y,\,$ it is clear that the largest non-representable $\rm\,k\,$ has normalization $\rm\,(x,y) = (n\!-\!1,-1),\,$ i.e. the lattice point that is rightmost (max $\rm\,x$) and topmost (max $\rm\,y$) in the nonrepresentable lower half $\rm (y < 0)$ of the normalized strip, i.e. the vertical strip where $\rm\, 0\le x \le n-1.\,$ Thus $\rm\,(x,y) = (\color{#0a0}{n\!-\!1},\color{#c00}{-1})\,$ yields that $\rm\, k = mx+ny = m\,(\color{#0a0}{n\!-\!1})+n\,(\color{#c00}{-1}) = mn\! -\! m\! -\! n\ $ is the largest nonrepresentable integer. $\ $ **QED**
Notice that the proof has a vivid geometric picture:
representations of $\rm\,k\,$ correspond to lattice points $\rm\,(x,y)\,$
on the line $\rm\, n\ y + m\ x = k\,$ with negative slope $\rm\, = -m/n\,.\,$
Normalization is achieved by shifting forward/backward
along the line by integral multiples of the vector $\rm\,(-n,m)\,$
until one lands in the normal strip where $\rm\,0 \le x \le n-1.\,$ If the normalized rep has $\rm\,y\ge 0\,$ then we are done; otherwise, by the lemma, $\rm\,k\,$ has no rep with both $\rm\,x,y\ge 0\,.\,$ This result may be viewed as a discrete analog of the fact that, in the plane $\,\mathbb R^2,\,$ a line of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ lies in the first quadrant, i.e. $\rm y\_0 \ge 0\,.$
There is much literature on this classical problem. To locate such work
you should ensure that you search on the many aliases,
e.g. postage stamp problem, Sylvester/Frobenius problem,
Diophantine problem of Frobenius, Frobenius conductor,
money changing, coin changing, change making problems,
h-basis and asymptotic bases in additive number theory,
integer programming algorithms and Gomory cuts,
knapsack problems and greedy algorithms, etc. | This problem is similar to the "coin problem", where you need to find the smallest integer from which every integer can be obtained with a linear combination of the values of your coins with positive coefficients.
For your problem with 2 numbers (aka 2 coin values), a solution can be found here : <http://www.cut-the-knot.org/blue/Sylvester.shtml#solution> |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | We **sketch** a proof. For my comfort, I will use $a$ and $b$ instead of $x$ and $y$. Sorry! So we show that every $n\ge (a-1)(b-1)$ is representable in the form $au + bv$ with $u$ and $v$ being nonnegative integers.
**1.** Because $a$ and $b$ are relatively prime, there exist integers $x\_0,y\_0$ (not necessarily both $\ge 0$) such that $ax\_0+by\_0=1$. Thus (multiplying through by $n$) we find that there exist integers $x\_1,y\_1$ such that $ax\_1+by\_1=n$.
**2.** Infinitely many solutions of the equation $ax+by=n$ are given by $x=x\_1-tb$, $y=y\_1+ta$, where $t$ ranges over the integers. (Actually these are all solutions, but we won't need this.)
**3.** Let $t$ be the **smallest** positive integer such that $y\_1+ta\ge 0$. We show that $x\_1-tb\ge 0$. We have
$$a(x\_1-tb)+b(y\_1+ta)=n \ge (a-1)(b-1),$$
thus
$$a(x\_1-tb) \ge (a-1)(b-1) - b(y\_1+ta).$$
But $y\_1+ta\le a-1$, else we could decrement $t$.
Thus
$$a(x\_1-tb)\ge (a-1)(b-1)-b(a-1) = -(a-1) > -a,$$
and therefore $x\_1-tb> -1$, so that $x\_1-tb \geq 0$ (since $x\_1-tb \in \mathbb{Z}$). So we have produced the required non-negative solution. | HINT:
We have
$$a x + b y = (a - q y) x + (b + q x) y$$
Therefore, every number that is an integer combination
$n = a x + b y$ is also an integer combination $n = a x + b y$, with $0 < a \le y$.
Now, consider a number $n > x y$ that is an integral combination of $x$, $y$, that is $n = a x + b y$. We may assume that $0 \le a \le y$. We conclude that $b >0$.
Since $x$, $y$ is relatively prime, every integer is an integer combination of $x$, $y$. This and the previous arguments implies: every integer $> x y$ is a positive integral combination of $x$, $y$.
Let us also show that $x y$ is not a positive integral combination of $x$, $y$. Indeed, consider
$$x y = a x + b y$$ Then $a x$ is divisible by $y$, and since $(x,y) = 1$, $a$ is divisible by $y$, $\&$ c $\ldots$
Note: it is easier to consider the problem for $a$, $b>0$, rather than $a$, $b\ge 0$. This is also @Atom: 's observation. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | By the extended Euclidean algorithm one finds $u,v\in\mathbb Z$ with $ux+vy=1$, hence for *any* integer $n$ we can find a representation $n=a x+b y$ with $a,b\in\mathbb Z$.
With $ax+by=n$ we also have $(a+ky)x+(b-kx)y=n$, hence there exist solutions to $n=ax+by$ with $a\ge 0$. Among all those solutions pick one that minimizes $a$.
Then $0\le a\le y-1$ because otherwise $(a-y)x+(b+x)y$ would be "better".
If $n\ge (x-1)(y-1)$, we find that
$$by = n-ax\ge (x-1)(y-1)-(y-1)x = 1-y>-y $$
hence $b>-1$, i.e. $b\ge 0$ as required. | This problem is similar to the "coin problem", where you need to find the smallest integer from which every integer can be obtained with a linear combination of the values of your coins with positive coefficients.
For your problem with 2 numbers (aka 2 coin values), a solution can be found here : <http://www.cut-the-knot.org/blue/Sylvester.shtml#solution> |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | We **sketch** a proof. For my comfort, I will use $a$ and $b$ instead of $x$ and $y$. Sorry! So we show that every $n\ge (a-1)(b-1)$ is representable in the form $au + bv$ with $u$ and $v$ being nonnegative integers.
**1.** Because $a$ and $b$ are relatively prime, there exist integers $x\_0,y\_0$ (not necessarily both $\ge 0$) such that $ax\_0+by\_0=1$. Thus (multiplying through by $n$) we find that there exist integers $x\_1,y\_1$ such that $ax\_1+by\_1=n$.
**2.** Infinitely many solutions of the equation $ax+by=n$ are given by $x=x\_1-tb$, $y=y\_1+ta$, where $t$ ranges over the integers. (Actually these are all solutions, but we won't need this.)
**3.** Let $t$ be the **smallest** positive integer such that $y\_1+ta\ge 0$. We show that $x\_1-tb\ge 0$. We have
$$a(x\_1-tb)+b(y\_1+ta)=n \ge (a-1)(b-1),$$
thus
$$a(x\_1-tb) \ge (a-1)(b-1) - b(y\_1+ta).$$
But $y\_1+ta\le a-1$, else we could decrement $t$.
Thus
$$a(x\_1-tb)\ge (a-1)(b-1)-b(a-1) = -(a-1) > -a,$$
and therefore $x\_1-tb> -1$, so that $x\_1-tb \geq 0$ (since $x\_1-tb \in \mathbb{Z}$). So we have produced the required non-negative solution. | **Key Idea** $ $ In the plane $\,\mathbb R^2,\,$ a line $\rm\,a\,x+b\,y = c\,$ of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ is in the first quadrant, i.e. $\,\rm y\_0 \ge 0\,.$ We can use an analogous "normalized" point test to check if a discrete line $\rm\,m\,x + n\,y = k\,$ has points in the first quadrant.
**Hint** $\ $ Normalize $\rm\,k = m\, x + n\, y\,$ so $\rm\,0 \le x < n\,$
by adding a multiple of $\rm\,(-n,m)\,$ to $\rm\,(x,y)$
**Lemma** $\rm\ \ k = m\ x + n\ y\,$ for some integers $\rm\,x,\,y \ge 0\,$
$\iff$ its normalization has $\rm\,y \ge 0.$
**Proof** $\ (\Rightarrow)\ $ If $\rm\ x,\, y \ge 0\,$ normalizing adds $\rm\,(-n,m)\,$ zero or more times, preserving $\rm\,y \ge 0\,.\,$
$(\Leftarrow)\ \,$ If the normalized rep has $\rm\ y < 0,\,$ then $\rm\,k\,$ has no representation with $\rm\, x,\,y \ge 0\,\, $ since to shift so that $\rm\,y > 0\,$
we must add $\rm\,(-n,m)\,$ at least once, which forces $\rm\,x < 0,\,$ by $\rm\,0\le x < n.\ \ \ $ **QED**
To solve the OP, note that since $\rm\, k = m\ x + n\ y\, $ is increasing in both $\rm\,x\,$ and $\rm\,y,\,$ it is clear that the largest non-representable $\rm\,k\,$ has normalization $\rm\,(x,y) = (n\!-\!1,-1),\,$ i.e. the lattice point that is rightmost (max $\rm\,x$) and topmost (max $\rm\,y$) in the nonrepresentable lower half $\rm (y < 0)$ of the normalized strip, i.e. the vertical strip where $\rm\, 0\le x \le n-1.\,$ Thus $\rm\,(x,y) = (\color{#0a0}{n\!-\!1},\color{#c00}{-1})\,$ yields that $\rm\, k = mx+ny = m\,(\color{#0a0}{n\!-\!1})+n\,(\color{#c00}{-1}) = mn\! -\! m\! -\! n\ $ is the largest nonrepresentable integer. $\ $ **QED**
Notice that the proof has a vivid geometric picture:
representations of $\rm\,k\,$ correspond to lattice points $\rm\,(x,y)\,$
on the line $\rm\, n\ y + m\ x = k\,$ with negative slope $\rm\, = -m/n\,.\,$
Normalization is achieved by shifting forward/backward
along the line by integral multiples of the vector $\rm\,(-n,m)\,$
until one lands in the normal strip where $\rm\,0 \le x \le n-1.\,$ If the normalized rep has $\rm\,y\ge 0\,$ then we are done; otherwise, by the lemma, $\rm\,k\,$ has no rep with both $\rm\,x,y\ge 0\,.\,$ This result may be viewed as a discrete analog of the fact that, in the plane $\,\mathbb R^2,\,$ a line of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ lies in the first quadrant, i.e. $\rm y\_0 \ge 0\,.$
There is much literature on this classical problem. To locate such work
you should ensure that you search on the many aliases,
e.g. postage stamp problem, Sylvester/Frobenius problem,
Diophantine problem of Frobenius, Frobenius conductor,
money changing, coin changing, change making problems,
h-basis and asymptotic bases in additive number theory,
integer programming algorithms and Gomory cuts,
knapsack problems and greedy algorithms, etc. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | We **sketch** a proof. For my comfort, I will use $a$ and $b$ instead of $x$ and $y$. Sorry! So we show that every $n\ge (a-1)(b-1)$ is representable in the form $au + bv$ with $u$ and $v$ being nonnegative integers.
**1.** Because $a$ and $b$ are relatively prime, there exist integers $x\_0,y\_0$ (not necessarily both $\ge 0$) such that $ax\_0+by\_0=1$. Thus (multiplying through by $n$) we find that there exist integers $x\_1,y\_1$ such that $ax\_1+by\_1=n$.
**2.** Infinitely many solutions of the equation $ax+by=n$ are given by $x=x\_1-tb$, $y=y\_1+ta$, where $t$ ranges over the integers. (Actually these are all solutions, but we won't need this.)
**3.** Let $t$ be the **smallest** positive integer such that $y\_1+ta\ge 0$. We show that $x\_1-tb\ge 0$. We have
$$a(x\_1-tb)+b(y\_1+ta)=n \ge (a-1)(b-1),$$
thus
$$a(x\_1-tb) \ge (a-1)(b-1) - b(y\_1+ta).$$
But $y\_1+ta\le a-1$, else we could decrement $t$.
Thus
$$a(x\_1-tb)\ge (a-1)(b-1)-b(a-1) = -(a-1) > -a,$$
and therefore $x\_1-tb> -1$, so that $x\_1-tb \geq 0$ (since $x\_1-tb \in \mathbb{Z}$). So we have produced the required non-negative solution. | This problem is similar to the "coin problem", where you need to find the smallest integer from which every integer can be obtained with a linear combination of the values of your coins with positive coefficients.
For your problem with 2 numbers (aka 2 coin values), a solution can be found here : <http://www.cut-the-knot.org/blue/Sylvester.shtml#solution> |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | By the extended Euclidean algorithm one finds $u,v\in\mathbb Z$ with $ux+vy=1$, hence for *any* integer $n$ we can find a representation $n=a x+b y$ with $a,b\in\mathbb Z$.
With $ax+by=n$ we also have $(a+ky)x+(b-kx)y=n$, hence there exist solutions to $n=ax+by$ with $a\ge 0$. Among all those solutions pick one that minimizes $a$.
Then $0\le a\le y-1$ because otherwise $(a-y)x+(b+x)y$ would be "better".
If $n\ge (x-1)(y-1)$, we find that
$$by = n-ax\ge (x-1)(y-1)-(y-1)x = 1-y>-y $$
hence $b>-1$, i.e. $b\ge 0$ as required. | Let me show another proof of this elementary problem (in terms of $a$ and $b$ as constants and $x$, $y$ as variables).
Let $i$ be the least (non-negative) residue of $y$ modulo $a$. Then one can rewrite the form $ax+by$ as $ax+b(i+az)=bi+a(x+bz)$. Given $0 \leq i \leq a-1$, we obtain the sequence $bi+an$, $n\geq 0$, of integers, which can be represented by the form (and only elements of these sequences possess this property).
Suppose that $a$ and $b$ are coprime positive integers. It follows from the extended Euclidean algorithm that $b$ is an invertible element of $\mathbb{Z}/a\mathbb{Z}$. Therefore, the multiplication by $b$ is an automorphism of the ring $\mathbb{Z}/a\mathbb{Z}$. Thus, all $bi$'s are distinct modulo $a$, i.e. two different sequences contain no common elements.
Note that the smallest element of each of these sequence is less than or equal to $b(a-1)$, i.e. they "begin" not later than this "moment". Obviously, any integer $N \geq b(a-1)$ appears in exactly one of those sequence. Moreover, the sequence that corresponds to $b(a-1)+m$, $0<m \leq a-1$, contains $b(a-1)+m-a \geq b(a-2)$, since it begins not later than $b(a-2)$. Thus, any integer $N \geq b(a-1) + 1 - a = (a-1)(b-1)$ can be represented by the form.
It suffices to see that $ax+by=(a-1)(b-1)-1$ has no non-negative solutions. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | We **sketch** a proof. For my comfort, I will use $a$ and $b$ instead of $x$ and $y$. Sorry! So we show that every $n\ge (a-1)(b-1)$ is representable in the form $au + bv$ with $u$ and $v$ being nonnegative integers.
**1.** Because $a$ and $b$ are relatively prime, there exist integers $x\_0,y\_0$ (not necessarily both $\ge 0$) such that $ax\_0+by\_0=1$. Thus (multiplying through by $n$) we find that there exist integers $x\_1,y\_1$ such that $ax\_1+by\_1=n$.
**2.** Infinitely many solutions of the equation $ax+by=n$ are given by $x=x\_1-tb$, $y=y\_1+ta$, where $t$ ranges over the integers. (Actually these are all solutions, but we won't need this.)
**3.** Let $t$ be the **smallest** positive integer such that $y\_1+ta\ge 0$. We show that $x\_1-tb\ge 0$. We have
$$a(x\_1-tb)+b(y\_1+ta)=n \ge (a-1)(b-1),$$
thus
$$a(x\_1-tb) \ge (a-1)(b-1) - b(y\_1+ta).$$
But $y\_1+ta\le a-1$, else we could decrement $t$.
Thus
$$a(x\_1-tb)\ge (a-1)(b-1)-b(a-1) = -(a-1) > -a,$$
and therefore $x\_1-tb> -1$, so that $x\_1-tb \geq 0$ (since $x\_1-tb \in \mathbb{Z}$). So we have produced the required non-negative solution. | By the extended Euclidean algorithm one finds $u,v\in\mathbb Z$ with $ux+vy=1$, hence for *any* integer $n$ we can find a representation $n=a x+b y$ with $a,b\in\mathbb Z$.
With $ax+by=n$ we also have $(a+ky)x+(b-kx)y=n$, hence there exist solutions to $n=ax+by$ with $a\ge 0$. Among all those solutions pick one that minimizes $a$.
Then $0\le a\le y-1$ because otherwise $(a-y)x+(b+x)y$ would be "better".
If $n\ge (x-1)(y-1)$, we find that
$$by = n-ax\ge (x-1)(y-1)-(y-1)x = 1-y>-y $$
hence $b>-1$, i.e. $b\ge 0$ as required. |
654,697 | I am asked to prove that:
>
> For integers $n, x,y > 0$, where $x,y$ are relatively prime,
> every $n \ge (x-1) (y-1)$ can be expressed as $xa + yb$, with nonnegative integers $a,b \ge0$.
>
>
>
How should I approach this? I have very limited knowledge in number theory. | 2014/01/28 | [
"https://math.stackexchange.com/questions/654697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/11855/"
] | **Key Idea** $ $ In the plane $\,\mathbb R^2,\,$ a line $\rm\,a\,x+b\,y = c\,$ of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ is in the first quadrant, i.e. $\,\rm y\_0 \ge 0\,.$ We can use an analogous "normalized" point test to check if a discrete line $\rm\,m\,x + n\,y = k\,$ has points in the first quadrant.
**Hint** $\ $ Normalize $\rm\,k = m\, x + n\, y\,$ so $\rm\,0 \le x < n\,$
by adding a multiple of $\rm\,(-n,m)\,$ to $\rm\,(x,y)$
**Lemma** $\rm\ \ k = m\ x + n\ y\,$ for some integers $\rm\,x,\,y \ge 0\,$
$\iff$ its normalization has $\rm\,y \ge 0.$
**Proof** $\ (\Rightarrow)\ $ If $\rm\ x,\, y \ge 0\,$ normalizing adds $\rm\,(-n,m)\,$ zero or more times, preserving $\rm\,y \ge 0\,.\,$
$(\Leftarrow)\ \,$ If the normalized rep has $\rm\ y < 0,\,$ then $\rm\,k\,$ has no representation with $\rm\, x,\,y \ge 0\,\, $ since to shift so that $\rm\,y > 0\,$
we must add $\rm\,(-n,m)\,$ at least once, which forces $\rm\,x < 0,\,$ by $\rm\,0\le x < n.\ \ \ $ **QED**
To solve the OP, note that since $\rm\, k = m\ x + n\ y\, $ is increasing in both $\rm\,x\,$ and $\rm\,y,\,$ it is clear that the largest non-representable $\rm\,k\,$ has normalization $\rm\,(x,y) = (n\!-\!1,-1),\,$ i.e. the lattice point that is rightmost (max $\rm\,x$) and topmost (max $\rm\,y$) in the nonrepresentable lower half $\rm (y < 0)$ of the normalized strip, i.e. the vertical strip where $\rm\, 0\le x \le n-1.\,$ Thus $\rm\,(x,y) = (\color{#0a0}{n\!-\!1},\color{#c00}{-1})\,$ yields that $\rm\, k = mx+ny = m\,(\color{#0a0}{n\!-\!1})+n\,(\color{#c00}{-1}) = mn\! -\! m\! -\! n\ $ is the largest nonrepresentable integer. $\ $ **QED**
Notice that the proof has a vivid geometric picture:
representations of $\rm\,k\,$ correspond to lattice points $\rm\,(x,y)\,$
on the line $\rm\, n\ y + m\ x = k\,$ with negative slope $\rm\, = -m/n\,.\,$
Normalization is achieved by shifting forward/backward
along the line by integral multiples of the vector $\rm\,(-n,m)\,$
until one lands in the normal strip where $\rm\,0 \le x \le n-1.\,$ If the normalized rep has $\rm\,y\ge 0\,$ then we are done; otherwise, by the lemma, $\rm\,k\,$ has no rep with both $\rm\,x,y\ge 0\,.\,$ This result may be viewed as a discrete analog of the fact that, in the plane $\,\mathbb R^2,\,$ a line of negative slope has points in the first quadrant $\rm\,x,y\ge 0\ $ iff its $\rm\,y$-intercept $\rm\,(0,\,y\_0)\,$ lies in the first quadrant, i.e. $\rm y\_0 \ge 0\,.$
There is much literature on this classical problem. To locate such work
you should ensure that you search on the many aliases,
e.g. postage stamp problem, Sylvester/Frobenius problem,
Diophantine problem of Frobenius, Frobenius conductor,
money changing, coin changing, change making problems,
h-basis and asymptotic bases in additive number theory,
integer programming algorithms and Gomory cuts,
knapsack problems and greedy algorithms, etc. | Let me show another proof of this elementary problem (in terms of $a$ and $b$ as constants and $x$, $y$ as variables).
Let $i$ be the least (non-negative) residue of $y$ modulo $a$. Then one can rewrite the form $ax+by$ as $ax+b(i+az)=bi+a(x+bz)$. Given $0 \leq i \leq a-1$, we obtain the sequence $bi+an$, $n\geq 0$, of integers, which can be represented by the form (and only elements of these sequences possess this property).
Suppose that $a$ and $b$ are coprime positive integers. It follows from the extended Euclidean algorithm that $b$ is an invertible element of $\mathbb{Z}/a\mathbb{Z}$. Therefore, the multiplication by $b$ is an automorphism of the ring $\mathbb{Z}/a\mathbb{Z}$. Thus, all $bi$'s are distinct modulo $a$, i.e. two different sequences contain no common elements.
Note that the smallest element of each of these sequence is less than or equal to $b(a-1)$, i.e. they "begin" not later than this "moment". Obviously, any integer $N \geq b(a-1)$ appears in exactly one of those sequence. Moreover, the sequence that corresponds to $b(a-1)+m$, $0<m \leq a-1$, contains $b(a-1)+m-a \geq b(a-2)$, since it begins not later than $b(a-2)$. Thus, any integer $N \geq b(a-1) + 1 - a = (a-1)(b-1)$ can be represented by the form.
It suffices to see that $ax+by=(a-1)(b-1)-1$ has no non-negative solutions. |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | Sounds like a file permission issue to me. Make sure that you are indeed copying files into the wwwroot folder and not moving them from another folder. When you copy the files they will automatically inherit the permissions from the parent folder, but if you move files they will retain their original permissions. I would recommend first copying the files to a folder on the computer and then copying them from there into the wwwroot folder.
Another thing to try would be to zip the files before copying them to the computer and then extract them to the local drive before copying them into the wwwroot folder. | IIS 7.5 should have given you detailed error on where you have ACCESS DENIED. If that does not help, use [Process Monitor](http://live.sysinternals.com/procmon.exe) and reproduce the error again and look for any ACCESS DENIED. |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | Sounds like a file permission issue to me. Make sure that you are indeed copying files into the wwwroot folder and not moving them from another folder. When you copy the files they will automatically inherit the permissions from the parent folder, but if you move files they will retain their original permissions. I would recommend first copying the files to a folder on the computer and then copying them from there into the wwwroot folder.
Another thing to try would be to zip the files before copying them to the computer and then extract them to the local drive before copying them into the wwwroot folder. | [See my answer here](https://serverfault.com/questions/70050/adding-a-virtual-directory-iis-7-5-windows-7-ultimate-x64/130322#130322). This IMO is a *breaking* change in Windows Server 2008 R2. |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | Sounds like a file permission issue to me. Make sure that you are indeed copying files into the wwwroot folder and not moving them from another folder. When you copy the files they will automatically inherit the permissions from the parent folder, but if you move files they will retain their original permissions. I would recommend first copying the files to a folder on the computer and then copying them from there into the wwwroot folder.
Another thing to try would be to zip the files before copying them to the computer and then extract them to the local drive before copying them into the wwwroot folder. | I was just struggling with this same issue. I'd deployed files to the IIS 7.5 server from another computer, and was getting 401 access denied errors. I tried adding the Application Domain Identity account (more on these here: <http://stevesmithblog.com/blog/working-with-application-pool-identities/>), the NETWORK SERVICE account, etc. and none of these worked.
What did work for me was adding the IUSR account to the web site's folder (recursively) with the default permissions (Read & execute, List folder contents, Read). |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | Sounds like a file permission issue to me. Make sure that you are indeed copying files into the wwwroot folder and not moving them from another folder. When you copy the files they will automatically inherit the permissions from the parent folder, but if you move files they will retain their original permissions. I would recommend first copying the files to a folder on the computer and then copying them from there into the wwwroot folder.
Another thing to try would be to zip the files before copying them to the computer and then extract them to the local drive before copying them into the wwwroot folder. | The problem not lies precisely in the authorization/authentication but in the modules that now manages the IIS.
Inside system.webServer you should have **runAllManagedModulesForAllRequests** set to **false** so you can display all images/css without problems with authentication.
In ASP.NET websites, the value of **runAllManagedModulesForAllRequests** previously had to be set to true to support routing. However, once **IIS 7 has been updated with a Service Pack**, the value of **runAllManagedModulesForAllRequests** can be set to **false** or omitted when working with ASP.NET routing.
Ref. <http://www.iis.net/configreference/system.webserver/modules>
P.S. Don't forget to add the following lines to the AppSettings section of my web.config file:
```
<add key="autoFormsAuthentication" value="false"/>
<add key="enableSimpleMembership" value="false"/>
``` |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | IIS 7.5 should have given you detailed error on where you have ACCESS DENIED. If that does not help, use [Process Monitor](http://live.sysinternals.com/procmon.exe) and reproduce the error again and look for any ACCESS DENIED. | [See my answer here](https://serverfault.com/questions/70050/adding-a-virtual-directory-iis-7-5-windows-7-ultimate-x64/130322#130322). This IMO is a *breaking* change in Windows Server 2008 R2. |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | I was just struggling with this same issue. I'd deployed files to the IIS 7.5 server from another computer, and was getting 401 access denied errors. I tried adding the Application Domain Identity account (more on these here: <http://stevesmithblog.com/blog/working-with-application-pool-identities/>), the NETWORK SERVICE account, etc. and none of these worked.
What did work for me was adding the IUSR account to the web site's folder (recursively) with the default permissions (Read & execute, List folder contents, Read). | [See my answer here](https://serverfault.com/questions/70050/adding-a-virtual-directory-iis-7-5-windows-7-ultimate-x64/130322#130322). This IMO is a *breaking* change in Windows Server 2008 R2. |
126,978 | I am having this weird issue with IIS 7.5 on Windows 2008 R2 x64. I created a site in IIS and **manually created** a test file index.html and everything worked. When I try to do a deployment, I copy all the files from my local PC to the IIS server, try to access index.html (this is the proper deployed file) and getting **401.3 access denied** error. I then try to manually recreate index.html and copy content into this newly created file and the page is accessible again... I just can't figure this out. **So the issue is that IIS 7.5 can't server files that have been copied from other PCs.** I tried to reset/apply permission settings to the copied folders/files but nothing has worked. Please help. Thanks! By the way, the files that I copied are just some html cutups i.e. generic html, css and image files, nothing special. | 2010/03/28 | [
"https://serverfault.com/questions/126978",
"https://serverfault.com",
"https://serverfault.com/users/27318/"
] | The problem not lies precisely in the authorization/authentication but in the modules that now manages the IIS.
Inside system.webServer you should have **runAllManagedModulesForAllRequests** set to **false** so you can display all images/css without problems with authentication.
In ASP.NET websites, the value of **runAllManagedModulesForAllRequests** previously had to be set to true to support routing. However, once **IIS 7 has been updated with a Service Pack**, the value of **runAllManagedModulesForAllRequests** can be set to **false** or omitted when working with ASP.NET routing.
Ref. <http://www.iis.net/configreference/system.webserver/modules>
P.S. Don't forget to add the following lines to the AppSettings section of my web.config file:
```
<add key="autoFormsAuthentication" value="false"/>
<add key="enableSimpleMembership" value="false"/>
``` | [See my answer here](https://serverfault.com/questions/70050/adding-a-virtual-directory-iis-7-5-windows-7-ultimate-x64/130322#130322). This IMO is a *breaking* change in Windows Server 2008 R2. |
8,180,189 | we're using JIRA with svn and looking for a way to include the revision id of the file automatically in the comment that appears in the dialog when commiting the file(s) so that JIRA catch that task.
Something like [ E-2 ] where the '2' is the id of the revision set by svn. Is there a way to create somethin similar to [ E- $id$ ] or something like that?
Thanks.
Edit : Well i've solved a part of it reading this [enter link description here](https://confluence.atlassian.com/display/JIRA/Integrating+JIRA+with+Subversion), i hope someone helps this. | 2011/11/18 | [
"https://Stackoverflow.com/questions/8180189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/715415/"
] | All the JIRA/Subversion integrations I've used (svn plugin, fisheye) handle this automatically. You add the JIRA issue key such as "TEST-123" somewhere in the svn commit message, and then the integration periodically notes all new commits and looks for JIRA issue keys in their messages. Then each JIRA issue has a tab with the list of commits associated with that issue. So there's no need to embed svn revision numbers into commit messages. | If you are not in the habit of doing commits in a particular way, and you don't mind doing a bit of scripting, this is what comes to mind -- I will probably do something like this myself, though I am using HG and not SVN...
Get the command line interface for Jira, rig it up so you can download 'my issues' into a list, parse the list with a script to create separate \*.issue files that get dumped in a directory. Then as you work on issues, you move them from that directory, to a 'done' directory. When you are ready to commit, you run another script that creates a template for your commit message which includes all the done issues -- then you fill in the blanks for each issue.
You don't even need the CLI really, if all your \*.issue files are associated with a script that will delete the file and add its ID to a commit template, then you can just create your own ID.issues files by hand. (empty files)
All that would be left is to script the commit. |
57,629,751 | I have `a_1.py`~`a_10.py`
I want to run 10 python programs in parallel.
I tried:
```
from multiprocessing import Process
import os
def info(title):
I want to execute python program
def f(name):
for i in range(1, 11):
subprocess.Popen(['python3', f'a_{i}.py'])
if __name__ == '__main__':
info('main line')
p = Process(target=f)
p.start()
p.join()
```
but it doesn't work
How do I solve this? | 2019/08/23 | [
"https://Stackoverflow.com/questions/57629751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11309950/"
] | I would suggest using the [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess) module instead of `multiprocessing`:
```
import os
import subprocess
import sys
MAX_SUB_PROCESSES = 10
def info(title):
print(title, flush=True)
if __name__ == '__main__':
info('main line')
# Create a list of subprocesses.
processes = []
for i in range(1, MAX_SUB_PROCESSES+1):
pgm_path = f'a_{i}.py' # Path to Python program.
command = f'"{sys.executable}" "{pgm_path}" "{os.path.basename(pgm_path)}"'
process = subprocess.Popen(command, bufsize=0)
processes.append(process)
# Wait for all of them to finish.
for process in processes:
process.wait()
print('Done')
``` | If you just need to call 10 external `py` scripts (`a_1.py` ~ `a_10.py`) as a separate processes - use [subprocess.Popen](https://docs.python.org/dev/library/subprocess.html#popen-constructor) class:
```
import subprocess, sys
for i in range(1, 11):
subprocess.Popen(['python3', f'a_{i}.py'])
# sys.exit() # optional
```
---
It's worth to look at a rich `subprocess.Popen` signature (you may find some useful params/options) |
57,629,751 | I have `a_1.py`~`a_10.py`
I want to run 10 python programs in parallel.
I tried:
```
from multiprocessing import Process
import os
def info(title):
I want to execute python program
def f(name):
for i in range(1, 11):
subprocess.Popen(['python3', f'a_{i}.py'])
if __name__ == '__main__':
info('main line')
p = Process(target=f)
p.start()
p.join()
```
but it doesn't work
How do I solve this? | 2019/08/23 | [
"https://Stackoverflow.com/questions/57629751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11309950/"
] | I would suggest using the [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess) module instead of `multiprocessing`:
```
import os
import subprocess
import sys
MAX_SUB_PROCESSES = 10
def info(title):
print(title, flush=True)
if __name__ == '__main__':
info('main line')
# Create a list of subprocesses.
processes = []
for i in range(1, MAX_SUB_PROCESSES+1):
pgm_path = f'a_{i}.py' # Path to Python program.
command = f'"{sys.executable}" "{pgm_path}" "{os.path.basename(pgm_path)}"'
process = subprocess.Popen(command, bufsize=0)
processes.append(process)
# Wait for all of them to finish.
for process in processes:
process.wait()
print('Done')
``` | You can use a multiprocessing pool to run them concurrently.
```py
import multiprocessing as mp
def worker(module_name):
""" Executes a module externally with python """
__import__(module_name)
return
if __name__ == "__main__":
max_processes = 5
module_names = [f"a_{i}" for i in range(1, 11)]
print(module_names)
with mp.Pool(max_processes) as pool:
pool.map(worker, module_names)
```
The `max_processes` variable is the maximum number of workers to have working at any given time. In other words, its the number of processes spawned by your program. The `pool.map(worker, module_names)` uses the available processes and calls worker on each item in your module\_names list. We don't include the .py because we're running the module by importing it.
Note: This might not work if the code you want to run in your modules is contained inside `if __name__ == "__main__"` blocks. If that is the case, then my recommendation would be to move all the code in the `if __name__ == "__main__"` blocks of the `a_{}` modules into a `main` function. Additionally, you would have to change the worker to something like:
```py
def worker(module_name):
module = __import__(module_name) # Kind of like 'import module_name as module'
module.main()
return
``` |
49,181,215 | This is a [solved problem](http://massivealgorithms.blogspot.com/2016/07/missing-int.html) where the we have to find a missing integer from the input data which is in form of a file containing 4 billion unsorted unsigned integers. The catch is that only 10 MBytes of memory can be used.
The author gives a solution where we do 2 passes. In the first pass we create an array of "blocks" of some size. Eg. Block 0 represents `0 to 999`, 1 represents `1000 to 1999`, so on. Thus we know how many values **should** be present in each block.
Now we scan through the file and count how many values are **actually present** in each block - which will lead us to the missing integer.
I understand the approach. However, to calculate the appropriate block size starts with this:
>
> The array in the first pass can fit in 10 MBytes, or roughly 2^23 bytes, of memory.
>
>
>
How is `10` MB the same as `2^23`? I am unable to understand where did the `2^23` number come from.
So `2^24` is 16MBytes, so probably he is taking `2^23` which is closest value that is 10 MBytes or less. If that is the case, why can he not use the whole 10 MBytes? i.e. why does he have to use a power of 2 to get the size here? | 2018/03/08 | [
"https://Stackoverflow.com/questions/49181215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641752/"
] | Not stated, but I'm assuming that the problem is to find the one missing integer from a file with a set of 2^32 (4294967296) unique 32 bit unsigned integers of values 0 to 4294967295. The file takes 17179869184 bytes of space.
Using 2^23 = 8388608 of memory space allows for 2^21 = 2097152 32 bit unsigned integer counts to be held in memory. Each group represents (2^32)/(2^21) = 2^11 = 2048 values. So count[0] is for values 0 to 2047, count[1] is for values 2048 to 4095, ... , count[2097151] is for values 4294965248 to 4294967295. The main line in the inner part of the loop would be count[value>>21] += 1. All counts will be 2048 except the count corresponding to the missing integer, which will have a count of 2047. The second pass will only need to read the 2047 values in the proper range to find the missing integer.
An alternative would be to use 4194304 16 bit counts with each group representing 1024 values (max count value is 1024), but there's no significant difference in time.
Assuming the 10MB = 10 \* 2^20 = 10485760, then 10 \* 2^18 = 2621440 32 bit counts could be used, each count for a range of 1639 values (the last count for a smaller group), which is awkward. If using 16 bit counts, then a range of 3278 values, also awkward. | I belive it should be 10\*2^23 or 5\*2^24 in bits.
Try to see if it is in byte or bit
```
10 MB = 2*5*2^20*2^3
M=2^20
B=2^3b
10=2*5
``` |
49,181,215 | This is a [solved problem](http://massivealgorithms.blogspot.com/2016/07/missing-int.html) where the we have to find a missing integer from the input data which is in form of a file containing 4 billion unsorted unsigned integers. The catch is that only 10 MBytes of memory can be used.
The author gives a solution where we do 2 passes. In the first pass we create an array of "blocks" of some size. Eg. Block 0 represents `0 to 999`, 1 represents `1000 to 1999`, so on. Thus we know how many values **should** be present in each block.
Now we scan through the file and count how many values are **actually present** in each block - which will lead us to the missing integer.
I understand the approach. However, to calculate the appropriate block size starts with this:
>
> The array in the first pass can fit in 10 MBytes, or roughly 2^23 bytes, of memory.
>
>
>
How is `10` MB the same as `2^23`? I am unable to understand where did the `2^23` number come from.
So `2^24` is 16MBytes, so probably he is taking `2^23` which is closest value that is 10 MBytes or less. If that is the case, why can he not use the whole 10 MBytes? i.e. why does he have to use a power of 2 to get the size here? | 2018/03/08 | [
"https://Stackoverflow.com/questions/49181215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641752/"
] | Not stated, but I'm assuming that the problem is to find the one missing integer from a file with a set of 2^32 (4294967296) unique 32 bit unsigned integers of values 0 to 4294967295. The file takes 17179869184 bytes of space.
Using 2^23 = 8388608 of memory space allows for 2^21 = 2097152 32 bit unsigned integer counts to be held in memory. Each group represents (2^32)/(2^21) = 2^11 = 2048 values. So count[0] is for values 0 to 2047, count[1] is for values 2048 to 4095, ... , count[2097151] is for values 4294965248 to 4294967295. The main line in the inner part of the loop would be count[value>>21] += 1. All counts will be 2048 except the count corresponding to the missing integer, which will have a count of 2047. The second pass will only need to read the 2047 values in the proper range to find the missing integer.
An alternative would be to use 4194304 16 bit counts with each group representing 1024 values (max count value is 1024), but there's no significant difference in time.
Assuming the 10MB = 10 \* 2^20 = 10485760, then 10 \* 2^18 = 2621440 32 bit counts could be used, each count for a range of 1639 values (the last count for a smaller group), which is awkward. If using 16 bit counts, then a range of 3278 values, also awkward. | It's not.
1 MB is 2^20 bytes (1024 X 1024) = 1048576
10 MB is then 10485760.
2^23 = 8388608
Of course that website says 10 MB is "roughly 2^23", which could be accurate depending on what is meant by roughly. |
4,825 | As I understand it there is a general recommendation towards wearing weight lifting shoes when lifting heavy weights for three main reasons:
* Less compression in a weight lifting shoe's than in a normal training shoe
* A more favourable angle for a more 'upright' position(surely just a more hips forward position)
* General support of the foot
One of my goals through lifting (I am referring to barbell Olympic-style lifts) is to strengthen the musculature and connective tissues of the hands and wrists. As such I opt to not wear wraps or gloves when lifting, which I imagine will at some point limit the amount I can safely lift (but not for some time).
By extension I wonder if there is development of the muscles of the foot, ankle, and shins to be gained from unsupported feet.
Has anyone experimented with this? Are there compelling reasons not to embark on shoeless weight lifting? It seems that the first feature of a weight lifting shoe would be provided by a raw heel, and the third seems subject to the same caveats as bare-foot running.
I'm particularly interested to hear from experienced lifters who would be willing to experiment with lifting without shoes and give their thoughts. | 2011/12/08 | [
"https://fitness.stackexchange.com/questions/4825",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/720/"
] | Most weightlifting shoes were designed for OLYMPIC weightlifting - the Clean and Jerk and the Snatch. You can read all about it on the web including the history and evolution of the shoes. Basically you absolutely need the heel to perform Olympic lifts with any real weight on the bar.
With that said, I do not believe in wearing shoes for power lifting - no shoe really helps you squat better, or deadlift more weight. You should be able to get your body into the correct position without the help of a shoe, which is the argument that people use for why you should wear a shoe for heavy power lifts.
I take the minimalist approach here as well - chances are if I need to move some heavy weight one day, I won't have a pair of shoes designed especially for it lying around anywhere.
Now if you are still interested in shoes I highly recommend you check out [WLShoes.com](http://wlshoes.com). They maintain a database of all weightlifting and training shoes and people post reviews and comments on them. | Some of the more successful heavy lifters at my Crossfit Box swear by firm shoes with elevated heels, but only when doing some very heavy loads.
To me this approach makes a lost of sense. If you're trying to exercise a muscle by performing a movement that is unnatural or really difficult, something like this may put your posture into a form more suitable to handle the load safely.
However, if like me you're typically only lifting to maintain decent health and strength then it may be a bit overkill to use special shoes. I can tell you from personal experience that after months of lifting barefoot or in vibrams/minimalist shoes I happened to try and do back squats in tennis shoes and found it extremely difficult to control.
Just my perspective, I tend to go minimalist with everything and only make modifications when safeguarding against injury. |
4,825 | As I understand it there is a general recommendation towards wearing weight lifting shoes when lifting heavy weights for three main reasons:
* Less compression in a weight lifting shoe's than in a normal training shoe
* A more favourable angle for a more 'upright' position(surely just a more hips forward position)
* General support of the foot
One of my goals through lifting (I am referring to barbell Olympic-style lifts) is to strengthen the musculature and connective tissues of the hands and wrists. As such I opt to not wear wraps or gloves when lifting, which I imagine will at some point limit the amount I can safely lift (but not for some time).
By extension I wonder if there is development of the muscles of the foot, ankle, and shins to be gained from unsupported feet.
Has anyone experimented with this? Are there compelling reasons not to embark on shoeless weight lifting? It seems that the first feature of a weight lifting shoe would be provided by a raw heel, and the third seems subject to the same caveats as bare-foot running.
I'm particularly interested to hear from experienced lifters who would be willing to experiment with lifting without shoes and give their thoughts. | 2011/12/08 | [
"https://fitness.stackexchange.com/questions/4825",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/720/"
] | All weightlifting shoes have one thing in common: an incompressible sole. The more inexpensive shoes use a hard plastic, and the more expensive shoes use wood. At one point in time there were power lifting shoes that had a flat sole. I haven't been able to find any of these lately, and almost all have a heel.
Whether a heel helps or not depends on the lift, as well as how much of a heel. For example:
* Deadlifts are best performed with no heel. Pulling with a heel increases the distance you have to pull, and puts you at a slight disadvantage leverage-wise.
* Squats work best with a heel, particularly front squats.
* Bench press can use a heel to improve leg drive, but it's not necessary.
* Any fast pull like cleans & jerks, snatches, etc. are best done with a heel.
At the end of the day, it really can be a personal preference. I know of many people who take their shoes off for deadlifts. As long as you are on a solid surface, you will have the best leverages this way.
If you need a heel, use weightlifting shoes. If not, go barefoot.
**NOTE:** Do *not* use your weightlifting shoes to do plyometrics and box jumps. The soles are not supposed to be flexible and they are not designed for that type of work. Take the weightlifting shoes off and either do it barefoot or with a different set of shoes. | Some of the more successful heavy lifters at my Crossfit Box swear by firm shoes with elevated heels, but only when doing some very heavy loads.
To me this approach makes a lost of sense. If you're trying to exercise a muscle by performing a movement that is unnatural or really difficult, something like this may put your posture into a form more suitable to handle the load safely.
However, if like me you're typically only lifting to maintain decent health and strength then it may be a bit overkill to use special shoes. I can tell you from personal experience that after months of lifting barefoot or in vibrams/minimalist shoes I happened to try and do back squats in tennis shoes and found it extremely difficult to control.
Just my perspective, I tend to go minimalist with everything and only make modifications when safeguarding against injury. |
4,825 | As I understand it there is a general recommendation towards wearing weight lifting shoes when lifting heavy weights for three main reasons:
* Less compression in a weight lifting shoe's than in a normal training shoe
* A more favourable angle for a more 'upright' position(surely just a more hips forward position)
* General support of the foot
One of my goals through lifting (I am referring to barbell Olympic-style lifts) is to strengthen the musculature and connective tissues of the hands and wrists. As such I opt to not wear wraps or gloves when lifting, which I imagine will at some point limit the amount I can safely lift (but not for some time).
By extension I wonder if there is development of the muscles of the foot, ankle, and shins to be gained from unsupported feet.
Has anyone experimented with this? Are there compelling reasons not to embark on shoeless weight lifting? It seems that the first feature of a weight lifting shoe would be provided by a raw heel, and the third seems subject to the same caveats as bare-foot running.
I'm particularly interested to hear from experienced lifters who would be willing to experiment with lifting without shoes and give their thoughts. | 2011/12/08 | [
"https://fitness.stackexchange.com/questions/4825",
"https://fitness.stackexchange.com",
"https://fitness.stackexchange.com/users/720/"
] | Most weightlifting shoes were designed for OLYMPIC weightlifting - the Clean and Jerk and the Snatch. You can read all about it on the web including the history and evolution of the shoes. Basically you absolutely need the heel to perform Olympic lifts with any real weight on the bar.
With that said, I do not believe in wearing shoes for power lifting - no shoe really helps you squat better, or deadlift more weight. You should be able to get your body into the correct position without the help of a shoe, which is the argument that people use for why you should wear a shoe for heavy power lifts.
I take the minimalist approach here as well - chances are if I need to move some heavy weight one day, I won't have a pair of shoes designed especially for it lying around anywhere.
Now if you are still interested in shoes I highly recommend you check out [WLShoes.com](http://wlshoes.com). They maintain a database of all weightlifting and training shoes and people post reviews and comments on them. | All weightlifting shoes have one thing in common: an incompressible sole. The more inexpensive shoes use a hard plastic, and the more expensive shoes use wood. At one point in time there were power lifting shoes that had a flat sole. I haven't been able to find any of these lately, and almost all have a heel.
Whether a heel helps or not depends on the lift, as well as how much of a heel. For example:
* Deadlifts are best performed with no heel. Pulling with a heel increases the distance you have to pull, and puts you at a slight disadvantage leverage-wise.
* Squats work best with a heel, particularly front squats.
* Bench press can use a heel to improve leg drive, but it's not necessary.
* Any fast pull like cleans & jerks, snatches, etc. are best done with a heel.
At the end of the day, it really can be a personal preference. I know of many people who take their shoes off for deadlifts. As long as you are on a solid surface, you will have the best leverages this way.
If you need a heel, use weightlifting shoes. If not, go barefoot.
**NOTE:** Do *not* use your weightlifting shoes to do plyometrics and box jumps. The soles are not supposed to be flexible and they are not designed for that type of work. Take the weightlifting shoes off and either do it barefoot or with a different set of shoes. |
14,077,100 | At my company we have a master pricing sheet in Excel that we keep updated. However, we have marketing materials in InDesign, Excel, on our website (with a MYSQL database), and 3rd party websites. Every month we update our prices, we have to update all of them by hand which is a lot of work, and prone to errors.
I am sure with all that is out there today, there is a way to streamline all of this from our master sheet, so we only have to update the master, and the rest can be automatically updated..
Can anyone suggest a solution for me, or at least a good direction? | 2012/12/28 | [
"https://Stackoverflow.com/questions/14077100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679202/"
] | The approach i would take is to move the master sheet into a database. This would allow me to create a simple web based gui that uses web services and role based authentication. The web services would generate xml, csv, etc. This would further allow for central management of pricing which in turn prevents rogue managers / sales people from hurting the company's bottom line. | I don't disagree with Woot4Moo's suggestion, however business reality (cost, experience, ongoing maintenance) may prevent you from moving off Excel as the master price list. Fortunately Excel works fine as an ODBC-compliant data source for simple queries.
Assuming the master Excel sheet is in an accessible location (i.e. on a shared network drive, not someone's PC), you can create ODBC connections from MySQL, Excel, and InDesign to pull data. 3rd-party web sites will probably be more difficult, given they won't have access to your network (this would be true even if you migrated to an internal RDBMS, although you could create APIs).
See [here](http://www.connectionstrings.com/excel) and [here](http://www.connectionstrings.com/excel-2007) for examples of Excel connection strings. |
4,360,058 | I have installed the Like Box in my blog, and I want to know if the user already like my page. I want to implement something like this to my reader because I want to offer them hidden contents if they already liked my page.
Is there an event where I will detect if the user already liked the page in the Like Box? | 2010/12/05 | [
"https://Stackoverflow.com/questions/4360058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/526816/"
] | You only assigning the new node to your local `head` variable in your `add()` method, not to the actual `CircleList` instance member.
You might want to do something like:
```
def add(self, element):
head = self.head
print(head)
size = self.size
if head is None:
self.head = head = Node(element, None) # Also set the instance member.
head.next = head
``` | Easy to fix! In your add function, you assign the new head to the `head` variable -- which is restricted to the scope of the function, and will dissapear when it returns!
You have to set the value of `self.head`, the attribute of the current instance.
Edit: when you assign `head = self.head` you are making them both point to the same object. But they are separate references: whether they happen to reference the same thing or not, changing one won't change the other. |
1,028,604 | **Ubuntu 18.04** came out April 26, 2018 and I want to try it to upgrade my programs and convert my data but don't want to commit if there are bugs.
I've shrunk Windows from 410 GB to 385 GB, rebooted Ubuntu 16.04 and ran `gparted` to create a new 25 GB partition labeled "Ubuntu18.04". I ran `rm-kernels` and removed about 20 kernels to eliminate about 10 GB on Ubuntu 16.04.
Now I want a script that will populate the new partition with 16.04 LTS and create a new Grub menu option to it. Only relevant directories should be copied. For example `/sys`, `/run`, `/proc` and `/dev` are virtual directories created during boot and shouldn't be copied.
I also want `/etc/fstab` patched with the correct UUID and `cron` reboot jobs disabled such that daily backups on cloned data isn't run after booting the clone.
I anticipate running the script many times over the next few weeks/months. As such the cloning process should effortlessly repeatable.
The same script could be used for testing security updates and new Ubuntu Kernel Team updates without effecting production systems. | 2018/04/27 | [
"https://askubuntu.com/questions/1028604",
"https://askubuntu.com",
"https://askubuntu.com/users/307523/"
] | Bash script to clone active Ubuntu Partition to clone partition
===============================================================
The `clone-ubuntu.sh` bash script will seamlessly and safely replicate 16.04 LTS into a partition for upgrading to 18.04 LTS:
[](https://i.stack.imgur.com/MgM3p.png)
Important points to consider:
* You must create an empty `ext4` partition large enough to hold a **Ubuntu 16.04 clone**
* When calling the script `clone-ubuntu.sh` the partition **cannot** be mounted. The script automatically mounts and unmounts the partition.
* The command `rsync` is used to copy files from `/` to the clone partition. The first time you run `clone-ubuntu.sh` it will take a few minutes. The second time you run the script only file changes are updated and it should take less than a minute.
* You might run this script and reboot multiple times. **Any new data** on the clone target will **deleted** to mirror the current `/` files & directories.
* All Cron `/etc/cron.d` (reboot) jobs are moved to a new sub-directory called `/etc/cron.d/hold`. After booting clone remember to run `sudo crontab -e` to prevent selected cron jobs from running.
* The cloned file `/etc/fstab` is modified with the appropriate UUID for the partition it is on.
* The cloned file `/boot/grub/grub.cfg` is modified with the appropriate UUID for successful clone booting. The cloned file's `quiet splash` is changed to `nosplash` so you get scrolling terminal messaging. This gives visual awareness booting a clone rather than "Real" version.
* `update-grub` is run to update Grub with new menu options pointing to the cloned partition.
* The cloned file `/etc/update-manager/release-upgrades` is modified to change `Prompt=never` to `Prompt=lts`. When you boot the clone and perform `do-release-upgrade -d` this allows Ubuntu 16.04 to be upgraded to 18.04.
* Before cloning a confirmation screen is displayed (shown in the next section) and you must type y/Y to proceed.
---
Confirmation Screen
-------------------
After selecting a target clone partition it is first verified to be `ext4` partition type and is not already mounted. If this test is passed, a confirmation message then appears:
```
=====================================================================
Mounting clone partition /dev/nvme0n1p8 as /mnt/clone16.04
=====================================================================
PLEASE: Carefully confirm Source (Live) and Target (Clone) partitions
SOURCE (BOOT /): /dev/nvme0n1p5 TARGET (CLONE): /dev/nvme0n1p8
ID: Ubuntu ID: Ubuntu
RELEASE: 16.04 RELEASE: 16.04
CODENAME: xenial CODENAME: xenial
DESCRIPTION: Ubuntu 16.04.3 LTS DESCRIPTION: Ubuntu 16.04.3 LTS
Size Used Avail Use% Size Used Avail Use%
44G 17G 26G 40% 24G 17G 5.8G 74%
NOTE: If you are recloning, new files in clone will be deleted,
modified files are reset to current source content and,
files deleted from clone are added back from source.
Type Y (or y) to proceed. Any other key to exit:
```
In this example a previous clone has been selected for recloning. The available space on the clone is a mute point because we already know there is enough space available.
If you have multiple Ubuntu installations, please verify you have selected the right partition to clone the currently booted Ubuntu, mounted as `/` (root), to.
This is your last chance to abort by pressing any key except `y` or `Y`.
---
Output listing
--------------
When you run the script you will get this output (excluding the output already listed above):
```
=====================================================================
Using rsync to clone / to /dev/nvme0n1p8 mounted as /mnt/clone16.04
6.11G 38% 86.46MB/s 0:01:07 (xfr#139123, to-chk=0/647700)
Number of files: 647,700 (reg: 470,100, dir: 104,694, link: 72,903, special: 3)
Number of created files: 127,824 (reg: 72,472, dir: 15,825, link: 39,526, special: 1)
Number of deleted files: 73,318 (reg: 59,766, dir: 9,701, link: 3,847, special: 4)
Number of regular files transferred: 139,123
Total file size: 15.92G bytes
Total transferred file size: 6.11G bytes
Literal data: 6.11G bytes
Matched data: 0 bytes
File list size: 8.50M
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 6.14G
Total bytes received: 7.82M
sent 6.14G bytes received 7.82M bytes 89.74M bytes/sec
total size is 15.92G speedup is 2.59
Time to clone files: 68 Seconds
=====================================================================
Making changes in: /mnt/clone16.04/etc/update-manager/release-upgrades
from Prompt=: never
to Prompt=: lts
Allows running 'do-release-upgrade -d' when rebooting clone target
Consider 'do-release-upgrade -d -f DistUpgradeViewNonInteractive' This
allows you to go to bed or go to lunch whilst upgrade runs.
* * * When you Upgrade, TURN OFF screen locking for inactivity. * * *
=====================================================================
Making changes in: /mnt/clone16.04/etc/fstab
from UUID: f3f8e7bc-b337-4194-88b8-3a513f6be55b
to UUID: 113f9955-a064-4ce2-9cae-74f2a9518550
=====================================================================
Making changes in: /mnt/clone16.04/boot/grub/grub.cfg
from UUID: f3f8e7bc-b337-4194-88b8-3a513f6be55b
to UUID: 113f9955-a064-4ce2-9cae-74f2a9518550
Also change 'quiet splash' to 'nosplash' for environmental awareness
Suggest first time booting clone you make wallpaper unique
=====================================================================
Calling 'update-grub' to create new boot menu
Generating grub configuration file ...
Found background: /home/rick/Pictures/1600x900/21.jpg
Found background image: /home/rick/Pictures/1600x900/21.jpg
Found linux image: /boot/vmlinuz-4.14.34-041434-generic
Found initrd image: /boot/initrd.img-4.14.34-041434-generic
Found linux image: /boot/vmlinuz-4.14.31-041431-generic
Found initrd image: /boot/initrd.img-4.14.31-041431-generic
Found linux image: /boot/vmlinuz-4.14.30-041430-generic
Found initrd image: /boot/initrd.img-4.14.30-041430-generic
Found linux image: /boot/vmlinuz-4.14.27-041427-generic
Found initrd image: /boot/initrd.img-4.14.27-041427-generic
Found linux image: /boot/vmlinuz-4.14.15-041415-generic
Found initrd image: /boot/initrd.img-4.14.15-041415-generic
Found linux image: /boot/vmlinuz-4.14.10-041410-generic
Found initrd image: /boot/initrd.img-4.14.10-041410-generic
Found linux image: /boot/vmlinuz-4.14.4-041404-generic
Found initrd image: /boot/initrd.img-4.14.4-041404-generic
Found linux image: /boot/vmlinuz-4.14.2-041402-generic
Found initrd image: /boot/initrd.img-4.14.2-041402-generic
Found linux image: /boot/vmlinuz-4.13.9-041309-generic
Found initrd image: /boot/initrd.img-4.13.9-041309-generic
Found linux image: /boot/vmlinuz-4.10.0-42-generic
Found initrd image: /boot/initrd.img-4.10.0-42-generic
Found linux image: /boot/vmlinuz-4.9.77-040977-generic
Found initrd image: /boot/initrd.img-4.9.77-040977-generic
Found linux image: /boot/vmlinuz-4.4.0-104-generic
Found initrd image: /boot/initrd.img-4.4.0-104-generic
Found linux image: /boot/vmlinuz-3.16.53-031653-generic
Found initrd image: /boot/initrd.img-3.16.53-031653-generic
Found Windows Boot Manager on /dev/nvme0n1p2@/EFI/Microsoft/Boot/bootmgfw.efi
Found Ubuntu 16.04.3 LTS (16.04) on /dev/nvme0n1p8
Found Windows Boot Manager on /dev/sda1@/efi/Microsoft/Boot/bootmgfw.efi
Adding boot menu entry for EFI firmware configuration
done
=====================================================================
Unmounting /dev/nvme0n1p8 as /mnt/clone16.04
```
---
`rsync` status display for new clone
------------------------------------
When cloning for the first time, `rsync` will give an update from 0 to 100% of all files created. No files will be deleted or changed as the clone is empty:
[](https://i.stack.imgur.com/22yrE.gif)
`rsync` status display when recloning
-------------------------------------
When `rsync` reclones it never hits `100%` because files that never changed are not copied. There will be delays in the update progress as `rsync` scans for the next file to be copied and when it deletes new files created in the clone that never existed in the original:
[](https://i.stack.imgur.com/bplnH.gif)
---
Bash script - `clone-ubuntu.sh`
-------------------------------
```
#!/bin/bash
# NAME: clone-ubuntu.sh
# PATH: /usr/local/bin
# DESC: Written for AU Q&A: https://askubuntu.com/questions/1028604/bash-seemless-safe-script-to-upgrade-16-04-to-18-04/1028605#1028605
# DATE: Apr 27, 2018. Modified May 6, 2018.
# UPDT: May 02 2018 - Display selected parition and get confirmation.
# May 06 2018 - Revise `do-release-upgrade -d` instructions.
# Correct listing of files in empty target partition.
# Aug 09 2018 - Add --inplace parameter to `rsync`
# Comment out disabling `/etc/cron.d` on clone target.
# Users may uncomment and/or revise to their needs.
# $TERM variable may be missing when called via desktop shortcut
CurrentTERM=$(env | grep TERM)
if [[ $CurrentTERM == "" ]] ; then
notify-send --urgency=critical \
"$0 cannot be run from GUI without TERM environment variable."
exit 1
fi
# Must run as root
if [[ $(id -u) -ne 0 ]] ; then echo "Usage: sudo $0" ; exit 1 ; fi
#
# Create unqique temporary file names
#
tmpPart=$(mktemp /tmp/clone-ubuntu.XXXXX) # Partitions list
tmpMenu=$(mktemp /tmp/clone-ubuntu.XXXXX) # Menu list
tmpInf1=$(mktemp /tmp/clone-ubuntu.XXXXX) # Soucre (Booted) Ubuntu Info
tmpInf2=$(mktemp /tmp/clone-ubuntu.XXXXX) # Target (Cloned) Ubuntu Info
tmpInf3=$(mktemp /tmp/clone-ubuntu.XXXXX) # Work file used by DistInfo ()
#
# Function Cleanup () Removes temporary files
#
CleanUp () {
[[ -f "$tmpPart" ]] && rm -f "$tmpPart" # If we created temp files
[[ -f "$tmpMenu" ]] && rm -f "$tmpMenu" # at various program stages
[[ -f "$tmpInf1" ]] && rm -f "$tmpInf1" # then remove them before
[[ -f "$tmpInf2" ]] && rm -f "$tmpInf2" # exiting.
[[ -f "$tmpInf3" ]] && rm -f "$tmpInf3"
if [[ -d "$TargetMnt" ]]; then # Did we create a clone mount?
umount "$TargetMnt" -l # Unmount the clone
rm -d "$TargetMnt" # Remove clone directory
fi
}
#
# Function GetUUID () gets UUIDs of source and clone target partitions in menu.
#
GetUUID () {
SrchLine="$1" # menu line passed to function
UUID_col=0 # start column of UUID in line
lsblk -o NAME,UUID > "$tmpPart" # Get list of UUID's
while read -r UUID_Line; do # Read through UUID list
# Establish UUID position on line
if [[ $UUID_col == 0 ]] ; then # First time will be heading
UUID_col="${UUID_Line%%UUID*}" # Establish column number
UUID_col="${#UUID_col}" # where UUID appears on line
NameLen=$(( UUID_col - 1 )) # Max length of partition name
continue # Skip to read next line
fi
# Check if Passed line name (/dev/sda1, /nvme01np8, etc.) matches.
if [[ "${UUID_Line:0:$NameLen}" == "${SrchLine:0:$NameLen}" ]] ; then
FoundUUID="${UUID_Line:UUID_col:999}"
break # exit function
fi
done < "$tmpPart" # Read next line & loop back
}
#
# Function DistInfo () builds information about source & target partitions
#
DistInfo () {
Mount="$1" # Mount name is '/' or $TargetMnt
FileName="$2" # "$tmpInf1" or "$tmpInf2" work file
cat "$Mount"/etc/lsb-release >> "$FileName"
sed -i 's/DISTRIB_//g' "$FileName" # Remove DISTRIB_ prefix.
sed -i 's/=/:=/g' "$FileName" # Change "=" to ":="
sed -i 's/"//g' "$FileName" # Remove " around "Ubuntu 16.04...".
# Align columns from "Xxxx:=Yyyy" to "Xxxx: Yyyy"
cat "$FileName" | column -t -s '=' > "$tmpInf3"
cat "$tmpInf3" > "$FileName"
}
#
# Mainline
#
lsblk -o NAME,FSTYPE,LABEL,SIZE,MOUNTPOINT > "$tmpMenu"
i=0
SPACES=' '
DoHeading=true
AllPartsArr=() # All partitions.
# Build whiptail menu tags ($i) and text ($Line) into array
while read -r Line; do
if [[ $DoHeading == true ]] ; then
DoHeading=false # First line is the heading.
MenuText="$Line" # Heading for whiptail.
FSTYPE_col="${Line%%FSTYPE*}"
FSTYPE_col="${#FSTYPE_col}" # Required to ensure `ext4`.
MOUNTPOINT_col="${Line%%MOUNTPOINT*}"
MOUNTPOINT_col="${#MOUNTPOINT_col}" # Required to ensure not mounted.
continue
fi
Line="$Line$SPACES" # Pad extra white space.
Line=${Line:0:74} # Truncate to 74 chars for menu.
if [[ "${Line:MOUNTPOINT_col:4}" == "/ " ]] ; then
GetUUID "$Line"
SourceUUID=$FoundUUID
# Build "/dev/Xxxxx" FS name from "├─Xxxxx" lsblk line
SourceDev="${Line%% *}"
SourceDev=/dev/"${SourceDev:2:999}"
fi
AllPartsArr+=($i "$Line") # Menu array entry = Tag# + Text.
(( i++ ))
done < "$tmpMenu" # Read next "lsblk" line.
#
# Display whiptail menu in while loop until no errors, or escape,
# or valid partion selection .
#
DefaultItem=0
while true ; do
# Call whiptail in loop to paint menu and get user selection
Choice=$(whiptail \
--title "Use arrow, page, home & end keys. Tab toggle option" \
--backtitle "Clone 16.04 for upgrade. ONLY CLONES / PARTITION" \
--ok-button "Select unmounted partition" \
--cancel-button "Exit" \
--notags \
--default-item "$DefaultItem" \
--menu "$MenuText" 24 80 16 \
"${AllPartsArr[@]}" \
2>&1 >/dev/tty)
clear # Clear screen.
if [[ $Choice == "" ]]; then # Escape or dialog "Exit".
CleanUp
exit 0;
fi
DefaultItem=$Choice # whiptail start option.
ArrNdx=$(( $Choice * 2 + 1)) # Calculate array offset.
Line="${AllPartsArr[$ArrNdx]}" # Array entry into $Line.
# Validation - Don't wipe out Windows or Ubuntu 16.04:
# - Partition must be ext4 and cannot be mounted.
if [[ "${Line:FSTYPE_col:4}" != "ext4" ]] ; then
echo "Only 'ext4' partitions can be clone targets."
read -p "Press <Enter> to continue"
continue
fi
if [[ "${Line:MOUNTPOINT_col:4}" != " " ]] ; then
echo "A Mounted partition cannot be a clone target."
read -p "Press <Enter> to continue"
continue
fi
GetUUID "$Line" # Get UUID of target partition.
TargetUUID=$FoundUUID
# Build "/dev/Xxxxx" FS name from "├─Xxxxx" menu line
TargetDev="${Line%% *}"
TargetDev=/dev/"${TargetDev:2:999}"
break # Validated: Break menu loop.
done # Loop while errors.
#
# Mount Clone Target partition
#
Release=$(lsb_release -rs) # Source version ie: '16.04'
TargetMnt="/mnt/clone$Release"
echo ""
echo "====================================================================="
echo "Mounting clone partition $TargetDev as $TargetMnt"
mkdir -p "$TargetMnt" # '-p' directory may already exist
mount -t auto -v $TargetDev "$TargetMnt" > /dev/null
# Confirm partition is empty. If not empty confirm it's Ubuntu. If not exit.
# If Ubuntu display prompt with the version it contains and get confirmation.
echo ""
echo "====================================================================="
echo "PLEASE: Carefully confirm Source (Live) and Target (Clone) partitions"
# Build source information (our current boot partition)
echo "SOURCE (BOOT /)=$SourceDev" > "$tmpInf1"
DistInfo "/" "$tmpInf1" # /etc/lsb_release information
df -h --output=size,used,avail,pcent "$SourceDev" >> "$tmpInf1"
# Build target information (the partition selected for cloning to)
LineCnt=$(ls "$TargetMnt" | wc -l)
if (( LineCnt > 1 )) ; then
# More than /Lost+Found exist so it's not an empty partition.
if [[ -f "$TargetMnt"/etc/lsb-release ]] ; then
echo "TARGET (CLONE)=$TargetDev" > "$tmpInf2"
DistInfo "$TargetMnt" "$tmpInf2" # /etc/lsb_release information
else
# TO-DO: might be cloning /boot or /home on separate partitions.
# the source partition is still `/` so can display message.
echo "Selected partition has data which is not Ubuntu OS. Aborting."
CleanUp # Remove temporary files
exit 1
fi
else
echo "Target (Clone) partition appears empty" > "$tmpInf2"
echo "/Lost+Found normal in empty partition" >> "$tmpInf2"
echo "Head of '/Clone/' files & directories:" >> "$tmpInf2"
ls "$TargetMnt" | head -n2 >> "$tmpInf2"
fi
# Target device free bytes
df -h --output=size,used,avail,pcent "$TargetDev" >> "$tmpInf2"
# Display source and target partitions side-by-side using bold text.
echo $(tput bold) # Set to bold text
paste -d '|' "$tmpInf1" "$tmpInf2" | column -t -s '|'
echo $(tput sgr0) # Reset to normal text
echo "NOTE: If you are recloning, new files in clone will be deleted,"
echo " modified files are reset to current source content and,"
echo " files deleted from clone are added back from source."
echo ""
read -p "Type Y (or y) to proceed. Any other key to exit: " -n 1 -r
echo # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]] ; then
CleanUp # Remove temporary files
exit 0
fi
# Copy non-virtual directories to clone. Credit to TikTak's Ask Ubuntu answer:
# https://askubuntu.com/questions/319805/is-it-safe-to-clone-the-current-used-disk?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
SECONDS=0
echo ""
echo "====================================================================="
echo "Using rsync to clone / to $TargetDev mounted as $TargetMnt"
rsync -haxAX --stats --delete --info=progress2 --info=name0 --inplace \
/* "$TargetMnt" \
--exclude={/dev/*,/proc/*,/sys/*,/tmp/*,/run/*,/mnt/*,/media/*,/lost+found}
# For 16GB on Samsung Pro 960: First time 98 seconds, second time 27 seconds.
rsyncTime=$SECONDS
echo ""
echo "Time to clone files: $rsyncTime Seconds"
# Change /etc/update-manager/release-upgrades prompt from never to LTS
echo ""
echo "====================================================================="
echo "Making changes in: $TargetMnt/etc/update-manager/release-upgrades"
echo " from Prompt=: never"
echo " to Prompt=: lts"
echo "Allows running 'do-release-upgrade -d' when rebooting clone target"
echo "Consider 'do-release-upgrade -d -f DistUpgradeViewNonInteractive' This"
echo "allows you to go to bed or go to lunch whilst upgrade runs."
echo ""
echo "* * * When you Upgrade, TURN OFF screen locking for inactivity. * * *"
echo ""
sed -i 's/Prompt=never/Prompt=lts/' "$TargetMnt"/etc/update-manager/release-upgrades
## This section commented out to prevent surprises. You may uncomment.
## You may want to revise to include `cron.daily`, `cron.hourly`, etc.
# Move `/etc/cron.d` reboot jobs to `/etc/cron.d/hold` to prevent running
# scripts such as daily backup or Ubuntu 16.04 specific problem fixes.
#echo ""
#echo "====================================================================="
#echo "Moving '$TargetMnt/etc/cron.d' to '.../hold' to prevent running."
#echo "After booting clone, move back individual files you want to run"
#if [[ ! -d "$TargetMnt"/etc/cron.d/hold ]]; then
# mkdir "$TargetMnt"/etc/cron.d/hold
#fi
#cp -p "$TargetMnt"/etc/cron.d/* "$TargetMnt"/etc/cron.d/hold/
#rm -fv "$TargetMnt"/etc/cron.d/*
# Update /etc/fstab on clone partition with clone's UUID
echo ""
echo "====================================================================="
echo "Making changes in: $TargetMnt/etc/fstab"
echo " from UUID: $SourceUUID"
echo " to UUID: $TargetUUID"
sed -i "s/$SourceUUID/$TargetUUID/g" "$TargetMnt"/etc/fstab
# Update /boot/grub/grub.cfg on clone partition with clone's UUID
echo ""
echo "====================================================================="
echo "Making changes in: $TargetMnt/boot/grub/grub.cfg"
echo " from UUID: $SourceUUID"
echo " to UUID: $TargetUUID"
echo "Also change 'quiet splash' to 'nosplash' for environmental awareness"
echo "Suggest first time booting clone you make wallpaper unique"
sed -i "s/$SourceUUID/$TargetUUID/g" "$TargetMnt"/boot/grub/grub.cfg
sed -i "s/quiet splash/nosplash/g" "$TargetMnt"/boot/grub/grub.cfg
# Update grub boot menu
echo ""
echo "====================================================================="
echo "Calling 'update-grub' to create new boot menu"
update-grub
# Unmount and exit
echo ""
echo "====================================================================="
echo "Unmounting $TargetDev as $TargetMnt"
CleanUp # Remove temporary files
exit 0
```
Copy and paste the bash code above to a new file called `/usr/local/bin/clone-ubuntu.sh`. Then make the new file executable using:
```
sudo chmod a+x /usr/local/bin/clone-ubuntu.sh
```
To call the script use:
```
sudo clone-ubuntu.sh
```
---
How to upgrade 16.04 LTS clone to Ubuntu 18.04 LTS
==================================================
This is a "bonus" section that may interest many people.
Reboot your machine. The `grub` menu will contain a new menu option pointing to the cloned partition. You can also select a specific kernel version from the clone's **Advanced Options** menu.
One way to convert the cloned 16.04 LTS to 18.04 LTS is to run:
```
sudo do-release-upgrade
```
Note the `-d` flag was required prior to July 26, 2018 but is no longer necessary.
***Read the 18.04 upgrade confirmation carefully***.
Before proceeding ensure inactive screen locking is turned off. The upgrade process could crash if your computer goes to the lock screen due to keyboard inactivity.
Summary of 18.04 upgrade process
--------------------------------
This section will be machine specific because different apps are installed by different users. Here is a brief summary I made based on notes and memory:
1. confirmation to proceed: ENTER
2. packages will be removed: Y
3. replace longind.conf: Y
4. Configuration file '/etc/sane.d/dll.conf', default N, take Y
5. '/etc/NetworkManager/conf.d/default-wifi-powersave-on.conf' Take default N
6. Configuration file '/etc/pulse/default.pa' default N, take Y
7. Configuration file '/etc/grub.d/30\_os-prober'' default N, take N
8. Full screen grub menu config appears. Take option: keep the local version currently installed
9. Configuration file '/etc/cron.d/anacron', default N, take Y to see what
10. An error message multiple times: /sbin/ldconfig.real: Warning: ignoring configuration file that cannot be opened: /etc/ld.so.conf.d/x86\_64-linux-gnu\_EGL.conf: No such file or directory
11. Non-standard: Configuration file '/etc/vnstat.conf' (display differences 1.13 vs 1.18) take Y
12. 220 packages are going to be removed. (can take hours) enter Y
13. To finish the upgrade, a restart is required. Take Y
Note step 10 most people will never see. I have an old nVidia driver installation on my Ubuntu 16.04 I never got around to fully removing. It's included because you might have similar old packages never fully removed.
Grub changes boot menu to clone under UEFI
------------------------------------------
Unlike 18.04 upgrades I found the 18.04.1 upgrade changed the Grub UEFI configuration to use the clone's grub menu instead of the original grub menu as per this answer: [Dual boot and the files /boot/grub/grub.cfg -- which one is used?](https://askubuntu.com/questions/752627/dual-boot-and-the-files-boot-grub-grub-cfg-which-one-is-used/1068993#1068993)
```
$ sudo cat /boot/efi/EFI/ubuntu/grub.cfg
search.fs_uuid b40b3925-70ef-447f-923e-1b05467c00e7 root
set prefix=($root)'/boot/grub'
configfile $prefix/grub.cfg
$ sudo grub-install
Installing for x86_64-efi platform.
Installation finished. No error reported.
```
Running `sudo update-grub` after booting the original partition isn't enough to change which `grub.cfg` is loaded by grub. You need to use `sudo grub-install` to force grub to use the original partition's configuration.
Both the original partition and clone partition can use `update-grub` to maintain their own `/boot/grub/grub.cfg` file but only one can be used during boot.
Of course if you want grub to use the Clone's grub menu do not do the above steps on the original's partition.
---
Edit history
============
**Edit May 6, 2018** - Information display for an empty clone (target) partition corrected.
**Edit August 26, 2018** - Use `--inplace` option with `rsync` so large files such as a 2 GB trash file are not duplicated on clone during copy process. This can lead to "out of disk space" error. Comment out `/etc/cron.d` overrides because users may want to keep or want a different directory altogether. Update instructions to use `do-release-upgrade` without `-d` flag because Ubuntu 18.04.1 LTS is now released. | Problems with upgrading from previous releases to 18.04 LTS
===========================================================
It is not at all straightforward to upgrade from previous releases to 18.04 LTS. I don't know if there are more problems than such upgrading in the past, but **people who do release upgrading now take a risk** for themselves. On the other hand they find bugs and [if the bugs are reported](https://launchpad.net/), it will help develop the upgrading tool as well as debug the Ubuntu 18.04 LTS system itself.
This means that **people who are patient enough** to wait until the upgrading is officially released with the first point release (18.04.1 LTS) **will get a smoother ride**.
### Testing before doing the full upgrade ...
The method that @WinEunuuchs2Unix describes here makes it possible to test with a copy of the real system, if upgrading to 18.04 LTS will work with your current [more or less modified] operating system with your computer hardware.
This can prevent several disasters with corrupted operating system.
I have not used @WinEunuuchs2Unix's script yet, but I understand, that it is very useful, and I intend to use it. I was able to upgrade from 8.04 to 10.04 to 12.04, which I used for a long time. But when I set out to upgrade via 14.04 to 16.04 I failed and could not find the errors.
### ... and if problems, make a fresh installation
I had **good backups**, so I made a fresh install of 16.04 and later on copied, what I wanted to keep and checked for tweaks, scripts, aliases and installed programs. If I had used @WinEunuuchs2Unix's method I had seen the problem early, I would have made a fresh install directly.
Upgrading a persistent live system
==================================
Persistent live systems are used to get very portable Ubuntu systems, that are sometimes used for testing but sometimes used for a long time.
It is a known problem, that you should not update & upgrade such a system like you do with an installed system because it will get corrupted sooner or later. Furthermore, you are stuck with the kernel and kernel drivers, that come with the iso file, because they are started before the overlay system is started.
But it is usually possible to keep the `/home` directory, like you can, when you make a fresh installation with a separate 'home' partition. If you create a `home-rw` partition, a persistent live system will find and use it automatically during boot.
I am developing and testing a shellscript, **mk-persistent-live\_with\_home-rw**, *that can create* a persistent live system with a `home-rw` partition, and *that can later upgrade* it,
* replace the iso file with a newer one. At least you should upgrade when a new iso file is released, but you can also upgrade an LTS system once a month and use the current daily iso files from the [testing tracker](http://iso.qa.ubuntu.com/),
* modify grub for the new iso file.
* wipe (reformat) the `casper-rw` file which stores the modifications of the operating system (so you must re-install the program packages that you added to the system),
* preserve the `home-rw` partition with your personal files, settings and tweaks.
* See [this link](https://ubuntuforums.org/showthread.php?t=2259682&p=13761527#post13761527) for more details.
Extra link
==========
General tips for people who want to test the latest and greatest version of Ubuntu can be found in the following link,
[How to participate in testing and development of Ubuntu](https://askubuntu.com/questions/1018033/ubuntu-development-version-how-to-participate/1018060#1018060) |
475,373 | "The original definition, in terms of a finitely additive invariant measure (or mean) on subsets of G, was introduced by John von Neumann in 1929 under the German name "messbar" ("measurable" in English) in response to the Banach–Tarski paradox. In 1949 Mahlon M. Day introduced the English translation "amenable", apparently as a pun." <https://en.wikipedia.org/wiki/Amenable_group>
I'm not a native speaker and I don't get the pun :) | 2013/08/24 | [
"https://math.stackexchange.com/questions/475373",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/70687/"
] | I will add a quote from Runde, V. (2002), Lectures on Amenability, Lecture Notes in Mathematics 1774, Springer, ISBN 9783540428527, [p.34](https://books.google.com/books?id=-YLoYK26rTsC&pg=PA34). (Notice that the Wikipedia article says in a footnote: "Day's first published use of the word is in his abstract for an AMS summer meeting in 1949, Means on semigroups and groups, Bull. A.M.S. 55 (1949) 1054–1055. Many text books on amenabilty, such as Volker Runde's, suggest that Day chose the word as a pun.")
>
> Amenable (discrete) groups were first considered by J. von Neumann, albeit under a different name ([Neu]). The first to use the adjective "amenable" was M. M. Day in [Day], apparently with a pun in mind: These groups $G$ are called a*men*able because they have an invariant mean on $L^\infty(G)$, but also since they are particularly pleasant to deal with and thus are truly *amenable* - just in the sense of that adjective in colloquial English.
>
>
>
So the above explanations confirms what André Nicolas wrote [in his comment](https://math.stackexchange.com/questions/475373/why-is-amenable-group-a-pun#comment1023502_475373)
Wiktionary: [amenable](https://en.wiktionary.org/wiki/amenable) | It suggests a group of people who get along well with one another. :)
I hadn't thought of @André's interpretation; pronunciation notwithstanding, I yield. :) |
11,880,549 | Using this code to exchange the initial code of the requests coming from Drive UI with a token i can use to make API requests.
```
public GoogleCredential exchangeCode(String authorizationCode) throws CodeExchangeException {
try {
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, authorizationCode, REDIRECT_URI).execute();
return new GoogleCredential.Builder().setClientSecrets(CLIENT_ID, CLIENT_SECRET).setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build().setFromTokenResponse(response);
}
catch (Exception e) {
log.error("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
```
In most cases it works, however in some cases (perhaps 5%), i get
```
An error occurred: com.google.api.client.auth.oauth2.TokenResponseException: 500 Error processing OAuth 2 request
<HTML>
<HEAD>
<TITLE>Error processing OAuth 2 request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Error processing OAuth 2 request</H1>
<H2>Error 500</H2>
</BODY>
</HTML>
```
What could be the problem? | 2012/08/09 | [
"https://Stackoverflow.com/questions/11880549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1587037/"
] | Yes, you can if you want. They work well in Symbian Emulator which is a usual Windows application. More over, you can build them from sources and use only those UI components, which you need. [Here](http://goo.gl/u2TCy) I published a sample project, which demonstrates that idea. | I don't think that you can use them for Desktop apps. However, some Qt Quick components for Desktop exists : <http://labs.qt.nokia.com/2011/03/10/qml-components-for-desktop/> |
5,919,760 | I'm trying to parse some string and it has some http links embedded in it. I'd like to dynamically create anchor tags within this string using jquery then display them on the front end so the user can click them.
Is there a way to do this?
Thanks! | 2011/05/07 | [
"https://Stackoverflow.com/questions/5919760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/382906/"
] | You can do it like this:
```
$(function(){
//get the string
var str = $("#text").html();
//create good link matching regexp
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g
// $1 is the found URL in the text
// str.replace replaces the found url with <a href='THE URL'>THE URL</a>
var replaced_text = str.replace(regex, "<a href='$1'>$1</a>")
//replace the contents
$("#text").html(replaced_text);
});
```
[working example](http://jsfiddle.net/) | @cfarm , you can grab the urls and construct html of your own.
parse the string and start making the urls and keep a place holder in your Html , use
<http://api.jquery.com/html/>
or
<http://api.jquery.com/append/> |
59,807,958 | I was building React Native Mobile Application with GraphQL. Now I've been stuck with passing array inside GraphQL mutation. I have been using redux-thunk as middleware to pass data to GraphQL mutation.
My GraphQL mutation info:
```
createVirtualChallenge(
name: String!
target: String!
image: String
description: String
from: String!
to: String!
selectedUsers: [String]
): VirtualChallengeResponse!
```
I have been passing selected users as an array which looks like this :
>
> ["5e2148d4b76df200314f4848", "5e213e6ab76df200314f47c4"]
>
>
>
My redux thunk fetch function is like this
```
fetch(URL.BASE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({
query: `mutation{ createVirtualChallenge( name:"${name}", target:"${target}", image:"${image_name}", description:"${description}", from:"${from}", to:"${to}", selectedUsers: "${selectedUsers}" , ){ success } }`,
}),
})
.then(res => res.json())
```
All the values are passing through props using redux.
If the array length is 1, then this mutation works.. But if the array length is greater than 1 then GraphQL throws an error.
>
> Response from the URL - {"data": null, "errors": [{"extensions":
> [Object], "locations": [Array], "message": "virtualChallenge
> validation failed: selectedUsers: Cast to Array failed for value \"[
> '5e213e6ab76df200314f47c4,5e214493b76df200314f47fa' ]\" at path
> \"selectedUsers\"", "path": [Array]}]}
>
>
> | 2020/01/19 | [
"https://Stackoverflow.com/questions/59807958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7867613/"
] | Remove the quotes for that argument since the quote is using for wrapping String. Since it's an array convert into a corresponding JSON string and which will be valid array input for graphql.
`selectedUsers: "${selectedUsers}"` ===> `selectedUsers: ${JSON.stringify(selectedUsers)}`
```
body: JSON.stringify({
query: `mutation{ createVirtualChallenge( name:"${name}", target:"${target}", image:"${image_name}", description:"${description}", from:"${from}", to:"${to}", selectedUsers: ${JSON.stringify(selectedUsers)} ){ success } }`,
}),
``` | You should never use string interpolation to inject values into a GraphQL query. The preferred way is to utilize variables, which can be sent along with your query as JSON object that the GraphQL service will parse appropriately.
For example, instead of
```
mutation {
createVirtualChallenge(name: "someName"){
success
}
}
```
you would write:
```
mutation ($name: String!) {
createVirtualChallenge(name: $name){
success
}
}
```
and then pass the value for `name` along with your request:
```
fetch(
...
body: JSON.stringify({
query: `...`,
variables: {
name: 'someName',
},
}),
)
```
Utilize a variable for each argument value you want to dynamically inject into your query. This is easier than trying to inject the values yourself since you don't have to worry about GraphQL-specific syntax -- you're just passing along a JSON object. You will, however, need to know the type for each argument you are replacing this way, so you'll need to refer to your GraphQL service's schema. |
7,182,786 | I was about to implement a table view behavior like the one used in a certain part of the twitter app for iPhone, precisely I'm talking about the tableview shown when, in a geolocalized tweet, I tap on the location displayed under the tweet. . .here's some pictures just to give it a look:


as you can see the table view has a background beneath (actually the map), but it is not just a background UIView (or Mapview) because the table view pulls it up and down with herself if the scrolling is about to "bounce". . .and it is certainly not a section header/footer, because the table floats on it. . .so, do you have any ideas on how to implement that table view? Could it be a webview?
---
edit: I found a solution and posted it down | 2011/08/24 | [
"https://Stackoverflow.com/questions/7182786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245558/"
] | It would be far easier to just use [`strftime()`](http://php.net/manual/en/function.strftime.php). All you have to do is set a `locale` and you can output in your desired language.
Example:
```
setlocale(LC_ALL, 'es_ES'); // I think it´s es_ES
$my_time = strftime("%B %e, %G, %I:%M %P"); // something like that...
``` | I think you mean
```
$search = array('August', 'September', 'October', 'November', 'December');
$replace = array('Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
```
instead of
```
$search = $time_english('August', 'September', 'October', 'November', 'December');
$replace = $times_spanish('Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
```
---
As a point of interest, the reason your error says it's trying to call a function named `August 24, 2011, 3:50 pm()` is because of the apparent variable function name `$time_english()`. It's returning the value of `$time_english` then trying to run that as a function.
---
Here's the whole thing:
```
$p['time'] = date("F j, Y, g:i a");
$time_english = $p['time'];
$search = array('August', 'September', 'October', 'November', 'December');
$replace = array('Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
$time_spanish = str_replace($search, $replace, $time_english);
``` |
7,182,786 | I was about to implement a table view behavior like the one used in a certain part of the twitter app for iPhone, precisely I'm talking about the tableview shown when, in a geolocalized tweet, I tap on the location displayed under the tweet. . .here's some pictures just to give it a look:


as you can see the table view has a background beneath (actually the map), but it is not just a background UIView (or Mapview) because the table view pulls it up and down with herself if the scrolling is about to "bounce". . .and it is certainly not a section header/footer, because the table floats on it. . .so, do you have any ideas on how to implement that table view? Could it be a webview?
---
edit: I found a solution and posted it down | 2011/08/24 | [
"https://Stackoverflow.com/questions/7182786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245558/"
] | It would be far easier to just use [`strftime()`](http://php.net/manual/en/function.strftime.php). All you have to do is set a `locale` and you can output in your desired language.
Example:
```
setlocale(LC_ALL, 'es_ES'); // I think it´s es_ES
$my_time = strftime("%B %e, %G, %I:%M %P"); // something like that...
``` | This is probably correct one
```
$p['time'] = date("F j, Y, g:i a");
$search = array('August', 'September', 'October', 'November', 'December');
$replace = array('Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
str_replace($search, $replace, $subject);
``` |
11,707,678 | i been reading for hours trying to make this work but i dont have much knowledge to do it.
I have this js code:
```
var username=$(this).attr("username");
```
It pull a list of users f.e (admin, test1, test2, test3)
and i needs to split it into another var like this:
```
var members = [
['admin'],
['test1'],
['test2'],
['test3'],
];
```
I tried a lot of codes but i cant make it work, thanks in advance! | 2012/07/29 | [
"https://Stackoverflow.com/questions/11707678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133401/"
] | To get an array of usernames:
```
var username = $(this).attr("username");
var members = username.split(',');
```
To get exactly what you've suggested you want (an array of arrays? - I don't think this is actually what you want):
```
var username = $(this).attr("username");
var membersArr = username.split(',');
var members = new Array();
for (var i = 0; i < membersArr.length; i++)
{
members[i] = [ membersArr[i] ];
}
```
To get "[test1]", "[test2]" etc:
```
var username = $(this).attr("username");
var members = username.split(',');
for (var i = 0; i < members.length; i++)
{
members[i] = '[' + members[i] + ']';
}
``` | **Update**
To get the array of arrays,
```
var username=$(this).attr("username");
var membersArray= username.split(' ').map(function(username){
return [username];
})
//[["admin"],["test"],["test1"],["test2"]]
```
I've added a [fiddle here](http://jsfiddle.net/NVENA/) |
27,520,257 | I need to close the window after alertbox, I used the codes which was asked in [Stack Question](https://stackoverflow.com/questions/17567126/how-to-close-the-current-window-in-browser-after-clicking-ok-in-the-alert-messag) But my alert box is inside a php code, I am getting the alert box but once i close it the window is not getting closed, I am new to php . The codes are below, Please help me out guys
```
<?php
$serial_get = trim(str_replace("(","",str_replace(")","",GetVolumeLabel("d"))));
if ($serial_get == '1233-2AZ2'){
}
else{
echo '<script language="javascript">
window.alert("This is not a Licensed Software. Please contact IT Solutions.");
window.close()
</script>'; }?>
``` | 2014/12/17 | [
"https://Stackoverflow.com/questions/27520257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2700327/"
] | You need `window.open(...)` to be able to `window.close()`. You are using `window.alert()`.
See **Best Practice** in the link <https://developer.mozilla.org/en-US/docs/Web/API/Window.open> | Some browsers won't respect the command unless it is user-initiated. But... Here's a workaround that may work for you. try this instead of `close`:
```
open(location, '_self').close();
```
Or maybe fool the browser into thinking it was user initiated. This may or may not work; haven't tested. I'm just throwing spaghetti at the wall...
```
var btn = document.createElement('button');
document.body.appendChild(btn);
btn.addEventListener('click', function() {
open(location, '_self').close();
}, false);
btn.dispatchEvent(new Event('click'));
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | Look into the mod operator. It is typed `%` and will produce the remainder of a long division operation.
Once you have the remainder, you can greatly simplify your rounding. You know if you need to round up or down with a simple if statement. Then to find out *which* multiple of 9 you need to round up or down to, divide (whole number division only) with the `/` operator and remultiply. | ```
private int getInventorySize(int max) {
if (max < 9) {
return 9;
}
if (max <= 54 && max > 9) {
int a = max / 9;
return a * 9;
} else
return 54;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You can do:
```
private int getInventorySize(int max) {
if (max <= 0) return 9;
int quotient = (int)Math.ceil(max / 9.0);
return quotient > 5 ? 54: quotient * 9;
}
```
Divide the number by `9.0`. And taking the ceiling will get you the next integral quotient. If quotient is `> 5`, then simply return `54`, else `quotient * 9` will give you multiple of `9` for that quotient.
Some test cases:
```
// Negative number and 0
System.out.println(getInventorySize(-1)); // 9
System.out.println(getInventorySize(0)); // 9
// max <= 9
System.out.println(getInventorySize(5)); // 9
System.out.println(getInventorySize(9)); // 9
// some middle case
System.out.println(getInventorySize(43)); // 45
// max >= 54
System.out.println(getInventorySize(54)); // 54
System.out.println(getInventorySize(55)); // 54
``` | ```
int round(int num) {
return (num>54)?54:(num%9==0)?num:((num/9)+1)*9;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | Look into the mod operator. It is typed `%` and will produce the remainder of a long division operation.
Once you have the remainder, you can greatly simplify your rounding. You know if you need to round up or down with a simple if statement. Then to find out *which* multiple of 9 you need to round up or down to, divide (whole number division only) with the `/` operator and remultiply. | ```
int round(int num) {
return (num>54)?54:(num%9==0)?num:((num/9)+1)*9;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You can do:
```
private int getInventorySize(int max) {
if (max <= 0) return 9;
int quotient = (int)Math.ceil(max / 9.0);
return quotient > 5 ? 54: quotient * 9;
}
```
Divide the number by `9.0`. And taking the ceiling will get you the next integral quotient. If quotient is `> 5`, then simply return `54`, else `quotient * 9` will give you multiple of `9` for that quotient.
Some test cases:
```
// Negative number and 0
System.out.println(getInventorySize(-1)); // 9
System.out.println(getInventorySize(0)); // 9
// max <= 9
System.out.println(getInventorySize(5)); // 9
System.out.println(getInventorySize(9)); // 9
// some middle case
System.out.println(getInventorySize(43)); // 45
// max >= 54
System.out.println(getInventorySize(54)); // 54
System.out.println(getInventorySize(55)); // 54
``` | Look into the mod operator. It is typed `%` and will produce the remainder of a long division operation.
Once you have the remainder, you can greatly simplify your rounding. You know if you need to round up or down with a simple if statement. Then to find out *which* multiple of 9 you need to round up or down to, divide (whole number division only) with the `/` operator and remultiply. |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You can do:
```
private int getInventorySize(int max) {
if (max <= 0) return 9;
int quotient = (int)Math.ceil(max / 9.0);
return quotient > 5 ? 54: quotient * 9;
}
```
Divide the number by `9.0`. And taking the ceiling will get you the next integral quotient. If quotient is `> 5`, then simply return `54`, else `quotient * 9` will give you multiple of `9` for that quotient.
Some test cases:
```
// Negative number and 0
System.out.println(getInventorySize(-1)); // 9
System.out.println(getInventorySize(0)); // 9
// max <= 9
System.out.println(getInventorySize(5)); // 9
System.out.println(getInventorySize(9)); // 9
// some middle case
System.out.println(getInventorySize(43)); // 45
// max >= 54
System.out.println(getInventorySize(54)); // 54
System.out.println(getInventorySize(55)); // 54
``` | ```
private int getInventorySize (int max) {
if (max < 9) return 9;
for (int i = 9; i <= 54; i += 9) {
if (max <= i) {
return i;
}
}
return 54;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | Look into the mod operator. It is typed `%` and will produce the remainder of a long division operation.
Once you have the remainder, you can greatly simplify your rounding. You know if you need to round up or down with a simple if statement. Then to find out *which* multiple of 9 you need to round up or down to, divide (whole number division only) with the `/` operator and remultiply. | its super easy! here you go:
```
Math.ceil((number/9))*9
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You do a one-liner with modulo like this:
```
return (max>=54) ? 54 : max+(9-max%9)*Math.min(1,max%9);
``` | ```
private int getInventorySize(int max) {
if (max < 9) {
return 9;
}
if (max <= 54 && max > 9) {
int a = max / 9;
return a * 9;
} else
return 54;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You do a one-liner with modulo like this:
```
return (max>=54) ? 54 : max+(9-max%9)*Math.min(1,max%9);
``` | The easiest way to do it with a formula is probably with integer divide, catching the special conditions first:
```
private int getInventorySize (int max) {
if (max < 1) return 9;
if (max > 54) return 54;
max += 8;
return max - (max % 9);
}
```
The following table shows how this works:
```
max max+8[A] A%9[B] A-B
--- -------- ------ ---
<1 9
1 9 0 9
2 10 1 9
:
8 16 7 9
9 17 8 9
10 18 0 18
:
18 26 8 18
19 27 0 27
:
53 61 7 54
54 62 8 54
>54 54
```
---
However, keep in mind that there's nothing intrinsically *wrong* with what you've proposed in your question, but you can clean it up considerably, to the point where it's more understandable than the math-based solutions (if your input range was larger, you wouldn't use this method since the number of `if` statements would become unwieldy):
```
private int getInventorySize (int max) {
if (max <= 9) return 9;
if (max <= 18) return 18;
if (max <= 27) return 27;
if (max <= 36) return 36;
if (max <= 45) return 45;
return 54;
}
```
The use of the `if ... return ... else` construct is totally unnecessary since the `else` is superfluous - if it wasn't going to happen the `return` would have already returned.
Similarly, there's no point having two separate cases returning 54 when they can be combined into one.
Honestly, if you're not expecting the input range to increase, I'd actually go for the second solution since, given its size, it's actually more easily understood.
As you can see from the following test harness, both these methods work (change which one is commented out to switch between them). I would suggest plugging any of the other answers here into the test harness to ensure they also work (you'll have to make them similarly `static` to get them to work as is):
```
public class Tester {
private static int getInventorySize (int max) {
if (max < 1) return 9;
if (max > 45) return 54;
max += 8;
return max - (max % 9);
}
//private static int getInventorySize (int max) {
// if (max <= 9) return 9;
// if (max <= 18) return 18;
// if (max <= 27) return 27;
// if (max <= 36) return 36;
// if (max <= 45) return 45;
// return 54;
//}
public static void check (int a, int b) {
int sz = getInventorySize(a);
if (sz != b)
System.out.println ("Error, " + a + " -> " + sz + ", not " + b);
}
public static void main (String [] args) {
for (int i = -9999; i <= 9; i++) check (i, 9);
for (int i = 10; i <= 54; i += 9) {
check (i+0, i+8); check (i+1, i+8); check (i+2, i+8);
check (i+3, i+8); check (i+4, i+8); check (i+5, i+8);
check (i+6, i+8); check (i+7, i+8); check (i+8, i+8);
}
for (int i = 55; i <= 9999; i++) check (i, 54);
}
}
```
---
And, just as an aside, I'm not *entirely* certain that it's kosher to round up your inventory like that (assuming the function name is accurate). I can imagine cases where you may want to round *down* your inventory (such as wanting to keep some stock in reserve) but rounding up seems like a big fat lie.
What are you going to tell your customers who paid good money for stock when they come in to find said stock is actually depleted?
Or are you one of those shonky operators who will do anything to get customers into the store? :-) |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | You do a one-liner with modulo like this:
```
return (max>=54) ? 54 : max+(9-max%9)*Math.min(1,max%9);
``` | ```
private int getInventorySize (int max) {
if (max < 9) return 9;
for (int i = 9; i <= 54; i += 9) {
if (max <= i) {
return i;
}
}
return 54;
}
``` |
19,173,774 | Can someone explain this question to me? I don't understand how the book arrived at its values or how one would arrive at the answer.
Here is the question:
>
> Suppose that `ch` is a type `char` variable. Show how to assign the carriage-return character to `ch` by using an escape sequence, a decimal value, an octal character constant, and a hex character constant. (Assume ASCII code values.)
>
>
>
Here is the answer:
>
> Assigning the carriage-return character to `ch` by using:
>
>
> a) escape sequence: `ch='\r';`
>
> b) decimal value: `ch=13;`
>
> c) an octal character constant: `ch='\015';`
>
> d) a hex character constant: `ch='\xd';`
>
>
>
I understand the answer to part a, but am completely lost for parts b, c, and d. Can you explain? | 2013/10/04 | [
"https://Stackoverflow.com/questions/19173774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839484/"
] | Look into the mod operator. It is typed `%` and will produce the remainder of a long division operation.
Once you have the remainder, you can greatly simplify your rounding. You know if you need to round up or down with a simple if statement. Then to find out *which* multiple of 9 you need to round up or down to, divide (whole number division only) with the `/` operator and remultiply. | ```
private int getInventorySize (int max) {
if (max < 9) return 9;
for (int i = 9; i <= 54; i += 9) {
if (max <= i) {
return i;
}
}
return 54;
}
``` |
29,455,732 | I have this Angular code:
```
.state('UserTables', {
url: '/Tables',
resolve: {
auth: function resolveAuthentication(SessionService) {
return SessionService.isUser();
}
},
views: {
"containerMain": {
templateUrl: 'Views/Tables',
controller: TableController
},
}
})
```
And would like to pass some request header to the templateUrl call.
Anyone done something like that?
Basically I have a REST service that can generate the view I need depending on 1 header and some property's. Property's are no problem but I have no clue how to make a call to the service and wait for the result.
*Tried:*
```
views: {
"containerMain": {
template: function (SessionService, $http, $q) {
console.log('template');
var resp = SessionService.getTable($http, $q, 'Generate/Table?objectId=WfObject');
var r = '';
resp.then(function (result) {
r = result;
console.log('resp:', r);
});
console.log('r:',r);
return r;
}
``` | 2015/04/05 | [
"https://Stackoverflow.com/questions/29455732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/728188/"
] | I created [working plunker here](http://plnkr.co/edit/EfVzz9TQihNW4oOv6O7l?p=preview)
To load template with custom headers, we can call do it like this *(check the state 'UserTables' in the plunker)*:
```
views: {
"containerMain": {
//templateUrl: 'Views/Tables',
templateProvider: ['$http',
function ($http) {
var tplRequest = {
method: 'GET',
url: 'Generate/Table?objectId=WfObject',
headers: {
'MyHeaderKey': 'MyHeaderValue'
},
}
return $http(tplRequest)
.then(function(response) {
console.log('loaded with custom headers')
var tpl = response.data;
return tpl;
}
);
}],
controller: 'TableController'
},
}
```
In case, we want (and can) cache the template, we can do it like this *(check the state 'UserTablesWithCache')*:
```
views: {
"containerMain": {
//templateUrl: 'Views/Tables',
templateProvider: ['$http', '$templateCache',
function ($http, $templateCache) {
var templateName = 'Generate/Table?objectId=WfObject';
var tpl = $templateCache.get(templateName)
if(tpl){
console.log('returning from cache');
return tpl;
}
var tplRequest = {
method: 'GET',
url: templateName,
headers: {
'MyHeaderKey': 'MyHeaderValue'
},
}
return $http(tplRequest)
.then(function(response) {
console.log('loaded, placing into cache');
var tpl = response.data;
$templateCache.put(templateName, tpl)
return tpl;
}
);
}],
controller: 'TableController'
},
}
```
And if we would not need headers, and we could cache, it is really very easy, as documented here:
* [Trying to Dynamically set a templateUrl in controller based on constant](https://stackoverflow.com/a/28872022/1679310)
Drafted version could be: *(no custom headers but effective loading and caching)*
```
templateProvider: ['$templateRequest', function(CONFIG, $templateRequest) {
var templateName = 'Generate/Table?objectId=WfObject';
return $templateRequest(templateName);
}],
``` | `templateUrl` property can also take function as value. So you can add dynamic properties to the templateUrl via there.
```
templateUrl : function(stateParams) {
// before returning the URL, add additional properties and send
// stateParamsargument object refers to $stateParams and you can access any url params from there.
return 'Views/Tables';
}
``` |
1,811,665 | I have a fully calibrated camera setup (that means $K$ and $P = [R|t]$ are known) and want to project a 3d line into the camera image.
The 3d line is defined via world coordinates $A$ and $B$ (as $4x1$ homogeneous vectors) and represented with Plücker coordinates:
$$
L = A\cdot B^T - B\cdot A^T\\
L\_{coord} = \{l\_{12},l\_{13},l\_{14},l\_{23},l\_{42},l\_{34}\}
$$
How is than the projection performed? I assume as the projection matrix for points is $3x4$ the new projection matrix should something like $3x6$. I could not find a good resource about this topic. | 2016/06/03 | [
"https://math.stackexchange.com/questions/1811665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128886/"
] | I found what I was looking for in "Harley & Zisserman" (I must overlooked it). The projected line in the image can be calculated by:
$$
[l]\_x = P\cdot L\cdot P^T
$$
and
$$
[l]\_x =\begin{bmatrix}
0&-c&b&\\
c&0&-a\\
-b&a&0
\end{bmatrix}
$$
where $(a,b,c)$ are coefficients in the line equation $ax+by+c=0$ and $P$ is the standard projection matrix. | Start by computing the plane spanned by the line and the point of the camera. If you don't know how to compute such a join using Plücker coordinates, I can expand on this. The projection of the line is the intersection of that plane with the plane of your image.
If you can choose the embedding of your drawing plane, embed it at $z=0$ in such a way that the $x$ and $y$ axes line up with those of the surrounding 3d space. That way, a point which has homogeneous coordinates $[x:y:0:w]$ in 3d space has homogeneous coordinates $[x:y:w]$ on the plane, you just leave out the third coordinate. Which means that a generic plane with the homogeneous equation $ax+by+cz+dw=0$ will intersect your plane in the line $ax+by+dw=0$, so $[a:b:d]$ would be the in-plane representation of the intersection.
You can also perform all of these steps symbolically using variables as the coordinates of the line. Then the result should be a vector of polynomials in these coordinates, which you can rewrite as a transformation matrix. |
1,811,665 | I have a fully calibrated camera setup (that means $K$ and $P = [R|t]$ are known) and want to project a 3d line into the camera image.
The 3d line is defined via world coordinates $A$ and $B$ (as $4x1$ homogeneous vectors) and represented with Plücker coordinates:
$$
L = A\cdot B^T - B\cdot A^T\\
L\_{coord} = \{l\_{12},l\_{13},l\_{14},l\_{23},l\_{42},l\_{34}\}
$$
How is than the projection performed? I assume as the projection matrix for points is $3x4$ the new projection matrix should something like $3x6$. I could not find a good resource about this topic. | 2016/06/03 | [
"https://math.stackexchange.com/questions/1811665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128886/"
] | Start by computing the plane spanned by the line and the point of the camera. If you don't know how to compute such a join using Plücker coordinates, I can expand on this. The projection of the line is the intersection of that plane with the plane of your image.
If you can choose the embedding of your drawing plane, embed it at $z=0$ in such a way that the $x$ and $y$ axes line up with those of the surrounding 3d space. That way, a point which has homogeneous coordinates $[x:y:0:w]$ in 3d space has homogeneous coordinates $[x:y:w]$ on the plane, you just leave out the third coordinate. Which means that a generic plane with the homogeneous equation $ax+by+cz+dw=0$ will intersect your plane in the line $ax+by+dw=0$, so $[a:b:d]$ would be the in-plane representation of the intersection.
You can also perform all of these steps symbolically using variables as the coordinates of the line. Then the result should be a vector of polynomials in these coordinates, which you can rewrite as a transformation matrix. | You could have simply projected the points A and B to image points a and b
$$a=PA$$
$$b=PB$$
Then compute the 2D line from the 2D image points with cross product. |
1,811,665 | I have a fully calibrated camera setup (that means $K$ and $P = [R|t]$ are known) and want to project a 3d line into the camera image.
The 3d line is defined via world coordinates $A$ and $B$ (as $4x1$ homogeneous vectors) and represented with Plücker coordinates:
$$
L = A\cdot B^T - B\cdot A^T\\
L\_{coord} = \{l\_{12},l\_{13},l\_{14},l\_{23},l\_{42},l\_{34}\}
$$
How is than the projection performed? I assume as the projection matrix for points is $3x4$ the new projection matrix should something like $3x6$. I could not find a good resource about this topic. | 2016/06/03 | [
"https://math.stackexchange.com/questions/1811665",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/128886/"
] | I found what I was looking for in "Harley & Zisserman" (I must overlooked it). The projected line in the image can be calculated by:
$$
[l]\_x = P\cdot L\cdot P^T
$$
and
$$
[l]\_x =\begin{bmatrix}
0&-c&b&\\
c&0&-a\\
-b&a&0
\end{bmatrix}
$$
where $(a,b,c)$ are coefficients in the line equation $ax+by+c=0$ and $P$ is the standard projection matrix. | You could have simply projected the points A and B to image points a and b
$$a=PA$$
$$b=PB$$
Then compute the 2D line from the 2D image points with cross product. |
10,125 | After moving to Canada six months ago, I still haven't found Yukon Gold potatoes at the grocery stores. Instead I find Yellow potatoes and was curious as to whether or not they are considered to be the same or if they are completely different. I find that the texture is a little bit "harder" than the Yukon Gold potatoes but overall seem pretty similar. So, are Yellow potatoes the same as Yukon Gold and can they be used interchangeably? | 2010/12/14 | [
"https://cooking.stackexchange.com/questions/10125",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3478/"
] | They are often used interchangeably. The truth is, yukon gold potatoes are a type of yellow potato. They were developed in Canada. You will definitely see them on store shelves here in Canada, but it can be seasonal, depending on your location. I am in Winnipeg, and I find YG about six months of the year. | Look for Maine Carola Potatoes. They are the closest to the actual Yukon in both flavor and texture. Maine grows lots of Yellow White and Russet potatoes. I'm willing to bet that some stores in the maritime have the Carola Potatoes. |
10,125 | After moving to Canada six months ago, I still haven't found Yukon Gold potatoes at the grocery stores. Instead I find Yellow potatoes and was curious as to whether or not they are considered to be the same or if they are completely different. I find that the texture is a little bit "harder" than the Yukon Gold potatoes but overall seem pretty similar. So, are Yellow potatoes the same as Yukon Gold and can they be used interchangeably? | 2010/12/14 | [
"https://cooking.stackexchange.com/questions/10125",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3478/"
] | They are often used interchangeably. The truth is, yukon gold potatoes are a type of yellow potato. They were developed in Canada. You will definitely see them on store shelves here in Canada, but it can be seasonal, depending on your location. I am in Winnipeg, and I find YG about six months of the year. | In Ontario I find that yellow potatoes are not the same as Yukon gold! Yukons have a different texture and cook differently. I can't find them right now (late September) and am disappointed. Hope they are available soon! |
10,125 | After moving to Canada six months ago, I still haven't found Yukon Gold potatoes at the grocery stores. Instead I find Yellow potatoes and was curious as to whether or not they are considered to be the same or if they are completely different. I find that the texture is a little bit "harder" than the Yukon Gold potatoes but overall seem pretty similar. So, are Yellow potatoes the same as Yukon Gold and can they be used interchangeably? | 2010/12/14 | [
"https://cooking.stackexchange.com/questions/10125",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/3478/"
] | Look for Maine Carola Potatoes. They are the closest to the actual Yukon in both flavor and texture. Maine grows lots of Yellow White and Russet potatoes. I'm willing to bet that some stores in the maritime have the Carola Potatoes. | In Ontario I find that yellow potatoes are not the same as Yukon gold! Yukons have a different texture and cook differently. I can't find them right now (late September) and am disappointed. Hope they are available soon! |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | `$` is not the start of a variable name, it indicates the start of an expression. You should use `${map[key]}` to access the property `key` in map `map`.
You can try it on a page with a `GET` parameter, using the following query string for example `?whatEver=something`
```
<c:set var="myParam" value="whatEver"/>
whatEver: <c:out value="${param[myParam]}"/>
```
This will output:
```
whatEver: something
```
See: <https://stackoverflow.com/tags/el/info> and scroll to the section "Brace notation". | I think that you should access your map something like:
```
${map.key}
```
and check some tutorials about jstl like [1](http://www.ibm.com/developerworks/java/library/j-jstl0211/index.html) and [2](http://www.ibm.com/developerworks/java/library/j-jstl0318/) (a little bit outdated, but still functional) |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | You can put the key-value in a map on `Java` side and access the same using `JSTL` on `JSP` page as below:
**Prior java 1.7:**
```
Map<String, String> map = new HashMap<String, String>();
map.put("key","value");
```
**Java 1.7 and above:**
```
Map<String, String> map = new HashMap<>();
map.put("key","value");
```
**JSP Snippet:**
```
<c:out value="${map['key']}"/>
``` | I think that you should access your map something like:
```
${map.key}
```
and check some tutorials about jstl like [1](http://www.ibm.com/developerworks/java/library/j-jstl0211/index.html) and [2](http://www.ibm.com/developerworks/java/library/j-jstl0318/) (a little bit outdated, but still functional) |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map
Something like this:
`<c:set var="keyString">${someKeyThatIsNotString}</c:set>`
`<c:out value="${map[keyString]}"/>`
Hope that helps | I think that you should access your map something like:
```
${map.key}
```
and check some tutorials about jstl like [1](http://www.ibm.com/developerworks/java/library/j-jstl0211/index.html) and [2](http://www.ibm.com/developerworks/java/library/j-jstl0318/) (a little bit outdated, but still functional) |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | My five cents. Now I am working with EL 3.0 (jakarta impl) and I can access map value using three ways:
```
1. ${map.someKey}
2. ${map['someKey']}
3. ${map[someVar]} //if someVar == 'someKey'
``` | I think that you should access your map something like:
```
${map.key}
```
and check some tutorials about jstl like [1](http://www.ibm.com/developerworks/java/library/j-jstl0211/index.html) and [2](http://www.ibm.com/developerworks/java/library/j-jstl0318/) (a little bit outdated, but still functional) |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | `$` is not the start of a variable name, it indicates the start of an expression. You should use `${map[key]}` to access the property `key` in map `map`.
You can try it on a page with a `GET` parameter, using the following query string for example `?whatEver=something`
```
<c:set var="myParam" value="whatEver"/>
whatEver: <c:out value="${param[myParam]}"/>
```
This will output:
```
whatEver: something
```
See: <https://stackoverflow.com/tags/el/info> and scroll to the section "Brace notation". | You can put the key-value in a map on `Java` side and access the same using `JSTL` on `JSP` page as below:
**Prior java 1.7:**
```
Map<String, String> map = new HashMap<String, String>();
map.put("key","value");
```
**Java 1.7 and above:**
```
Map<String, String> map = new HashMap<>();
map.put("key","value");
```
**JSP Snippet:**
```
<c:out value="${map['key']}"/>
``` |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | `$` is not the start of a variable name, it indicates the start of an expression. You should use `${map[key]}` to access the property `key` in map `map`.
You can try it on a page with a `GET` parameter, using the following query string for example `?whatEver=something`
```
<c:set var="myParam" value="whatEver"/>
whatEver: <c:out value="${param[myParam]}"/>
```
This will output:
```
whatEver: something
```
See: <https://stackoverflow.com/tags/el/info> and scroll to the section "Brace notation". | I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map
Something like this:
`<c:set var="keyString">${someKeyThatIsNotString}</c:set>`
`<c:out value="${map[keyString]}"/>`
Hope that helps |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | `$` is not the start of a variable name, it indicates the start of an expression. You should use `${map[key]}` to access the property `key` in map `map`.
You can try it on a page with a `GET` parameter, using the following query string for example `?whatEver=something`
```
<c:set var="myParam" value="whatEver"/>
whatEver: <c:out value="${param[myParam]}"/>
```
This will output:
```
whatEver: something
```
See: <https://stackoverflow.com/tags/el/info> and scroll to the section "Brace notation". | My five cents. Now I am working with EL 3.0 (jakarta impl) and I can access map value using three ways:
```
1. ${map.someKey}
2. ${map['someKey']}
3. ${map[someVar]} //if someVar == 'someKey'
``` |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map
Something like this:
`<c:set var="keyString">${someKeyThatIsNotString}</c:set>`
`<c:out value="${map[keyString]}"/>`
Hope that helps | You can put the key-value in a map on `Java` side and access the same using `JSTL` on `JSP` page as below:
**Prior java 1.7:**
```
Map<String, String> map = new HashMap<String, String>();
map.put("key","value");
```
**Java 1.7 and above:**
```
Map<String, String> map = new HashMap<>();
map.put("key","value");
```
**JSP Snippet:**
```
<c:out value="${map['key']}"/>
``` |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | You can put the key-value in a map on `Java` side and access the same using `JSTL` on `JSP` page as below:
**Prior java 1.7:**
```
Map<String, String> map = new HashMap<String, String>();
map.put("key","value");
```
**Java 1.7 and above:**
```
Map<String, String> map = new HashMap<>();
map.put("key","value");
```
**JSP Snippet:**
```
<c:out value="${map['key']}"/>
``` | My five cents. Now I am working with EL 3.0 (jakarta impl) and I can access map value using three ways:
```
1. ${map.someKey}
2. ${map['someKey']}
3. ${map[someVar]} //if someVar == 'someKey'
``` |
12,517,938 | I have these 2 tables,
```
Student
(Id, Name, DOB)
School
(Id, name)
Table 3
(student.Id, School.Id, expiryDate)
```
I need to ADD, new student, new school and create new record for table 3)
Is there a way I can do this through entity framework? | 2012/09/20 | [
"https://Stackoverflow.com/questions/12517938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214082/"
] | I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map
Something like this:
`<c:set var="keyString">${someKeyThatIsNotString}</c:set>`
`<c:out value="${map[keyString]}"/>`
Hope that helps | My five cents. Now I am working with EL 3.0 (jakarta impl) and I can access map value using three ways:
```
1. ${map.someKey}
2. ${map['someKey']}
3. ${map[someVar]} //if someVar == 'someKey'
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | This is the part you are missing
```
// Move k1_start to end of keyword1
k1_start += strlen(keyword1);
// Copy text from k1_start to k2_start
char sub_string[32];
int len = k2_start - k1_start;
strncpy(sub_string, k1_start, len);
// Be sure to terminate the string
sub_string[len] = '\0';
``` | ```
void look_for_middle(const char *haystack,
const char *needle1, const char *needle2) {
const char *start; /* start of region between keywords */
const char *end; /* end of region between keywords */
const char *pos1; /* match needle1 within haystack */
const char *pos2; /* match needle2 within haystack */
int length; /* length of region between needles */
/* Look for needles in haystack. */
pos1 = strstr(haystack, needle1);
pos2 = strstr(haystack, needle2);
if (pos1 != NULL && pos2 != NULL) {
/* Both needles were found. */
if (pos1 < pos2) {
/* needle1 appears before needle2 */
start = pos1 + strlen(needle1);
end = pos2;
} else {
/* needle2 appears before needle1 */
start = pos2 + strlen(needle2);
end = pos1;
}
length = end - start;
} else {
/* One or more needles were not found. */
start = NULL;
end = NULL;
length = 0;
}
/* Report result. */
if (start != NULL) {
/* Both needles were found. */
if (length < 0) {
printf("Needles overlap\n");
} else {
/*
* In this printf, the "precision" of the string
* is set so that it only prints the portion between
* the needles.
*/
printf("Middle pos %d len %d: %.*s\n",
(int)(start - haystack), length, length, start);
}
} else {
if (pos1 == NULL) {
printf("Needle 1 not found\n");
}
if (pos2 == NULL) {
printf("Needle 2 not found\n");
}
}
}
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | Yeah..
This is C-like and uses `char *` and supporting char array.
```
#include <stdio.h>
#include <string.h>
int main(void) {
char* long_text = "key1(text)key2";
char* keyword1 = "key1";
char* keyword2 = "key2";
char* k1 = strstr(long_text, keyword1);
char* k2 = strstr(long_text, keyword2);
// from first char of match up to first char of second match
char text[strlen(k1) - strlen(k2)];
int len = (int)strlen(k1);
for (int i = 0;; i++) {
text[i] = *k1; k1++;
if (i == (len - strlen(k2))) {
text[len - strlen(k2)] = '\0';
break;
}
}
char* res;
//We have now only keyword1 + middle part, compare until diff.,
//then remember position and just iterate from to it later.
int j = 0;
for (int i = 0;; i++) {
if (*keyword1 == text[i]) {
j = i;
keyword1++;
} else {
res = &text[++j];
break;
}
}
printf("%s\n", res);
return 0;
}
``` | ```
void look_for_middle(const char *haystack,
const char *needle1, const char *needle2) {
const char *start; /* start of region between keywords */
const char *end; /* end of region between keywords */
const char *pos1; /* match needle1 within haystack */
const char *pos2; /* match needle2 within haystack */
int length; /* length of region between needles */
/* Look for needles in haystack. */
pos1 = strstr(haystack, needle1);
pos2 = strstr(haystack, needle2);
if (pos1 != NULL && pos2 != NULL) {
/* Both needles were found. */
if (pos1 < pos2) {
/* needle1 appears before needle2 */
start = pos1 + strlen(needle1);
end = pos2;
} else {
/* needle2 appears before needle1 */
start = pos2 + strlen(needle2);
end = pos1;
}
length = end - start;
} else {
/* One or more needles were not found. */
start = NULL;
end = NULL;
length = 0;
}
/* Report result. */
if (start != NULL) {
/* Both needles were found. */
if (length < 0) {
printf("Needles overlap\n");
} else {
/*
* In this printf, the "precision" of the string
* is set so that it only prints the portion between
* the needles.
*/
printf("Middle pos %d len %d: %.*s\n",
(int)(start - haystack), length, length, start);
}
} else {
if (pos1 == NULL) {
printf("Needle 1 not found\n");
}
if (pos2 == NULL) {
printf("Needle 2 not found\n");
}
}
}
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | ```
void look_for_middle(const char *haystack,
const char *needle1, const char *needle2) {
const char *start; /* start of region between keywords */
const char *end; /* end of region between keywords */
const char *pos1; /* match needle1 within haystack */
const char *pos2; /* match needle2 within haystack */
int length; /* length of region between needles */
/* Look for needles in haystack. */
pos1 = strstr(haystack, needle1);
pos2 = strstr(haystack, needle2);
if (pos1 != NULL && pos2 != NULL) {
/* Both needles were found. */
if (pos1 < pos2) {
/* needle1 appears before needle2 */
start = pos1 + strlen(needle1);
end = pos2;
} else {
/* needle2 appears before needle1 */
start = pos2 + strlen(needle2);
end = pos1;
}
length = end - start;
} else {
/* One or more needles were not found. */
start = NULL;
end = NULL;
length = 0;
}
/* Report result. */
if (start != NULL) {
/* Both needles were found. */
if (length < 0) {
printf("Needles overlap\n");
} else {
/*
* In this printf, the "precision" of the string
* is set so that it only prints the portion between
* the needles.
*/
printf("Middle pos %d len %d: %.*s\n",
(int)(start - haystack), length, length, start);
}
} else {
if (pos1 == NULL) {
printf("Needle 1 not found\n");
}
if (pos2 == NULL) {
printf("Needle 2 not found\n");
}
}
}
``` | This function can do your job . .
```
char* strInner(char *long_text , char *keyword1 , char* keyword2)
{
char * a = strstr(long_text,keyword1);
a+= strlen(keyword1);
if(a==NULL)
{
cout<<"Keyword1 didn't found ! ";
return a ;
}
char * b = strstr(a,keyword2);
if(b==NULL)
{
cout<<"Keyword2 didn't found Or, found before Keyword1 ! ";
return b ;
}
char *inner = (char*)malloc(strlen(a)-strlen(b));
memcpy(inner,a,strlen(a)-strlen(b) );
return inner ;
}
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | This is the part you are missing
```
// Move k1_start to end of keyword1
k1_start += strlen(keyword1);
// Copy text from k1_start to k2_start
char sub_string[32];
int len = k2_start - k1_start;
strncpy(sub_string, k1_start, len);
// Be sure to terminate the string
sub_string[len] = '\0';
``` | Yeah..
This is C-like and uses `char *` and supporting char array.
```
#include <stdio.h>
#include <string.h>
int main(void) {
char* long_text = "key1(text)key2";
char* keyword1 = "key1";
char* keyword2 = "key2";
char* k1 = strstr(long_text, keyword1);
char* k2 = strstr(long_text, keyword2);
// from first char of match up to first char of second match
char text[strlen(k1) - strlen(k2)];
int len = (int)strlen(k1);
for (int i = 0;; i++) {
text[i] = *k1; k1++;
if (i == (len - strlen(k2))) {
text[len - strlen(k2)] = '\0';
break;
}
}
char* res;
//We have now only keyword1 + middle part, compare until diff.,
//then remember position and just iterate from to it later.
int j = 0;
for (int i = 0;; i++) {
if (*keyword1 == text[i]) {
j = i;
keyword1++;
} else {
res = &text[++j];
break;
}
}
printf("%s\n", res);
return 0;
}
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | This is the part you are missing
```
// Move k1_start to end of keyword1
k1_start += strlen(keyword1);
// Copy text from k1_start to k2_start
char sub_string[32];
int len = k2_start - k1_start;
strncpy(sub_string, k1_start, len);
// Be sure to terminate the string
sub_string[len] = '\0';
``` | This function can do your job . .
```
char* strInner(char *long_text , char *keyword1 , char* keyword2)
{
char * a = strstr(long_text,keyword1);
a+= strlen(keyword1);
if(a==NULL)
{
cout<<"Keyword1 didn't found ! ";
return a ;
}
char * b = strstr(a,keyword2);
if(b==NULL)
{
cout<<"Keyword2 didn't found Or, found before Keyword1 ! ";
return b ;
}
char *inner = (char*)malloc(strlen(a)-strlen(b));
memcpy(inner,a,strlen(a)-strlen(b) );
return inner ;
}
``` |
44,185,042 | Let `long_text`, `keyword1` and `keyword2` be three `char*` pointers. `_keyword1_` and `_keyword2_` being two substrings of `long_text`. Using `strstr(long_text, keyword1)` I can get a `char*` which points to the first occurrence of `keyword1` in `long_text`, and using `strstr(long_text, keyword2)` I can get a `char*` which points to the first occurrence of `keyword2` in `long_text`. `keyword1` and `keyword2` do not overlap.
Is there a way to extract a substring from `long_text` representing the string between `keyword1` and `keyword2` using the two `char*` obtained from [`strstr()`](http://www.cplusplus.com/reference/cstring/strstr/)?
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char* long_text = "this is keyword1 and this is keyword2 in long_text";
char* keyword1 = "keyword1";
char* keyword2 = "keyword2";
char* k1_start = strstr(long_text, keyword1);
char* k2_start = strstr(long_text, keyword2);
// TODO Be able to print " and this is "
return 0;
}
``` | 2017/05/25 | [
"https://Stackoverflow.com/questions/44185042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264899/"
] | Yeah..
This is C-like and uses `char *` and supporting char array.
```
#include <stdio.h>
#include <string.h>
int main(void) {
char* long_text = "key1(text)key2";
char* keyword1 = "key1";
char* keyword2 = "key2";
char* k1 = strstr(long_text, keyword1);
char* k2 = strstr(long_text, keyword2);
// from first char of match up to first char of second match
char text[strlen(k1) - strlen(k2)];
int len = (int)strlen(k1);
for (int i = 0;; i++) {
text[i] = *k1; k1++;
if (i == (len - strlen(k2))) {
text[len - strlen(k2)] = '\0';
break;
}
}
char* res;
//We have now only keyword1 + middle part, compare until diff.,
//then remember position and just iterate from to it later.
int j = 0;
for (int i = 0;; i++) {
if (*keyword1 == text[i]) {
j = i;
keyword1++;
} else {
res = &text[++j];
break;
}
}
printf("%s\n", res);
return 0;
}
``` | This function can do your job . .
```
char* strInner(char *long_text , char *keyword1 , char* keyword2)
{
char * a = strstr(long_text,keyword1);
a+= strlen(keyword1);
if(a==NULL)
{
cout<<"Keyword1 didn't found ! ";
return a ;
}
char * b = strstr(a,keyword2);
if(b==NULL)
{
cout<<"Keyword2 didn't found Or, found before Keyword1 ! ";
return b ;
}
char *inner = (char*)malloc(strlen(a)-strlen(b));
memcpy(inner,a,strlen(a)-strlen(b) );
return inner ;
}
``` |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Modern macOS makes it *really* hard to crash your machine as an unprivileged user (i.e. without using `sudo`), because UNIX systems are meant to handle thousands of users without letting any of them break the whole system. So, thankfully, you'll usually have to be prompted before you do something that destroys your machine.
Unfortunately, that protection only applies to the system itself. As xkcd illustrates, there's lots of stuff that *you* care about that isn't protected by System Integrity Protection, root privileges or password prompts:
[](https://imgs.xkcd.com/comics/authorization.png)
So, there's tons of stuff you can type in that will just wreck your user account and all your files if you aren't careful. A few examples:
* `rm -rf ${TEMPDIR}/*`. This seems totally reasonable, until you realize that the environment variable is spelt **`TMPDIR`**. `TEMPDIR` is usually undefined, which makes this `rm -rf /`. Even without `sudo`, this will happily remove anything you have delete permissions to, which will usually include your entire home folder. If you let this run long enough, it'll nuke any drive connected to your machine, too, since you usually have write permissions to those.
* `find ~ -name "TEMP*" -o -print | xargs rm`. `find` will normally locate files matching certain criteria and print them out. Without the `-o` this does what you'd expect and deletes every file starting with `TEMP*` (*as long as you don't have spaces in the path*). But, the `-o` means "or" (not "output" as it does for many other commands!), causing this command to actually delete all your files. Bummer.
* `ln -sf link_name /some/important/file`. I get the syntax for this command wrong occasionally, and it will rather happily overwrite your important file with a useless symbolic link.
* `kill -9 -1` will kill every one of your programs, logging you out rather quickly and possibly causing data loss. | ```
sudo kill -9 -1
```
I accidently performed a `kill -9 -1` in a perl-script, running as root.
That was as fast, as pulling the power-cord. On reboot, the server made a filesystem-check and continued running properly.
I never tried that `sudo kill -9 -1` command on the commandline. It might not work, because the process-ID "-1" means "kill all processes that belongs to the caller's process-group".
Not sure, if with sudo, that also means init and all the kernel-stuff...
But if you are root, `kill -9 -1` will definitely make an immediate stop - just like pulling the power-cord.
By the way - nothing will appear in logfiles, because that command is the fastest killer in the west!
Actually, to recover, I went to our sysadmins and told them, what I did. They did a hard reboot, because there was no way to log in on that server (RHEL6).
A `kill -9 -1` as root kills every process, that runs as root. That is i.e. sshd. That logged me out immediately and prevented anyone from logging in again. Any process started by init - including init have been killed, unless they changed UID or GID. Even logging in through serial console wasn't possible any more. `ps -eaf | grep root` shows some fancy processes, which, if they react on a SIGKILL in the default way, would pretty much stop even basic writing to HD.
I will not try this now on my laptop :-) I am not curious enough to finding out, if a `kill -9 165` ([ext4-rsv-conver]) would really stop writing to the HD. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Causing a kernel panic is a more akin to crashing than the other answers I've seen here thus far:
```
sudo dtrace -w -n "BEGIN{ panic();}"
```
(code taken from [here](https://stackoverflow.com/a/8829277/2636454) and [also found in Apple's own documentation](https://developer.apple.com/library/content/technotes/tn2004/tn2118.html#DTRACEPANICTRIGGER))
You might also try:
```
sudo killall kernel_task
```
I haven't verified that the second one there actually works (and I don't intend to as I actually have some work open right now). | Another one you can do (that I have done by mistake before) is:
```
sudo chmod 0 /
```
This will render your entire file system (which means all commands and programs) unaccessible...except by the root user. This means you would need to log in directly as the root user and restore the file system, BUT you are unable to access the `sudo` command (or any other command, for that matter). You can restore access to commands and files by booting into single-user mode, mounting and restoring the file system with `chmod 755 /`.
If this is done recursively with `chmod -R 0 /` then this will render the system unusable. The proper fix at that point is to use Disk Utility from the recovery partition to [repair disk permissions](https://support.apple.com/en-us/HT201560). You may be better off just to restore a snapshot or backup of your file system if this was run recursively. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Suppose you don't know what your doing and attempting to do a backup of some hard drive
```
dd if=/dev/disk1 of=/dev/disk2
```
Well if you mix those up (switch if and of), it will overwrite the fresh data with old data, no questions asked.
Similar mix ups can happen with archive utils. And frankly with most command line utilities.
If you want an example of a one character mix up that will crash your system take a look at this scenario: You want to move all the files in the current directory to another one:
```
mv -f ./* /path/to/other/dir
```
Let's accept the fact that you learned to use `./` to denote the current directory. (I do)
Well if you omit the dot, it will start moving *all* your files. Including your system files. You are lucky you didn't sudo this. But if you read somewhere that with 'sudo -i' you will never again have to type in sudo you are logged in as root now. And now your system is eating itself in front of your very eyes.
But again I think stuff like overwriting my precious code files with garbage, because I messed up one character or because I mixed up the order of parameters, is more trouble.
Let's say I want to check out the assembler code that gcc is generating:
```
gcc -S program.c > program.s
```
Suppose I already had a program.s and I use TAB completion. I am in a hurry and forget to TAB twice:
```
gcc -S program.c > program.c
```
Now I have the assembler code in my program.c and no c code anymore.
Which is at least a real setback for some, but to others it's start-over-from-scratch-time.
I think these are the ones that will cause real "harm". I don't really care if my system crashes. I would care about my data being lost.
Unfortunately these are the mistakes that will have to be made until you learn to use the terminal with the proper precautions. | Modern macOS makes it *really* hard to crash your machine as an unprivileged user (i.e. without using `sudo`), because UNIX systems are meant to handle thousands of users without letting any of them break the whole system. So, thankfully, you'll usually have to be prompted before you do something that destroys your machine.
Unfortunately, that protection only applies to the system itself. As xkcd illustrates, there's lots of stuff that *you* care about that isn't protected by System Integrity Protection, root privileges or password prompts:
[](https://imgs.xkcd.com/comics/authorization.png)
So, there's tons of stuff you can type in that will just wreck your user account and all your files if you aren't careful. A few examples:
* `rm -rf ${TEMPDIR}/*`. This seems totally reasonable, until you realize that the environment variable is spelt **`TMPDIR`**. `TEMPDIR` is usually undefined, which makes this `rm -rf /`. Even without `sudo`, this will happily remove anything you have delete permissions to, which will usually include your entire home folder. If you let this run long enough, it'll nuke any drive connected to your machine, too, since you usually have write permissions to those.
* `find ~ -name "TEMP*" -o -print | xargs rm`. `find` will normally locate files matching certain criteria and print them out. Without the `-o` this does what you'd expect and deletes every file starting with `TEMP*` (*as long as you don't have spaces in the path*). But, the `-o` means "or" (not "output" as it does for many other commands!), causing this command to actually delete all your files. Bummer.
* `ln -sf link_name /some/important/file`. I get the syntax for this command wrong occasionally, and it will rather happily overwrite your important file with a useless symbolic link.
* `kill -9 -1` will kill every one of your programs, logging you out rather quickly and possibly causing data loss. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Modern macOS makes it *really* hard to crash your machine as an unprivileged user (i.e. without using `sudo`), because UNIX systems are meant to handle thousands of users without letting any of them break the whole system. So, thankfully, you'll usually have to be prompted before you do something that destroys your machine.
Unfortunately, that protection only applies to the system itself. As xkcd illustrates, there's lots of stuff that *you* care about that isn't protected by System Integrity Protection, root privileges or password prompts:
[](https://imgs.xkcd.com/comics/authorization.png)
So, there's tons of stuff you can type in that will just wreck your user account and all your files if you aren't careful. A few examples:
* `rm -rf ${TEMPDIR}/*`. This seems totally reasonable, until you realize that the environment variable is spelt **`TMPDIR`**. `TEMPDIR` is usually undefined, which makes this `rm -rf /`. Even without `sudo`, this will happily remove anything you have delete permissions to, which will usually include your entire home folder. If you let this run long enough, it'll nuke any drive connected to your machine, too, since you usually have write permissions to those.
* `find ~ -name "TEMP*" -o -print | xargs rm`. `find` will normally locate files matching certain criteria and print them out. Without the `-o` this does what you'd expect and deletes every file starting with `TEMP*` (*as long as you don't have spaces in the path*). But, the `-o` means "or" (not "output" as it does for many other commands!), causing this command to actually delete all your files. Bummer.
* `ln -sf link_name /some/important/file`. I get the syntax for this command wrong occasionally, and it will rather happily overwrite your important file with a useless symbolic link.
* `kill -9 -1` will kill every one of your programs, logging you out rather quickly and possibly causing data loss. | I am only a bash beginner, but you could use something like this:
`while True; do COMMAND; done;`
Most people would try to use Ctrl+C to stop the command, not the external process (Ctrl+Z, which then need to be killed).
If the command in the `while True` loop is a resource-intensive operation (such as multiplying large number to its own power), that could mess with your system resources and bog down your processor. However, modern operating systems are usually protected against such catastrophes. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Suppose you don't know what your doing and attempting to do a backup of some hard drive
```
dd if=/dev/disk1 of=/dev/disk2
```
Well if you mix those up (switch if and of), it will overwrite the fresh data with old data, no questions asked.
Similar mix ups can happen with archive utils. And frankly with most command line utilities.
If you want an example of a one character mix up that will crash your system take a look at this scenario: You want to move all the files in the current directory to another one:
```
mv -f ./* /path/to/other/dir
```
Let's accept the fact that you learned to use `./` to denote the current directory. (I do)
Well if you omit the dot, it will start moving *all* your files. Including your system files. You are lucky you didn't sudo this. But if you read somewhere that with 'sudo -i' you will never again have to type in sudo you are logged in as root now. And now your system is eating itself in front of your very eyes.
But again I think stuff like overwriting my precious code files with garbage, because I messed up one character or because I mixed up the order of parameters, is more trouble.
Let's say I want to check out the assembler code that gcc is generating:
```
gcc -S program.c > program.s
```
Suppose I already had a program.s and I use TAB completion. I am in a hurry and forget to TAB twice:
```
gcc -S program.c > program.c
```
Now I have the assembler code in my program.c and no c code anymore.
Which is at least a real setback for some, but to others it's start-over-from-scratch-time.
I think these are the ones that will cause real "harm". I don't really care if my system crashes. I would care about my data being lost.
Unfortunately these are the mistakes that will have to be made until you learn to use the terminal with the proper precautions. | Surely you still can cause a system crash using commands entered with Terminal.
With years it's getting harder probably due to all kinds of limits and protective measures applied but as Murphy's-like law states: "Nothing is foolproof to a sufficiently capable fool."
"Fork bombs" and all that `rm -rf` script kiddies stuff are anciently known things for UNIX. With Mac OS X you can have more fun using its GUI sub-system parts (`WindowServer` to mention) or something like OpenBSD firewall aka `PF` that Apple's engineers brought in but never managed to update since its 2008 state of things. `PF` works in kernel so when it catches a quirk it's time Apple tells you "*you* restarted computer due to a panic" or stuff like this.
The worst part of this is you never can have an idea of where-n-why it panicked —
cause Apple doesn't provide any meaningful stack traces; you can only have hex numbers of stack frame's return addresses. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.