text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Return value from timer class
I'm working on a timer-class which I want to use to return a character at a time from a word after a set amount of seconds. Basically I want to display the characters in another class in a JPanel and change the letter I show after a second or so. I can get it to write out the characters in a System.out.println in the same class, but I'm not sure how I'd use it with another class if I only want to return the one character at a time with the time interval. I can't return anything from the run-method as it's void, so any help in how I could solve this would be greatly appreciated.
package GU4;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
Timer timer;
private String name;
private int i = 0;
public TimerTest(int seconds, String name){
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000, 1000);
this.name = name;
}
class RemindTask extends TimerTask{
public void run() {
int length = name.length();
if(i < length){
System.out.println(name.charAt(i));
i++;
}
else{
timer.cancel();
}
}
}
public static void main(String[] args) {
new TimerTest(2, "Bengt");
}
}
A:
Make your class take 1 additional parameter which is a callback for the timer task. Such as:
public TimerTest(int seconds, String name, Consumer<String> callback)
Then call that callback and pass it the value you would normally want to return.
public void run() {
int length = name.length();
if(i < length){
callback.accept(String.valueOf(name.charAt(i));
i++;
} else {
timer.cancel();
}
}
If your using Java 8 then the java.util.function.Consumer class will exist. If your not using java 8 then you can just add your own interface like:
public interface Consumer<T> {
void accept(T t);
}
Putting this all together you would end up with something like: (using java 8)
package GU4;
import java.util.Timer;
import java.util.TimerTask;
public class TimerTest {
Timer timer;
private String name;
private int i = 0;
private Consumer<String> callback;
public TimerTest(int seconds, String name, Consumer<String> callback) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000, 1000);
this.name = name;
this.callback = callback;
}
class RemindTask extends TimerTask{
public void run() {
int length = name.length();
if(i < length){
callback.accept(String.valueOf(name.charAt(i)));
i++;
} else {
timer.cancel();
}
}
}
public static void main(String[] args) {
new TimerTest(2, "Bengt", (c)-> {
System.out.println("New Val: " + c);
});
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to include a current branch name variable in linux command prompt?
I have to do a repetitive work that includes introduce a lot of commands like:
git pull upstream client
git push upstream client
git pull origin client
git pull upstream client2
git push upstream client2
git pull origin client2
...
I was wondering if is there anyway to do something like this:
git pull current_branch
and when I push enter what the system receives is:
git pull client
Thanks in advance!
A:
You can use
git pull $(git branch | grep \* | cut -d ' ' -f2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Overriding Ember Controller 'needs' with Reopen
I have a basic controller that I'd like to reopen so I can override the 'needs' parameter, but instead, the new parameter adds to the 'needs' parameter.
For example, my original controller looks something like this:
App.MessagesController = Ember.ArrayController.extend({
needs: ['blog', 'services', 'post_edit']
});
I have a build process that includes this controller file in another app, and to avoid code redundancy, I'd like to be able to reopen the controller and make small changes to it as needed, including the 'needs' parameter. Like so:
App.MessagesController.reopen({
needs: ['post', 'services']
});
The problem is that when this code is run, the 'needs' parameter isn't overridden -- it's extended. It essentially becomes: needs: ['blog', 'services', 'post_edit', 'post']
Is there a way to override the 'needs' parameter of a controller with reopen? Or perhaps there is a better method altogether?
Edit for clarity:
Doing a lookup on the controller displays a console error that shows the 'needs' parameter is not being overridden.
$: App.__container__.lookup('controller:Messages');
Error: <App.MessagesController:ember322> needs [ controller:blog, controller:post_edit ] but they could not be found
Adding another fake controller item to the 'needs' parameter in reopen adds to this error message.
A:
You might want to extract the functionality that belongs in app 1 into a mixin, and include that on the controller. Then share the base controller, with the shared functionality, across the two apps.
//Included in both apps
App.BaseMessagesController = Ember.ArrayController.extend({
sharedValue:'foo'
});
//App 1
App.App1Mixin = Ember.Mixin.create({
needs: ['blog', 'services', 'post_edit']
});
App.MessagesController = Ember.BaseMessagesController.extend(App.App1Mixin,{
});
| {
"pile_set_name": "StackExchange"
} |
Q:
FindIndex on list by linq
How may i get index using linq ? I want to find by FieldNo and get back to index. let say if i search 2 it should be return index 1.
Regards,
A:
With LINQ:
int index = fields.Select((f, i) => new { Field = f, Index = i})
.Where(x => x.Field.FieldNo == 2)
.Select(x => x.Index)
.DefaultIfEmpty(-1)
.First();
without LINQ using List.FindIndex, more readable, efficient and works even on .NET 2:
int index = fields.FindIndex(f => f.FieldNo == 2);
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there such thing as best exercises for weightlifting?
I've heard this many times from powerlifters that I've work with, "All you really need is 3 lifts to hit all major muscle groups, and technically that's all you really need for maintenance, too."
On top of my head, I would think that squat, deadlift and bench press are the three exercises that really target pretty much all the major muscle groups. I would also recommend chin-ups/pull-ups and clean and press.
What are your thoughts about these 3 exercises (squat, deadlift and bench press) for hitting all the major muscle groups? Also, are there any other exercises that you would recommend?
A:
Everything always depends on your goals.
The best exercises are the ones that help you accomplish your goals.
If you are a power lifter, your goals are to get the biggest squat, deadlift, and bench press you can. Obviously, it helps to do those exercises to make them stronger. It does also happen that they are very good exercises for General Physical Preparedness (GPP); but they aren't the only ones that are good for GPP. If an Olympic lifter were to make the same observations they would select their competition lifts--which hit all the major muscle groups as well.
If your goal is bodybuilding, compound lifts are great for building general strength and large slabs of muscle. However, you'll still need isolation exercises to fine tune the proportions of the muscles with each other. That's important if you are a physique competitor. On the same token, isolation exercises in the proper proportions can keep your joints healthy.
If you are a strongman, you need to put heavy things over your head, so overhead pressing becomes much more important than bench pressing. This is true for the continental press, the log press, keg tossing, etc.
For GPP I would recommend:
Incline press--more useful in most team sports, and provides good carry over to both overhead pressing and bench pressing.
Squats in all variations--Helps with jumping ability, sprinting, core strength, leg strength, and a good muscle builder.
Pulls from the floor (deadlifts, cleans, snatches, high pulls)--excellent posterior chain work, mental toughness, and strength builder.
Rows in all variations--balances out the pressing, keeps the shoulders from becoming slumped forward, and helps out both the squat and deadlift
Beyond that, do whatever is necessary to fine tune work. I find that light weight high volume curls help flush out inflammation in the elbows before it has a chance to start. However, if you do too many of them it can become a source of inflammation themselves.
There is no absolute best exercise. There is only what's more appropriate for your given goals at the moment.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to keep receiving data while keeping data in state in order?
I'm working on this react table sorting when the user clicks on table header it needs to sort the table, sorting is working but the problem is I'm receiving new data every second through SignalR hub and it sets state udata to new data. When a user clicks on table header it sorts the table but again goes back to the new state changed by new data. And cancells the sorted table back to unsorted.
Is there any way I can keep sorted state and still receive data?
I'm new to react any help would be appreciated
constructor() {
super()
this.state = {
udata: [],
sort: {
column: null,
direction: 'desc',
},
}
}
componentDidMount() {
let connection = new signalR.HubConnectionBuilder()
.withUrl('/signalserver')
.build()
connection
.start()
.then(function() {})
.catch(function(err) {
return console.error(err.toString())
})
connection.on(
'APIChannel',
function(data) {
this.setState({udata: data})
}.bind(this),
)
async function start() {
try {
await connection.start()
console.log('connected')
} catch (err) {
console.log(err)
setTimeout(() => start(), 5000)
}
}
connection.onclose(async () => {
await start()
})
}
onSort(column) {
return function(e) {
let direction = this.state.sort.direction
if (this.state.sort.column === column) {
// Change the sort direction if the same column is sorted.
direction = this.state.sort.direction === 'asc' ? 'desc' : 'asc'
}
// Sort ascending.
const sortedData = this.state.udata.sort((a, b) => {
if (column === 'appName') {
// This sorts strings taking into consideration numbers in strings.
// e.g., Account 1, Account 2, Account 10. Normal sorting would sort it Account 1, Account 10, Account 2.
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base',
})
return collator.compare(a.appName, b.appName)
} else {
return a.contractValue - b.contractValue
}
})
// Reverse the order if direction is descending.
if (direction === 'desc') {
sortedData.reverse()
}
// Set the new state.
this.setState({
udata: sortedData,
sort: {
column,
direction,
},
})
}.bind(this) // Bind "this" again because the onSort function is returning another function.
}
renderItem(item, key) {
const itemRows = [
<tr onClick={clickCallback} key={'row-data-' + key}>
<td>{item.appName}</td>
<td>
<h6 className="text-muted">
<i
className={
'fa fa-circle text-c-' +
(item.appState === 'STARTED' ? 'green' : 'red') +
' f-10 m-r-15'
}
/>
{item.appState}
</h6>
</td>
<td>{item.spaceName}</td>
<td>
<h6 className="text-muted">{item.orgName}</h6>
</td>
<td>
<h6 className="text-muted">
{new Date(item.appUpdatedAt).toLocaleString()}
</h6>
</td>
</tr>,
]
return itemRows
}
render() {
let allItemRows = []
this.state.udata.forEach((item, key) => {
const perItemRows = this.renderItem(item, key)
allItemRows = allItemRows.concat(perItemRows)
})
return (
<Aux>
<Row>
<Table hover responsive>
<thead>
<tr>
<th className="sortable" onClick={this.onSort('appName')}>
{' '}
Account Name
</th>
<th> State</th>
<th> Space</th>
<th> Organization</th>
<th className="sortable" onClick={this.onSort('appUpdatedAt')}>
{' '}
Updated At
</th>
</tr>
</thead>
<tbody> {allItemRows}</tbody>
</Table>
</Row>
</Aux>
)
}
A:
Move the sorting part of the function to new a function:
const sortData = (data, column, direction) => {
// Sort ascending.
const sortedData = data.sort((a, b) => {
if (column === 'appName') {
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base',
})
return collator.compare(a.appName, b.appName)
} else {
return a.contractValue - b.contractValue
}
})
// Reverse the order if direction is descending.
if (direction === 'desc') {
return sortedData.reverse()
}
return sortedData
}
You can use this function in componentDidMount before setting the state with the newData and also in onSort function.
onSort(column) {
return function(e) {
let direction = this.state.sort.direction
if (this.state.sort.column === column) {
// Change the sort direction if the same column is sorted.
direction = this.state.sort.direction === 'asc' ? 'desc' : 'asc'
}
// Sort ascending.
const sortedData = this.sortData(this.state.udata, column, direction)
// Set the new state.
this.setState({
udata: sortedData,
sort: {
column,
direction,
},
})
}.bind(this) // Bind "this" again because the onSort function is returning another function.
}
componentDidMount:
componentDidMount() {
// Code
connection.on(
'APIChannel',
function(data) {
let sortedData = []
if (this.state.sort.column) {
sortedData = this.sortData(data, this.state.sort.column,
this.state.sort.direction)
} else {
sortedData = data
}
this.setState({udata: sortedData})
}.bind(this),
)
// Rest of the code
}
EDIT:
import React, { Component } from "react";
import { Row, Col, Form, Card, Table, Tab, Nav } from "react-bootstrap";
import Aux from "../../hoc/_Aux";
import * as signalR from "@aspnet/signalr";
class Dashboard extends Component {
constructor() {
super();
this.state = {
udata: [],
sysdata: [],
expandedRows: [],
user: "active",
system: "",
data: [],
UserFilters: {
appState: [],
orgName: [],
spaceName: []
},
SysFilters: {
appState: []
},
intervalId: 0, //Scroll on top feature
sort: {
column: null,
direction: "desc"
}
};
}
sortData = (data, column, direction) => {
// Sort ascending.
const sortedData = data.sort((a, b) => {
if (column === 'appName') {
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base',
})
return collator.compare(a.appName, b.appName)
} else {
return a.contractValue - b.contractValue
}
})
// Reverse the order if direction is descending.
if (direction === 'desc') {
return sortedData.reverse()
}
return sortedData
};
componentDidMount() {
let connection = new signalR.HubConnectionBuilder()
.withUrl("/signalserver")
.build();
connection
.start()
.then(function () { })
.catch(function (err) {
return console.error(err.toString());
});
connection.on(
"SBUserBrodcasting",
function (data) {
let sortedData = [];
if (this.state.sort.column) {
sortedData = this.sortData(
data,
this.state.sort.column,
this.state.sort.direction
);
} else {
sortedData = data;
}
this.setState({ udata: sortedData });
}.bind(this)
);
connection.on(
"SBSystemBrodcasting",
function (data) {
this.setState({ sysdata: data });
}.bind(this)
);
async function start() {
try {
await connection.start();
console.log("connected");
} catch (err) {
console.log(err);
setTimeout(() => start(), 5000);
}
}
connection.onclose(async () => {
await start();
});
}
onSort(column) {
return function (e) {
let direction = this.state.sort.direction;
if (this.state.sort.column === column) {
// Change the sort direction if the same column is sorted.
direction = this.state.sort.direction === "asc" ? "desc" : "asc";
}
// Sort ascending.
const sortedData = this.sortData(this.state.udata, column, direction);
// Set the new state.
this.setState({
udata: sortedData,
sort: {
column,
direction
}
});
}.bind(this); // Bind "this" again because the onSort function is returning another function.
}
scrollStep() {
if (window.pageYOffset === 0) {
clearInterval(this.state.intervalId);
}
window.scroll(0, window.pageYOffset - this.props.scrollStepInPx);
}
scrollToTop() {
let intervalId = setInterval(
this.scrollStep.bind(this),
this.props.delayInMs
);
this.setState({ intervalId: intervalId });
}
FilterUserArray = (array, UserFilters) => {
let getValue = value =>
typeof value === "string" ? value.toUpperCase() : value;
const filterKeys = Object.keys(UserFilters);
return array.filter(item => {
// validates all filter criteria
return filterKeys.every(key => {
// ignores an empty filter
if (!UserFilters[key].length) return true;
return UserFilters[key].find(
filter => getValue(filter) === getValue(item[key])
);
});
});
};
FilterSysArray = (array, SysFilters) => {
let getValue = value =>
typeof value === "string" ? value.toUpperCase() : value;
const filterKeys = Object.keys(SysFilters);
return array.filter(item => {
// validates all filter criteria
return filterKeys.every(key => {
// ignores an empty filter
if (!SysFilters[key].length) return true;
return SysFilters[key].find(
filter => getValue(filter) === getValue(item[key])
);
});
});
};
HandleRowClick(rowId) {
const currentExpandedRows = this.state.expandedRows;
const isRowCurrentlyExpanded = currentExpandedRows.includes(rowId);
const newExpandedRows = isRowCurrentlyExpanded
? currentExpandedRows.filter(id => id !== rowId)
: currentExpandedRows.concat(rowId);
this.setState({ expandedRows: newExpandedRows });
}
SpaceRenderFilterList(item, key) {
const itemRows = [
<li key={"li-data-" + key}>
<Form.Check
custom
type="checkbox"
value={item}
id={"SBSpace-" + item}
label={item}
onChange={this.UserAppSpaceFilter.bind(this)}
/>
</li>
];
return itemRows;
}
OrgRenderFilterList(item, key) {
const itemRows = [
<li key={"li-data-" + key}>
<Form.Check
custom
type="checkbox"
value={item}
id={"SBOrg-" + item}
label={item}
onChange={this.UserAppOrgFilter.bind(this)}
/>
</li>
];
return itemRows;
}
RenderItem(item, key) {
const clickCallback = () => this.HandleRowClick(key);
const itemRows = [
<tr onClick={clickCallback} key={"row-data-" + key}>
<td>{item.appName}</td>
<td>
<h6 className="text-muted">
<i
className={
"fa fa-circle text-c-" +
(item.appState === "STARTED" ? "green" : "red") +
" f-10 m-r-15"
}
/>
{item.appState}
</h6>
</td>
<td>{item.spaceName}</td>
<td>
<h6 className="text-muted">{item.orgName}</h6>
</td>
<td>
<h6 className="text-muted">
{new Date(item.appUpdatedAt).toLocaleString()}
</h6>
</td>
</tr>
];
if (this.state.expandedRows.includes(key)) {
itemRows.push(
<tr key={"row-expanded-" + key}>
<td colSpan="6">
<Card className="card-event">
<Card.Body>
<div className="row align-items-center justify-content-center">
<div className="col">
<h5 className="m-0">Upcoming Event</h5>
</div>
<div className="col-auto">
<label className="label theme-bg2 text-white f-14 f-w-400 float-right">
34%
</label>
</div>
</div>
<h2 className="mt-2 f-w-300">
45<sub className="text-muted f-14">Competitors</sub>
</h2>
<h6 className="text-muted mt-3 mb-0">
You can participate in event{" "}
</h6>
<i className="fa fa-angellist text-c-purple f-50" />
</Card.Body>
</Card>
</td>
</tr>
);
}
return itemRows;
}
onClickfn = () => {
this.setState({ user: "active", system: "inactive" });
};
onClickfnsys = () => {
this.setState({ user: "inactive", system: "active" });
};
UserAppStateFilter(e) {
let index;
// current array of options
const options = this.state.UserFilters.appState;
// check if the check box is checked or unchecked
if (e.target.checked) {
// add the numerical value of the checkbox to options array
options.push(e.target.value);
} else {
// or remove the value from the unchecked checkbox from the array
index = options.indexOf(e.target.value);
options.splice(index, 1);
}
// update the state with the new array of options
this.setState({
UserFilters: { ...this.state.UserFilters, appState: options }
});
}
UserAppSpaceFilter(e) {
let index;
// current array of options
const options = this.state.UserFilters.spaceName;
// check if the check box is checked or unchecked
if (e.target.checked) {
// add the numerical value of the checkbox to options array
options.push(e.target.value);
} else {
// or remove the value from the unchecked checkbox from the array
index = options.indexOf(e.target.value);
options.splice(index, 1);
}
// update the state with the new array of options
this.setState({
UserFilters: { ...this.state.UserFilters, spaceName: options }
});
}
UserAppOrgFilter(e) {
let index;
// current array of options
const options = this.state.UserFilters.orgName;
// check if the check box is checked or unchecked
if (e.target.checked) {
// add the numerical value of the checkbox to options array
options.push(e.target.value);
} else {
// or remove the value from the unchecked checkbox from the array
index = options.indexOf(e.target.value);
options.splice(index, 1);
}
// update the state with the new array of options
this.setState({
UserFilters: { ...this.state.UserFilters, orgName: options }
});
}
SysAppStateFilter(e) {
let index;
// current array of options
const options = this.state.SysFilters.appState;
// check if the check box is checked or unchecked
if (e.target.checked) {
// add the numerical value of the checkbox to options array
options.push(e.target.value);
} else {
// or remove the value from the unchecked checkbox from the array
index = options.indexOf(e.target.value);
options.splice(index, 1);
}
// update the state with the new array of options
this.setState({
SysFilters: { ...this.state.SysFilters, appState: options }
});
}
render() {
let Spacefilterlist = [];
Array.from(new Set(this.state.udata.map(item => item.spaceName))).forEach(
(item, key) => {
const perItemRows = this.SpaceRenderFilterList(item, key);
Spacefilterlist = Spacefilterlist.concat(perItemRows);
}
);
let Orgfilterlist = [];
Array.from(new Set(this.state.udata.map(item => item.orgName))).forEach(
(item, key) => {
const perItemRows = this.OrgRenderFilterList(item, key);
Orgfilterlist = Orgfilterlist.concat(perItemRows);
}
);
let allItemRows = [];
this.FilterUserArray(this.state.udata, this.state.UserFilters).forEach(
(item, key) => {
const perItemRows = this.RenderItem(item, key);
allItemRows = allItemRows.concat(perItemRows);
}
);
let sysallItemRows = [];
this.FilterSysArray(this.state.sysdata, this.state.SysFilters).forEach(
(item, key) => {
const perItemRows = this.RenderItem(item, key);
sysallItemRows = sysallItemRows.concat(perItemRows);
}
);
return (
<Aux>
<Row>
<Col sm={12}>
<Tab.Container defaultActiveKey="user">
<Row>
<Col sm={2}>
<Nav variant="pills" className="flex-column">
<Nav.Item>
<Nav.Link eventKey="user" onClick={this.onClickfn}>
User
</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="system" onClick={this.onClickfnsys}>
System
</Nav.Link>
</Nav.Item>
</Nav>
<br />
<Card
style={{
display: this.state.user === "active" ? "" : "none"
}}
>
<Tab.Pane eventKey="user">
<Card.Header>
<Card.Title as="h5">Filters</Card.Title>
</Card.Header>
<Card.Body>
<h6>By State</h6>
<hr />
<ul className="list-inline m-b-0">
<Form.Group onReset={this.handleFormReset}>
<li>
<Form.Check
custom
type="checkbox"
id="checkbox1"
value="STARTED"
label="STARTED"
onChange={this.UserAppStateFilter.bind(this)}
/>
</li>
<li>
<Form.Check
custom
type="checkbox"
id="checkbox2"
value="STOPPED"
label="STOPPED"
onChange={this.UserAppStateFilter.bind(this)}
/>
</li>
</Form.Group>
</ul>
<h6>By Space</h6>
<hr />
<ul className="list-inline m-b-0">
<Form.Group>{Spacefilterlist}</Form.Group>
</ul>
<h6>By Organization</h6>
<hr />
<ul className="list-inline m-b-0">
<Form.Group>{Orgfilterlist}</Form.Group>
</ul>
</Card.Body>
</Tab.Pane>
</Card>
<Card>
<Tab.Pane
eventKey="system"
style={{
display: this.state.system === "active" ? "" : "none"
}}
>
<Card.Header>
<Card.Title as="h5">Filters</Card.Title>
</Card.Header>
<Card.Body>
<h6>By State</h6>
<hr />
<ul className="list-inline m-b-0">
<Form.Group>
<li>
<Form.Check
custom
type="checkbox"
id="chec1"
value="STARTED"
label="STARTED"
onChange={this.SysAppStateFilter.bind(this)}
/>
</li>
<li>
<Form.Check
custom
type="checkbox"
id="chec2"
value="STOPPED"
label="STOPPED"
onChange={this.SysAppStateFilter.bind(this)}
/>
</li>
</Form.Group>
</ul>
</Card.Body>
</Tab.Pane>
</Card>
</Col>
<Col sm={10}>
<Tab.Content>
<Tab.Pane eventKey="user">
<Table hover responsive>
<thead>
<tr>
<th
className="sortable"
onClick={this.onSort("appName")}
>
Account Name
</th>
<th>State</th>
<th>Space</th>
<th>Organization</th>
<th
className="sortable"
onClick={this.onSort("appUpdatedAt")}
>
Updated At
</th>
</tr>
</thead>
<tbody>{allItemRows}</tbody>
</Table>
</Tab.Pane>
<Tab.Pane eventKey="system">
<Table hover responsive>
<thead>
<tr>
<th>App Name</th>
<th>State</th>
<th>Space</th>
<th>Organization</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>{sysallItemRows}</tbody>
</Table>
</Tab.Pane>
</Tab.Content>
</Col>
</Row>
</Tab.Container>
</Col>
<button
id="myBtn"
title="Back to top"
className="scroll"
onClick={() => {
this.scrollToTop();
}}
>
<span className="feather icon-chevron-up" />
</button>
</Row>
</Aux>
);
}
}
export default Dashboard;
| {
"pile_set_name": "StackExchange"
} |
Q:
Best approach to camping in snow?
What is the best way for a trekking group of two to sleep in deep snow (meter or more). What equipment is to be brought?
Preferably, the technique should work on shallow snow and plain frozen ground as well.
Google results:
Build a snow shelter
Carry a 4-season tent
A:
Best is of course subjective, but overall, given your question and caveats, I would say a good solid winter tent.
To elaborate on the alternatives, if you have an assured amount of snow, then you can attempt some form of snow shelter. Building an actual igloo takes quite a bit of practice. Building a snow cave on the other hand is not that difficult, but does need quite a pile of snow of the right texture. Given that you want this method to work on plain frozen ground then any kind of snow shelter is likely out.
Other temporary shelters, like lean-tos also largely depend upon the surrounding area for building materials. If you are in more open country, you may well lack the requisite branches/trees, in order to make this work. Also depending on where you camp, you might get in trouble for stripping live branches for your shelter, or to sleep on, so know your area.
Overall, therefore, a good solid winter-rated tent is probably your best bet. You'll know you have it with you, and even if you want to try out a snow shelter or other variation for one night, you'll have the tent to fall back on.
Good Luck
A:
Given your criteria, I would go with bivy sacks. Making shelters from snow (even just tarp covered windbreaks) is energy and time consuming, eating up your already scarce daylight and what little energy you have leftover from hiking/snowshoeing/skiing to camp.
A commentary on group size, though: it's almost always a bad idea to go winter mountaineering with less than three people, both for trailbreaking reasons and most winter (four season) tents are heavy and not made for less than three people.
No matter what you decide, you will need a snow shovel to carve out and help pack down a space for your shelter (or carve out your shelter). Snowshoes are also very handy for packing down snow to make a surface for a bivy sack or tent.
| {
"pile_set_name": "StackExchange"
} |
Q:
Emacs - Load ParEdit Mode on Startup
Is there a straightforward way to enable paredit mode by default every time I launch emacs? I have this code in my .emacs:
(scroll-bar-mode -1)
(tool-bar-mode -1)
(menu-bar-mode -1)
(show-paren-mode 1)
(global-rainbow-delimiters-mode 1)
(global-hl-line-mode 1)
(global-linum-mode t)
(paredit-mode 1)
Every mode except for paredit-mode gets loaded. Why is this happening?
Thank you.
A:
You probably don't want to enable Paredit globally:
Paredit behaves badly if parentheses are unbalanced, so exercise caution when forcing Paredit Mode to be enabled, and consider fixing unbalanced parentheses instead.
Instead, you can invoke it for modes where it makes sense, e.g.
(add-hook 'emacs-lisp-mode-hook #'enable-paredit-mode)
| {
"pile_set_name": "StackExchange"
} |
Q:
Noob question (Java): problem with simple battleship game
I have a problem with this code:
import java.util.Random;
public class DotComObjects {
public int[][] setBarcos(int tablero[][]) {
boolean repetido; //Variable booleana para comprobar si una casilla ya esta ocupada por otro barco
do {
repetido = false; //Suponesmos que no esta ocupada ninguna de las casillas
Random aRandom = new Random();
boolean horizontal = aRandom.nextBoolean(); //Booleana al azar para la colocacion del barco. True = horizontal, false = vertical
if (horizontal == true) { //Si el barco va en horizontal
int ancho = aRandom.nextInt(tablero.length - 2); //Calculamos al azar la casilla
int alto = aRandom.nextInt(tablero[0].length); //central del barco (tendra 3)
if ((tablero[ancho - 1][alto] == 1) || (tablero[ancho][alto] == 1) || (tablero[ancho + 1][alto] == 1)) { //Si una de las casillas ya esta ocupada
repetido = true; //Variable booleana repetida en true
}
} else { //Si el barco va en vertical
int ancho = aRandom.nextInt(tablero.length); //Calculamos al azar la casilla
int alto = aRandom.nextInt(tablero[0].length - 2); //central del barco (tendra 3)
if ((tablero[ancho][alto - 1] == 1) || (tablero[ancho][alto] == 1) || (tablero[ancho][alto + 1] == 1)) { //Si una de las casillas ya esta ocupada
repetido = true; //Variable booleana repetida en true
}
}
} while (repetido == true); //Repetimos hasta que no haya una casilla ocupada (variable repetido = false)
*** if (horizontal == true) { //Si el barco va en horizontal
*** tablero[ancho - 1][alto] = 1;
*** tablero[ancho][alto] = 1; //Colocamos el barco en el tablero
*** tablero[ancho + 1][alto] = 1;
} else { //Si el barco va en vertical
*** tablero[ancho][alto - 1] = 1;
*** tablero[ancho][alto] = 1; //Colocamos el barco en el tablero
*** tablero[ancho][alto + 1] = 1;
}
return tablero; //Devolvemos el tablero con el barco colocado
}
}
Its on ***s . Problem is the same for the 3 variables: horizontal/ancho/alto cannot be resolved to a variable.
Thanks.
A:
This is a clasic scoping problem.
All three of those variables are declared within the do {] while loop, and therefore do not exist outside of it.
To solve the problem, move the declarations to before the do
boolean repetido; //Variable .....
boolean horizontal = false;
int ancho = 0;
int alto = 0;
do {
repetido = false; //Suponesmos ...
Random aRandom = new Random();
horizontal = aRandom.nextBoolean();
ancho = aRandom.nextInt(tablero.length - 2); //Calculamos ...
alto = aRandom.nextInt(tablero[0].length); //central ...
| {
"pile_set_name": "StackExchange"
} |
Q:
Show timer in an app?
I'm using Xcode with Objective C language. I wanted to know if there is any method to show a timer or a counter which shows as to how long the application is being running. It simple increments the counter to seconds, minutes however long the app is running. Any help would be appreciated.
Thank You
A:
Create one UILable in your RootViewController or UIWindow and then update it frequently with following way.
create one Variable in .h file.
@property (nonatomic) int seconds;
put following code in ViewDidLoad method of your RootViewController
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];
[timer fire];
Create following Function to update UILabel.
- (void) updateLabel {
self.seconds = self.seconds + 1;
NSLog(@"You can show time in minutes, hours and day also after doing some calculation as per your need");
[self.lblDemo setText:[NSString stringWithFormat:@"%d seconds",self.seconds]];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Pork shoulder low slow cook time
I am planning to cook a 10lb (4.5kg) bone-in pork shoulder at 250°F (121°C) for about 8 hours.
Is there any danger in overcooking if I cook for a few hours longer? I know it needs the time for the collagen to break down. I'm just wondering if there is an outside time danger of it becoming dry?
A:
If you cook it too long uncovered it will lose moisture and dry out. If it is covered and you have a bit of liquid in there you could cook it longer and it would stay moist. You could turn it down to 200 too to slow the cooking process.
EDIT:
If I was going to cook a piece of meat that long I'd opt for a braise instead of a roast as if you cook any meat dry too long it will dry out even if it's well covered. For pork some thin stock and white wine would do, or maybe cola or ginger ale which works well for ham.
| {
"pile_set_name": "StackExchange"
} |
Q:
overload class new operator when custom CUDA allocator is present using tag-dispatch
have created an STL-style, allocator aware class which I'm trying to use with a custom CUDA allocator. The CUDA allocator works fine for allocating the data storage in unified memory, but in order for the this pointer to be accessible on both host and device, I need to make sure that whenever the data is allocated in unified memory, that the class is as well.
To solve this, I thought a simple tag dispatch would be appropriate. If the allocater is a cudaAllocator, new should create the class in unified memory, and if not, it should just return the regular new output. Unfortunately I think I'm missing something with how tag-dispatch works. Here's the relevant part of the class:
#ifdef __CUDACC__
public:
using cudaAllocator_tag = std::true_type;
using hostAllocator_tag = std::false_type;
void *operator new(size_t len)
{
return new(len, std::is_same<Alloc, cudaAllocator<value_type>>());
}
void operator delete(void *ptr)
{
return delete(ptr, std::is_same<Alloc, cudaAllocator<value_type>>());
}
void *operator new(size_t len, cudaAllocator_tag)
{
void *ptr;
cudaMallocManaged(&ptr, len);
cudaDeviceSynchronize();
return ptr;
}
void operator delete(void *ptr, cudaAllocator_tag)
{
cudaDeviceSynchronize();
cudaFree(ptr);
}
void *operator new(size_t len, hostAllocator_tag)
{
return ::new(len);
}
void operator delete(void *ptr, hostAllocator_tag)
{
::delete(ptr);
}
#endif // __CUDACC__
but the (NVCC) compiler throws up with the following errors:
2> error : expected a type specifier
2>
2> detected during instantiation of "void *CircularQueue<T, Alloc>::operator new(size_t) [with T=float, Alloc=cudaAllocator<float>]"
2>
2> main.cu(21): here
2>
2>
2>
2> error : no instance of overloaded "operator new" matches the argument list
2>
2> argument types are: (unsigned long long, size_t, std::is_same<cudaAllocator<float>, cudaAllocator<float>>)
2>
2> detected during instantiation of "void *CircularQueue<T, Alloc>::operator new(size_t) [with T=float, Alloc=cudaAllocator<float>]"
2>
2> main.cu(21): here
Any ideas on what I'm doing wrong?
A:
There are several problems here:
new is missing the identifier of the object to create. Assuming your container is called myContainer It should be:
static void *operator new(size_t len)
{
return new myContainer(len, std::is_same<Alloc, cudaAllocator<value_type>>());
}
The arguments of operator delete cannot be overloaded like they can for new. You can get around this by having delete invoke a custom destroy function, using inline and tag-dispatch to avoid any run-time penalties.
static void operator delete(void *ptr)
{
destroy(ptr, std::is_same<Alloc, cudaAllocator<value_type>>());
}
to avoid confusion /infinite recursion, it's probably best to do with with new as well.
Complete Solution:
#ifdef __CUDACC__
public:
using cudaAllocator_tag = std::true_type;
using hostAllocator_tag = std::false_type;
using isCudaAllocator = typename std::is_same<Alloc, cudaAllocator<value_type>>;
static void *operator new(size_t len)
{
return create(len, isCudaAllocator());
}
static void operator delete(void *ptr)
{
destroy(ptr, isCudaAllocator());
}
protected:
static inline void *create(size_t len, cudaAllocator_tag)
{
void *ptr;
cudaMallocManaged(&ptr, len);
cudaDeviceSynchronize();
return ptr;
}
static inline void destroy(void *ptr, cudaAllocator_tag)
{
cudaDeviceSynchronize();
cudaFree(ptr);
}
static inline void *create(size_t len, hostAllocator_tag)
{
return ::new CircularQueue(len);
}
static inline void destroy(void *ptr, hostAllocator_tag)
{
::delete(static_cast<CircularQueue*>(ptr));
}
#endif // __CUDACC__
| {
"pile_set_name": "StackExchange"
} |
Q:
angular - set/edit route queries(or params) without navigating
Hi I want to use routes to store certain information like pagination data or filter data in the queries (or params). For example I'm on
app/datagrid
and I want to add page=2 and pageSize=10 to it
app/datagrid?page=2&pageSize=10
Is there a way to edit/set them to the current route without triggering a route change/update?
thanks!
A:
If you are adding it to the current route, then the route will not change. It won't reload the component if only the parameters change.
You can see an example here: Passing params angular 2 traditional way
This uses the .navigate command, but if it is navigating to the same component it is currently displaying, it won't actually "navigate".
Alternatively, you could build a service that retains that data instead of using route parameters. I have an example here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
The service would basically look like this:
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
serviceData: string;
}
But instead of serviceData you'd have your page and pageSize.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you buy an inexpensive rectifier/dc power source for cheap flickering LED Christmas lights?
OK, I bit on Home Depot's door buster LED christmas lights... 150 LED lights for under $5 each. How could I resist? (Answer: By remembering that cheap LEDs flicker, AND that I'm sensitive to it. )
https://www.instyleled.co.uk/what-causes-led-flicker-and-how-can-i-stop-it-happening/
Seeing as how they were door-busters, they are also non-returnable. I'd like to figure out how to make them work. I've done some research, which has shown that it's possible to create a dc rectifier/transformer/ that will make the flickering stop.
https://www.youtube.com/watch?v=mqRd3q7k9OU
Now, I think I can do all of that (I love soldering that gives you that much room to screw up. BUT, I'd rather just pay $5 for a professional version that absolutely positively won't overheat and burn down my house. I can NOT find anything that's not built for uses like under-cabinet lighting or dimmers, and which have specific connectors for specific manufacturers. Does anyone know if anyone sells something like this, or if there are kits that are a little LESS DIY in nature? Thanks!
A:
No-one will sell a commercial product like that. It's dangerous.
DC is nasty business. Seriously, go to mouser and pick any random power relay. Look at its specs for AC, and then look at its specs for DC. Whoa!
DC is de-rated by a large factor because when a DC arc strikes, it doesn't self-extinguish because the voltage never goes to zero. An arc, once struck, doesn't feel pity or remorse or fear and it absolutely will not stop until it's burned up so much conductor it can no longer bridge the gap, and if that sets your house on fire, too bad. If you've seen old "snap switches" which have a considerable action to them, they are preloading and releasing a "snap" action which creates a large gap when the contact breaks. Larger switches and contactors have designed-in "blowouts" which bend the arc into an arc-chute. The point is, interrupting DC takes a lot more design and engineering than interrupting AC. And a short is a much bigger deal.
Now when you rectify AC into DC, you get a bouncing-ball waveform.
Supposedly that should self-extinguish same as full-wave AC, but capacitance will prevent it from getting all the way to zero. If you add a smoothing capacitor, then it has no chance to extinguish. You wouldn't want to do that anyway, because that would raise the average (RMS) voltage, which could overcurrent the LEDs. LEDs are non-linear, so a small voltage increase makes a big current increase. The curves are in LED spec sheets.
Of course if you could constant-current regulate each LED chain, it's perfectly wired for that.
| {
"pile_set_name": "StackExchange"
} |
Q:
(Symfony 4) How do I access the Liip Imagine bundle from within PHP code?
I want to be able to upload a file, and create 3 thumbnails from it and store everything on an S3 server.
I have my liip/LiipImagineBundle set up as follows:
liip_imagine :
# configure resolvers
resolvers :
# setup the default resolver
default :
# use the default web path
web_path : ~
# your filter sets are defined here
filter_sets :
# use the default cache configuration
cache : ~
# the name of the "filter set"
my_thumb :
# adjust the image quality to 75%
quality : 75
# list of transformations to apply (the "filters")
filters :
# create a thumbnail: set size to 120x90 and use the "outbound" mode
# to crop the image when the size ratio of the input differs
thumbnail : { size : [120, 90], mode : outbound }
# create a 2px black border: center the thumbnail on a black background
# 4px larger to create a 2px border around the final image
background : { size : [124, 94], position : center, color : '#000000' }
# the name of the "filter set"
thumb_square :
# adjust the image quality to 75%
quality : 75
# list of transformations to apply (the "filters")
filters :
thumbnail : { size : [300, 300], mode : outbound }
# create a 2px black border: center the thumbnail on a black background
# 4px larger to create a 2px border around the final image
background : { size : [304, 304], position : center, color : '#000000' }
# the name of the "filter set"
thumb_rectangle_md :
# adjust the image quality to 75%
quality : 75
# list of transformations to apply (the "filters")
filters :
thumbnail : { size : [670, 400], mode : outbound }
# create a 2px black border: center the thumbnail on a black background
# 4px larger to create a 2px border around the final image
background : { size : [674, 404], position : center, color : '#000000' }
# the name of the "filter set"
thumb_hd :
# adjust the image quality to 75%
quality : 75
# list of transformations to apply (the "filters")
filters :
thumbnail : { size : [1920, 1080], mode : outbound }
# create a 2px black border: center the thumbnail on a black background
# 4px larger to create a 2px border around the final image
background : { size : [1924, 1084], position : center, color : '#000000' }
This is the documentation I am looking at: https://symfony.com/doc/2.0/bundles/LiipImagineBundle/basic-usage.html#runtime-options
The problem I am having is that in the documentation it just says to do it like the following:
$this['imagine']->filter('/relative/path/to/image.jpg', 'my_thumb')
The obvious error I am getting is:
Cannot use object of type App\Controller\CreatorDashboard\PostsController as array
I understand why I am getting the error, it thinks I'm trying to use my controller class as an array.
But how do you access this Liip/LiipImagineBundle in the code then? How do I get a "handle" on it in Symfony 4?
The documentation isn't clear.
A:
The example you shared is for template usage without twig. If you're in a controller (an assumption based on the error you shared) you need to get the Liip Cache Manager off of container.
/** @var CacheManager */
$imagineCacheManager = $this->get('liip_imagine.cache.manager'); // gets the service from the container
/** @var string */
$resolvedPath = $imagineCacheManager->getBrowserPath('/relative/path/to/image.jpg', 'my_thumb'); // resolves the stored path
| {
"pile_set_name": "StackExchange"
} |
Q:
Print time from external server in bash
I'd like to know if it's possible to simply retrieve a Unix timestamp from an external server (using NTP, I suppose). I know there's ntpd, which will update the current system time to the time given by an NTP server, but I only want to read the timestamp. Is it possible using a Bash command in Linux? If not, I guess I'll just have to write a Python (or something) app to get it and print it on the shell.
A:
Some servers provide the daytime daemon which can give you what you want, in textual form anyway.
Try:
telnet SERVER daytime
on your favorite SERVER.
Example transcript:
pax$ telnet time.nist.gov daytime
Trying 192.43.244.18...
Connected to time.nist.gov.
Escape character is '^]'.
55860 11-10-26 06:33:38 12 0 0 438.2 UTC(NIST) *
Connection closed by foreign host.
| {
"pile_set_name": "StackExchange"
} |
Q:
exam: Making the header a stack of tables with different number of columns
For the header, I would like to make it consist of three rows with a different number of cells. However, I tried the following where I piled up three tables which made the final result not decent.
Therefore, I would like to:
1- optimize the header and find a better way, if possible, instead of three tables on top of each other,
2- make the color in the highlighted cell span all of it without the white margin surrounding it
3- and remove the extra vertical skip at the third row before the header rule.
Minor comments:
1- is it possible to make the header height predict the required extra height and set it automatically instead of trial and error?
2- Why is there a space, in the first row, to the right of the word "right"?
\documentclass[
addpoints,
]{exam}
\usepackage{lipsum,graphicx,mdframed,array,ragged2e,booktabs,fmtcount}
\usepackage[table]{xcolor}
\newcolumntype{L}[1]{>{\RaggedRight\hspace{0pt}}p{#1}}
\newcolumntype{R}[1]{>{\RaggedLeft\hspace{0pt}}p{#1}}
\newcolumntype{C}[1]{>{\Centering\hspace{0pt}}p{#1}}
\pagestyle{headandfoot}
\extraheadheight{3cm}
\firstpageheadrule
\firstpageheader%
{}%
{%
\setlength{\tabcolsep}{0em}
\begin{tabular*}{\textwidth}{@{}L{0.33\textwidth}C{0.33\textwidth}R{0.33\textwidth}@{}}
\toprule
left & center & right\\
\midrule
\end{tabular*}
\begin{tabular*}{\textwidth}{C{\textwidth}}
\cellcolor{gray!30}loooooooooooong text\\
\midrule
\end{tabular*}
\begin{tabular*}{\textwidth}{L{0.5\textwidth}R{0.5\textwidth}}
Some looooooooooooooooong sentence. & another one
\end{tabular*}
}%
{}
\begin{document}
\begin{questions}
\question some question
\end{questions}
\end{document}
A:
This solution uses boxes instead of a tabular. One can easily adjust the spacing to be more like a tabular using \struts or increasing \fboxsep.
\documentclass[addpoints,]{exam}
\usepackage{lipsum,graphicx,mdframed,array,ragged2e,booktabs,fmtcount}
\usepackage[table]{xcolor}
\pagestyle{headandfoot}
\newsavebox{\headbox}
\savebox{\headbox}{\def\strut{\vrule height\arraystretch\ht\strutbox
depth\arraystretch\dp\strutbox width0pt}%
\parbox{\textwidth}{\hrule
\strut\rlap{left}\hfill\mbox{center}\hfill\llap{right}\hrule
\fboxsep=1pt
\colorbox{gray!30}{\makebox[\dimexpr \textwidth-2\fboxsep][c]{\strut loooooooooooong text}}\hrule
\strut Some looooooooooooooooong sentence.\hfill another one}}
\extraheadheight{\dimexpr \ht\headbox+\dp\headbox}
\firstpageheadrule
\firstpageheader%
{}%
{\usebox\headbox}%
{}
\begin{document}
\begin{questions}
\question some question
\end{questions}
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cygwin - how do I search scrollback?
Going to be pretty depressed if this is not a feature by now. To be clear, by scrollback, I mean scrolling up and down on the terminal emulator to see history.
A:
How do I scroll up and down in mintty to see the terminal buffer?
To scroll in mintty use one of the following:
Mouse:
scrolling behaviour is normal like any other windows window
Keyboard:
shift followed by up arrow or down arrow will scroll the terminal buffer by a single line
shift followed by page up or page down will scroll the terminal buffer by a page
To change the modifier key from shift:
Click the top left icon (which drops down the menu).
Select "Options".
Select "Window".
Change Modifier for Scrolling" as appropriate.
You can also choose to allow page up or page down to work without a modifier.
Press "Apply", then "OK".
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the definitions for LPARAM and WPARAM?
I know I'm being lazy here and I should trawl the header files for myself, but what are the actual types for LPARAM and WPARAM parameters? Are they pointers, or four byte ints? I'm doing some C# interop code and want to be sure I get it working on x64 systems.
A:
LPARAM is a typedef for LONG_PTR which is a long (signed 32-bit) on win32 and __int64 (signed 64-bit) on x86_64.
WPARAM is a typedef for UINT_PTR which is an unsigned int (unsigned 32-bit) on win32 and unsigned __int64 (unsigned 64-bit) on x86_64.
MSDN link
A:
These typedefs go back to the 16-bit days. Originally, LPARAM was a long (signed 32-bit) and WPARAM was a WORD (unsigned 16-bit), hence the W and L. Due to the common practice of passing casted pointers as message parameters, WPARAM was expanded to 32 bits on Win32, and both LPARAM and WPARAM were expanded to 64 bits on Win64.
In C#, you should use IntPtr for LPARAM and UIntPtr for WPARAM.
Note that despite the LP prefix, LPARAM is not a far pointer to an ARAM.
A:
LPARAM refers to a LONG_PTR and WPARAM refers to a UINT_PTR
On x86 they will be 4 bytes and on x64 they will be 8 bytes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to develop an Xamarin Forms app with only Xamarin Studio for MAC?
I need to create a new application for Iphone with Xamarin? Forms
Is it possible to do this without any windows system?
I know this sounds bizare but that is the requirment.
A:
Yes, this is possible. You can develop Android and iOS apps with Visual Studio for Mac. Of course you won't be able to develop UWP apps.
With Visual Studio for Mac you can build websites with ASP.NET Core and apps using .NET Core, games with Unity, and mobile apps for Android and iOS using Xamarin. (emphasis mine, see here)
| {
"pile_set_name": "StackExchange"
} |
Q:
Moving between DataGridView rows via code and show through textboxes
I'm not an experienced programmer and I must have made some misconceptions.
I have two forms, one for the search (FormSearch) and one to show the results (FormMain).
The question is: how can I populate the textboxes with the previous results (click on the btnPrev button) or the next results (click on the btnNext button)?
FormSearch
Imports System.Data.SqlClient
Public Class FormSearch
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
Dim con As New SqlConnection("Data Source=" & Form1.server & "," & Form1.port & "; Initial Catalog=" & Form1.database & "; User Id=" & Form1.txtUsername.Text & "; Password=" & Form1.txtPassword.Text & ";")
Dim cmd As New SqlCommand("select * FROM dbo.customers;", con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
FormMain.TextBox1.Text = row.Cells("Name").Value.ToString
FormMain.TextBox2.Text = row.Cells("Surname").Value.ToString
FormMain.TextBox3.Text = row.Cells("Age").Value.ToString
Me.Hide()
FormMain.Show()
End If
End Sub
End Class
FormMain
Public Class FormMain
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
FormSearch.Show()
Me.Hide()
End Sub
Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
'Show prev result
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'Show next result
End Sub
End Class
A:
Try this:
1) Apply the code below in FormMain
Public Class FormMain
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
FormSearch.Show()
Me.Hide()
End Sub
Private Sub btnPrev_Click(sender As Object, e As EventArgs) Handles btnPrev.Click
BS.Position = BS.Position - 1
DisplayRecords()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
BS.Position = BS.Position + 1
DisplayRecords()
End Sub
End Class
2) Apply the code below in FormSearch
Imports System.Data.SqlClient
Public Class FormSearch
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim con As New SqlConnection("Data Source=" & Form1.server & "," & Form1.port & "; Initial Catalog=" & Form1.database & "; User Id=" & Form1.txtUsername.Text & "; Password=" & Form1.txtPassword.Text & ";")
Dim adapter As New SqlDataAdapter("select * FROM [dbo.customers]", con)
adapter.Fill(DS, "myTableNane")
BS.DataSource = DS
BS.DataMember = "myTableNane"
DataGridView1.DataSource = BS
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.RowIndex >= 0 Then
BS.Position = e.RowIndex
Me.Hide()
FormMain.Show()
End If
End Sub
End Class
2) Create a Module and place the below code.
Module Module1
Public DS As New DataSet
Public WithEvents BS As New BindingSource
Sub DisplayRecords(Optional ByVal table As String = "myTableNane")
FormMain.TextBox1.Text = DS.Tables(table).Rows(BS.Position)("Name").ToString
FormMain.TextBox2.Text = DS.Tables(table).Rows(BS.Position)("Surename").ToString
FormMain.TextBox3.Text = DS.Tables(table).Rows(BS.Position)("Age").ToString
End Sub
End Module
Hope you find it helpful and solved your problem.
Moiyd
| {
"pile_set_name": "StackExchange"
} |
Q:
Actions, Permissions and Architecture
Within my logic layer I have the need to check permissions for a wide variety of actions. Some actions are generic but some are highly specialized. Each action has a corresponding permission hierarchy that is evaluated prior to performing the action. I have been tossing around architecture ideas in my head but haven't reached a solid one that I think will be extensible, simple and elegant.
The current code looks something like this:
public class LogicObject
{
public void Add()
{
Check Add Permission
Perform
}
public void Update()
{
Check Update Permission
Perform
}
}
The problem with this architecture is that, first it isn't really all that extensible, and second it doesn't allow me to check the permission without performing the action.
Another idea I had was to have something like this:
public class AddAction : IAction
{
public bool IsPermitted;
public void Perform();
}
public class LogicObject
{
public IAction AddAction {get { return new AddAction(); } }
}
I like this architecture better but I am not quite set on it. It seems a bit hokey. I can't imagine that this type of architecture is unique. What are some examples of a better way of doing this?
A:
Another option you have is to use Aspect Oriented Programming to have a components external from your services to control the method access authorization. What it basically means is that your methods will be wrapped in runtime by code that will perform the authorization.
An example solution for implementing this for java is Spring Security which will give you a multitude of ways to customize and define your authorization scheme.
The object would then look something like:
public class logicObject {
@PreAuthorize("hasRole('ROLE_USER')")
public void update() {
//Perform
}
//...
}
Off course you will need additional code to define the security context and create a proxy for the logicObject class with that context, along with defining your authorization itself.
Since it seems like the code example you gave is in C# you might want to have a look at Role Based Security, and all the goods in [System.Security.Permissions][2] namespace. It allows you to use attributes to control the access of a method in run time. You can define your own custom attributes and authorization provider. Using it might look something like:
public class LogicObject
{
[PrincipalPermissionAttribute(SecurityAction.Demand, Role="ROLE_USER")]
public void Add()
{
//Perform
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Temporary table postgresql function
I can't find a clear explanation of the syntax to create (and use) tables just for the inside calculations of a function. Could anyone give me a syntax exemple please ?
From what I've found, I have tried this (with and without @ before temp_table) :
CREATE FUNCTION test.myfunction()
RETURNS SETOF test.out_table
AS $$
DECLARE @temp_table TABLE
(
id int,
value text
)
BEGIN
INSERT INTO @temp_table
SELECT id, value
FROM test.another_table;
INSERT INTO test.out_table
SELECT id, value
FROM @temp_table;
RETURN END
$$ LANGUAGE SQL;
I get :
ERROR: syntax error at or near "DECLARE"
LINE 5: DECLARE @temp_table TABLE
-
I also tried the CREATE TABLE approach suggested here, this way :
CREATE FUNCTION test.myfunction()
RETURNS SETOF test.out_table
AS $$
CREATE TABLE temp_table AS
SELECT id, value
FROM test.another_table;
INSERT INTO test.out_table
SELECT id, value
FROM temp_table;
$$ LANGUAGE SQL;
And I get this :
ERROR: relation "temp_table " does not exist
LINE 11: FROM temp_table
(Obviously, I'm aware the temp_table is not necessary for what I'm doing in the code above, but that's not the point :) => I want to understand the syntax to get it to work)
A:
The appropriate syntax for creating a temp table is
create temp table...
but you have to be sure to drop the temp table before existing out of the function. Also, I'd suggest this syntax instead:
CREATE TEMP TABLE IF NOT EXISTS temp_table AS
SELECT id, value
FROM test.another_table;
Thus your function will be like this:
CREATE FUNCTION test.myfunction()
RETURNS SETOF test.out_table
AS $$
CREATE TEMP TABLE IF NOT EXISTS temp_table AS
SELECT id, value
FROM test.another_table;
INSERT INTO test.out_table
SELECT id, value
FROM temp_table;
DROP TABLE temp_table;
$$ LANGUAGE SQL;
But if I can be so kind, I'd like to rewrite this function so it is more correct:
CREATE FUNCTION test.myfunction()
RETURNS TABLE (id int, value varchar) -- change your datatype as needed
AS $$
BEGIN;
CREATE TEMP TABLE IF NOT EXISTS temp_table AS
SELECT id, value
FROM test.another_table;
INSERT INTO test.out_table
SELECT id, value
FROM temp_table;
DROP TABLE temp_table;
RETURN QUERY
SELECT id, value
from temp_table;
END;
$$ LANGUAGE plpgsql;
Untested; let me know if this fails.
| {
"pile_set_name": "StackExchange"
} |
Q:
SD card directory
I want to access to sd card files and read all contents of the file. First I could not write the path of sd card plugged to my computer, because sd card names can be changed. Besides I want to get all file names in my directory path.
There are too more files in the directory and they are named with numbers like "1.txt", "2.txt". But I have to access the last file and read the last file lines. I am using the code below. Any advise?
public void readSDcard()
{
//here i want to get names all files in the directory and select the last file
string[] fileContents;
try
{
fileContents = File.ReadAllLines("F:\\MAX\\1.txt");// here i have to write any sd card directory path
foreach (string line in fileContents)
{
Console.WriteLine(line);
}
}
catch (FileNotFoundException ex)
{
throw ex;
}
}
A:
.NET Framework does not provide a way to identify, which drive is a SD Card (I doubt there is a reliable way to do so at all, at least not without very low-level progaming, such as querying system driver). Best you can do is to check DriveType property of DriveInfo to be equal to DriveType.Removable, but this will also select all flash drives etc.
But even then, you will need some another information to select proper SD card (think, there could be more than one SD card inserted in the computer). If SD card has volume label that will be always the same, you can use it to choose the right drive. Otherwise, you will have to ask user, which of the removable drives he wishes to use, as shown bellow.
Question does not specify, what does last file mean. Is it last created file, last modified file, last file enumerated by operating system, or file with the biggest number in it's file name? So I assume you want a file with the biggest number.
public void readSDcard()
{
var removableDives = System.IO.DriveInfo.GetDrives()
//Take only removable drives into consideration as a SD card candidates
.Where(drive => drive.DriveType == DriveType.Removable)
.Where(drive => drive.IsReady)
//If volume label of SD card is always the same, you can identify
//SD card by uncommenting following line
//.Where(drive => drive.VolumeLabel == "MySdCardVolumeLabel")
.ToList();
if (removableDives.Count == 0)
throw new Exception("No SD card found!");
string sdCardRootDirectory;
if(removableDives.Count == 1)
{
sdCardRootDirectory = removableDives[0].RootDirectory.FullName;
}
else
{
//Let the user select, which drive to use
Console.Write($"Please select SD card drive letter ({String.Join(", ", removableDives.Select(drive => drive.Name[0]))}): ");
var driveLetter = Console.ReadLine().Trim();
sdCardRootDirectory = driveLetter + ":\\";
}
var path = Path.Combine(sdCardRootDirectory, "MAX");
//Here you have all files in that directory
var allFiles = Directory.EnumerateFiles(path);
//Select last file (with the greatest number in the file name)
var lastFile = allFiles
//Sort files in the directory by number in their file name
.OrderByDescending(filename =>
{
//Convert filename to number
var fn = Path.GetFileNameWithoutExtension(filename);
if (Int64.TryParse(fn, out var fileNumber))
return fileNumber;
else
return -1;//Ignore files with non-numerical file name
})
.FirstOrDefault();
if (lastFile == null)
throw new Exception("No file found!");
string[] fileContents = File.ReadAllLines(lastFile);
foreach (string line in fileContents)
{
Console.WriteLine(line);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the gender of adjectives that describe implied nouns?
I went to a Mexican restaurant and this is how my conversation went:
Yo: Quiero un vaso de agua de sandía.
Camarera: ¿Chica o Grande?
Yo: Chica.
Why did the waitress use "chica" instead of "chico"? Isn't she asking me how big of a cup I want? Cup is masculine, so I would presume that the adjective describing it should also be masculine. The waitress also used the same feminine "chica" with the next customer, so I doubt she botched up the word.
In general, how do you decide on the gender of an adjective when its noun is implied?
A:
That's not incorrect and actually you asked what you shuld have to. But people use to refer to "vaso de agua" as just "agua"
e.g. ¿Me da un agua de sandía? Chica, por favor.
(when a standard unit is understood: e.g. vaso or jarra)
Imagine the lot of times a waitress deal with the expression vaso grande/chico de agua. It's totally correct, but just too long to be pronounced 10 times/hour. Waitress and costumers use the more confortable expression "agua chica/grande", provided there is no missunderstanding whether we are referring to jarra or vaso.
So, in your example,
Usted: Quiero un vaso de agua de sandía.
Camarera: ¿(agua) chica o grande?
Usted: (agua) chica.
What if you didn't have asked that? A possible conversation is
Usted: Quiero un agua grande de sandía.
Camarera: ¿Jarra o vaso?
Usted: Vaso.
Camarera: ¿chico o grande?
Usted: Chico.
A:
It's always the same gender, she messed it up.
Being a native Spanish speaker with good orthography, I see that usually even the native speakers make silly mistakes (especially in verb conjugation), just let it pass through.
Edit: Further explanation from the comments: "Quiero un vaso de agua de sandía.", Quiero un vaso de agua de sandía; el sujeto de la oración es Yo, pero es un sujeto tácito, donde tú tienes que inferir cuál pronombre es, y el resto es el predicado, el núcleo de predicado es el sustantivo "vaso" y "de agua" es simplemente un complemento (y comienza con "de", que de por sí es una preposición). Así que la pregunta correcta es "¿Chico o grande?".
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a separate site to ask questions about God?
I saw religious SE sites like Hinduism, Christianity, Islam, etc. But over all we can say God regardless of religious. I want to ask a question about God, but not specific to a religion. Is there a separate SE available?
Note: My question will be 'If God exist then why do people, who didn't do any crime or sin (particularly children or new born baby), get deadly diseases?
The pain they are getting is their own pain that God is not feeling instead of them.'
If I want to ask this question, what is the best suitable site to ask and I don't mind if it will be closed as off topic.
Note: I can ask this question on Hinduism as I'm based in that religion, but I want a generic answer.
A:
People mean different things when they talk about God, so it's hard to ask a question without reference to some religion. You might be able to ask a question about this on Philosophy; they have a "god" tag.
Your question as you've outlined it here might be closed as either too broad or primarily opinion-based. Your question sounds like a topic for discussion more than an answerable question. Theodicy is a huge topic with many possible answers. Instead, consider asking according to somebody -- what does such-and-such theology/philosopher teach about this?
Be sure to read the tour and "what is on-topic" Help Center post on any site before asking this question. Doing so will help you learn what a site needs for your question to be accepted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set Cookie with Javascript and sanitize value
I need to set a cookie with javascript which I'm doing this with the following command:
document.cookie = name+"="+value;
My problem is that value is a string, which can contain any unicode-character.
Is there a function which automatically replaces special characters (like ;) - and if not, which characters are forbidden?
Something like the "encodeURIComponent()"-Function for Get-Parameters would be perfect
A:
You should use window.escape.
The escape() method converts special characters (any characters that are not regular text or numbers) into hexadecimal characters, which is especially necessary for setting the values of cookies. Also useful when passing name=value pairs in the URL of a GET request, or an AJAX GET/POST request.
It also has window.unescape counterpart.
Upd.
It may make some sense to use base64 encoding/decoding prior to escaping in order not to suffer that much from unicode characters expenditure by window.encode.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django - ImportError: No module named views
I am developing an application in python 2.7 and using Django, when I run it on my local machine (windows 7) it runs well without any error, but when I try to run it in a virtual machine with ubuntu server where it also used to work well, it crashes with the
following error
This is my project working tree:
- MYSITE
* BMM
·admin.py
·apps.py
·models.py
·pdf_utils.py
·urls.py
·views.py
*Mysite
·settings.py
·urls.py
·wsgi.py
This is the app\urls.py file:
from django.conf.urls import url
from wkhtmltopdf.views import PDFTemplateView
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
# url(r'^$', views.pdf, name='pdf'),
# url(r'^$', views.ganttChart, name='ganttChart'),
url(r'^pdf/$', PDFTemplateView.as_view(template_name='billReport.html',filename='my_pdf.pdf'), name='pdf'),
url(r'^report/$', views.report, name='report'),
]
And this is the mysite/urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
#from wkhtmltopdf.views import PDFTemplateView
urlpatterns = [
url(r'',include('bmm.urls')),
url(r'^ganttchart/', include('bmm.urls')),
url(r'^admin/', admin.site.urls),
#url(r'^pdf/$', PDFTemplateView.as_view(template_name='billReport.html', filename='my_pdf.pdf'), name='pdf'),
]
Any help about how to solve this would be really appreciated
A:
error you are getting is self-explanatory.
It seems you have installed wrong package. you have installed wkhtmltopdf package which has no module named "view". That's why you are getting error: "No module named views"
The correct package is django-wkhtmltopdf, which has module named "view".
Uninstall wkhtmltopdf and install django-wkhtmltopdf.
You can find installation and setup instruction for django-wkhtmltopdf here.
1.pip uninstall wkhtmltopdf
2.pip install django-wkhtmltopdf
Don't forget to put wkhtmltopdf in `INSTALLED_APPS:
INSTALLED_APPS = (
# ...
'wkhtmltopdf',
# ...
)
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the grammatical function of 'that' in this sentence?
Scenario: 'Are you stressed by his threat?' Answer: 'I'm not that concerned.'
What is the grammatical function of 'that' in this sentence?
A:
Adverb. It means "very" and applies to concerned. The sentence means the same as I'm not very concerned.
| {
"pile_set_name": "StackExchange"
} |
Q:
Compilation error in Delphi XE4
[dcc32 Error] MSSQLQuery.pas(29): E2037 Declaration of 'DataEvent' differs from previous declaration
I have done some research and found that this issue is caused during function overriding, if the declaration in super class and sub class are different
DataEvent is a library function and Ive checked the library and found that the declaration in code is correct ,but Im not sure why this compilation error occurs
I have also confirmed that there is only one DataEvent function in this class
I am new to Delphi So please help me in resolving this error
This is the class I have defined
TMSSQLQuery = Class (TADOQuery)
Private
FAutoNoLock : Boolean;
Protected
procedure DataEvent(Event: TDataEvent; Info: Longint); override;
Public
Constructor Create (AOwner : TComponent);Override;
Destructor Destroy;Override;
End;
This is the procedure definition
Procedure TMSSQLQuery.DataEvent(Event: TDataEvent; Info: Longint);
Begin
{ Call inherited method }
Inherited DataEvent (Event, Info);
If Event in [deConnectChange, dePropertyChange]
Then RefreshParams;
End;
A:
Note: After your recent edit, the issue is clear.
You've declared your DataEvent handler with a second parameter of LongInt:
procedure DataEvent(Event: TDataEvent; Info: Longint); override;
The VCL defines it as NativeInt (see the documentation):
procedure DataEvent(Event: TDataEvent; Info: NativeInt); override;
NativeInt and LongInt are not the same in that declaration, and therefore the descendant class definition does not match that of the ancestor you're attempting to override. (See the next section of my answer).
This error occurs if you have a declaration in the implementation section that is different from the interface declaration.
type
TSomeClass=class(TSomething)
procedure DoThisThing(const AParameter: TSomeParamType);
end;
implementation
// Note difference in parameter name
procedure TSomeClass.DoThisThing(AParam: TSomeParamType);
begin
end;
// This would cause the same error - note the missing 'const'
procedure TSomeClass.DoThisThing(AParameter: TSomeParamType);
begin
end;
// This can cause the same error - note different param type
procedure TSomeClass.DoThisThing(AParameter: TDiffParamType);
The easiest solution to the problem is to use Class Completion to write the implementation definition for you. Type the declaration in the interface, and then (while still in that class definition) use Ctrl+Shift+C. It will generate the proper method stub in the implementation section for you.
(You can generate several at the same time; just declare them all before using the keystroke combination. Using Ctrl+Shift+UpArrow (or DownArrow) helps you move back and forth between the implementation and interface sections.)
The documentation (see below) indicates that this error message also occurs when you try to override a virtual method, but the overriding method has a different parameter list, calling convention etc. This code is from that linked documentation:
type
MyClass = class
procedure Proc(Inx: Integer);
function Func: Integer;
procedure Load(const Name: string);
procedure Perform(Flag: Boolean);
constructor Create;
destructor Destroy(Msg: string); override; (*<-- Error message here*)
class function NewInstance: MyClass; override; (*<-- Error message here*)
end;
For more info, see the Delphi documentation for E2037.
| {
"pile_set_name": "StackExchange"
} |
Q:
Type hierarchy in java annotations
I am facing problem with creating some metadata structure inside annotations. We are using annotations for define special attributes for hibernate entity attributes but it might be usable everywhere.
I want to create condition which represent these structure:
attribute1 = ...
OR
(attribute2 = ...
AND
attribute3 = ...)
Problem is that I need to define some "tree" structure using this annotations. Here is some design I want to reach:
@interface Attribute {
... some attributes ...
}
@interface LogicalExpression {
}
@interface OR extends LogicalExpression {
Attribute[] attributes() default {};
LogicalExpression logicalExpressions() default {};
}
@interface AND extends LogicalExpression {
Attribute[] attributes() default {};
LogicalExpression logicalExpressions() default {};
}
@interface ComposedCondition {
Attribute[] attributes() default {};
LogicalExpression logicalExpressions() default {};
}
All these annotation I want to use according to this example:
public class Table {
@ComposedCondition(logicalExressions = {
@OR(attributes = {@Attribute(... some settings ...)},
logicalExpressions = {
@AND(attributes = {@Attribute(...), @Attribute(...)})
})
}
private String value;
}
I know that inheritance in that way I defined in the annotation definition above is not possible. But how can I consider my annotations AND, OR to be in one "family"?
A:
Please check Why it is not possible to extends annotations in java?
But you can create meta annotations that can be used on annotation to create groups of annotations.
@LogicalExpression
@interface OR {
Attribute[] attributes() default {};
LogicalExpression logicalExpressions() default {};
}
But this will not help you with your second problem ie. use LogicalExpression as a Parent.
But you can do something like below. Declare LogicExpression as enum This way you can use single enum and various set of Attributes to execute conditions.
e.g. If you want to execute AND, OR condition then you can pass LogicExpression.AND, LogicExpression.OR and use orAttributes() method to execute OR condition and andAttributes() to execute AND condition
public enum LogicExpression {
OR,AND,NOT;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface ComposedCondition {
LogicExpression[] getExpressions() default {};
Attributes[] orAttributes() default {};
Attributes[] andAttributes() default {};..
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Golang. Map of channels
I'd like to index some channels based on a string. I am using a map but it won't allow me to assign a channel to it. I keep getting "panic: assignment to entry in nil map", what am i missing?
package main
import "fmt"
func main() {
var things map[string](chan int)
things["stuff"] = make(chan int)
things["stuff"] <- 2
mything := <-things["stuff"]
fmt.Printf("my thing: %d", mything)
}
https://play.golang.org/p/PYvzhs4q4S
A:
You need to initialize the map first. Something like:
things := make(map[string](chan int))
Another thing, you're sending and trying to consume from an unbuffered channel, so the program will be deadlocked. So may be use a buffered channel or send/consume in a goroutine.
I used a buffered channel here:
package main
import "fmt"
func main() {
things := make(map[string](chan int))
things["stuff"] = make(chan int, 2)
things["stuff"] <- 2
mything := <-things["stuff"]
fmt.Printf("my thing: %d", mything)
}
Playground link: https://play.golang.org/p/DV_taMtse5
The make(chan int, 2) part makes the channel buffered with a buffer length of 2. Read more about it here: https://tour.golang.org/concurrency/3
| {
"pile_set_name": "StackExchange"
} |
Q:
Apache Mod-rewrite: How to write search engine friendly URL
Basically I have seen some examples on this forum however mine is pretty straight forward and I havent been able to locate just my case.
1) I need to change this url: domain.com/page.php to domain.com/page
2) I need to change this url: domain.com/page.php?ID=1 to domain.com/page/1 -> 1 being any number between 1 and infinity
All this running on Apache server.
Thanks,
Update
Any one has any idea? I feel I am so close to getting this working. Please help!
A:
Can use a regex based rule...
RewriteRule ^page/([0-9]+)/?$ page.php?id=$1
| {
"pile_set_name": "StackExchange"
} |
Q:
Getting rockets to display next to each other
Yes this is a homework question. However, I don't think it is a problem to use stack exchange to solve homework problems. This is what real programmers do, don't they.
I have this program that prints two rocket ships to the console. The rockets are stacked vertically. I would like them to appear side-by-side. Is there a way to do this without changing all my static methods?
public class TwoRockets {
public static void main (String[] args) {
appearrocket();
appearrocket();
}
public static void appearrocket() {
cone();
box();
label();
box();
cone();
}
public static void box() {
System.out.println("+------+");
System.out.println("| |");
System.out.println("| |");
System.out.println("+------+");
}
public static void cone() {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println(" / \\");
}
public static void label() {
System.out.println("| VIVA |");
System.out.println("|MEXICO|");
}
}
A:
You have to modify the static methods.
By using concatenation operator you can achieve two rockets side by side.
comment out one //appearrocket();
package com.stackover.ex;
public class TwoRockets {
public static void main (String[] args) {
appearrocket();
//appearrocket();
}
public static void appearrocket() {
cone();
box();
label();
box();
cone();
}
public static void box() {
System.out.println("+------+\t"+"+------+");
System.out.println("| |\t"+"| |");
System.out.println("| |\t"+"| |");
System.out.println("+------+\t"+"+------+");
}
public static void cone() {
System.out.println(" /\\\t\t"+" /\\");
System.out.println(" / \\\t\t"+" / \\");
System.out.println(" / \\\t\t"+" / \\");
}
public static void label() {
System.out.println("| VIVA |\t"+"| VIVA |");
System.out.println("|MEXICO|\t"+"|MEXICO|");
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How did the British and French train their troops during the colonial eras?
From what I saw in movies, during many battles throughout the 1700s to early 1800s involving the French or British armies, rows of troops from both sides would fire volleys of bullets into each other and many soldiers would get hit and fall, but the rest of the soldiers would hold their ground or advance without flinching, and I was wondering how were these soldiers trained to be so disciplined and why would anyone sign up for war, as they would likely die.
A:
as all battles in the period were decided by one side giving way and giving up the fight by running or fleeing, the men were not robots and morale was a very important factor and it soldiers failing to be steady and press forward or whole ground was a regular occurrence
casualties in battle were often not particularly huge, the volleys often rapidly obscured vision, (musket gunpowder produced lot of smoke) the hit rate with muskets was ridiculously low in general, whole range of factors, such levelling not readily understood by many. these were confusing battlefields, noise and smoke.
the superior morale in the ability of the troops to remain steady under fire was a crucial factor. the principal factor in troop quality rather than the skills in shooting and fighting.
the British did not use conscription, and generally their troops were better paid. However the enlistments tended be those with few other choices. the Scots, Irish and kings German subjects were often very large parts of the British army.
"For much of the 18th century, the army was recruited in a wide variety of places, and many of its recruits were mercenaries from continental Europe, including Danes, Hessians and Hanoverians.[3] These mercenaries were hired out by other rulers on contracted terms. Other regiments were formed of volunteers such as French Huguenots. By 1709, during the War of the Spanish Succession, the British Army totalled 150,000 men, of whom 81,000 were foreign mercenaries"
https://en.wikipedia.org/wiki/Recruitment_in_the_British_Army#18th_and_19th_centuries
pre revolutionary France from what I can research did not use conscription either (for regular units in peace time) but when short or wartime unofficial impressment rather than conscription was used.
http://www.napolun.com/mirror/web2.airmail.net/napoleon/FRENCH_ARMY.htm
"The French royal army of the 17th and 18th centuries had consisted primarily of long-service regulars together with a number of regiments recruited from foreign mercenaries. Limited conscription for local militia units was widely resented and only enforced in times of emergency."
https://en.wikipedia.org/wiki/Conscription_in_France
| {
"pile_set_name": "StackExchange"
} |
Q:
How effective is the Reactionary trait?
First, I'm pretty sure that you can't really calculate how good an attack bonus is without knowing an opponent's AC. If that logic holds true, then we can't specifically calculate how good a +2 initiative bonus is without knowing your opponent's initiative modifier.
Typically, perhaps these values are best represented on a table. Is there a way to mathematically evaluate how much more often you will go first in a battle, only considering the effectiveness of a +2 initiative bonus from the Reactionary trait?
A:
This is probably one of the most variable things in the game. Even ignoring the fact that going first is not always better, and that the tactical situation might well change whether or not it is better to go before the bad guys, there are innumerable different combinations of creatures you can encounter, which have many different sets of special abilities and stats. In addition, with 2-5 other PCs in the party, you may want to go before or after some of them.
Assuming you always want to go first, the next issue is with determining what your chance of going first is. In a d20 contested roll, if both sides have the same modifier, and there is a roll-off for a tie, then both sides have an exactly 50% chance of going first. For the first +1 modifier of one side over the other (which, incidentally, also ensures that side breaks ties), the chance of winning initiative goes from 200 in 400 to 229 in 400. From here, every +1 modifier changes the odds by 20, less the difference + 1. So, for a 2 greater modifier, the chance is 247 in 400, for 3 greater, it's 264 in 400, and for 4 greater, it's 280 in 400. You can convert this to a percentage by dividing. This continues until a modifier of 19, at which point, the lower side cannot possibly win.
So, to work out how much benefit +2 is going to give you, you need to know what range of modifiers you will compete against. For a given average party level (APL), in theory, you should face single creatures with a Challenge Rating of 1 lower than your APL, to 3 higher. Of course, if the GM puts you up against more creatures, they will have even lower CRs.
If you look at the d20pfsrd Monster DB, you can see some stats for creatures, and you could use that list to filter to a specific CR, and get some idea of the rough initiative ratings. The initiative modifier is not explicitly on the sheet, but you can use the Dexterity score to get an idea, and look for Improved Initiative in the feat list. Of course, doing this totally ignores custom creatures, templates, or NPCs with class levels. This also gives no indication of the distribution of these creatures during the encounters you will face.
For even the simplest case, of a level 2 party, the single creatures they can face range from CR1 to CR5. The creatures in that range have initiative modifiers ranging from -4 to +11. These entries will change at every level, with no guarantee that the distribution of creatures will ever match what is in the table, or any guarantee of what creatures the GM will use in encounters. NPCs with class levels built by the GM could vary this even more.
For the sake of some illustration, take creatures with a +0, +2 or +4 modifer. The chance of going first against those is shown below, with Initiative Modifiers of +0, +2 and +4 (10 Dex, 10 Dex with Reactionary, and 10 Dex with Improved Initiative).
$$
\large{\text{Chance for PC to go first}} \\
\begin{array}{r|lll}
& \rlap{\rightarrow \text{PC initiative bonus}} \\
\text{Creature initiative bonus} \; \downarrow & +0 & +2 & +4 \\
\hline
+0 & 50\% & 61.75\% & 70\% \\
+2 & 38.25\% & 50\% & 61.75\% \\
+4 & 30\% & 38.25\% & 50\% \\
\end{array}
$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Properly venting a gas water heater
Ahh, the joys of an old house.
The former owners of my house did some funky stuff with venting the water heater. Let me explain:
the water heater is in the basement
there is a 3 in single
walled vent pipe that goes up towards the first floor at about 45
degrees
next there is a joint that points up into the first floor
a short single walled 3 inch vent goes up into the floor
now
in the first floor in a closet there is another joint that connects
horizontally into a vertical 12 inch(?) mega pipe.
this "stand
pipe" appears to have been used as a exhaust vent for an oven in the
kitchen, but is no longer used for that.
at the top of the pipe
you can see that this big pipe is double walled and has a 10 inch (?) clay pipe
going through the attic and out into a roof vent.
the roof vent
is new, it is a standard vent with the cap on it.
So, my question is: can I just connect a double walled vent pipe from the basement joint (#3) up through the attic (#8) (after removing all the funkiness (#4-7)
Here are a few issues:
ideally this double walled vent pipe would be in the wall and not in the middle of the closet as it is now. I believe that is safe, and it can touch drywall/studs as long as it is double walled.
Edit: No it is not safe. d-wall must be 1 inch from combustibles
I'd like to plug the hole in the attic. I think I can safely just cut a piece of drywall to fit around the smaller double walled pipe.
Edit: No it is not safe. d-wall must be 1 inch from combustibles so you can't let sheetrock touch the pipe. You must use a "firestop" flashing
we have a whole house fan. This means the attic gets pressurized. Is there any issue with vent pipe being so loose in the old riser on the roof? Ie can the pressure go up the riser and then down the vent and backdraft? I suspect this is not an issue. I could also seal the riser from inside the attic to prevent issues.
Edit: I should use a firestop again directly under the roof plywood so the pressurized attic air can't escape up the old vent riser.
Comments?
A:
I did a lot more research and I have concluded that what I proposed is mostly safe. There are a few important points
Single wall vent pipes must be 6 inches or more from combustibles (this includes sheetrock!). That means you basically can't use it in walls or near joists/rafters.
Double wall vent pipes must be 1 inch or more from combustibles. You can't put it against sheetrock or studs, etc. That means for a 3 inch pipe (4-5 inches double walled) you need a 6-7 inch wall.
You should use a firestop (a sheet of flashing with a pipe sized hole) at walls and floors/ceilings to keep the pipe a safe distance from studs/sheetrock.
to prevent backdrafting from a Whole House Fan another fire stop should be installed directly below the roof plywood to limit the airflow from the attic to the top of the vent pipe.
| {
"pile_set_name": "StackExchange"
} |
Q:
In iOS9 Interface Builder how can I keep my view below the status bar?
In IB I have this scene in my storyboard
And when ran in simulator it looks exactly like this
Obviously I would like the search bar vertically below the status bar. How can I accomplish that? My UITableViewController is embedded inside a UITabBarController btw.
I looked at this technical Q&A QA1797 (link), but it talks about iOS 7, and according to this document it should work for UITabBarController, but in my case it does not.
I am using XCode 7.0 (7A220)
UPDATE 1: UITableView not draggable
UPDATE 2: Document Outline view of my Search Scene
UPDATE 3: Size inspector for Table (UITableView) showing that the Size X/Y is not editable (I don't know why), and so I can't reposition the Table
A:
The best solution is embed the initial view controller of your storyboard into a navigation controller.
Steps:
1. Select the initial view controller from storyboard.
2. Then go to editor -> Embed in Navigation Controller.
Now run and you'll see problem is resolved.
| {
"pile_set_name": "StackExchange"
} |
Q:
Prototype JS: Document.observe fires "undefined is not a function" error
I try to use the Event.observe method which is provided by Prototype JS. To be sure that the DOM is loaded, I use document.observe. This causes the error Uncaught TypeError: undefined is not a function. Prototype JS was loaded as you can see below:
HTML
<!DOCTYPE html>
<html>
<head>
<title>playground</title>
<script language="javascript" type="text/javascript" src="../js/prototype.js"></script>
<script language="javascript" type="text/javascript" src="../js/functions.js"></script>
</head>
<body>
<div>
<a href="#" id="meinLink">Hello World</a>
</div>
<input type="button" onclick="changeLinkText()" value="Change link by using Prototype">
</body>
JavaScript
//this works
var changeLinkText = function(){
$("meinLink").innerHTML="prototypeWorks";
};
//this causes the error
Document.observe("dom:loaded", function() {
$("meinLink").observe('click', function(e) {
document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
});
});
A:
Your D in
Document.observe("dom:loaded", function() {
is upper-case, fixing it to it's correct notation
document.observe("dom:loaded", function() {
will probably do the job.
You can also try to invoke an on-click-event listener.
$$('meinLink').invoke('on', 'click', '.item', function(event, el) {
// el is the 'meinLink' element
});
It's even possible that just using on will do the job.
$("meinLink").on("click", function(event) {
document.getElementById('meinLink').innerHTML="prototypeDoesntWork";
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I quickly estimate my level in go by playing against a computer/tablet?
I would like to have an idea of my level in go (in kyu). This would for instance help me choose the most appropriate go books to read. I would like to do this through playing against a program—because I can play anywhere anytime.
I read on Wikipedia that each difference of one point in kyu is equivalent to one stone of handicap, and also that one stone is valued to 13–16 points in score difference. So, if I knew the level of the program I play against, this would allow me to quickly adjust the handicap (depending on the score difference) so that games are balanced, and then counting one kyu of difference for each stone of handicap.
But what is the level of computer/tablet programs? Is there a reference somewhere, or some resources that would give some information on that? In my case, I would love to have some idea of the current level of Little Go on iOS (which is based on Fuego), for 19x19 go.
A:
There are several rating systems, for most players their KGS rating and EGF rating will be different, and it can be different from national rating systems (e.g. it is often assumed that French and British ratings for the same player are 2 stones different). So, in a sense, your question cannot be answered unless you specify the rating system you want to be measured against.
The benchmark could be a KGS rating, because KGS is so widely used. The best way to know your rating is to play on KGS with the real players, and KGS will answer your question.
It might be more psychologically comfortable to play against robots, but, from a personal experience, I would not recommend it, they do not help you to improve at the rate that the games against humans will. Also, they have flaws that you might identify and this will allow you to win the games against these robots, but this won't translate in your improved ability to play against humans.
A:
Usually when one has no hint about is level in go it's because he is just a beginner that is between 25 kyu and 15 kyu.
The level of Fuego on iOS is probably something between 3 kyu and 1 dan. So if you win at 9 handicap on 19x19 it's already very good on. If you success, try to decrease the handicap one stone each time.
For book reading really good books for beginners level are graded go problems for beginners volume 1 and volume 2
If you only can play against a computer and not on a server or in real (which are really better to learn), my advice would be to start at the lowest level at 9 handicap and decrease handicap every one or two win when you win 0 handicap increase the computer level and restart at 9 handicap. Be aware that only win/loss count. (especially against monte-carlo computer such as fuego which tend to reach a 0.5 point win).
A better time spent for improve when can't playing against real opponent is to do life and death problems like the ones are found in graded go problems for beginners.
A good tip to know an approx level in doing problems is http://goproblems.com/ (under the section go to problems) when you reach a plateau it's approx your level plus our minus 2 kyu. That should be enough to choose a book.
The really point for knowing your level is to choose a fair handicap against a an opponent you don't play often. When you play often against the same opponent the best is to change handicap every one or two consecutive win.
| {
"pile_set_name": "StackExchange"
} |
Q:
Копировать и вставить файл в android
Здравствуйте. На карте памяти есть файл file.txt. Как с помощью Java переместить его в другую папку? То есть сейчас файл в папке FolderA, а нужно, чтобы он оказался в папке FolderB.
File source = new File(Environment.getExternalStorageDirectory().getPath() + "/FolderA/file.txt");
File destination = new File(Environment.getExternalStorageDirectory().getPath() + "/FolderB/file.txt");
Нужно сделать что-то вроде того:
CopyFile(source, destination);
public void CopyFile(File ОТКУДА, File КУДА) {...}
A:
public void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
GCM java server example
Does anyone have a link to GCM java 3rd Party Server example? I can't understand how to implement it. In http://developer.android.com/google/gcm/server.html, I could not find a complete example.
A:
The easiest way is to use gcm-server.jar (which you can get from here).
Then the code you'll need to send a GCM message will look like this :
Sender sender = new Sender(apiKey);
Message message = new Message.Builder()
.addData("message", "this is the message")
.addData("other-parameter", "some value")
.build();
Result result = sender.send(message, registrationId, numOfRetries);
| {
"pile_set_name": "StackExchange"
} |
Q:
Access-Control-Allow-Origin: *
Возникла проблема с Access-Control-Allow-Origin:
<?php
header('Access-Control-Allow-Origin: *');
$data = "count";
$number = 1;
if($data == "count")
if (is_int($number)){
echo json_encode(['status' => 1, 'count' => $number);
} else {
echo json_encode(['status' => 0, 'count' => 0]);
}
?>
Почему выдает ошибку 500 и как решить проблему? (делаю запрос через $.post)
$.post('http://192.168.100.67/vtnuft/count.php',function(response){
response = JSON.parse(response);
switch (response['status']){
case 1:
$.each(response,function(key,val){
if (key ==="count"){
groupcount = parseInt(val); }
});
break;
case 0:
console.log('Произошла ошибка');
break;
}
});
A:
синтаксическая ошибка
json_encode(['status' => 1, 'count' => $number);
// нужно
echo json_encode(array('status' => 1, 'count' => $number));
и включи вывод ошибок и в лог стоит заглянуть
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I enable multimode emacs to program PHP without messing up my indents?
Whenever I indent HTML in PHP mode, emacs (22.1.1, basic install on Redaht Linux over Putty-SSH) pops up a frame and tells me to get MUMODE or somesuch extra add-on. I installed PHP Mode without a big hassle, but I don't know how to get this multi-mode rolling.
I'd like to know 2 things
How to install and configure multi-mode
How to disable pop-ups in Emacs
A:
If you're running emacs 22, you should just be able to run:
M-x nxhtml-mumamo
when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:
http://www.emacswiki.org/cgi-bin/wiki/MuMaMo
http://www.emacswiki.org/cgi-bin/wiki/PhpMode
| {
"pile_set_name": "StackExchange"
} |
Q:
loading huge XLS data into Oracle using python
I have a 3+ million record XLS file which i need to dump in Oracle 12C DB (direct dump) using a python 2.7.
I am using Cx_Oracle python package to establish connectivity to Oracle , but reading and dumping the XLS (using openpyxl pckg) is extremely slow and performance degrades for thousands/million records.
From a scripting stand point used two ways-
I've tried bulk load , by reading all the values in array and then dumping it using cursor prepare (with bind variables) and cursor fetchmany.This doesn't work well with huge data.
Iterative loading of the data as it is being fetched.Even this way has performance issues.
What options and techniques/packages can i deploy as a best practise to load this volume of data from XLS to Oracle DB ?Is it advisable to load this volume of data via scripting or should i necessarily use an ETL tool ?
As of now i only have option via python scripting so please do answer the former
A:
If is possible to export your excel fila as a CSV, then all you need is to use sqlldr to load the file in db
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there any well-known, proprietary RP games in which a powerful wizard can compel suicide or murder?
Are there any well-known, proprietary RP games in which a powerful wizard can compel suicide or murder?
I'm not a player but I sometimes read questions and answers here.
Out of curiosity I wondered just how powerful a wizard might become and whether they could compel a fellow PC to commit murder or even suicide. Could the GM intervene?
I'm thinking mainly of D&D but I'm open to hearing about other systems if suitable. For clarification: the character doesn't have to be a wizard if another characters could force it to happen.
A:
Yes, magic to compel suicide or homicide are available in D&D.
Homicide isn’t even particularly rare—since most creatures in D&D are at least circumstantially willing to use violence to solve problems, getting one to choose a new target they wouldn’t otherwise consider an enemy often isn’t very difficult. Many forms of mind-control allow targets to resist orders that go against their very nature, but killing isn’t, as a general rule, against the nature of most characters in the world of D&D (though it is, of course, possible that a given situation will be one that the Dungeon Master rules resistable, either because the character actually does oppose killing or because of something about this killing).
As for suicide, most forms of mind control do not allow “Obviously self-destructive orders” as D&D 3.5e’s dominate person puts it, but more powerful and/or more specific options exist that can, in fact, compel suicide. For example, death urge causes a fairly powerful—albeit brief—suicidal urge that can certainly cause death. (Note that death urge isn’t available to the “wizard” class, per se, but the distinction between a wizard and a psion gets into semantic details about how the supernatural works under D&D’s particular rules, which doesn’t seem relevant to the question.)
Out of curiosity I wondered just how powerful a wizard might become and whether they could compel a fellow PC to commit murder or even suicide. Could the GM intervene?
Under the rules, yes and yes. Many—if not most—editions of D&D don’t make any firm distinction between player characters and non-player characters, so anything PCs can do to enemies, they can also do to each other, or have done to them by enemies. As for GM intervention, “Rule 0” of the game is that the DM can always intervene, including by changing the actual rules, in the name of improving the game—which is easily plausible for a case like this, if most of the group isn’t comfortable with this action, as seems likely to be true at most tables. However, absent an invocation of that Rule 0 authority, the GM may or may not really have a chance to intervene with this: dominate person, for example, calls for the DM to make a ruling on whether or not the particular kill order goes against the subject’s nature (in which case they could attempt to resist). For death urge, it’s automatically assumed that the subject is going to resist. But in both cases, if they fail to resist, then per the rules, the subject is going to perform those actions. Anything the DM does at that point to prevent it is changing the rules—which means they’re using Rule 0.
I make the distinction on whether or not the DM uses Rule 0 not because using Rule 0 is in any way illegitimate or inappropriate—it’s precisely the tool the DM is supposed to use to avoid uncomfortable-for-the-players situations like this. I do it merely to indicate, in a sense, the “default” expectation of the game is, which is that dominate person and death urge are things that can happen to people and can cause involuntary homicidal or suicidal behavior.
Finally, I would offer a commentary here: many, many tables, probably most, ban “player-vs-player” behavior, either explicitly, or implicitly as part of a “gentlemen’s contract.” It simply isn’t a part of what many people expect or are looking for when playing Dungeons & Dragons, nor is it what the game is really about (in other systems, that may well not be true). Furthermore, death urge is a fairly obscure, little-known power, and dominate person is something that a lot of tables are kind of uncomfortable with to begin with. So I would say that it would be fairly rare for this kind of thing to actually come up at most D&D tables. For instance, I don’t believe death urge has ever been used at a table I’ve been at, and while dominate person has been, it’s been quite rare and the usages have generally been far more mundane.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual studio 2017 problem with namespaces in F#
I wrote this in HelperFunctions.fs:
namespace Tutorial1.HelperFunctions
module Factorials =
let rec fact n =
match n with
| 0 -> 1
| 1 -> 1
| _ -> n * fact (n - 1)
And then this in Tutorial.fsx:
#load "HelperFunctions.fs"
open Tutorial1.HelperFunctions
module start =
let x = Factorials.fact 5
printfn "%d" x
Code compiles and returns 120 as expected BUT: VS throws FS0039 error: Factorials and Tutorial1 namespace, type or module not defined... Tried many other combinations of open, module etc but then codes does not even compile. What is the problem I am not seeing here?
A:
Okay, apparently the order of files in the vstudio matters, even if you include the file with #load. I had to shift the files upwards and it worked
| {
"pile_set_name": "StackExchange"
} |
Q:
Overriding a plugin's non-templated layout files?
I've been trying to figure out how to do this, but nothing seems to really work:
I want to override the results/pagination renderers from ZOOFilter which I know is in /plugins/system/zoofilter/zoofilter/layouts/{search,_pagination}.php, however it only appears that I can override templates?
The way that ZOOFilter is currently built is that it does not have any /tmpl directories in any of the plugin's locations within my installation, and obviously overwriting the plugin's code itself is more or less out of the question.
A:
To override zoofilter plugin: if you create your own system plugin with the same zoofilter class and it's loaded in order before zoofilter (you can even disable it), it should never be instantiated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Vue.js - I have dynamic buttons and I want that the color changes if I clicked one button
I have created buttons dynamically with v-for and now I want that the button which is clicked changes the colour and the other have all the same colour.
<template>
<div id="exam-screen" class="exam jumbotron">
<h1>{{ title }}</h1>
<div class="row">
<p class="col-md-6" v-bind:key="exam.id" v-for="exam in getExam">
<button
class="exam exam-btn btn btn-secondary btn-lg btn-block"
v-bind:id="
'exam-' + exam.id + '-' + exam.season + '-' + exam.year + '-btn'
"
>
<span>{{ exam['season_de'] }} {{ exam.year }} </span>
</button>
</p>
</div>
<div class="row">
<p class="col-md-8"></p>
<BaseButton>{{ startButton }}</BaseButton>
</div>
</div>
</template>
I know that I need a v-on:click directive, but I don't know how I change the color...
I already managed that in JavaScript, but I don't know how it works in Vue.js...
How I do it in JavaScript:
function selectAnswer(id) {
$(id).addClass("btn-primary");
$(id).removeClass("btn-secondary");
}
function deselectAnswer(id) {
$(id).addClass("btn-secondary");
$(id).removeClass("btn-primary");
}
I hope someone can help me...
A:
You can add & remove a class from the buttons using @click & :class like this:
new Vue({
el: "#myApp",
data: {
items: [{text: 'This is Button 1'},{text: 'This is Button 1'},{text: 'This is Button 3'}]
},
methods: {
toggleClass(index) {
this.items.forEach(item => item.active=false);
let item = this.items[index];
item.active = !item.active;
this.$set(this.items, index, item);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="myApp">
<div v-for="(item, index) in items" :key="index">
<button
:class="{ 'btn-primary': item.active, 'btn-secondary': !item.active}"
@click="toggleClass(index)"
class="btn btn-md btn-block m-3">
<span>{{ item.text }} </span>
</button>
</div>
</div>
Please note that @click is just a shorthand for v-on:click and :class is just a shorthand for v-bind:class. Also, we need to remove btn-secondary class that we set initially to the buttons otherwise btn-primary does not take effect on the button on click.
| {
"pile_set_name": "StackExchange"
} |
Q:
A simple way to apply a .gitignore file to all subfolders containing individual projects in the repository
I have a Git repository containing a lot of subfolders, each of which is an IntelliJ IDEA project.
I have found a JetBrains .gitignore which ignores files in an IntelliJ IDEA project and I want to apply it to all such projects in these subfolders.
Of course, I can make a copy for each project, or leave it in the root folder and edit the patterns in the .gitignore file to match files in subfolders.
However, I am wondering whether there is a simpler way to do this rather than making copies or editing a long .gitignore file.
A:
To ignore same set of files put that .gitignore file into root of your Git repository and prefix all lines that apply to all subdirectories with wildcard /*/. Same set of files will then be ignored in all subdirectories, with no need to update .gitignore when you add or remove subdirectory.
If there is a separator at the beginning or middle (or both) of the
pattern, then the pattern is relative to the directory level of the
particular .gitignore file itself.
So if you have following directory structure:
my_repo/
.gitignore
project1/
foo.txt
bar.txt
project2/
foo.txt
bar.txt
And want to ignore bar.txt in all project directories then your .gitignore will be:
/*/bar.txt
| {
"pile_set_name": "StackExchange"
} |
Q:
Single Email limit per execution using Apex Trigger
How many emails can be sent using trigger per execution?
A:
You can send as many as you need to, as long as you don't violate any of the governor limits. There is no specific limit to the number of emails that can be sent per execution. You are limited by a daily limit for non-user recipients, a per-transaction limit of 10 Messaging.sendEmail calls, and a maximum of 100 emails per Messaging.SingleMessage. It is conceptually possible to send 10,000+ emails in a single trigger execution if you design the code properly.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create popup window(modal dialog box) in HTML
On my web site a have a page where where user can ask questions.
Now I want to add Add Image button that must invoke kinda modal dialog box where user
needs to upload the picture from computer. Then window is closed and link to image is placed back to post.
I wanna do something similar like in SO https://stackoverflow.com/questions/ask - try pressing Image button and u'll see nice popup window coming up.
Please suggest what is best way to implement that stuff. I am asking for code snippet rather about technology
A:
Perhaps this could be of some help once you have started http://jqueryui.com/demos/dialog/#modal-form. Other wise you can use the DOM structure and create each and every element using appendChild and CreateElement and use css to give a good look.
A:
You will need client side scripting. I reccomend learning Javascript, then Jquery, then Jquery UI. If you know php it should not be too dificult to pickup the basics.
| {
"pile_set_name": "StackExchange"
} |
Q:
POM Strategy multiple Git repos and a Library Project
I have begun the daunting task of porting my Android projects to use Maven. I am having some trouble finding information on the best way to organize my pom files and dependencies. I have two Android apps that both use the same Android Library project that contains resources and network code. All three projects are source controlled with git and on github in separate repos. I put all the 3rd party library dependencies on the Library Project as well such as Action Bar Sherlock, View Pager Indicator, etc and exported them to the projects using the library.
I want to make it as easy as possible for other members of my team to build both Android apps with their dependencies. Should I go the route of cloning all three repos into the same directory and make the poms depend on the library assuming the same directory or would it be better to use one git repo with a parent pom couple with git sub modules and pom modules? I am worried this will get too confusing however.
A:
I would manage my projects and github repositories based on the natural correlation between the two Android projects.
Say if they are birds and birds season, it would be more reasonable to organize them as a multi-module projects and use a single github repository:
parent/
birds/
birds-season/
common-lib/
If they are birds and piggies, I would keep them separate in three github repositories:
birds/
piggies/
common-lib/
In addition, you should also consider your project release strategy, for example if you plan to use maven-release-plugin and want complete independent release life cycle (version number, scm tag and etc) for birds and brids season, it would be more efficient to separate them into different github repository (so that maven-release-plugin can manage auto version increment and scm tagging properly).
| {
"pile_set_name": "StackExchange"
} |
Q:
how can i generate Javascript and with PHP and put it into a .js file
I want to generate javascript dinamically with php, but i want the code to appear in a different file, and call it from my index file in order to have a better structured code.
Do you know a good way to do so?
A:
You can name a file anything you want as long as the file name ends with .php (or whatever extension is run by PHP).
In the past I have used a file name like script.js.php so that I know it's JavaScript built by PHP.
At the beginning of the file make sure you change the mime type. This has to be at the very beginning of the file with no white space before it.
<?php header("Content-type: text/javascript"); ?>
In your index file you would reference it like common JavaScript.
<script src="script.js.php"></script>
After your header you would have code like this:
var data = <?php echo json_encode($data); ?>;
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are the fitted values from this linear model not continuous?
I would like to estimate the length of individuals based on their age and sex, using OLS in R. To that purpose I built the following model: m1 <- lm(length ~ age + sex, data = data.frame). Next, I created some simple residual plots by running:
op <- par(mfrow = c(2,2))
plot(resid(m1) ~ fitted(m1))
plot(resid(m1) ~ data.frame$age)
plot(resid(m1) ~ data.frame$sex)
qqnorm(resid(m1)); qqline(resid(m1))
par(op)
yielding this plot:
Strange enough, the fitted values do not seem to have the range [165,180], but rather [165,170] ∪ [175,180] (top left plot). I do not understand why this is happening.
Below some sample data producing the plots above:
structure(list(length = c(173, 170, 172, 160, 162.5, 180, 179.5,
175, 168, 186.5, 163.5, 170.5, 160, 175.5, 186.5, 176.5, 168,
180.5, 179, 167, 183, 188.5, 176, 165, 170, 171, 176, 172, 187,
189, 180, 175.5, 162.5, 187, 164, 177, 170.5, 159.5, 161.5, 167,
178, 180.5, 168.5, 162, 171, 173, 171.5, 174.5, 177, 158, 175,
170, 183.5, 166, 174.5, 174, 176, 165, 163.5, 171.5, 161, 173,
165, 186, 171, 164.5, 182.5, 156.5, 156, 175, 168.5, 195, 164,
167.5, 168, 165.5, 172.5, 167, 175, 190, 170.5, 166, 155, 179.5,
175, 185, 174, 158.5, 172.5, 172.5, 173, 177, 161.5, 173.5, 159,
181, 176, 181.5, 167.5, 170.5), age = c(31.0965092402464, 67.7481177275838,
60.9062286105407, 54.776180698152, 57.8316221765914, 42.0287474332649,
47.1786447638604, 51.315537303217, 68.0876112251882, 32.3613963039014,
52.1259411362081, 50.7652292950034, 53.6947296372348, 64.6242299794661,
66.9733059548255, 66.8829568788501, 63.668720054757, 73.533196440794,
57.7659137577002, 43.7262149212868, 51.2416153319644, 30.7953456536619,
73.0403832991102, 52.2984257357974, 46.2614647501711, 35.7618069815195,
74.0670773442847, 35.6878850102669, 43.3894592744695, 65.0458590006845,
55.9671457905544, 71.2306639288159, 58.5653661875428, 40.0520191649555,
39.9698836413415, 44.0109514031485, 34.4722792607803, 47.5400410677618,
51.8822724161533, 46.9596167008898, 39.0143737166324, 49.0349075975359,
39.3812457221081, 48.2518822724162, 37.0376454483231, 30.425735797399,
31.5838466803559, 74.9459274469541, 46.3353867214237, 56.0602327173169,
54.4476386036961, 58.4120465434634, 47.64681724846, 39.047227926078,
45.2183436002738, 48.0246406570842, 41.5140314852841, 61.0732375085558,
52.2600958247776, 62.9760438056126, 70.715947980835, 70.5735797399042,
40.2436687200548, 35.0198494182067, 41.1772758384668, 57.2210814510609,
64.2710472279261, 59.6221765913758, 63.0088980150582, 48.5366187542779,
30.0369609856263, 48.8898015058179, 49.7741273100616, 54.7624914442163,
61.284052019165, 37.0102669404517, 58.4695414099932, 55.3483915126626,
39.4579055441478, 49.3333333333333, 37.9712525667351, 57.388090349076,
70.8199863107461, 37.0212183436003, 51.3675564681725, 48.3860369609856,
35.895961670089, 39.5208761122519, 37.4209445585216, 46.8692676249144,
65.3826146475017, 51.9425051334702, 33.2594113620808, 55.1156741957563,
33.9493497604381, 33.2895277207392, 42.0369609856263, 29.4976043805613,
54.9514031485284, 36.2327173169062), sex = structure(c(1L, 2L,
2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L,
1L, 2L), .Label = c("0", "1"), class = "factor")), row.names = c(1L,
2L, 3L, 4L, 5L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 17L,
18L, 19L, 20L, 21L, 22L, 23L, 25L, 26L, 27L, 28L, 29L, 30L, 32L,
33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L,
47L, 48L, 49L, 50L, 51L, 53L, 54L, 56L, 57L, 58L, 59L, 60L, 62L,
63L, 64L, 65L, 66L, 67L, 68L, 70L, 73L, 74L, 75L, 76L, 77L, 78L,
79L, 81L, 82L, 85L, 86L, 87L, 88L, 90L, 92L, 94L, 95L, 96L, 97L,
98L, 99L, 100L, 102L, 103L, 104L, 105L, 106L, 107L, 109L, 110L,
111L, 112L, 113L, 114L, 115L, 116L, 117L, 118L, 119L), class = "data.frame")
Does anyone know the flaw?
A:
Following @Roland's comment: the plot shows that the within-group variation of the predicted values is much smaller than the observed values.
library(ggplot2); theme_set(theme_bw())
lm1 <- lm(length~age+sex,data=dd)
pp <- expand.grid(age=30:75,sex=factor(0:1))
pp$length <- predict(lm1,newdata=pp)
ggplot(dd,aes(age,length,colour=sex))+
geom_point()+
geom_point(data=pp,shape=2)
| {
"pile_set_name": "StackExchange"
} |
Q:
Sum each row of a multidimensional array
I want to sum each row of a multidimensional array :
$number = array
(
array(0.3,0.67, 0.3),
array(0.3,0.5,1),
array(0.67,0.67,0.3),
array(1,0.3,0.5)
);
The result what i want is like this :
row1 = 1.27
row2 = 1.8
row3 = 1.64
row4 = 1.8
I already tried this code :
for($i = 0; $i < 4; $i++) {
for($j = 0; $j < 5; $j++) {
$sumresult[] = array_sum($number[$i][$j]);
}
}
But it appear an error like this :
Warning: array_sum() expects parameter 1 to be array, double given in xxxx
A:
array_sum needs array not values. Do like this:
for($i = 0; $i < 4; $i++) {
$sumresult[] = array_sum($number[$i]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How find this function $f(x)$
Let $f:\mathbb{R}\to\mathbb{R}$ be continuous such that $\dfrac{f(x)}{x}=f'\left(\dfrac{x}{2}\right)$. Find $f(x)$.
(2):if $f(x)$ on $x\in[a,b] $ be continuous,find all $f(x)$?
I think this is an ODE.
A:
Let $\alpha_0 = 1, \alpha_1 = 2$ and let $\alpha_2, \alpha_3, \ldots$ be the complete set of roots in the complex plane of the equation:
$$\alpha = 2^{\alpha-1} \quad\text{ subject to constraint }\quad \Re{\alpha} > 1, \Im{\alpha} > 0$$
For $k \ge 2$, write $\alpha_k$ as $\beta_k + \gamma_k i$ where $\beta_k, \gamma_k \in \mathbb{R}$.
For any set of real constants $A_0, A_1, \ldots$ and $\delta_2, \delta_3, \ldots \in \mathbb{R}$. It is easy to check the function defined by:
$$\begin{align}f(x)
&= A_0 x + A_1 x^2 + \sum_{k=2}^{\infty} \Re{\left( A_k e^{i\delta_k} x^{\alpha_k}\right)}\\
&= A_0 x + A_1 x^2 + \sum_{k=2}^{\infty} A_k x^{\beta_k} \cos(\gamma_k\log(x) + \delta_k)
\end{align}$$
is a solution of the functional equation over $[0,\infty)$ provided this series and the series associated with its derivative converge.
The condition $\Re{\alpha_k} > 1$ for $k \ge 2$ ensure $f(x)$ falls off to zero fast enough so that $f'(0+)$ is defined and equal to $A_0$.
Over $(-\infty,0]$, we can define another function $\tilde{f}(x)$ in a similar manner:
$$\begin{align}\tilde{f}(x)
&= \tilde{A}_0 x + \tilde{A}_1 x^2 + \sum_{k=2}^{\infty} \Re{\left( \tilde{A}_k e^{i\tilde{\delta}_k} |x|^{\alpha_k}\right)}\\
&= \tilde{A}_0 x + \tilde{A}_1 x^2 + \sum_{k=2}^{\infty} \tilde{A}_k |x|^{\beta_k} \cos(\gamma_k\log|x| + \tilde{\delta}_k)
\end{align}$$
Once again, this is a solution for the functional equation over $(-\infty,0]$ provided
this series and the series associated with its derivative converge. Furthermore,
$f'(0-)$ exists and equal to $\tilde{A}_0$.
If $A_0 = \tilde{A}_0$, we can paste this two solution together to construct a $C^{1}$ solution of the functional equation over whole $\mathbb{R}$.
For an example, $\alpha_2 \sim 4.545364930374021 + 10.75397517526888 i$ implies
$$f(x) \sim |x|^{4.545364930374021} \cos(10.75397517526888 \log|x|)$$
will be a non-trivial $C^1$ solution for the functional equation.
| {
"pile_set_name": "StackExchange"
} |
Q:
Поиск по текстовому файлу C#
Всем добрый день. Такая проблема, нужно найти в текстовом файле определенное слово, например "имя" и записать в переменную следующее, после найденного, слово.
Например: Имя Петя- нашло имя, в переменную записало Петя. Понятно, что ориентироваться в отделении слов нужно по пробелам, но как это реализовать не знаю. В программировании новичок.
A:
Спасибо всем за ответы, взял ото всюду понемногу:
private void SearchInTxt(string fileLocation, string keyWord)
{
string str = File.ReadAllText(fileLocation);
var kek = str.Split(new Char[] { ' ', '.', ',', ':', '\t' }).ToList();
foreach (string s in kek)
{
if (s.Trim() != "" && Regex.IsMatch(s, keyWord))
{
textBox1.Text = kek[kek.IndexOf(keyWord) + 1] + " " + kek[kek.IndexOf(keyWord) + 3];
break;
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Create a dictionary that uses the same pairs from another dictionary, but keys are translated
I'm trying to create a dictionary "aaComp" that has the same keys and values as another dictionary "codonComp", then translate the keys of aaComp using another dictionary "rnaCodonTable". I need the same pairings of values and keys, but the keys need to be under a different name. I attempted to write this myself, but ended up with two identical dictionaries:
aaComp = {key.translate(self.rnaCodonTable):value for key, value in codonComp.items()}
The two original dictionaries are as follows:
rnaCodonTable = {
# RNA codon table
# U
'UUU': 'F', 'UCU': 'S', 'UAU': 'Y', 'UGU': 'C', # UxU
'UUC': 'F', 'UCC': 'S', 'UAC': 'Y', 'UGC': 'C', # UxC
'UUA': 'L', 'UCA': 'S', 'UAA': 'STOP', 'UGA': 'STOP', # UxA
'UUG': 'L', 'UCG': 'S', 'UAG': 'STOP', 'UGG': 'W', # UxG
# C
'CUU': 'L', 'CCU': 'P', 'CAU': 'H', 'CGU': 'R', # CxU
'CUC': 'L', 'CCC': 'P', 'CAC': 'H', 'CGC': 'R', # CxC
'CUA': 'L', 'CCA': 'P', 'CAA': 'Q', 'CGA': 'R', # CxA
'CUG': 'L', 'CCG': 'P', 'CAG': 'Q', 'CGG': 'R', # CxG
# A
'AUU': 'I', 'ACU': 'T', 'AAU': 'N', 'AGU': 'S', # AxU
'AUC': 'I', 'ACC': 'T', 'AAC': 'N', 'AGC': 'S', # AxC
'AUA': 'I', 'ACA': 'T', 'AAA': 'K', 'AGA': 'R', # AxA
'AUG': 'M', 'ACG': 'T', 'AAG': 'K', 'AGG': 'R', # AxG
# G
'GUU': 'V', 'GCU': 'A', 'GAU': 'D', 'GGU': 'G', # GxU
'GUC': 'V', 'GCC': 'A', 'GAC': 'D', 'GGC': 'G', # GxC
'GUA': 'V', 'GCA': 'A', 'GAA': 'E', 'GGA': 'G', # GxA
'GUG': 'V', 'GCG': 'A', 'GAG': 'E', 'GGG': 'G' # GxG
}
codonComp = {'UUU': 0, 'UCU': 0, 'UAU': 0, 'UGU': 0, 'UUC': 2, 'UCC': 0, 'UAC': 2, 'UGC': 1, 'UUA': 1, 'UCA': 0, 'UAA': 1, 'UGA': 0, 'UUG': 0, 'UCG': 0, 'UAG': 0, 'UGG': 2, 'CUU': 1, 'CCU': 0, 'CAU': 0, 'CGU': 0, 'CUC': 0, 'CCC': 2, 'CAC': 0, 'CGC': 1, 'CUA': 1, 'CCA': 0, 'CAA': 2, 'CGA': 1, 'CUG': 4, 'CCG': 1, 'CAG': 6, 'CGG': 1, 'AUU': 0, 'ACU': 0, 'AAU': 0, 'AGU': 0, 'AUC': 2, 'ACC': 0, 'AAC': 2, 'AGC': 1, 'AUA': 2, 'ACA': 1, 'AAA': 2, 'AGA': 0, 'AUG': 5, 'ACG': 0, 'AAG': 2, 'AGG': 3, 'GUU': 0, 'GCU': 0, 'GAU': 0, 'GGU': 0, 'GUC': 2, 'GCC': 4, 'GAC': 5, 'GGC': 2, 'GUA': 1, 'GCA': 1, 'GAA': 0, 'GGA': 0, 'GUG': 0, 'GCG': 4, 'GAG': 3, 'GGG': 0}
Can this be written on one line, or do I have to write it as two lines? After seeing one comment, I realize what I'm asking for is more complicated than I thought. Typing the full desired result would be difficult, but there are several keys in the rnaCodonTable that match to the letter F. In codonComp, there is a total of 2 (0+2) codons (the 3 letter items) that match the keys in rnaCodonTable for F. aaComp would show this as 'F':2 .
A:
Because duplicates are possible, a for loop with collections.defaultdict is best:
from collections import defaultdict
rnaCodonTable = {'UUU': 'F', 'UCU': 'S', 'UAU': 'Y', 'UGU': 'C', 'UUC': 'F', 'UCC': 'S', 'UAC': 'Y', 'UGC': 'C', 'UUA': 'L', 'UCA': 'S', 'UAA': 'STOP', 'UGA': 'STOP', 'UUG': 'L', 'UCG': 'S', 'UAG': 'STOP', 'UGG': 'W', 'CUU': 'L', 'CCU': 'P', 'CAU': 'H', 'CGU': 'R', 'CUC': 'L', 'CCC': 'P', 'CAC': 'H', 'CGC': 'R', 'CUA': 'L', 'CCA': 'P', 'CAA': 'Q', 'CGA': 'R', 'CUG': 'L', 'CCG': 'P', 'CAG': 'Q', 'CGG': 'R', 'AUU': 'I', 'ACU': 'T', 'AAU': 'N', 'AGU': 'S', 'AUC': 'I', 'ACC': 'T', 'AAC': 'N', 'AGC': 'S', 'AUA': 'I', 'ACA': 'T', 'AAA': 'K', 'AGA': 'R', 'AUG': 'M', 'ACG': 'T', 'AAG': 'K', 'AGG': 'R', 'GUU': 'V', 'GCU': 'A', 'GAU': 'D', 'GGU': 'G', 'GUC': 'V', 'GCC': 'A', 'GAC': 'D', 'GGC': 'G', 'GUA': 'V', 'GCA': 'A', 'GAA': 'E', 'GGA': 'G', 'GUG': 'V', 'GCG': 'A', 'GAG': 'E', 'GGG': 'G'}
codonComp = {'UUU': 0, 'UCU': 0, 'UAU': 0, 'UGU': 0, 'UUC': 2, 'UCC': 0, 'UAC': 2, 'UGC': 1, 'UUA': 1, 'UCA': 0, 'UAA': 1, 'UGA': 0, 'UUG': 0, 'UCG': 0, 'UAG': 0, 'UGG': 2, 'CUU': 1, 'CCU': 0, 'CAU': 0, 'CGU': 0, 'CUC': 0, 'CCC': 2, 'CAC': 0, 'CGC': 1, 'CUA': 1, 'CCA': 0, 'CAA': 2, 'CGA': 1, 'CUG': 4, 'CCG': 1, 'CAG': 6, 'CGG': 1, 'AUU': 0, 'ACU': 0, 'AAU': 0, 'AGU': 0, 'AUC': 2, 'ACC': 0, 'AAC': 2, 'AGC': 1, 'AUA': 2, 'ACA': 1, 'AAA': 2, 'AGA': 0, 'AUG': 5, 'ACG': 0, 'AAG': 2, 'AGG': 3, 'GUU': 0, 'GCU': 0, 'GAU': 0, 'GGU': 0, 'GUC': 2, 'GCC': 4, 'GAC': 5, 'GGC': 2, 'GUA': 1, 'GCA': 1, 'GAA': 0, 'GGA': 0, 'GUG': 0, 'GCG': 4, 'GAG': 3, 'GGG': 0}
aaComp = defaultdict(int)
for k, v in codonComp.items():
aaComp[rnaCodonTable[k]] += v
aaComp will be
{'F': 2, 'S': 1, 'Y': 2, 'C': 1, 'L': 7, 'STOP': 1, 'W': 2, 'P': 3, 'H': 0, 'R': 6, 'Q': 8, 'I': 4, 'T': 1, 'N': 2, 'K': 4, 'M': 5, 'V': 3, 'A': 9, 'D': 5, 'G': 2, 'E': 3}
| {
"pile_set_name": "StackExchange"
} |
Q:
Set name of all empty field in view
I have a date/time field name DeliveryDate and I have a view that will list all Delivery date. Some of document will have empty delivery date. Below here the example of the view.
Right now, the view show "(Not Categorized)". How can I change it to another name such as "Old Record". Any help will be appreciated. Thanks!
A:
The easiest thing to do is change the formula for that view column to e.g.:
@if(DeliveryDate=“”;”Old Record”;DeliveryDate)
Of course you might prefer to remove those records from the view all together. In that case just add the following to the Select formula for the view:
& !DeliveryDate=“”
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I export test cases in HP ALM to be re-imported into another ALM project?
to cut a long story short I've been put on a new project which has some legacy test cases, these test cases exist in ALM. I would like to export certain sections of this test plan for use in the new project, which again exists in ALM. Both of these projects exist on the same server, but on different domains.
Is there a simple way I can export the test cases I want from one ALM project to another? I need the tests, their steps, any attachments etc. I basically just want exactly what exists in the test plan section, to be ported across to a different project.
I've already looked at similar questions, exporting to excel without test steps, attachments etc is a no go. Exporting to a report is no go because I need to import the data.
Has anyone done this before? I'm using the latest ALM.
Thank you
A:
Hilariously the answer to this is copy and paste! You can use Tools -> Change Project to navigate between projects. Simply right click what you wish to migrate, copy, change project and paste where you desire!
You will have to decide what to do with related entities when copying across.
| {
"pile_set_name": "StackExchange"
} |
Q:
What versions of Sync Framework are compatible with Windows Mobile 6.5?
We have an app developed for a Windows Mobile 6.5 device that uses Microsoft Sync Framework 1.0. What other framework versions are compatible with Mobile 6.5?
A:
1.0 is the only supported version if you're running the older SqlCeClientSyncSyncProvider. Your only other option on Sync Fx is the Sync Framework Toolkit. other than that, have a look at Zumero.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java LDAP returning always a single value instead of a list
I want to query my ldap to give me all users where sn contains a specific value (maier). However I always get a single result.
public LdapContext getLdapContext(){
LdapContext ctx = null;
try{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.url:389");
ctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
}catch(NamingException nex){
System.out.println("LDAP Connection: FAILED");
nex.printStackTrace();
}
return ctx;
}
private User getUserBasicAttributes(String username, LdapContext ctx) {
User user=null;
try {
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { "distinguishedName",
"sn",
"givenname",
"mail",
"telephonenumber"};
constraints.setReturningAttributes(attrIDs);
constraints.setCountLimit(200);
NamingEnumeration answer = ctx.search("DC=myDc,DC=com", "sn=*maier*", constraints);
if (answer.hasMore()) {
Attributes attrs = ((SearchResult) answer.next()).getAttributes();
System.out.println("distinguishedName "+ attrs.get("distinguishedName"));
System.out.println("givenname "+ attrs.get("givenname"));
System.out.println("sn "+ attrs.get("sn"));
System.out.println("mail "+ attrs.get("mail"));
System.out.println("telephonenumber "+ attrs.get("telephonenumber"));
}else{
throw new Exception("Invalid User");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return user;
}
Did I do anything wrong?
A:
You're not looping, so of course you're only getting one result. Change if (answer.hasMore()) to while (answer.hasMore()).
| {
"pile_set_name": "StackExchange"
} |
Q:
css3: change font size ratio
i'm just trying out the new font-face feature in css3 for implementing own ttf/otf fonts.
my question: is it possible to change the default font size ratio?
example: i'm using tahoma with 9pt as default font and want to implement ownfont.ttf - the problem: if the browser supports @font-face, the ownfont.ttf with 9pt is much smaller than tahoma with 9pt. is there a way to increase its size ratio?
A:
Have a look at the css3 property font-size-adjust.
| {
"pile_set_name": "StackExchange"
} |
Q:
min value from two columns (Oracle SQL)
Searching for a while now, but haven't found a suitable answer to my problem.
Explanation:
ID | Year | Factor1 | Number1 | Number2
1 | 2010 | 213 | 1 | 1
2 | 2010 | 213 | 1 | 2
3 | 2010 | 214 | 2 | 1
4 | 2010 | 214 | 2 | 2
6 | 2010 | 210 | 3 | 1
7 | 2010 | 210 | 3 | 2
8 | 2011 | 250 | 3 | 5
5 | 2012 | 214 | 2 | 4
EDIT:
Forgot Something, corrected that in the above table.
I need 2 combinations: year and factor1 only once, then min(number1) and last min(number2).
For example above I would need IDs 1,3,5,6,8 (sorry they are mixed for better readability of the other values).
Anyone any idea how to realize that?
A:
Got the code now from another forum, works fine for me:
SELECT
tab.*
FROM
t33 tab
INNER JOIN (
SELECT
m1.y,
m1.factor1,
m1.min_1,
m2.min_2
FROM
(
SELECT
y,
factor1,
MIN(number1) AS min_1
FROM
t33 tab
GROUP BY
y,
factor1
) m1
INNER JOIN (
SELECT
y,
factor1,
number1,
MIN(number2) AS min_2
FROM
t33
GROUP BY
y,
factor1,
number1
) m2
ON m1.y = m2.y
AND m1.factor1 = m2.factor1
AND m1.min_1 = m2.number1
) sel
ON tab.y = sel.y
AND tab.factor1 = sel.factor1
AND tab.number1 = sel.min_1
AND tab.number2 = sel.min_2
| {
"pile_set_name": "StackExchange"
} |
Q:
Does TCP congestion affect other ports?
I heard when TCP packet gets lost, everything gets stuck because of congestion until lost packet eventually gets received. e.g. server sends these packets on the same port:
1(UDP), 2(UDP), 3(TCP), 4(UDP), 5(UDP), 6(UDP)
so if packet 3 gets lost, client won't be able to receive 4, 5, 6, until packet 3 gets received, right?
If application uses two ports, one for TCP and other one for UDP, would TCP congestion affect UDP port performance? I mean would UDP packets get stuck?
A:
TCP congestion should only affect the current connection (socket).
In short, for each connection there is a TCP sliding window which is used to assemble the packets. If one packet gets lost, other packets on te same connection will be received and placed in the window, unless the the window is full.
So this should not affect other connections.
See TCP window scale option, Congestion window and TCP Receive Window Auto-Tuning.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to compile distributable Fortran binaries on Mac OS X Mountain Lion?
Since Apple have stopped distributing gfortran with Xcode, how should I compile architecture independent Fortran code? I have Mac OS X Mountain Lion (10.8), and XCode 4.4 installed, with the Command Line Tools package installed.
Apple's Native Compilers
As far as I can tell, the Xcode C / C++ / ObjC compilers use a fork of the GNU compiler collection, with llvm as a backend; the latter I figure enables compiling and optimising "universal" binaries, for both Intel and PPC architectures.
3rd party binary Fortran compilers
HPC
I've only found a single website that distributes a binary version of gfortran specifically for Mountain Lion: the HPC website. However, I failed to get this to compile SciPy, and later saw in SciPy's README that it is "known to generate buggy scipy binaries".
CRAN/R
SciPy's recommended (free) Fortran compiler is the one on CRAN's R server, but this has not been updated for Mountain Lion yet. They provide instructions and a script for Building a Universal Compiler, but, again, this hasn't been updated for Mountain Lion yet..
G95
The G95 project hasn't had an update since 2010, so I didn't try it.. Anyone tried this on Mountain Lion?
MacPorts
I guess this will be the easiest way to get gfortran installed, but port search gfortran comes up with nothing, and I've not had any joy with MacPorts in the past (no offence to MacPorts; it's looks like a very active project, but I've been spoilt with Linux package managers, my favourite manager being aptitude) so on Mac OS X I've compiled software and libraries from source code in the past. Never been a problem 'til now...
Building a Fortran compiler
Having dug around on the internet a lot in the last couple of days, I've found other Fortran compilers, but I've failed to get any to cross-compile universal binaries, or to compile SciPy.
GCC - The Gnu Compiler Collection
I compiled the entire GCC collection (v4.6.3), including autotools, automake, libtool and m4 - like the GCC wiki and this blog describe - but the resulting compilers didn't compile universal binaries, probably because LLVM wasn't used as a backend.
DragonEgg
DragonEgg is a "gcc plugin that replaces GCC's optimisers and code-generators ... with LLVM". This looks interesting, but I don't know how I could use it to compile 'llvm-gfortran-4.x'. Can this be done?
Compatibility
Libraries
The compiler that comes with Xcode is (a fork of?) GCC v4.2. But GCC's current release and development branches are versions 4.6 and 4.7, respectively. Apparently, a GNU license change, or something, stopped Apple from updating to more modern versions of GCC. So, if I was to build dynamic libraries made with GCC's gfortran v4.6, could they then be linked with C code compiled by Xcode's native compiler? At a minimum, I figure resulting Mach-O binaries need both x86_64 and i386 code paths. Do GCC provide backwards compatibility with Apple's (forks of?) GCC? I know gfortran has the -ff2c flag, but is this stable across versions?
Compile flags
The GCC Fortran compiler I built from source didn't support the use of the -arch compile flag. I had been including the flags -arch x86_64 -arch i386 in both CFLAGS and FFLAGS environment variables on earlier OSX versions (Snow Leopard to Lion). Python's distutils, and probably other OSX compilers, expect these flags to work, when configured to build apps or frameworks, using Xcode's universal SDK.
In case you're wondering what compile flags I use, I've uploaded the script I use to pastebin, which I source before I compile anything, using: source ~/.bash_devenv.
The Ideal OSX Fortran Compiler
Create ppc and intel (32 and 64bit) universal binaries, specified by using the -arch flags.
Makes binaries compatible with XCode's linker.
Compiles SciPy, giving no errors (compatible with numpy's distutils and f2py).
I don't use Xcode so much, but integration with it would surely benefit other users. Even Intel are still having problems integrating ifort into Xcode 4.4, so this is not something I expect to work..
If you read all the above, then thank you! You can probably tell that I'm not averse to building my own Fortran compiler from source, but is it even possible? Have I missed something? A configure flag maybe? And if such a compiler is not available yet, then why not?!
(Update:) Apple's GCC
Apple provide the source code for their patched version of GCC, at opensource.apple.com. This actually includes the source code for gfortran, but what do you know - it doesn't compile (easily). I'm in the process of writing a build script to get this to work. Unfortunately, I've had to apply a couple of patches, and learn about "the Apple way" of building GNU software. This is the way to go I think. Any reasons why it shouldn't be? I'll update with an answer if I get it to work...
A:
I managed to compile after installing gfortran from http://r.research.att.com/tools/gcc-42-5666.3-darwin11.pkg, as explained here. I had to try to open the package a couple of times, though. First time it said that only apps from App Store can be installed. After installing gfortran, python setup.py build and python setup.py install worked fine. The unit tests of scipy though give a fairly high number of fails, not sure it's normal.
Ran 5481 tests in 82.079s
FAILED (KNOWNFAIL=13, SKIP=42, errors=11, failures=72)
<nose.result.TextTestResult run=5481 errors=11 failures=72>
A:
In case you didn't already notice this: In newer versions of Xcode you have to explicitly install command line tools in the following way:
Preferences -> Downloads -> Components
And then click the "install" button for command line tools. This includes gfortran:
> gfortran -v
Using built-in specs.
Target: i686-apple-darwin10
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5664)
Admittedly, this does not solve all of my fortran needs (in some cases "./configure" scripts will complain that they cannot "compile a simple fotran program").
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I generate a keyboard macro in my Emacs init file?
I am defining a particular keyboard macro quite often, so I thought that it might be handy if it was automatically available every time I load Emacs.
How can I do this?
A:
How about the save keyboard macros section of the manual?
C-x C-k n
Give a command name (for the duration of the Emacs session) to the most recently defined keyboard macro (kmacro-name-last-macro).
C-x C-k b
Bind the most recently defined keyboard macro to a key sequence (for the duration of the session) (kmacro-bind-to-key).
M-x insert-kbd-macro
Insert in the buffer a keyboard macro's definition, as Lisp code.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to display data from firestore using react native
I'm trying to display data from firestore on the home page but i dont seem to get it working. I want to show all the data in the collection. the collection includes name, id, location etc...
import Firebase from "./lib/firebase";
import { useEffect, useState } from "react";
import { SnapshotViewIOS } from "react-native";
// export async function getRestaurants(restaurantsRetrieved) {
// var restaurantList = [];
// var snapshot = await firebase.firestore().collection("Restaurants").get();
// snapshot.forEach((doc) => {
// restaurantList.push(doc.data());
// });
// restauantsRetrieved(restaurantList);
// }
export default () => {
const [restaurantsList, setRestaurantsList] = useState([]); //Initialise restaurant list with setter
const [errorMessage, setErrorMessage] = useState("");
const getRestaurants = async () => {
try {
const list = [];
var snapshot = await Firebase.firestore().collection("Restaurants").get();
console.log("Here");
snapshot.forEach((doc) => {
list.push(doc.data());
});
setRestaurantsList(list);
} catch (e) {
setErrorMessage(
"There's nae bleeding restaurants, I told you to upload them!"
);
}
};
//Call when component is rendered
useEffect(() => {
getRestaurants();
}, []);
return (
<View style={tailwind('py-10 px-5')}>
<Text style={tailwind('text-4xl font-bold')}>
{restaurantsList}
</Text>
};
A:
The State is not updating becuase it just taking the reference of list. So you need to update the like code below
.....
setRestaurantsList([...list]);
......
| {
"pile_set_name": "StackExchange"
} |
Q:
Too many arguments Q
I am trying to write a measure that will allow me to filter on statuscode and Datesbetween. With the filter, plus the two conditions, I have too many arguments for the FILTER function. What syntax can I use to get the desired result?
Won-Existing =
SUMX (
FILTER ( _enquiries,
_enquiries[_GUID] = _2018_Budget[_GUID] &&
_enquiries[statuscode] = 866120005 &&
DATESBETWEEN(_enquiries[Date Contract Awarded],DATE(2018,8,1),DATE(2018,8,31)
),
_enquiries[Amount (Enq)]
))
A:
Looks like some parentheses mismatching to me. Try this:
Won-Existing =
SUMX (
FILTER ( _enquiries,
_enquiries[_GUID] = _2018_Budget[_GUID] &&
_enquiries[statuscode] = 866120005 &&
DATESBETWEEN(_enquiries[Date Contract Awarded], DATE(2018,8,1), DATE(2018,8,31))
),
_enquiries[Amount (Enq)]
)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why adjustbox needs a tweak of raise=-0.3ex with enumitem?
The MWE below yields the desired results. But, is there a better way to get this alignment instead of the raise=-0.3ex:
Without the raise=-0.3ex, the item number is not aligned with the text:
Code:
\documentclass{article}
\usepackage{enumitem}
\usepackage[export]{adjustbox}
\fboxsep=0pt
\newadjustboxenv{MyAdjustbox}{valign=t, raise=-0.3ex}%
\begin{document}
\begin{enumerate}
\item
\begin{MyAdjustbox}
\fbox{%
\begin{minipage}[t]{\linewidth}
Some text that takes up several lines, so we need to adjust the
item number to align with the top baseline.
\end{minipage}%
}%
\end{MyAdjustbox}%
\end{enumerate}%
\end{document}
A:
The option valign=t of adjustbox doesn't retrieve the inner top baseline as the [t] option of minipage or tabular do. adjustbox calculates a height which takes the current text font size into account: by default valign=t sets the height to the height of the current \strutbox.
This means that depending on the text on the first line it can be too high or too low relative to the number. You can "repair" the first case with the code from Mico but for the second case there is no easy fix.
In my opinion adjustbox is the wrong environment for such boxes. It is useful for aligning pictures which have no intrinsic baseline, but not for text boxes.
\documentclass{article}
\usepackage{enumitem}
\usepackage[export]{adjustbox}
\newadjustboxenv{MyAdjustbox}{valign=t}
\begin{document}
\begin{enumerate}
\item
\begin{MyAdjustbox}%too high
\begin{minipage}[t]{\linewidth}
aaaa
\end{minipage}%
\end{MyAdjustbox}
\item \begin{MyAdjustbox}%too low
\begin{minipage}[t]{\linewidth}
$\int\limits_1^3 f(x) $
\end{minipage}%
\end{MyAdjustbox}
\end{enumerate}
\end{document}
A:
I think that there are two separate issues. The main one arises from the use of a minipage environment.
The first row in the material inside the fbox has no material taller than uppercase letters. Because that material is encased in a minipage, the unused vertical whitespace needed for symbols such as ( and ) is removed. In contrast, the enumeration symbol is not encased in a minipage, and hence its baseline is chosen without removing the implicit \strut. If one inserts a \strut in the first line of the \fbox, most of the need for vertical adjustment is removed.
To fully align the baselines of the "1." particle before the \fbox and the material inside the minipage, one also needs to make an adjustment (pun intended) for the thickness of the rule (given by the parameter \fboxrule; default value: \arrayrulewidth, usually 0.4pt) that surrounds the fbox. And, since the value of \fboxsep is nonzero in general, I suggest using the following code
\newadjustboxenv{MyAdjustbox}{valign=t, raise=\fboxrule+\fboxsep}
in lieu of
\newadjustboxenv{MyAdjustbox}{valign=t, raise=-0.3ex}
With these two adjustments (yet another pun -- ouch!), I get this screenshot:
\documentclass{article}
\usepackage{enumitem}
\usepackage[export]{adjustbox}
\fboxsep=0pt
\newadjustboxenv{MyAdjustbox}{valign=t, raise=\fboxrule+\fboxsep}
\begin{document}
\begin{enumerate}
\item
\begin{MyAdjustbox}
\fbox{%
\begin{minipage}{\linewidth}\strut%
Some text that takes up several lines, so we need
to adjust the item number to align with the top
baseline.
\end{minipage}%
}%
\end{MyAdjustbox}%
\end{enumerate}%
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Don't include the brief description in the detailed description when using Doxygen
I am using Doxygen with C++ and with JAVADOC_AUTOBRIEF set to YES. Is it possible to not include the brief description in the detailed description? Is there a way to configure this in the Doxyfile maybe?
A:
There's an option named REPEAT_BRIEF, take a look at it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex extract string after the second "." dot character at the end of a string
I want to extract the second "file extension" of a file name so:
/Users/path/my-path/super.lol.wtf/main.config.js
What I need is:
.config.js
What would be totally awesome if I got an array with 2 strings in return:
var output = ['main', '.config.js'];
What I have tried:
^(\d+\.\d+\.)
But that ain't working.
Thanks
A:
You could use the following:
([^\/.\s]+)(\.[^\/\s]+)$
Example Here
([^\/.\s]+) - Capturing group excluding the characters / and . literally as well as any white space character(s) one or more times.
(\.[^\/\s]+) - Similar to the expression above; capturing group starting with the . character literally; excluding the characters / and . literally as well as any white space character(s) one or more times.
$ - End of a line
Alternatively, you could also use the following:
(?:.*\/|^)([^\/.\s]+)(\.[^\/\s]+)$
Example Here
(?:.*\/|^) - Same as the expression above, except this will narrow the match down to reduce the number of steps. It's a non-capturing group that will either match the beginning of the line or at the / character.
The first expression is shorter, but the second one has better performance.
Both expressions would match the following:
['main', '.config.js']
In each of the following:
/Users/path/my-path/some.other.ext/main.config.js
some.other.ext/main.config.js
main.config.js
A:
Here is what you need:
(?:\/?(?:.*?\/)*)([^.]+)*\.([^.]+\.[^.]+)$
(?: means detect and ignore,
[^.]+ means anything except .
.*? means pass until last /
Check Here
| {
"pile_set_name": "StackExchange"
} |
Q:
Firebase not initializing before it gets called in other files
Im trying to use firebase in a vue project. I have other js files such as auth.js that use firebase, but im initializing it in my main.js(which should be the entry point for webpack) but it seems like the other files are getting called first? Im using vue-cli with the webpack template.
The error I am getting is
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
Here is the first part of my main.js
// main.js
import Vue from 'vue';
import firebase from 'firebase';
// import firebaseui from 'firebaseui';
import VueFire from 'vuefire';
import App from './App';
import router from './router';
import database from './js/database';
Vue.use(VueFire);
const config = {
apiKey: '***',
authDomain: '***',
databaseURL: '***',
storageBucket: '***',
messagingSenderId: '***',
};
firebase.initializeApp(config);
database.init();
This is my first time really using firebase, any ideas what going on?
A:
This is how i did it
import Vue from 'vue'
import VueResource from 'vue-resource'
import VueRouter from 'vue-router'
import App from './App.vue'
import { routes } from './routes'
import * as firebase from 'firebase'
import { store } from './store/store'
Vue.use(VueResource);
Vue.use(VueRouter);
const router = new VueRouter({
routes,
});
let config = {
apiKey: "XXXX",
authDomain: "XXXXXX",
databaseURL: "xXxxxxxx",
storageBucket: "XXXXXX",
messagingSenderId: "XXXXXX"
};
Vue.prototype.$firebase = firebase.initializeApp(config);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
I did not use vue fire
But i can use firebase functionality from alll over my app by calling
this.$firebase.auth()
this.$firebase.database()
this.$firebase.storage()
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run a GPU instance using Amazon EC2 Panel?
I would like to run a Ubuntu GPU instance from the AWS EC2 control panel, but the combo box does not have the g2.2xlarge option to select. It looks like GPU instances are available only for Amazon AMI. When I choose Ubuntu, it does not list GPU. Is there any way to make it work?
A:
In order to use the g2.2xlarge instance type, you need to first select an AMI that is built with HVM (hardware assisted virtualization).
At the time of this writing, the official HVM AMIs for Ubuntu are not available in all regions, but are at least in us-east-1, us-west-2, eu-west-1.
You can type "HVM" as one of your keywords into the Ubuntu AMI finder.
I also provide an updated list of Ubuntu AMIs on Alestic.com. Simply select a region in the pulldown on the top right, then click on the orange [>] arrow next to the AMI you want to run in your account.
| {
"pile_set_name": "StackExchange"
} |
Q:
What thickness/depth of water would be required to provide radiation shielding in Earth orbit?
If using water or ice as a radiation shield how thick/deep would it need to be? Would it make a difference if the water was frozen (water ice being less dense then liquid)?
Edit
I would like to know how much shielding would be required for an indefinite stay. Preferably at Terrestrial limits per Code of Federal Regulations (29 CFR 1910.96), but at least at levels per National Council on Radiation Protection and Measurements (NCRP) presented in its Report 98 A beginning place for research is the Spaceflight Radiation Health Program at JSC A listing of all different types of radiation NASA "What is space radiation?"
A:
We know from the nuclear power industry that spent fuel storage pools are pretty safe places to be around, radiation-wise. They're actually safe to swim in, to a point, because they're serviced routinely by human divers. They just can't get too close to the spent fuel.
We use these pools for short-term storage because water is a really good radiation shield. How good? Well, according to a report on the topic prepared for the DoE back in 1977, a layer of water 7 centimeters thick reduces the ionizing radiation (rays and particles) transmitted through it by half (the remainder is captured or moderated to non-ionizing energy levels, mainly heat). Freshly discharged nuclear fuel puts out about 100,000 R/hour as measured from one foot away in air (at that rate, certain death is about 5 minutes' exposure and you'd fall into a coma in about 10). Background ionizing radiation levels on Earth's surface are about .000001 R/hour (1 mSv/hr), while a "safe dose" to live with long-term is about .0004 R/hr. A halving represents about .3 of a power of 10, so in rough terms, to reduce a fresh fuel rod's radioactivity to safe levels, you would need about 2 meters (8/0.3 * 7 / 100), and through more than 2.5m the radioactivity of the fuel rods is indistinguishable from background radiation. In fact, according to the link from the comment, diving about 6 feet down would expose you to less radiation than at the surface of the pool.
According to Wikipedia, the upper estimate for a dose equivalent received by unshielded astronauts operating outside Earth's magnetic field (such as a mission to Mars) is about 90,000 R/yr or about 10 R/hour. If we assume the energy levels are comparable, reducing that to lower than Earth background radiation would only require a layer of water around 1 meter thick.
However, let's do some more math. Let's say that the Mars vehicle that will get them there and back is a cylinder roughly 3.5m by 20m (same as was used for the MARS-500 experiments; that is a very small tin can in which to spend 3 1/2 years with 4 or 5 other people). With 1m of shielding water around all surfaces of that cylinder, the outer hull would be about 5.5m by 22m.
The volume of shielding water needed is the difference between those two cylinders, or $22\cdot\pi\cdot2.75^2 - 20\cdot\pi\cdot1.75^2 \approx 522.68 - 192.42 = 330.26 m^3$. As one cubic meter of water weighs 1 metric ton (1,000kg), that's 330,260kg to get into space.
Putting that in perspective, the current record holder for payload-to-LEO is the Saturn V rocket, which had a maximum LEO payload of 120,000kg (said payload being the S-IVb, including CSM, LEM and Earth departure stage, for most of its missions). To put the volume of water we'd need into orbit would require 3 Saturn V rockets. The planned-but-never-built Ares V was spec'ed to have 188 tonnes P2LEO capacity, which would have cut down the number of launches to only 2. Doing it with Space Shuttles (25 tonnes cargo to LEO) would take 14 missions. The SLS Block II (130 tonnes payload to LEO) would take just about 3 launches. Doing it with any orbital rocket currently in service, manned or unmanned (Soyuz II, Soyuz FG, Delta IV, Atlas V, Falcon 9) would require between 50 and 100 launches.
Given that we could achieve getting this much mass into LEO, getting it to break orbit and out into interplanetary space is that much harder; going to Mars using a Hohmann transfer orbit takes about as much delta-V as getting to LEO in the first place, so all the fuel expended to get the craft and its water shield into space has to be brought up into orbit, requiring many more launches. Using a gravity assist, say from Venus, would be a logistical nightmare requiring all three planets to be in alignment as of departure from LEO, and while it would save fuel it would require us to cover much more distance and take much more time, possibly placing the mission further beyond our current capabilities.
A:
A 1 km cube with room for 1,000,000 people each with 16 rooms of 20 Square meters, would require 18 tons per person for a 3 meter shield, which would reduce radiation levels to less than the .000001 R/Hr of the Earths surface.
Allocating each person 1000 cubic meters. If a floor height is 3 meters the 1000 cubic meters provides 333 square meters of floor space. This space can be divided 16 rooms of 20 square meters (200 square feet). The assumption is that people will share part of that space for common areas.
A 1 km cube has 6 sides each 1000 x 1000 meters. The total surface area is thus 6 * 1000 * 1000 or 6 million square meters . Divided among the 1 million occupants means 6 meters of shielding each. Three meters of shielding is required for each square meter of surface. This is a Stack of 3, 1 meter cubes. A cubic meter of water weighs/has a mass of 1 metric tonne (very close to 1 ton). The stack of 3 * surface area of 6 totals 18 tons.
For a 100 meter cube (1,000 people) the figure is 180 tons per person.
The surface area is 6 * 100 * 100 = 60,000 square meters , which is 60 square meters for each of the 1000 people. Thus 3 * 60 or 180 tons.
The 3 meter shield size is derived from the information in keithS's post for the same question.
It is required to reduce 100,000 R/hr to .000001 (1 millionth ) R/hr which is a reduction of 100 thousand million times - which is under $2^{38}$.
Each 7cm (http://www.nist.gov/pml/data/xraycoef/index.cfm) of water divides the radiation by a factor of 2. Thus the total required is 38 * 7cm or 266 cm.
Use 300 cm / 3 meters to make calculation easier and it provides an extra safety margin which makes the calculation easier.
| {
"pile_set_name": "StackExchange"
} |
Q:
adding a case statement
I have a table and creating a materialized view for this which will ultimately be hosted as a WMS. Users will click on a polygon and for each polygon this will take them to a url link which is contained within a table called view_params.
The polygon column is called nature_sites, so my current script looks like this:
REPLACE ( ( SELECT VALUE FROM view_params
WHERE parameter = 'nature_sites_url'),
'[nature_sites]',
nature_sites)
This works fine but half of the nature_sites do not have a relevant url. How can I write a case statement so that if the value is NOT NULL populate the column otherwise leave blank.
New to oracle/sql so I hope this makes sense.
A:
CASE WHEN nature_sites is null THEN '' else REPLACE ( ( SELECT VALUE FROM view_params
WHERE parameter = 'nature_sites_url'),
'[nature_sites]',
nature_sites) END
| {
"pile_set_name": "StackExchange"
} |
Q:
add shortauthor to references (after author)
I need to amend the references to include the "shortauthor" in biblatex. My question is almost identical to
How to print shortauthor in the references as well?
but I need the reference to be of the form
World Health Organization [WHO]. (2016). ...
Right now, it is
World Health Organization. (2016). ...
and \begentry only lets you amend the beginning of the entry. I use biblatex with style=apa. How can I achieve this?
A:
With biblatex-apa you only need
\renewbibmacro*{author}{%
\ifnameundef{author}
{\usebibmacro{labeltitle}}
{\printnames[apaauthor][-\value{listtotal}]{author}%
\setunit*{\addspace}%
\printfield{nameaddon}%
\ifnameundef{shortauthor}
{}
{\setunit*{\addspace}%
\printtext[brackets]{\printnames{shortauthor}}}%
\ifnameundef{with}
{}
{\setunit{}\addspace\mkbibparens{\printtext{\bibstring{with}\addspace}%
\printnames[apaauthor][-\value{listtotal}]{with}}
\setunit*{\addspace}}}%
\newunit\newblock%
\usebibmacro{labelyear+extrayear}}
Where we just added the part starting with \ifnameundef{shortauthor}.
MWE
\documentclass[british]{scrartcl}
\listfiles
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@book{iea,
author = {{International Energy Agency}},
title = {World Energy Outlook},
shortauthor = {IEA},
date = {2005}
}
\end{filecontents}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel,csquotes}
\usepackage[
style=apa,
backend=biber
]{biblatex}
\addbibresource{\jobname.bib}
\addbibresource{biblatex-examples.bib}
\DeclareLanguageMapping{british}{british-apa}
\renewbibmacro*{author}{%
\ifnameundef{author}
{\usebibmacro{labeltitle}}
{\printnames[apaauthor][-\value{listtotal}]{author}%
\setunit*{\addspace}%
\printfield{nameaddon}%
\ifnameundef{shortauthor}
{}
{\setunit*{\addspace}%
\printtext[brackets]{\printnames{shortauthor}}}%
\ifnameundef{with}
{}
{\setunit{}\addspace\mkbibparens{\printtext{\bibstring{with}\addspace}%
\printnames[apaauthor][-\value{listtotal}]{with}}
\setunit*{\addspace}}}%
\newunit\newblock%
\usebibmacro{labelyear+extrayear}}
\begin{document}
\cite{companion,iea}
\printbibliography
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
XNA 4 2D Tiled Sprite - Weird Line
I have a 512x512 image that I need to tile for a background.
I am doing this by setting SamplerState.LinearWrap and setting a larger source rectangle on the image.
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.Default, RasterizerState.CullNone);
spriteBatch.Draw(texture, bounds, bounds, Color.White);
spriteBatch.End();
bounds is new Rectangle(0, 0, 1024, 768)
Right now it is looking like this:
Those lines are where the image is being tiled. The original png does not have any lines on the edges (I zoomed in and checked it out in Photoshop).
What is going on here to cause this? Here is an example project on DropBox.
I tried using a non-power-of-two texture, and it gave an error on the SamplerState, so I am using a texture of proper size, I believe.
A:
Seems to be a graphical artifact in the image.
I copied and pasted a section of the image to the edges and it works as expected, your code is working. Try it with a different image to confirm.
| {
"pile_set_name": "StackExchange"
} |
Q:
Matlab: how to run a For loop with multiple outputs?
So my question refers to the regress() function in matlab. Click here for the Matlab documentation
If I want to run multiple regressions using this function and output both the coefficients and the confidence intervals, what's the best way to do this in a For loop?
Matlab's own syntax for this is [b,bint] = regress(y,X). But when I try to implement this in a for loop it tells me that the dimension mismatch. My code is the following:
for i=1:6
[a, b]=regress(Dataset(:,i),capm_factors);
capm_coefs(i,:)=a;
capm_ci(i,:)=b;
end
Please help, thanks!
A:
regress outputs a column vector of coefficients that minimize the least squared error between your input data (capm_factors) and your predicted values (Dataset(:,i)). However, in your for loop, you are assuming that a and b are row vectors.
Also, the first output of regress is the solution to your system, but the second output contains a matrix of confidence values where the first column denotes the lower end of the confidence interval for each variable and the second column denotes the upper end of the confidence interval.
Specifically, your input capm_factors should be a M x N matrix where M is the total number of input samples and N is the total number of features. In your code, a would thus give you a N x 1 vector and b would give you a N x 2 matrix.
If you'd like use a loop, make sure capm_coefs is a N x l matrix where l is the total number of times you want to loop and capm_ci should either be a N x 2 x l 3D matrix or perhaps a l element cell array. Either way is acceptable.... but I'll show you how to do both.
Something like this comes to mind:
Confidences as a 3D matrix
l = 6; %// Define # of trials
[M,N] = size(capm_factors); %// Get dimensions of data
capm_coefs = zeros(N, l);
capm_ci = zeros(N, 2, l);
for ii = 1 : l
[a,b] = regress(Dataset(:,i), capm_factors);
capm_coefs(:,ii) = a;
capm_ci(:,:,ii) = b;
end
You'd then access the coefficients for a trial via capm_coefs(:,ii) where ii is the iteration you want. Similarly, the confidence matrix can be accessed via capm_ci(:,:,ii)
Confidences as a cell array
l = 6; %// Define # of trials
[M,N] = size(capm_factors); %// Get dimensions of data
capm_coefs = zeros(N, l);
capm_ci = cell(l); %// Cell array declaration
for ii = 1 : l
[a,b] = regress(Dataset(:,i), capm_factors);
capm_coefs(:,ii) = a;
capm_ci{ii} = b; %// Assign confidences to cell array
end
Like above, you'd access the coefficients for a trial via capm_coefs(:,ii) where ii is the iteration you want. However, the confidence matrix can be accessed via capm_ci{ii} as we are now dealing with cell arrays.
| {
"pile_set_name": "StackExchange"
} |
Q:
bash не срабатывает сравнение строк
batStat=$(cat /sys/class/power_supply/BAT1/status)
[ "$batStat" != "Discharging" ] && (let limit=limit-1; batStat="+") || batStat=""
После выполнения фрагмента batStat остаётся содержащим "Full" (текущий статус из файла). То есть не выполняется ни истинное, ни ложное срабатывание. Что не так?
A:
в данном случае вместо вызова subshell-а:
(let limit=limit-1; batStat="+")
логичнее использовать простой блок кода:
{ let limit=limit-1; batStat="+"; }
ведь у него нет кода возврата (в отличие от subshell-а).
а вообще (на начальных порах освоения нового языка программирования) лучше, мне кажется, не «экономить на спичках» и писать развёрнуто:
batStat=$(cat /sys/class/power_supply/BAT1/status)
if [ "$batStat" != "Discharging" ]; then
let limit=limit-1; batStat="+"
else
batStat=""
fi
код сразу становится понятнее, и, главное, работает так, как и ожидается.
| {
"pile_set_name": "StackExchange"
} |
Q:
Doctrine: use user defined function in ORDERBY
What I want to achieve is something like this:
SELECT * FROM users ORDER BY (IF ranking IS NULL, 9999, ranking) ASC
So, I need an if in my orderby. But it seems that user defined functions (I created one named ComplexIf) are not working in OrderBy.
->addOrderBy('ComplexIf(u.ranking IS NULL, 9999, u.ranking )', 'asc')
What am I doing wrong? How can I achieve this?
A:
Thanks SO MUCH to Nic, I finally found the solution with a CASE instead of an IF!
$query = $this
->createQueryBuilder( 'a' )
->select('a')
->add('from', 'path\to\whatever\table a')
->addSelect('CASE WHEN a.ranking IS NULL THEN 9999 ELSE a.ranking END as HIDDEN ORD')
->where( 'a.deleted IS NULL' )
->orderBy( 'ORD', 'asc' )
->getQuery()
;
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to 'remove' blackened water-stain from hardwood floor?
We have several large (3' x 6') blackened areas on our hardwood floor where water damage occurred. This discoloration goes deep. Our goal is to sand the floors and apply a clear coat, but we first want to know if there is a product that will remove the black stain. Also, if this cannot be done will a dark stain hide the problem?
A:
Removing Dark Stains With Sandpaper
Remove the finish over the stain gently with sandpaper, moving with the grain of the wood. Use #100-grit sandpaper, and then feather the
edges with #150-grit sandpaper.
Sand the stain with #150-grit sandpaper, now that you have removed the finish. Feather the edges around the stained area with #0000 steel
wool.
Use tack cloth (lint-free cloth) to remove sanding dust.
Put on several light coats of varnish to match the original finish.
Feather the edges of the new varnish with #0000 steel wool to remove the slight bump between the old and new varnish.
Wax the wood with a quality polish.
Remove Dark Stains With Bleach
Bleach the wood with chlorine bleach if the stain turns out to be too deep to remove without excessive sanding.
Don your rubber gloves and apply the bleach with a brush.
Let it sit for a few hours. The stain should fade to nearly the wood’s original color, but it’s a slow process.
Use a clean sponge and water to remove the bleach completely and prevent further fading of the wood color.
Apply vinegar to neutralize the wood. This will prevent the wood from lightening the stain or varnish when you brush it on.
Let the wood dry thoroughly.
Apply wood stain, if needed, and let it dry again.
Brush on several light coats of varnish to match the original finish.
Feather the edges of the new varnish with #0000 steel wool to remove the slight bump between the old and new varnish. Remove dust
with a tack cloth.
Wax the wood with a quality polish.
Taken from: http://www.wikihow.com/Get-Water-Stains-Off-Wood
| {
"pile_set_name": "StackExchange"
} |
Q:
Как заблокировать Memo?
Прошу прощения, возможно тупой вопрос, но как написать в Memo что-нибудь (не режиме работы программы), а написанное заблокировать?
И если не затруднит, расшифруйте
if (not fileexists('testf.txt')) or (not fileexists('otvf.txt')) then begin
showmessage('123');
close;
end;
A:
В run-time:
memo1.Text := 'Hello world!';
memo1.Enabled := false;
В design-time: воспользуйтесь свойствами Lines,Enabled и Read-only.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error in starting Spark streaming context
I am new to Spark Streaming and writing a code for twitter connector. when i run this code more than one time, it gives the following exception. I have to create a new hdfs directory for checkpointing each time to make it run successfully and moreover it doesn't get stopped.
ERROR StreamingContext: Error starting the context, marking it as stopped
org.apache.spark.SparkException: org.apache.spark.streaming.dstream.WindowedDStream@532d0784 has not been initialized
at org.apache.spark.streaming.dstream.DStream.isTimeValid(DStream.scala:321)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:342)
at org.apache.spark.streaming.dstream.DStream$$anonfun$getOrCompute$1.apply(DStream.scala:342)
at scala.Option.orElse(Option.scala:257)
at org.apache.spark.streaming.dstream.DStream.getOrCompute(DStream.scala:339)
at org.apache.spark.streaming.dstream.ForEachDStream.generateJob(ForEachDStream.scala:38)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:120)
at org.apache.spark.streaming.DStreamGraph$$anonfun$1.apply(DStreamGraph.scala:120)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:251)
at scala.collection.AbstractTraversable.flatMap(Traversable.scala:105)
at org.apache.spark.streaming.DStreamGraph.generateJobs(DStreamGraph.scala:120)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$restart$4.apply(JobGenerator.scala:227)
at org.apache.spark.streaming.scheduler.JobGenerator$$anonfun$restart$4.apply(JobGenerator.scala:222)
at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:108)
at org.apache.spark.streaming.scheduler.JobGenerator.restart(JobGenerator.scala:222)
at org.apache.spark.streaming.scheduler.JobGenerator.start(JobGenerator.scala:92)
at org.apache.spark.streaming.scheduler.JobScheduler.start(JobScheduler.scala:73)
at org.apache.spark.streaming.StreamingContext.liftedTree1$1(StreamingContext.scala:588)
at org.apache.spark.streaming.StreamingContext.start(StreamingContext.scala:586)
at twitter.streamingSpark$.twitterConnector(App.scala:38)
at twitter.streamingSpark$.main(App.scala:26)
at twitter.streamingSpark.main(App.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:664)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:169)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:192)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:111)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
the relavent code is
def twitterConnector() :Unit =
{
val atwitter=managingCredentials()
val ssc=StreamingContext.getOrCreate("hdfsDirectory",()=> { managingContext() })
fetchTweets(ssc, atwitter )
ssc.start() // Start the computation
ssc.awaitTermination()
}
def managingContext():StreamingContext =
{
//making spark context
val conf = new SparkConf().setMaster("local[*]").setAppName("twitterConnector")
val ssc = new StreamingContext(conf, Seconds(1))
val sqlContext = new org.apache.spark.sql.SQLContext(ssc.sparkContext)
import sqlContext.implicits._
//checkpointing
ssc.checkpoint("hdfsDirectory")
ssc
}
def fetchTweets (ssc : StreamingContext , atwitter : Option[twitter4j.auth.Authorization]) : Unit = {
val tweets =TwitterUtils.createStream(ssc,atwitter,Nil,StorageLevel.MEMORY_AND_DISK_2)
val twt = tweets.window(Seconds(10),Seconds(10))
//checkpoint duration
/twt.checkpoint(new Duration(1000))
//processing
case class Tweet(createdAt:Long, text:String)
twt.map(status=>
Tweet(status.getCreatedAt().getTime()/1000, status.getText())
)
twt.print()
}
Can anyone help me in this regards?
A:
The issue you're facing should be related to the fact that you have to put the management of your tranformations and action on DStreams should be performed in the managingContext function.
Thus, moving fetchTweets(ssc, atwitter ) inside managingContext should solve the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fail to upgrade from 11.04 to 12.04
Possible Duplicate:
Can I skip over releases?
I tried to upgrade from 11.04 to 12.04 by Update manager, but failed.
The error message was:
Failed to fetch http://kr.archive.ubuntu.com/ubuntu/pool/main/t/ttf-alee/ttf-alee_12+nmu1ubuntu1_all.deb'
How can I fix it?
A:
You can't upgrade from 11.04 to 12.04. You must upgrade to 11.10 and then to 12.04. You can only skip upgrades if you upgrade from an LTS (10.04) to a LTS (12.04). You can't skip in-between.
I suggest you download an 11.10 image from here. And then upgrades via a usb-stick (live-cd). and then upgrades to 12.04, via the same method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is my dependent destroy not working in Rails?
Thanks for your help with this! I have many newsavedmaps, and each can have multiple waypoints. The waypoints table connects to the newsavedmaps id with a field, "newsavedmap_id." I am new to Rails (using Rails 2), and I'm having trouble with a destroy feature. Essentially, if a user gets rid of a newsavedmap, I also want to eliminate the waypoints.
newsavedmap.rb
has_many :waypoints, :dependent => :destroy
waypoint.rb
belongs_to :newsavedmap
newsavedmap controller (I think this is the problem)
def destroy
@newsavedmap = Newsavedmap.find(params[:id])
@waypoint = Waypoint.find(params[:id])
@newsavedmap.destroy
@waypoint.destroy
respond_to do |format|
format.html { redirect_to "/CODE" }
format.xml { head :ok }
end
end
I also have a view, newmaps.html.erb. A user sees his newsavedmap on the page, and he can click a link:
<a href="/newsavedmaps/<%= newsavedmap.id %>" class="newremovemap"></a>
When he does, this is the javascript that kicks in:
$('.newremovemap').click(function(){
if (confirm('Are you sure you want to remove this map?')) {
var mappage = $(this).closest('.wholemap');
var map = $(this).parent();
$.post(this.href, { _method: "delete", authenticity_token: $('#auth_token').val() }, function(){
mappage.fadeOut();
});
};
return false;
})
Now, when I click the link, the alert message repeats many times, but the records are not removed. The error code is ActiveRecord::RecordNotFound (Couldn't find Waypoint without an ID). I've tried applying links like this to the problem (
Rails dependent destroy error), but I can't seem to find a solution.
A:
you need to just destroy the newsavedmap, and associated waypoints will be automatically deleted.
def destroy
@newsavedmap = Newsavedmap.find(params[:id])
@newsavedmap.destroy
respond_to do |format|
format.html { redirect_to "/CODE" }
format.xml { head :ok }
end
end
the other most important thing is that with a single params[:id], you are trying to find objects of two classes(Newsavedmap,Waypoint), that is wrong. as per the code link is for Newsavedmap and hence you can find its object by params[:id], not of Waypoint.
One more thing, that is important that you are trying to call a javascript function on that click, which is redirecting to newsavedmap show page.Try to change that link as well :
<%= link_to 'Destroy', newsavedmap_path(@newsavedmap),
:confirm => 'Are you sure?', :method => :delete %>
| {
"pile_set_name": "StackExchange"
} |
Q:
How set scrolling only for BorderLayout.CENTER?
I have top bar, list and bottom bar.
this.setLayout(new BorderLayout());
this.addComponent(BorderLayout.NORTH, bottomBar);
this.addComponent(BorderLayout.CENTER, list);
this.addComponent(BorderLayout.SOUTH, bottomBar);
List is very long. bottomBar and bottomBar is hide. Scrolling is on the full screen.
How to make that scrolling was only for BorderLayout.CENTER. bottomBar and bottomBar will be visible.
A:
Disable the scrollable in the Form. For example do like this,
Form f = new Form();
f.setLayout(new BorderLayout());
f.setScrollable(false);
f.addComponent(BorderLayout.NORTH, new Label("Top bar"));
f.addComponent(BorderLayout.CENTER, list);
f.addComponent(BorderLayout.SOUTH, new Label("Bottom bar"));
f.show();
| {
"pile_set_name": "StackExchange"
} |
Q:
Proper use of ARC (Automatic Reference Counting)?
While creating properties, is it correct to replace all retains with strong, and all assigns with weak?
I'm switching to ARC any helpful tips?
A:
Read Transitioning to ARC Release Notes
Use Xcode's guide: Edit > Refactor > Convert to Objective-C ARC.
At first, it may report various issues( in the precheck building phase), just try fixing all issues, try again and (build and fail )again, and it would be done mostly smoothly in the end when all issues are fixed, leaving your code with ARC.
Note that the pre-checking rules are more tough than usual build settings.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android project for social networking system
Hi everyone i have one question about android.
I have created a social networking website. Now i want to make my own website to android application. I am a good designer for android application template like (material design ext.).
I searched on the internet how to created login and register script from android aplication using PHP,MYSQL and i found some example but that examples is not clearly.
My question is how can i use my PHP code in android aplication ?
Note: I am a new on android only php section. My website link is oobenn
A:
You shouldn't try to port the website on Android. You should instead:
create REST APIs for your website exposing JSON Data.
download Android Studio
start developing an Android native application connecting to your website, retrieving data (JSON) and showing data to the user through the native Android UI elements
I strongly recommend you this course https://www.udacity.com/course/ud853
| {
"pile_set_name": "StackExchange"
} |
Q:
UWP Grid RowSpan with ScroolViewer
If you paste this code in the mainpage of a new UWP app (or look at the 1st picture) you can see that the orange grid is taking more space than needed (VerticalAlignment is set to top). To make it work like it should, you have to set the 2nd row's height of this grid to Auto (see 2nd picture). The problem is that I want to give the extra space to the 2nd/last row and not to distribute it across all rows.
Putting the controls in the left column inside their own grid works (obviously, because there is no rowspan) but I can't do that because when the screen narrows the stackpanel in the right column goes inside a row in the left column.
The second problem is that if you click on the orange/green/yellow space, focus goes always to the textbox in the first row (yellow).
UPDATE: both problems are fixed without the scrollviewer but I clearly need it.
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer Background="DarkGreen" VerticalScrollBarVisibility="Auto">
<Grid Background="DarkOrange" Margin="10" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Background="Yellow">
<TextBlock Text="Title" />
<TextBox Margin="20" />
</StackPanel>
<Grid Grid.Row="1" Background="DeepPink" VerticalAlignment="Top">
<ListView Margin="10" VerticalAlignment="Top">
<ListView.Items>
<TextBlock Text="Item1" />
</ListView.Items>
</ListView>
</Grid>
<StackPanel Grid.Column="1" Grid.RowSpan="2" Background="Blue" VerticalAlignment="Top">
<StackPanel>
<TextBlock Text="Title1" />
<GridView Margin="0,10,0,0">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="4" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.Items>
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
</GridView.Items>
</GridView>
</StackPanel>
<StackPanel>
<TextBlock Text="Title2" />
<GridView Margin="0,10,0,0">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="4" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.Items>
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
<Rectangle Width="80" Height="80" Fill="White" />
</GridView.Items>
</GridView>
</StackPanel>
</StackPanel>
</Grid>
</ScrollViewer>
</Grid>
A:
I found a workaround. Since the first row is not going to expand or change, I set the first row's MaxHeight property equal to the actual height of the row at runtime.
For the second problem set the IsTabStop property of the scrollviewer to True as explained here:
https://social.msdn.microsoft.com/Forums/windowsapps/en-US/32e026dd-8338-4c19-a7d6-1bb8797044b3/first-input-control-in-the-scroll-viewer-is-always-getting-focused?prof=required
| {
"pile_set_name": "StackExchange"
} |
Q:
Download Content From External URL and save in db with Ruby
This isn't webservices. I want to pass a url to a controller and then have it fetch the html from that page. Then store the information in a db.
What do you think? How can I accomplish this?
A:
In your controller:
html = %x[curl #{params[:url]}]
That will execute the system curl command and save the result (this is, the content extracted from the url) in the variable html. Then you can make hot cakes with that string if you want to.
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery animate doesn't complete (slideUp/slideDown)
I have a web interface to a system which has a left navigation. On the navigation, I can expand/collapse some menus. I use jQuery slideUp/slideDown to animate them like this:
if (enable)
{
navbar_slide_down = true;
$j(l1_folder).slideDown("normal", function() {
navbar_slide_down = false;
on_navbar_animation_complete();
});
}
else
{
navbar_slide_up = true;
$j(l1_folder).slideUp("normal", function() {
navbar_slide_up = false;
on_navbar_animation_complete();
});
}
Both animations run simultaneously to provide an accordion-like effect. This works in nearly all cases.
The problem I'm encountering now is that after performing some actions in a content frame (not the same frame as the navigation), the slideDown and slideUp functions no longer work. The animations start, but stop nearly immediately, and the callback is never fired. This causes the menu to lockup. I can only reproduce this issue in FireFox 3.5.7 (other versions seem OK). If I turn on Firebug, the problem doesn't occur.
I've tried upgrading from jQuery 1.3.2 to 1.4.1, no luck.
Is there any reason the animations would fail and not call the callback? How can I debug this with an unminified jQuery?
A:
The problem was sequence dependent (ie: click on this, and then that, and the hang will occur). I found the problem in the first page:
addEvent(window, 'unload', end_page);
And changed it to:
addEvent(window, 'onbeforeunload', end_page);
I'm still not sure why this would effect the outer frame (and cause jQuery animations to break), but my best guess is that code in the unload handler was running on the second page and conflicting somewhere.
| {
"pile_set_name": "StackExchange"
} |
Q:
Kotlin lazy default property
In Kotlin, how do i define a var that has a lazy default value ?
for example, a val would be something like this:
val toolbarColor by lazy {color(R.color.colorPrimary)}
What i want to do is, have a default value for some property (toolbarColor), and i can change that value for anything else. Is it possible?
EDIT: This does the partial trick.
var toolbarColor = R.color.colorPrimary
get() = color(field)
set(value){
field = value
}
Is it possible to ease this by writing
var toolbarColor = color(R.color.colorPrimary)
set(value){
field = value
}
in a way that the default value is computed lazily? At the moment it won't work because color() needs a Context that is only initialized later.
A:
You can create your own delegate method:
private class ColorDelegate<T>(initializer: () -> T) : ReadWriteProperty<Any?, T> {
private var initializer: (() -> T)? = initializer
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: initializer!!()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
Declare in some delegate:
object DelegatesExt {
fun <T> lazyColor(initializer: () -> T): ReadWriteProperty<Any?, T> = ColorDelegate(initializer)
}
And use as follow:
var toolbarColor by DelegatesExt.lazyColor {
// you can have access to your current context here.
// return the default color to be used
resources.getColor(R.color.your_color)
}
...
override fun onCreate(savedInstanceState: Bundle?) {
// some fun code
// toolbarColor at this point will be R.color.your_color
// but you can set it a new value
toolbarColor = resources.getColor(R.color.new_color)
// now toolbarColor has the new value that you provide.
}
I think this could be a cleaner way to do, but I don't know yet (starting with kotlin few days ago). I will take a look and see if this could be done with less code.
| {
"pile_set_name": "StackExchange"
} |
Q:
get elements produced by a dom-repeat template selected by a content element
i'm trying to get elements produced by a helper elements on polymer, which is selected of a content tag.
this a simple example that I trying to do:
dom-module
<dom-module id="x-foo">
<template>
<content id="content"></content>
</template>
<script>
Polymer({
is: 'x-foo',
attached: function()
var effectiveChildren = this.getEffectiveChildren("span");
console.log(effectiveChildren);
}
});
</script>
</dom-module>
index.html
<template is="dom-bind">
<x-foo>
<template is="dom-repeat" items="{{list}}">
<span>{{item.name}}</span>
</template>
</x-foo>
</template>
<script>
var scope = document.querySelector("template[is='dom-bind']");
scope.list = [{"name":"javier"},{"name":"pedro"},{"name":"javier2"}]
</script>
--- edit ---
I try with:
getDistributedNodes()
getEffectiveChildren()
getContentChildren()
any hint??
A:
So there was a little bit more to this, but also a little bit less. The code you looking for is:
this.queryAllEffectiveChildren('span');
However, there's gonna be a lot of particularities around when all of the DOM is available to actually run this depending on the final application of your component. I've got it working here: http://plnkr.co/edit/nfER4vTe5y7CddHYO5bk?p=preview the main thing being I'm waiting for the dom-change event on the dom-repeat to check for those elements. There's definitely something cleaner to be used around DOM flush or the like, but I'm not sure which way to direct you in there. The main crux is:
<template>
There are {{childCount}} children.<br/>
<content></content>
</template>
<script>
Polymer({
is: 'my-element',
listeners: {
'dom-change': 'childCheck'
},
childCheck: function() {
this.childCount = this.queryAllEffectiveChildren('span').length;
console.log(this.queryAllEffectiveChildren('span'));
}
});
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Improving efficiency with lazy/eager loading using a virtual (foreign key) reference
I am relatively new to Lambda/Linq, however I want to retrieve all events from a specific calendar where the events are still in the future...
If I use:
EventCalendar eventCalendar;
eventCalendar = db.Events_Calendars.Find(id);
I can get all events and filter by the current date in the view, but I don't think that is the best method.
The Model is as follows:
[Table("Events_Calendars")]
public class EventCalendar
{
public int Id { get; set; }
public string Calendar { get; set; }
public virtual List<Event> Events { get; set; }
}
Event Model is:
public class Event
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public int? Capacity { get; set; }
.
.
.
}
The View is:
@model WebApps.Areas.Events.Models.EventCalendar
@* does some stuff with the EventCalendar *@
@Html.Partial("_Events", Model.Events.ToList())
_Events partial view:
@model IEnumerable<WebApps.Areas.Events.Models.Event>
.
.
.
@foreach (var item in Model)
{
if (item.End > DateTime.Today)
{
@* Do that thing *@
}
}
The above example works, but is putting logic flow in the view. I want to remove the filter logic from the view and make the query do all the work.
The following gives me the calendar only if it has at least one future event which is due to the same where clause conditions. I left it in as a reference of what I need to filter, yet it still returns all events both past and future:
eventCalendar = db.Events_Calendars
.Where(x => x.Events.Any(y => y.End >= DateTime.Today) && x.Id == id)
.FirstOrDefault();
Is there a way that I can filter the events when I ask for the calendar and still use only one statement?
Note: Eager loading is defaulted to on with this system.
Edit clarification = return "no more than 1 calendar with all associated future events";
A:
The Events.Any will filter the Events_Calendars that have at least one event where End >= DateTime.Today. It will not filter the Events_Calendar.Events themselves.
The following will return the Events.End >= DateTime.Today for the matching Events_Calendar only.
var events = db.Events_Calendars
.Where(x => x.Id == id)
.SelectMany(x => x.Events)
.Where(x => x.End >= DateTime.Today);
If you add a Events_Calendar property to the Events, you'll still be able to display the calendar.
Alternatively, you can remap the Events_Calendar, for example by using a factory method:
var newCal = Events_Calendars.WithFutureEvents(db.Events_Calendars.Find(id))
class Events_Calendar
{
public static Events_Calendar WithFutureEvents(Events_Calendar cal)
{
return new Events_Calendar()
{
Id = cal.Id,
Calendar = cal.Calendar,
Events = cal.Events.Where(x => x.End >= DateTime.Today).ToList()
};
}
}
Note that the code example means the new Events_Calendar has reference copies for the Events.
Another possibility is a covenience method on Events_Calendar
class Events_Calendar
{
public IEnumerable<Event> FutureEvents => Events.Where(e => e.End >= DateTime.Today);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
GCD, Threads, Program Flow and UI Updating
I'm having a hard time figuring out how to put this all together.
I have a puzzle solving app on the mac.
You enter the puzzle, press a button, and while it's trying to find the number of solutions,
min moves and such I would like to keep the UI updated.
Then once it's finished calculating, re-enable the button and change the title.
Below is some sample code from the button selector, and the solving function:
( Please keep in mind I copy/paste from Xcode so there might be some missing {} or
some other typos.. but it should give you an idea what I'm trying to do.
Basicly, user presses a button, that button is ENABLED=NO, Function called to calculate puzzle. While it's calculating, keep the UI Labels updated with moves/solution data.
Then once it's finished calculating the puzzle, Button is ENABLED=YES;
Called when button is pressed:
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = @"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:@selector(createTreeFromNode:) withObject:rootNode];
// I've tried to use GCD but similar issue and can't get UI updated.
//dispatch_queue_t queue = dispatch_queue_create("com.gamesbychris.createTree", 0);
//dispatch_sync(queue, ^{[self createTreeFromNode:rootNode];});
}
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
if (numSolutions == 0) {
solveButton.title = @"Not Solvable";
} else {
solveButton.title = @"Solve Puzzle";
}
}
Needs to run in background so UI can be updated:
-(void)createTreeFromNode:(TreeNode *)node
{
// Tried using GCD
dispatch_queue_t main_queue = dispatch_get_main_queue();
...Create Tree Node and find Children Code...
if (!solutionFound){
// Solution not found yet so check other children by recursion.
[self createTreeFromNode:newChild];
} else {
// Solution found.
numSolutions ++;
if (maxMoves < newChild.numberOfMoves) {
maxMoves = newChild.numberOfMoves;
}
if (minMoves < 1 || minMoves > newChild.numberOfMoves) {
solutionNode = newChild;
minMoves = newChild.numberOfMoves;
// Update UI on main Thread
dispatch_async(main_queue, ^{
minMovesLabel.stringValue = [NSString stringWithFormat:@"%d",minMoves];
numSolutionsLabel.stringValue = [NSString stringWithFormat:@"%d",numSolutions];
maxMovesLabel.stringValue = [NSString stringWithFormat:@"%d",maxMoves];
});
}
A:
GCD and performSelectorInBackground samples below. But first, let's look at your code.
You cannot wait where you want to in the code above.
Here's the code you had. Where you say wait in the comment is incorrect. See where I added NO.
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = @"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:@selector(createTreeFromNode:) withObject:rootNode];
// NO - do not wait or enable here.
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
}
A UI message loop is running on the main thread which keeps the UI running. solvePuzzle is getting called on the main thread so you can't wait - it will block the UI. It also can't set the button back to enabled - the work hasn't been done yet.
It is the worker function's job on the background thread to do the work and then when it's done to then update the UI. But you cannot update the UI from a background thread. If you're not using blocks and using performSelectInBackground, then when you're done, call performSelectorOnMainThread which calls a selector to update your UI.
performSelectorInBackground Sample:
In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:@"Working ..."];
[[self doWorkButton] setEnabled:NO];
[self performSelectorInBackground:@selector(performLongRunningWork:) withObject:nil];
}
- (void)performLongRunningWork:(id)obj
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
[self performSelectorOnMainThread:@selector(workDone:) withObject:nil waitUntilDone:YES];
}
- (void)workDone:(id)obj
{
[[self feedbackLabel] setText:@"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
GCD Sample:
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:@"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:@"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
A:
dispatch_queue_t backgroundQueue;
backgroundQueue = dispatch_queue_create("com.images.bgqueue", NULL);
- (void)process {
dispatch_async(backgroundQueue, ^(void){
//background task
[self processHtml];
dispatch_async(main, ^{
// UI updates in main queue
[self workDone];
});
});
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert column values to comma separated with alias
How to convert column values to comma separated with alias for using this output in dynamic query? MyTable table has two columns DayNo & CR_Date with data:
Day1 01/01/2000
Day2 01/02/2002
Day3 05/01/2003
Day4 01/01/1999
Day5 08/01/1998
Day6 01/19/2010
Day7 01/01/2000
Day8 01/01/2011
Day9 12/05/2000
Day10 01/01/2017
My attempt:
declare @AllRowsInOneRow nvarchar (2000)
set @AllRowsInOneRow = ''
select @AllRowsInOneRow =
case when @AllRowsInOneRow = ''
then CR_Date
else @AllRowsInOneRow + coalesce(''' as '+Day_No+',''' + CR_Date, '')
end
from MyTable
select @AllRowsInOneRow = 'select ''' + @AllRowsInOneRow + ''''
select @AllRowsInOneRow
Output:
select '01/01/2000' as Day2,'01/02/2002' as Day3,'05/01/2003' as Day4,
'01/01/1999' as Day5,'08/01/1998' as Day6,'01/19/2010' as Day7,
'01/01/2000' as Day8,'01/01/2011' as Day9,'12/05/2000' as Day10, '01/01/2017'
Desired output:
select '01/01/2000' as Day1,'01/02/2002' as Day2,'05/01/2003' as Day3,
'01/01/1999' as Day4,'08/01/1998' as Day5,'01/19/2010' as Day6,
'01/01/2000' as Day7,'01/01/2011' as Day8,'12/05/2000' as Day9,
'01/01/2017' as Day10
DDL:
Create table MyTable (Day_No varchar(5), CR_Date varchar(20))
go
insert into MyTable values ( 'Day1' , '01/01/2000')
insert into MyTable values ( 'Day2' , '01/02/2002')
insert into MyTable values ( 'Day3' , '05/01/2003')
insert into MyTable values ( 'Day4' , '01/01/1999')
insert into MyTable values ( 'Day5' , '08/01/1998')
insert into MyTable values ( 'Day6' , '01/19/2010')
insert into MyTable values ( 'Day7' , '01/01/2000')
insert into MyTable values ( 'Day8' , '01/01/2011')
insert into MyTable values ( 'Day9' , '12/05/2000')
insert into MyTable values ( 'Day10' , '01/01/2017')
A:
try this this will give you the desired output .
declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + ''''+ CR_Date + '''' + ' as ' +Day_No + ', ' from MyTable
select + 'select ' + SUBSTRING(@tmp, 0, LEN(@tmp))
Output:-
select '01/01/2000' as Day1, '01/02/2002' as Day2,
'05/01/2003' as Day3, '01/01/1999' as Day4,
'08/01/1998' as Day5, '01/19/2010' as Day6,
'01/01/2000' as Day7, '01/01/2011' as Day8,
'12/05/2000' as Day9, '01/01/2017' as Day10
| {
"pile_set_name": "StackExchange"
} |
Q:
Complex return in Ternary Operator?
I am trying to return a specifically styled date after checking the state of an element but struggling with the exact way to write this.
I have this code for a textview in my XML:
android:text='@{String.format(item.status.toLowerCase().contains("check") ? ("Scheduled for %s", item.ScheduledDate) : ("Published on %s", item.PublishedDate))}'
but it is expecting a +<>=- rather than the ,
Can someone please help me encapsulate this properly?
A:
Unfortunately, you will have to do that from within whichever Java class sets the content view to the xml file in question.
Like so:
TextView tv = (TextView) findViewById(R.id.textview);
String text = (item.status.toLowerCase().contains("check") ? String.format("Scheduled for %1$s", item.ScheduledDate) : String.format("Published on %1$s", item.PublishedDate);
tv.setText(text);
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a non-array incomplete type?
All I have found in C11 Standard for incomplete types are incomplete array types.
I was wondering if there is a non-array incomplete type.
A:
An incomplete type is a type that describes an identifier but lacks information needed to determine the size of the identifier. An "incomplete type" can be
A structure type whose members you have not yet specified.
A union type whose members you have not yet specified.
An array type whose dimension you have not yet specified.
The void type is an incomplete type that cannot be completed
A:
For reference, what is incomplete, complete?
At various points within a translation unit an object type may be
incomplete (lacking sufficient information to determine the size of objects of that type) or complete (having sufficient information). C11 §6.2.5 1
In addition to potentially struct, union, arrays and always void, enum are temporarily incomplete in that their size is incomplete until the }
... The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations, and complete thereafter. C11 §6.7.2.2 4
int main() {
enum ee1 { a1 = 0, b1 = sizeof(int), c1 };
printf("%zu\n", sizeof(enum ee1)); // OK
// error: invalid application of 'sizeof' to incomplete type 'enum ee2'
// v--------------v
enum ee2 { a2 = 0, b2 = sizeof(int), c2 = sizeof(enum ee2) }; // Bad
printf("%zu\n", sizeof(enum ee2)); // OK
}
Further
All declarations of structure, union, or enumerated types that have the same scope and use the same tag declare the same type. Irrespective of whether there is a tag or what other declarations of the type are in the same translation unit, the type is incomplete until immediately after the closing brace of the list defining the content, and complete thereafter. §6.7.2.3 4
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.