qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
6,781,886 | can anybody tell me that in c# why does char takes two bytes although it can be stored in one byte. Don't you think it is wastage of a memory. if not , then how is extra 1-byte used?
in simple words ..please make me clear what is the use of extra 8-bits.!! | 2011/07/21 | [
"https://Stackoverflow.com/questions/6781886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856755/"
] | >
> although it can be stored in one byte
>
>
>
What makes you think that?
It only takes one byte to represent every character in the English language, but other languages use other characters. Consider the number of different alphabets (Latin, Chinese, Arabic, Cyrillic...), and the number of symbols in each of these alphabets (not only letters or digits, but also punctuation marks and other special symbols)... there are tens of thousands of different symbols in use in the world ! So one byte is never going to be enough to represent them all, that's why the [Unicode](http://en.wikipedia.org/wiki/Unicode) standard was created.
Unicode has several representations (UTF-8, UTF-16, UTF-32...). .NET strings use UTF-16, which takes two bytes per character (code points, actually). Of course, two bytes is still not enough to represent all the different symbols in the world; surrogate pairs are used to represent characters above U+FFFF | because utf-8 was probably still too young for microsoft to consider using it |
354,899 | I created this script to do date calculation between a date and today, but for some reason I get a decimal number.
How can I just get the number of date without decimal point ?
Tried to use a roundup formula but that's messy, what the best way to handle this?
```
set theDateWantedValue to "25/03/2019"
set [dayVal, MonthVal, YearVal] to the words of theDateWantedValue
set the text item delimiters to "/"
##set date_string to {d, ordinal, Y} as text
##set myotherDate to date_string
set dateDelaybetwentheDate to ((date (theDateWantedValue as string)) - (current date)) / days
set myResultDateRound to RoundDecimal(dateDelaybetwentheDate, 1, down)
on RoundDecimal(NumberToRound, DecimalPlace, UpDown)
set RoundFactor to 10 ^ DecimalPlace
NumberToRound * RoundFactor
round result rounding UpDown
result / RoundFactor
end RoundDecimal
``` | 2019/03/26 | [
"https://apple.stackexchange.com/questions/354899",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/124098/"
] | Maybe using a different approach will accomplish what you were looking for?
```
set someDate to "09/ 09 / 2019"
set theDate to date someDate
set currentDate to (current date)
set secondsBetweenDates to (theDate - currentDate)
set timeInDays to (secondsBetweenDates div days)
set timeInWeeks to (secondsBetweenDates div weeks)
set extraDays to (timeInDays mod timeInWeeks)
display dialog ((timeInWeeks as text) & " Weeks & " & extraDays & " Days Remaining Until " & someDate) ¬
buttons {"Cancel", "OK"} default button "OK"
```
Obviously change the value of `someDate` to whatever you need | maybe adding " as integer" ? although that won't remove the negative sign
```
set dateDelaybetwentheDate to ((date (theDateWantedValue as string)) - (current date)) / days as integer
``` |
36,184,206 | Basically I'm building an iOS app which allows users to track their moods throughout the month so that they can evaluate when they are most stressed and when they are most happy.
Each day, users can write a block of information about the day and colour code each day so that in a list view they can quickly see how the month is going (for example, if most of the month is red then it indicates that they are having a bad month).
I am using green, amber, and red to identify the moods of users. But I'm having trouble making each individual cell the colour that the user has selected. I have given each colour cell a tag to identify the user's choice. I'm just having trouble actually calling the function to allow it to be displayed on the screen.
This is the code in my list view controller:
```
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
let post = posts[indexPath.row]
let cellTitle = cell.viewWithTag(1) as! UILabel
cellTitle.text = post.title
let cellText = cell.viewWithTag(2) as! UILabel
cellText.text = post.text
return cell
}
```
I know that I need to call the functions, but how do I do this? | 2016/03/23 | [
"https://Stackoverflow.com/questions/36184206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605583/"
] | As I have already commented, you will have to loop over array and compute html and set it. Your function `clearAndShow` will set last value only.
I have taken liberty to update your code. You should not save data in different arrays. Its better to use one array with proper constructed object.
[JSFiddle](https://jsfiddle.net/RajeshDixit/s5tqxkyL/)
```js
var data = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
var title, name, ticket;
title = titleInput.value;
name = nameInput.value;
ticket = ticketInput.value;
data.push({
title: title,
name: name,
ticket: ticket
});
clearAndShow();
}
function clearAndShow() {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = computeHTML();
}
function computeHTML() {
var html = "<table>";
console.log(data)
data.forEach(function(item) {
html += "<tr>";
html += "<td>" + item.title + "</td>"
html += "<td>" + item.name + "</td>"
html += "<td>" + item.ticket + "</td>"
html += "</tr>";
});
html += "</table>"
return html;
}
```
```css
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<head>
<script class="jsbin" src=""></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
``` | Please try and change your js code like below, not the most elegant but a start:
```
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>Titles</td>";
messageBox.innerHTML += "<td>Name</td>";
messageBox.innerHTML += "<td>Tickets</td>";
messageBox.innerHTML += "</tr>";
for(i = 0; i <= titles.length - 1; i++)
{
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>" + titles[i]+ "</td>";
messageBox.innerHTML += "<td>" + names[i] + "</td>";
messageBox.innerHTML += "<td>" + tickets[i]+ "</td>";
messageBox.innerHTML += "</tr>";
}
}
```
and your display html like so:
```
<table id="display"></table>
```
have a look at fiddle over here <https://jsfiddle.net/gvanderberg/cwmzyjf4/>
The data array in Rajesh's example is the better option to go for. |
36,184,206 | Basically I'm building an iOS app which allows users to track their moods throughout the month so that they can evaluate when they are most stressed and when they are most happy.
Each day, users can write a block of information about the day and colour code each day so that in a list view they can quickly see how the month is going (for example, if most of the month is red then it indicates that they are having a bad month).
I am using green, amber, and red to identify the moods of users. But I'm having trouble making each individual cell the colour that the user has selected. I have given each colour cell a tag to identify the user's choice. I'm just having trouble actually calling the function to allow it to be displayed on the screen.
This is the code in my list view controller:
```
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
let post = posts[indexPath.row]
let cellTitle = cell.viewWithTag(1) as! UILabel
cellTitle.text = post.title
let cellText = cell.viewWithTag(2) as! UILabel
cellText.text = post.text
return cell
}
```
I know that I need to call the functions, but how do I do this? | 2016/03/23 | [
"https://Stackoverflow.com/questions/36184206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605583/"
] | As I have already commented, you will have to loop over array and compute html and set it. Your function `clearAndShow` will set last value only.
I have taken liberty to update your code. You should not save data in different arrays. Its better to use one array with proper constructed object.
[JSFiddle](https://jsfiddle.net/RajeshDixit/s5tqxkyL/)
```js
var data = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
var messageBox = document.getElementById("display");
function insert() {
var title, name, ticket;
title = titleInput.value;
name = nameInput.value;
ticket = ticketInput.value;
data.push({
title: title,
name: name,
ticket: ticket
});
clearAndShow();
}
function clearAndShow() {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = computeHTML();
}
function computeHTML() {
var html = "<table>";
console.log(data)
data.forEach(function(item) {
html += "<tr>";
html += "<td>" + item.title + "</td>"
html += "<td>" + item.name + "</td>"
html += "<td>" + item.ticket + "</td>"
html += "</tr>";
});
html += "</table>"
return html;
}
```
```css
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
display: block;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<head>
<script class="jsbin" src=""></script>
<script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<body>
<form>
<h1>Please enter data</h1>
<input id="title" type="text" placeholder="Title" />
<input id="name" type="text" placeholder="Name" />
<input id="tickets" type="text" placeholder="Tickets" />
<input type="button" value="Save/Show" onclick="insert()" />
</form>
<div id="display"></div>
</body>
``` | you deleted your last question about the numbering of authors, but I wrote a big answer to you for it. Just for you to have it :
--------------------------------------------------------------------------------------------------------------------------------
Wow, man you have several problems in your logic.
First, you have to specify to your form not to submit when you click on one or the other submit buttons (Add a book, or Display book) :
```
<form onsubmit="return false;">
```
Second, you have to define your *numbering* var to *0* and use it when you want to assign a number to a book :
```
var numbering = 0;
```
Then, in your addBook function, you have to use that global numbering variable to set you *no* variable :
```
function addBook() {
numbering++; // increments the number for the books (1, 2, 3, etc)
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
...
}
```
Then you have all kind of mistakes like double ";" on certain lines etc.
A **huge** mistake is also done on your code when you use "***forEach***". Notice this function only works when you use ***jQuery*** library ! You have to include it before you use it :
```
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
```
An other **huge** mistake you do is that your "*Display*" button has the id "*display*" and your messageBox also has this id. This is forbidden because when you want to use the element which has this ID, Javascript won't know which of the two is the good one. So rename your button id in *displayAuthors* :
```
<input type="submit" id="displayAuthors" value="Display" onclick="displayBook()" />
```
Now, what you also can do, is to call your ***displayBooks*** function everytime you add a new book like this :
```
function addBook() {
numbering++;
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
data.push({
book: book,
author: author,
no: no
});
displayBook();
}
```
So I did all these things here on CodePen : <https://codepen.io/liorchamla/pen/JMpoxM>
---
***The JQuery solution***
Here you used the basics of Javascript (called Vanilla JS) which is very cool because you have to learn it, but I also wrote you a CodePen to show you how you could have done this with jQuery :-)
Here it is : <http://codepen.io/liorchamla/pen/oxwNwd>
Basicly, the javascript changed to this :
```
$(document).ready(function(){
var data = []; // data is an empty array
// binding the addBook button with the action :
$('#addBook').on('click', function(){
var book = {
title: $('#bookname').val(),
author: $('#authors').val(),
// note we won't use a numbering variable
};
data.push(book);
// let's automaticly trigger the display button ?
$('#displayBooks').trigger('click');
});
// binding the displayBooks button with the action :
$('#displayBooks').on('click', function(){
$('#display').html(computeHTML());
});
function computeHTML(){
// creating the table
html = "<table><tr><th>No</th><th>Book</th><th>Author</th></tr>";
// for each book in the data array, we take the element (book) and the index (number)
data.forEach(function(element, index){
// building the table row, note that index starts at 0, so we increment it to have a start at 1 if it is 0, 2 if it is 1 etc.
html += "<tr><td>" + parseInt(index++) + "</td><td>" + element.title + "</td><td>" + element.author + "</td></tr>";
})
html += "</table>";
// returning the table
return html;
}
})
```
You might find it complicated, but with time you will see that jQuery helps a lot !
They are lot of things we could enpower in this script but this is a good starting, don't you think ?
Cheers from Marseille, France ! |
36,184,206 | Basically I'm building an iOS app which allows users to track their moods throughout the month so that they can evaluate when they are most stressed and when they are most happy.
Each day, users can write a block of information about the day and colour code each day so that in a list view they can quickly see how the month is going (for example, if most of the month is red then it indicates that they are having a bad month).
I am using green, amber, and red to identify the moods of users. But I'm having trouble making each individual cell the colour that the user has selected. I have given each colour cell a tag to identify the user's choice. I'm just having trouble actually calling the function to allow it to be displayed on the screen.
This is the code in my list view controller:
```
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")!
let post = posts[indexPath.row]
let cellTitle = cell.viewWithTag(1) as! UILabel
cellTitle.text = post.title
let cellText = cell.viewWithTag(2) as! UILabel
cellText.text = post.text
return cell
}
```
I know that I need to call the functions, but how do I do this? | 2016/03/23 | [
"https://Stackoverflow.com/questions/36184206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5605583/"
] | Please try and change your js code like below, not the most elegant but a start:
```
function clearAndShow () {
// Clear our fields
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>Titles</td>";
messageBox.innerHTML += "<td>Name</td>";
messageBox.innerHTML += "<td>Tickets</td>";
messageBox.innerHTML += "</tr>";
for(i = 0; i <= titles.length - 1; i++)
{
messageBox.innerHTML += "<tr>";
messageBox.innerHTML += "<td>" + titles[i]+ "</td>";
messageBox.innerHTML += "<td>" + names[i] + "</td>";
messageBox.innerHTML += "<td>" + tickets[i]+ "</td>";
messageBox.innerHTML += "</tr>";
}
}
```
and your display html like so:
```
<table id="display"></table>
```
have a look at fiddle over here <https://jsfiddle.net/gvanderberg/cwmzyjf4/>
The data array in Rajesh's example is the better option to go for. | you deleted your last question about the numbering of authors, but I wrote a big answer to you for it. Just for you to have it :
--------------------------------------------------------------------------------------------------------------------------------
Wow, man you have several problems in your logic.
First, you have to specify to your form not to submit when you click on one or the other submit buttons (Add a book, or Display book) :
```
<form onsubmit="return false;">
```
Second, you have to define your *numbering* var to *0* and use it when you want to assign a number to a book :
```
var numbering = 0;
```
Then, in your addBook function, you have to use that global numbering variable to set you *no* variable :
```
function addBook() {
numbering++; // increments the number for the books (1, 2, 3, etc)
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
...
}
```
Then you have all kind of mistakes like double ";" on certain lines etc.
A **huge** mistake is also done on your code when you use "***forEach***". Notice this function only works when you use ***jQuery*** library ! You have to include it before you use it :
```
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
```
An other **huge** mistake you do is that your "*Display*" button has the id "*display*" and your messageBox also has this id. This is forbidden because when you want to use the element which has this ID, Javascript won't know which of the two is the good one. So rename your button id in *displayAuthors* :
```
<input type="submit" id="displayAuthors" value="Display" onclick="displayBook()" />
```
Now, what you also can do, is to call your ***displayBooks*** function everytime you add a new book like this :
```
function addBook() {
numbering++;
var no, book, author;
book = bookInput.value;
author = nameInput.value;
no = numbering;
data.push({
book: book,
author: author,
no: no
});
displayBook();
}
```
So I did all these things here on CodePen : <https://codepen.io/liorchamla/pen/JMpoxM>
---
***The JQuery solution***
Here you used the basics of Javascript (called Vanilla JS) which is very cool because you have to learn it, but I also wrote you a CodePen to show you how you could have done this with jQuery :-)
Here it is : <http://codepen.io/liorchamla/pen/oxwNwd>
Basicly, the javascript changed to this :
```
$(document).ready(function(){
var data = []; // data is an empty array
// binding the addBook button with the action :
$('#addBook').on('click', function(){
var book = {
title: $('#bookname').val(),
author: $('#authors').val(),
// note we won't use a numbering variable
};
data.push(book);
// let's automaticly trigger the display button ?
$('#displayBooks').trigger('click');
});
// binding the displayBooks button with the action :
$('#displayBooks').on('click', function(){
$('#display').html(computeHTML());
});
function computeHTML(){
// creating the table
html = "<table><tr><th>No</th><th>Book</th><th>Author</th></tr>";
// for each book in the data array, we take the element (book) and the index (number)
data.forEach(function(element, index){
// building the table row, note that index starts at 0, so we increment it to have a start at 1 if it is 0, 2 if it is 1 etc.
html += "<tr><td>" + parseInt(index++) + "</td><td>" + element.title + "</td><td>" + element.author + "</td></tr>";
})
html += "</table>";
// returning the table
return html;
}
})
```
You might find it complicated, but with time you will see that jQuery helps a lot !
They are lot of things we could enpower in this script but this is a good starting, don't you think ?
Cheers from Marseille, France ! |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | No, and in my experience you shouldn't rely on anyone trying to give you compiled resources.
For the CPU miner you would need at least "automake libcurl4-openssl-dev make", those are the names for Ubuntu.
For the GPU miner if you are using R9 cards you can use these instructions.
<https://www.reddit.com/r/Monero/comments/50dzu7/questionany_guide_on_linux_gpu_ati_mining/d74eyip>
Those instructions are for Ubuntu 14.04 as the newer versions of Ubuntu only support the AMD pro drivers. | For **CPU** Miner on linux, you can check Yam releases here:
<https://mega.nz/#F!UlkU0RyR!E8n4CFkqVu0WoOnsJnQkSg>
And for **GPU** releases, you could try Claymore v9.1, available here:
<https://drive.google.com/drive/folders/0B69wv2iqszefdkVDNkxla3BCZHc>
Note: Both are **closed source**. |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | No, and in my experience you shouldn't rely on anyone trying to give you compiled resources.
For the CPU miner you would need at least "automake libcurl4-openssl-dev make", those are the names for Ubuntu.
For the GPU miner if you are using R9 cards you can use these instructions.
<https://www.reddit.com/r/Monero/comments/50dzu7/questionany_guide_on_linux_gpu_ati_mining/d74eyip>
Those instructions are for Ubuntu 14.04 as the newer versions of Ubuntu only support the AMD pro drivers. | There is no pre-built linux pool miner provided by the core team.
You can only solo mine with the official binaries.
For Wolf's CPU Miner, you need "libcurl4-openssl-dev make automake gcc"
For his GPU Miner, You can refer to [this SE question](https://monero.stackexchange.com/q/1626/110) |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | No, and in my experience you shouldn't rely on anyone trying to give you compiled resources.
For the CPU miner you would need at least "automake libcurl4-openssl-dev make", those are the names for Ubuntu.
For the GPU miner if you are using R9 cards you can use these instructions.
<https://www.reddit.com/r/Monero/comments/50dzu7/questionany_guide_on_linux_gpu_ati_mining/d74eyip>
Those instructions are for Ubuntu 14.04 as the newer versions of Ubuntu only support the AMD pro drivers. | Most pools maintain a "Getting started" page which includes a list of available miners, as well as startup instructions. Links to binaries (or to announcement pages which old those, to reasonably enough ensure the link is from the original author) are included.
See for instance <http://monero.crypto-pool.fr/#getting_started> |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | For **CPU** Miner on linux, you can check Yam releases here:
<https://mega.nz/#F!UlkU0RyR!E8n4CFkqVu0WoOnsJnQkSg>
And for **GPU** releases, you could try Claymore v9.1, available here:
<https://drive.google.com/drive/folders/0B69wv2iqszefdkVDNkxla3BCZHc>
Note: Both are **closed source**. | There is no pre-built linux pool miner provided by the core team.
You can only solo mine with the official binaries.
For Wolf's CPU Miner, you need "libcurl4-openssl-dev make automake gcc"
For his GPU Miner, You can refer to [this SE question](https://monero.stackexchange.com/q/1626/110) |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | For **CPU** Miner on linux, you can check Yam releases here:
<https://mega.nz/#F!UlkU0RyR!E8n4CFkqVu0WoOnsJnQkSg>
And for **GPU** releases, you could try Claymore v9.1, available here:
<https://drive.google.com/drive/folders/0B69wv2iqszefdkVDNkxla3BCZHc>
Note: Both are **closed source**. | Most pools maintain a "Getting started" page which includes a list of available miners, as well as startup instructions. Links to binaries (or to announcement pages which old those, to reasonably enough ensure the link is from the original author) are included.
See for instance <http://monero.crypto-pool.fr/#getting_started> |
2,335 | I've been having problems compiling wolf's miners.
Are there any pre-built linux miners, and if not, what are the packages that I need to fully build his CPU and GPU miners? | 2016/10/15 | [
"https://monero.stackexchange.com/questions/2335",
"https://monero.stackexchange.com",
"https://monero.stackexchange.com/users/727/"
] | There is no pre-built linux pool miner provided by the core team.
You can only solo mine with the official binaries.
For Wolf's CPU Miner, you need "libcurl4-openssl-dev make automake gcc"
For his GPU Miner, You can refer to [this SE question](https://monero.stackexchange.com/q/1626/110) | Most pools maintain a "Getting started" page which includes a list of available miners, as well as startup instructions. Links to binaries (or to announcement pages which old those, to reasonably enough ensure the link is from the original author) are included.
See for instance <http://monero.crypto-pool.fr/#getting_started> |
34,290,418 | I have created a wallboard application for a service desk team, which uses WPF for front-end and the Cisco database of the phones in the back-end. The application is made of two screens that show different information, and these are displayed in the same screen and change between each other with a `System.Timers.Timer`.
The application is made so that if `WindowA` is visible, `WindowB` is shown and then `WindowA` is hidden. The moment one of the Windows becomes visible, that Window's timer become active again which resumes the database calls, while the other Window's timer becomes disabled:
```
private static void InterfaceChanger_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (WindowA.Visibility == Visibility.Visible)
{
WindowAEnabled = false;
ChangeVisibility(Visibility.Visible, WindowB);
WindowBEnabled = true;
WindowB_Elapsed(null, null); // force the call of the timer's callback
ChangeVisibility(Visibility.Collapsed, WindowA);
}
else
{
WindowBEnabled = false;
ChangeVisibility(Visibility.Visible, WindowA);
WindowAEnabled = true;
WindowA_Elapsed(null, null); // force the call of the timer's callback
ChangeVisibility(Visibility.Collapsed, WindowB);
}
}
private static void ChangeVisibility(Visibility visibility, Window window)
{
window.Dispatcher.Invoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
window.Visibility = visibility;
}, null);
}
```
The problem is that this works perfectly... at most 90% of the time. The problem is that sometimes, if for example `WindowA's` visibility is changed to Visible and `WindowB's` visibility is changed to Collapsed, `WindowB` collapses but `WindowA` takes 2-3 seconds to become visible, while most times `WindowA` becomes visible and it's not seen when `WindowB` collapses. This (when it doesn't work) results in the Desktop being visible instead of the application.
I originally used `DispatcherPriority.Background` but that resulted in the screen changer working 70-80% of the time, so I decided to change it for `DispatcherPriority.Normal` (`DispatcherPriority.Send`results basically in the same situation as Normal).
Questions:
1. Is this the normal behavior to be expected by the Dispatcher, taking into account this is running in x64 mode in a quad-core CPU?
2. Knowing that the queries are performed in async methods not awaited, shouldn't the Dispatcher take priority over the methods?
3. Is there another way (without using the Dispatcher, or using another Window property) to accomplish what I'm looking for?
This is the code used to access/start the Windows:
```
//WindowA:
<Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="WindowA.xaml">
//WindowA class:
public static WindowA WindowAInstance;
public WindowA()
{
// unnecessary code hidden
WindowAInstance = this;
WindowB b = new WindowB;
}
// WindowB class
public static WindowB WindowBInstance;
public WindowB()
{
// unnecessary code hidden
WindowBInstance = this;
}
// this is the code that starts the timers
public static void StartTimersHandling()
{
Database.RemoveAgents();
InterfaceChangerTimer = new System.Timers.Timer();
InterfaceChangerTimer.Interval = ApplicationArguments.InterfaceChangerTime;
InterfaceChangerTimer.Elapsed += InterfaceChanger_Elapsed;
InterfaceChangerTimer.AutoReset = true;
InterfaceChangerTimer.Start();
WindowATimer = new System.Timers.Timer();
WindowATimer.Interval = 1000;
WindowATimer.Elapsed += WindowATimer_Elapsed;
WindowATimer.AutoReset = true;
WindowATimer.Start();
WindowBTimer = new System.Timers.Timer();
WindowBTimer.Interval = 1000;
WindowBTimer.Elapsed += WindowBTimer_Elapsed;
WindowBTimer.AutoReset = true;
WindowBTimer.Start();
}
``` | 2015/12/15 | [
"https://Stackoverflow.com/questions/34290418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141621/"
] | It sounds like you're writing a kiosk application (ie. full-screen, non-interactive). If this is the case I think you would be better off having a single window and switching the views inside it, rather than switching between two separate windows. Also, you need to separate the database query work from the refreshing of the window content. Furthermore, I think it would help if the views knew nothing about each other: at the moment your first window is tightly coupled to your second, which is not really a good idea.
In my opinion, if you changed your architecture a little, a lot of the problems you are having would disappear. Here's what I would recommend:
First, just go with a single window. Create two *user controls* (Project > Add User Control), and move your XAML layout from your existing windows into these two new controls. Then make your main window look something like this:
```
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:StackOverflow"
WindowState="Maximized" WindowStyle="None">
<Grid>
<my:UserControl1 x:Name="_first" Panel.ZIndex="1" />
<my:UserControl2 Panel.ZIndex="0" />
</Grid>
<Window.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard AutoReverse="True" RepeatBehavior="Forever">
<ObjectAnimationUsingKeyFrames BeginTime="0:0:5" Duration="0:0:5"
Storyboard.TargetName="_first"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0:0:0"
Value="{x:Static Visibility.Hidden}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
</Window>
```
This is a full-screen window with no chrome that contains your two user controls (essentially the contents of your existing windows). They are layered in a `Grid` element so that one sits on top of the other: I'm using the `Panel.ZIndex` property to force the first control to the top of the pile. Finally, I'm using an animation (triggered when the window loads) that toggles the visibility of one of the controls to hide it after a certain period of time. The animation is set to repeat and auto-reverse, the effect of which is to hide one of the controls, then make it visible again. You can change the `Duration` attribute value to control how long each control "stays" visible; it's set to 5 seconds in this example, which means a 10 second delay between switches.
The key to this working is that the first user control, when visible, must fully obscure the other user control that lies beneath it. This is easy to accomplish by setting the background colour of the control.
Your user controls can contain anything that a window would contain. Here's the example user control XAML that I used:
```
<UserControl x:Class="StackOverflow.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="White" Padding="40">
<TextBlock Text="{Binding Number}" FontSize="60"
TextAlignment="Center" VerticalAlignment="Top" />
</UserControl>
```
As you can see it's just a `TextBlock` element whose `Text` property binds to a `Number` property defined in the user control's code-behind. I used the same XAML for both user controls, just varying the `VerticalAlignment` of the text so that I could tell which control was visible at any given time.
The code-behind looks like this (it's the same for both, with the exception of the class name):
```
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Threading;
namespace StackOverflow
{
public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
public UserControl1()
{
InitializeComponent();
DataContext = this;
_timer = new DispatcherTimer
{ Interval = TimeSpan.FromSeconds(5), IsEnabled = true };
_timer.Tick += (sender, e) => Task.Run(async () => await DoWorkAsync());
}
readonly DispatcherTimer _timer;
readonly Random _random = new Random();
public event PropertyChangedEventHandler PropertyChanged;
public int Number
{
get
{
return _number;
}
private set
{
if (_number != value)
{
_number = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Number"));
}
}
}
}
int _number;
async Task DoWorkAsync()
{
// Asynchronous code started on a thread pool thread
Console.WriteLine(GetType().Name + " starting work");
_timer.IsEnabled = false;
try
{
await Task.Delay(TimeSpan.FromSeconds(_random.Next(4, 12)));
Number++;
}
finally
{
_timer.IsEnabled = true;
}
Console.WriteLine(GetType().Name + " finished work");
}
}
}
```
It basically contains a single `Number` property (which implements `INotifyPropertyChanged`) that gets incremented by a "worker" method. The worker method is invoked by a timer: here, I'm using a `DispatcherTimer`, but as I'm not changing any UI elements directly any of the .NET timers would have done.
The worker is scheduled to run on the thread pool using `Task.Run`, and then runs asynchronously. I'm simulating a long-running job by waiting for a period of time with `Task.Delay`. This worker method would be where your database query gets called from. You can vary the gap between successive queries by setting the timer's `Interval` property. There's nothing to say that the gap between queries need be the same as the refresh interval of your UI (ie. the speed at which the two views are switched); indeed, as your query takes a variable amount of time, syncing the two would be tricky anyway. | Try to use `Dispatcher.CurrentDispatcher` instead of `window.Dispatcher` and BeginInvoke:
```
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.DataBind, new Action(() =>
{
window.Visibility = visibility;
}));
```
**Updated**
Switch your timer to DispatcherTimer:
```
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += (sender, args) => InterfaceChanger_Elapsed();
timer.Start();
``` |
24,961 | From the start of the game what is the longest possible series of consecutive white moves where white can do those moves no matter what black does?
So I want the longest list of moves white can do after starting the game no matter what moves black does. So what is the maximum number of moves he can plan ahead and be sure he will be able to do it? | 2019/07/24 | [
"https://chess.stackexchange.com/questions/24961",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/19618/"
] | Three moves.
On move 3, Black can crash through with his queen on f2 or d2 via several different squares, forcing White to respond. There is no series of White moves that can prevent all such checks.
```
[FEN ""]
1. Nf3 (1. e3 e5 2. c3 Qf6 3. g3 Qxf2+) 1... c6 (1... e5 2. c3 Qh4 3. e3 Qxf2+) 2. g3 Qa5 (2... Qb6 3. c3 Qxf2+) 3. e3 Qxd2+ *
``` | The accepted answer gives the correct number, but is incomplete. It's true that Black can always force either 3. ... Q(x)d2+ or 3. ... Q(x)f2+. However, what if White could choose a fourth move that is valid even if such a check is made? The only possible options are 4. Kd1, 4. Kf1, 4. Kd2 or 4. Kf2. It turns out that Black can still prevent such sequences, but for various different reasons that don't necessarily involve one of these checks.
First, White needs three moves to prevent all the routes to Qf2+, and none of these can be bishop moves so 4. Kf1 is out. If White moves the f pawn and makes two other moves to block Qf2+ Black can always play Qxf3 or Qxf4, so 4. Kf2 is also out (White doesn't have time to play Nf3 here without allowing Qf2+). Note that, even if you consider 4. Kxf2 and 4. Kf2 to be the same move, White must block Qf2+ here because otherwise Black can just leave the queen attacking f2 to prevent Kf2.
So does White have a sequence ending 4. Kd1 or 4. Kd2? To do this, White must use two moves to prevent Qd2+. This means there is no time to get anything on c5, and so White can't avoid 1. ... e3, 2. ... Bb4, 3. ... Bc3, (where the bishop moves might be captures) which prevents 4. Kd2.
The only option remaining is 4. Kd1 and that requires two moves to prevent both routes to Qd2+, and one queen move to vacate d1. The non-queen moves need to be (b4 or c3 or Nc3) and (e3 or f4). However, f4 is not possible: Black can play 2. Qh4, which is either a check preventing White's intended third move or prevents 3. f4.
If White plays e3, Black's plan is to avoid 4. Kd1 by getting a bishop to the d1-h5 diagonal. If the White queen is on this diagonal after White's third move, Black can always capture with the bishop on move 3. If not, Bg4 is sufficient to prevent 4. Kd1, and White can't stop this while also stopping Qd2+ and moving the queen. |
42,280,058 | as the title says I'm getting an error code when I attempt render one of my website pages.
Here are the parts of the traceback that are pointing to my code:
```
File "/vagrant/catalog/project.py", line 48, in newMenuItem
return render_template('newMenuItem.html', restaurant_id=restaurant.id)
File "/vagrant/catalog/templates/newMenuItem.html", line 9, in block "content"
<form action="{{ url_for('newMenuItem', restaurant_id=restaurant.id) }}" method="POST">
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
UndefinedError: 'restaurant' is undefined
```
As you can see it is telling me that 'restaurant' is not defined, at first I thought perhaps I wasn't querying my database correctly so I double checked that section of my code and I can't find any problems.
Here is my python module and relevant html file:
```
### Create new menu item. ###
@app.route('/restaurant/<int:restaurant_id>/menu/new/',
methods=['GET', 'POST'])
def newMenuItem(restaurant_id):
restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
if request.method == 'POST':
newMenuItem = MenuItem(name=request.form['name'],
description=request.form['description'],
price=request.form['price'],
restaurant_id=restaurant.id)
session.add(newMenuItem)
session.commit()
return redirect(url_for('showMenu', restaurant_id=restaurant.id))
else:
return render_template('newMenuItem.html', restaurant_id=restaurant.id)
```
and here is the newMenuItem html file:
```
{% extends "base.html" %}
{% block content %}
<div class="twelve columns">
New Item.
</div>
<div class="row">
<div class="six columns">
<form action="{{ url_for('newMenuItem', restaurant_id=restaurant.id) }}" method="POST">
<div class="row">
<div class="six columns">
<label for="Item Name">Item Name</label>
<input class="u-full-width" placeholder="New Item" name="name" type="text">
</div>
<div class="six columns">
<label for="Item Name">Item Description</label>
<input class="u-full-width" placeholder="Description" description="description" type="text">
</div>
<div class="six columns">
<label for="Item Name">Item Price</label>
<input class="u-full-width" placeholder="Price" price="price" type="text">
</div>
<div class="six columns">
<input class="button" value="Create" type="submit">
<a class="button" href="{{ url_for('showMenu', restaurant_id=restaurant.id) }}">Cancel</a>
</div>
</div>
</form>
</div>
</div>
{% endblock %}
```
I am having trouble understanding why this error is being thrown with this specific page, as I have used similar url\_for code to create a new restaurant. The only thing I could think of that would be causing this issue is that my template cannot figure out the restaurant id where the new menu item should be created. I am unsure of how to read this error code as I do not know whether it is telling me that 'restaurant' as a variable is undefined, or that 'restaurant' is undefined in the sense that my code cannot call the correct id.
Any suggestions? Thanks in advance for any help offered. | 2017/02/16 | [
"https://Stackoverflow.com/questions/42280058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7416542/"
] | So create it like this
```
$file = date('Ymd') . '-dumpDB.sql.gz';
system(sprintf(
'mysqldump --no-tablespaces --opt -h%s -u%s -p"%s" %s | gzip > %s/%s',
$host,
$user,
$pass,
$db,
getenv('DOCUMENT_ROOT'),
$file
));
``` | this should work... it just appends the date to the filename.
```
system(sprintf(
'mysqldump --no-tablespaces --opt -h%s -u%s -p"%s" %s | gzip > %s/%s-dumpDB.sql.gz',
$host,
$user,
$pass,
$db,
getenv('DOCUMENT_ROOT'),
date("Ymd")
));
``` |
42,280,058 | as the title says I'm getting an error code when I attempt render one of my website pages.
Here are the parts of the traceback that are pointing to my code:
```
File "/vagrant/catalog/project.py", line 48, in newMenuItem
return render_template('newMenuItem.html', restaurant_id=restaurant.id)
File "/vagrant/catalog/templates/newMenuItem.html", line 9, in block "content"
<form action="{{ url_for('newMenuItem', restaurant_id=restaurant.id) }}" method="POST">
File "/usr/lib/python2.7/dist-packages/jinja2/environment.py", line 397, in getattr
return getattr(obj, attribute)
UndefinedError: 'restaurant' is undefined
```
As you can see it is telling me that 'restaurant' is not defined, at first I thought perhaps I wasn't querying my database correctly so I double checked that section of my code and I can't find any problems.
Here is my python module and relevant html file:
```
### Create new menu item. ###
@app.route('/restaurant/<int:restaurant_id>/menu/new/',
methods=['GET', 'POST'])
def newMenuItem(restaurant_id):
restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
if request.method == 'POST':
newMenuItem = MenuItem(name=request.form['name'],
description=request.form['description'],
price=request.form['price'],
restaurant_id=restaurant.id)
session.add(newMenuItem)
session.commit()
return redirect(url_for('showMenu', restaurant_id=restaurant.id))
else:
return render_template('newMenuItem.html', restaurant_id=restaurant.id)
```
and here is the newMenuItem html file:
```
{% extends "base.html" %}
{% block content %}
<div class="twelve columns">
New Item.
</div>
<div class="row">
<div class="six columns">
<form action="{{ url_for('newMenuItem', restaurant_id=restaurant.id) }}" method="POST">
<div class="row">
<div class="six columns">
<label for="Item Name">Item Name</label>
<input class="u-full-width" placeholder="New Item" name="name" type="text">
</div>
<div class="six columns">
<label for="Item Name">Item Description</label>
<input class="u-full-width" placeholder="Description" description="description" type="text">
</div>
<div class="six columns">
<label for="Item Name">Item Price</label>
<input class="u-full-width" placeholder="Price" price="price" type="text">
</div>
<div class="six columns">
<input class="button" value="Create" type="submit">
<a class="button" href="{{ url_for('showMenu', restaurant_id=restaurant.id) }}">Cancel</a>
</div>
</div>
</form>
</div>
</div>
{% endblock %}
```
I am having trouble understanding why this error is being thrown with this specific page, as I have used similar url\_for code to create a new restaurant. The only thing I could think of that would be causing this issue is that my template cannot figure out the restaurant id where the new menu item should be created. I am unsure of how to read this error code as I do not know whether it is telling me that 'restaurant' as a variable is undefined, or that 'restaurant' is undefined in the sense that my code cannot call the correct id.
Any suggestions? Thanks in advance for any help offered. | 2017/02/16 | [
"https://Stackoverflow.com/questions/42280058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7416542/"
] | So create it like this
```
$file = date('Ymd') . '-dumpDB.sql.gz';
system(sprintf(
'mysqldump --no-tablespaces --opt -h%s -u%s -p"%s" %s | gzip > %s/%s',
$host,
$user,
$pass,
$db,
getenv('DOCUMENT_ROOT'),
$file
));
``` | Use `date('Ymd')` output: `20170216`
```
$file = date('Ymd') . '-dumpDB.sql.gz'; //20170216-dumpDB.sql.gz
system(sprintf(
'mysqldump --no-tablespaces --opt -h%s -u%s -p"%s" %s | gzip > %s/%s',
$host,
$user,
$pass,
$db,
getenv('DOCUMENT_ROOT'),
$file
));
``` |
36,225,212 | I am implementing a Huffman encoder. Huffman trees are built bottom-up using a priority queue. I have a simple node class with pointers to two other nodes.
The loop that builds the tree is:
```
while(q.size() > 1)
{
huffnode n1 = q.top();
q.pop();
huffnode n2 = q.top();
q.pop();
q.push(huffnode((char)0, n1.freq+n2.freq, &n1, &n2));
}
```
The remaining node when the loop terminates is the tree root.
This code looks innocent enough, but on my test input it gives a tree where the root's right child points to itself and to the root's left child instead of to the two nodes that were just popped from the queue. I have confirmed that the queue is sorted correctly.
What I think is happening is that n1 and n2 are local variables that always have the same address, as seen in the debugger. When a new node is pushed, it points to those addresses. When that node gets popped later, its copy gets put into one of those addresses, one of which it is already pointing to, so it ends up pointing to itself.
How should I fix this? I can't make n1 and n2 pointers, because then they would have to be `const` since top() returns a const reference, and assigning the result of top() to a const reference or const pointer makes the queue immutable. | 2016/03/25 | [
"https://Stackoverflow.com/questions/36225212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043521/"
] | When you have the curly braces `{}` you are in a new scope. and variables declared in that scope are local to that scope and only valid inside that scope. When the scope ends, which for you your loop is every time the loop iterates, the scope disappears and the variables in that scope are destructed and exists no more.
Saving a pointer to a variable that goes out of scope will lead to *undefined behavior* when you try to dereference that pointer. | C++ does not have garbage collection, and does not allocate objects on the heap unless you tell it to -- you need to manage your memory yourself.
If you want to build a dynamically allocated tree, you need to allocate your nodes on the heap explicitly, by using `new` or some higher-level library facility. You will also need to make sure they are destroyed when you know that there are no more references to them.
As others have mentioned, your `huffnode` variables `n1` and `n2` are local variables, and are destroyed when they go out of scope (which is, every pass of your `while` loop). |
36,225,212 | I am implementing a Huffman encoder. Huffman trees are built bottom-up using a priority queue. I have a simple node class with pointers to two other nodes.
The loop that builds the tree is:
```
while(q.size() > 1)
{
huffnode n1 = q.top();
q.pop();
huffnode n2 = q.top();
q.pop();
q.push(huffnode((char)0, n1.freq+n2.freq, &n1, &n2));
}
```
The remaining node when the loop terminates is the tree root.
This code looks innocent enough, but on my test input it gives a tree where the root's right child points to itself and to the root's left child instead of to the two nodes that were just popped from the queue. I have confirmed that the queue is sorted correctly.
What I think is happening is that n1 and n2 are local variables that always have the same address, as seen in the debugger. When a new node is pushed, it points to those addresses. When that node gets popped later, its copy gets put into one of those addresses, one of which it is already pointing to, so it ends up pointing to itself.
How should I fix this? I can't make n1 and n2 pointers, because then they would have to be `const` since top() returns a const reference, and assigning the result of top() to a const reference or const pointer makes the queue immutable. | 2016/03/25 | [
"https://Stackoverflow.com/questions/36225212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043521/"
] | When you have the curly braces `{}` you are in a new scope. and variables declared in that scope are local to that scope and only valid inside that scope. When the scope ends, which for you your loop is every time the loop iterates, the scope disappears and the variables in that scope are destructed and exists no more.
Saving a pointer to a variable that goes out of scope will lead to *undefined behavior* when you try to dereference that pointer. | comingstorm is right. I need to use `new`.
The fixed code is
```
while(q.size() > 1)
{
huffnode* n1 = new huffnode(q.top().data, q.top().freq, q.top().left, q.top().right);
q.pop();
huffnode* n2 = new huffnode(q.top().data, q.top().freq, q.top().left, q.top().right);
q.pop();
q.push(huffnode((char)0, n1->freq + n2->freq, n1, n2));
}
``` |
11,436,755 | Here's what I am trying to write:
```
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
```
The signature of the Bar() method is:
```
public void Bar<T>(T parameter) where T: class
```
So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
```
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class - I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11436755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38908/"
] | You can use the [`dynamic` keyword](http://msdn.microsoft.com/en-us/library/dd264741.aspx) like this:
```
public void Foo<T>(T parameter)
{
dynamic p = parameter
otherObject.Bar(p);
}
```
What's happening is that the resolution of the call to `otherObject.Bar` is being made at run-time, because one of the parameters has a type of `dynamic`. Assuming that `T` is a reference type, the resolution will succeed.
Granted, this ultimately uses reflection (as you've indicated), but the syntax is *probably* better than what you're using.
Of course, this will give you a run-time error in the event that `T` is *not* a class. | ```
public void Foo<T>(T parameter)
{
otherObject.Bar<object>(parameter);
}
``` |
11,436,755 | Here's what I am trying to write:
```
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
```
The signature of the Bar() method is:
```
public void Bar<T>(T parameter) where T: class
```
So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
```
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class - I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11436755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38908/"
] | You can use the [`dynamic` keyword](http://msdn.microsoft.com/en-us/library/dd264741.aspx) like this:
```
public void Foo<T>(T parameter)
{
dynamic p = parameter
otherObject.Bar(p);
}
```
What's happening is that the resolution of the call to `otherObject.Bar` is being made at run-time, because one of the parameters has a type of `dynamic`. Assuming that `T` is a reference type, the resolution will succeed.
Granted, this ultimately uses reflection (as you've indicated), but the syntax is *probably* better than what you're using.
Of course, this will give you a run-time error in the event that `T` is *not* a class. | If you are the owner of otherObject.Bar, could you not just remove the class constraint? of that method. Or create a new similar method without the constraint?
casperOne. I am not sure your answer is correct, as you have the class constraint on your Foo method. The question stated that this was not possible as Foo was an implementation of an external interface. For instance, the code below does not work.
```
public void Foo<T>(T param)
{
dynamic xx = param;
this.Bar(param);
}
private void Bar<T>(T param) where T: class {
}
```
And shows up as an error. |
11,436,755 | Here's what I am trying to write:
```
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
```
The signature of the Bar() method is:
```
public void Bar<T>(T parameter) where T: class
```
So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
```
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class - I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11436755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38908/"
] | You can use the [`dynamic` keyword](http://msdn.microsoft.com/en-us/library/dd264741.aspx) like this:
```
public void Foo<T>(T parameter)
{
dynamic p = parameter
otherObject.Bar(p);
}
```
What's happening is that the resolution of the call to `otherObject.Bar` is being made at run-time, because one of the parameters has a type of `dynamic`. Assuming that `T` is a reference type, the resolution will succeed.
Granted, this ultimately uses reflection (as you've indicated), but the syntax is *probably* better than what you're using.
Of course, this will give you a run-time error in the event that `T` is *not* a class. | Here's a slightly different take on casperOne's answer, using implicit interface implementation:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
void IFoo.Foo<T>(T parameter){
Foo((dynamic)parameter);
}
```
This allows you to include the constraint on anything that knows what specific object type they're calling `.Foo` on at compile time, while still allowing you to implement the `IFoo` interface. |
11,436,755 | Here's what I am trying to write:
```
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
```
The signature of the Bar() method is:
```
public void Bar<T>(T parameter) where T: class
```
So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
```
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class - I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11436755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38908/"
] | ```
public void Foo<T>(T parameter)
{
otherObject.Bar<object>(parameter);
}
``` | If you are the owner of otherObject.Bar, could you not just remove the class constraint? of that method. Or create a new similar method without the constraint?
casperOne. I am not sure your answer is correct, as you have the class constraint on your Foo method. The question stated that this was not possible as Foo was an implementation of an external interface. For instance, the code below does not work.
```
public void Foo<T>(T param)
{
dynamic xx = param;
this.Bar(param);
}
private void Bar<T>(T param) where T: class {
}
```
And shows up as an error. |
11,436,755 | Here's what I am trying to write:
```
public void Foo<T>(T parameter) {
otherObject.Bar<T>(parameter);
}
```
The signature of the Bar() method is:
```
public void Bar<T>(T parameter) where T: class
```
So I get a compile error because the T in Foo's signature doesn't have the same constraint. Unfortunately I can't write:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
```
because Foo is implementing a method defined in an external interface. Question is:
Can I somehow transpose the T within the method Foo before calling Bar. (Note, I can be sure that T always will be a class - I just need to get past the compiler).
The only way I have found is using reflection but I wonder if there is a simpler trick I'm missing. | 2012/07/11 | [
"https://Stackoverflow.com/questions/11436755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38908/"
] | Here's a slightly different take on casperOne's answer, using implicit interface implementation:
```
public void Foo<T>(T parameter) where T: class {
otherObject.Bar<T>(parameter);
}
void IFoo.Foo<T>(T parameter){
Foo((dynamic)parameter);
}
```
This allows you to include the constraint on anything that knows what specific object type they're calling `.Foo` on at compile time, while still allowing you to implement the `IFoo` interface. | If you are the owner of otherObject.Bar, could you not just remove the class constraint? of that method. Or create a new similar method without the constraint?
casperOne. I am not sure your answer is correct, as you have the class constraint on your Foo method. The question stated that this was not possible as Foo was an implementation of an external interface. For instance, the code below does not work.
```
public void Foo<T>(T param)
{
dynamic xx = param;
this.Bar(param);
}
private void Bar<T>(T param) where T: class {
}
```
And shows up as an error. |
2,659,908 | If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this?
```
>>> # Modified for readability
>>> import pytz
>>> import datetime
>>> sweden = pytz.timezone('Europe/Stockholm')
>>>
>>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>)
>>>
>>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>)
>>>
``` | 2010/04/17 | [
"https://Stackoverflow.com/questions/2659908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311998/"
] | The `sweden` object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.
In the first example, you create a `datetime` object and convert it to local time. The `sweden` object knows that the UTC time you passed occurs during daylight savings time and can convert it appropriately.
In the second example, the `datetime` constructor always interprets your input as not-daylight-savings-time and returns an appropriate object.
If `datetime` treated your input as wall-clock time and chose the appropriate daylight-savings setting for you, there would be an ambiguity during the time of year when clocks are set back. On a wall-clock the same hour occurs twice. Hence, `datetime` forces you to specify which timezone you're using when you create the `datetime` object. | Timezone abbreviations are not unique. For example "IST" could refer to "Irish Standard Time", "Iranian Standard Time", "Indian Standard Time" or "Isreali Standard Time". You shouldn't rely on parsing that, and instead should use zoneinfo timezones. |
18,062,063 | How do i pass a bool from the viewmodel to the view and change the value.
For example in my viewmodel i have created a bool
```
public bool load
{
get { return m_load; }
set
{
m_load = value;
OnPropertyChanged(this, o => o.load);
}
}
```
I then have my `SelectedVm` code
```
public ViewModel SelectedVm
{
get { return _selectedVm; }
set
{
_selectedVm = value;
if (_selectedVm != null && load == true)
{
_selectedVm.Load();
}
Load = false;
OnPropertyChanged(this, o => o.SelectedVm);
}
}
```
In my View the `SelectedVm` is bound twice but only on one of the bindings do i want Load to be called, hence the need to change the bool `load`
So in my view if i have the following
```
<ListView Grid.Row="1" Name="Sample"
ItemsSource="{Binding Path=SampleViewModel}"
SelectedItem="{Binding SelectedVm, Mode=TwoWay}"
IsSynchronizedWithCurrentItem="True" Width="500">
</ListView>
```
How do i change the `bool` load to either true or false
All of the above are just quick samples, i think this is probably quite simple however i am not that used to `WPF` and am still learning. any advice would be great | 2013/08/05 | [
"https://Stackoverflow.com/questions/18062063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653666/"
] | Ok if you want to get value of Load in View and you want to do it in pure MVVM pattern then create DependencyProperty of bool type in View and Bind it to Load property of VM like
```
public partial class MainWindow : Window
{
public static readonly DependencyProperty LoadProperty = DependencyProperty.Register("MyCustom", typeof(bool), typeof(MainWindow), new PropertyMetadata(new PropertyChangedCallback(LoadPropertyChangedCallback)));
public bool Load
{
get
{
return (bool)this.GetValue(LoadProperty) ;
}
set
{
this.SetValue(LoadProperty, value);
}
}
static void LoadPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//Do your load stuff here
}
public MainWindow()
{
InitializeComponent();
this.SetBinding(LoadProperty, new Binding("load"));
DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
load = true;
}
bool m_load;
public bool load
{
get { return m_load; }
set
{
m_load = value;
OnPropertyChanged("load");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
``` | The code you published ensures that `Load()` is being called once, even with multiple bindings.
If I understand your real question correctly, you are actually asking for a way to make sure that each `SelectedVM` is calling `Load()` function once, and only once. Right?
if that so, you need to add a bool property to the `ViewModel` class, instead of the main class, that's all.
And then:
```
public ViewModel SelectedVm
{
get { return _selectedVm; }
set
{
_selectedVm = value;
if (_selectedVm != null && _selectedVm.load == true)
{
_selectedVm.Load();
_selectedVm.load = false;
}
OnPropertyChanged(this, o => o.SelectedVm);
}
}
```
you can keep your XAML as it is. |
54,008,357 | I am looking to sort a string list numerically which has both string and number also as a string.
['har 1', 'zee 3']
expected output :
zee 3
har 1 | 2019/01/02 | [
"https://Stackoverflow.com/questions/54008357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9510689/"
] | I found 2 problems:
* The Q3 recursion only starts from cells in the top row and the
right-most column. It should start from every cell. So simply loop all cells using 2 for loops instead of using recursion (although that could be done too, of course).
* 2 of the if statements were wrong. See `>= 0` in 2 of the if statements below.
The 2 problems are fixed here:
```
public static int longestSlope(int[][] A, int num) {
int max = 0;
for (int row = 0; row < A.length; row++) {
for (int col = 0; col < A[0].length; col++) {
max = Math.max(max, Q3(A, num, row, col, 1));
}
}
return max;
}
private static int Q3(int[][] A, int NUM1, int ind1, int ind2, int Step) {
if ((ind1 + 1) < A.length && A[(ind1 + 1)][(ind2 + 0)] == A[ind1][ind2] - NUM1)
return Q3(A, NUM1, ind1 + 1, ind2, Step + 1);
if ((ind1 - 1) >= 0 && A[(ind1 - 1)][(ind2 + 0)] == A[ind1][ind2] - NUM1)
return Q3(A, NUM1, ind1 - 1, ind2, Step + 1);
if ((ind2 + 1) < A[0].length && A[(ind1 - 0)][(ind2 + 1)] == A[ind1][ind2] - NUM1)
return Q3(A, NUM1, ind1, ind2 + 1, Step + 1);
if ((ind2 - 1) >= 0 && A[(ind1 + 0)][(ind2 - 1)] == A[ind1][ind2] - NUM1)
return Q3(A, NUM1, ind1, ind2 - 1, Step + 1);
else return Step; //if a cell next to current index is in the same slop move to that cell and add 1 step
}
``` | I think you need to rethink your strategy. I'm guessing your code is not doing what you want it to do.
This is what happens in your code: The method recursion will first call itself five times because of the first if statement (col) and then five times because of the second if statement (row). Then it will call Q3 a five times (although I would have guessed 10 times at a first glance). None of the if statements in Q3 evaluate to true to Q3 always returns/fallbacks on 0 (Step).
Please explain what "the int Num given by the user is remainder of the cell next to it". Is it that the difference (cell1-cell2) must be equal to Num. If so, fix your sample matrix since there is no valid path where the difference between the cells is 1 (Num).
Also explain how the step-jumping works. Does it start from and/or end in a specific position? Can it be in any direction (here the answer is probably 'yes')? |
4,203,607 | I have stuck in a point when I convert a psd to html/css
The page is this : <http://valogiannis.com/freelancer/neurosport/editdetails.html>
Below the title "Edit Account Details" I have a table to show the user data.
I have I have the following rule for the rows
```
#editAccountDetails tr {
border-bottom:#cdd3e0 solid 1px;
border-top:#fff solid 1px;
line-height:3;
}
```
As you can see in the page the blue bottom-border overlap the white border-top. I get the same result in all browser so I suppose is normal behavior and it's something that I can't understand.
What I want to achieve is the border-bottom to be exactly above the white border-top. Any suggestion?
P.S Something else that would help me if you know. How can I make the border-bottom don't appear for the latest row and border-top for the first row? I think it's something like `tr + tr {... }` but I don't remember exactly. | 2010/11/17 | [
"https://Stackoverflow.com/questions/4203607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407382/"
] | The reason you cant see your borders is because this is in your reset.css
```
table {
border-collapse: collapse
}
```
add in this to your css
```
#editAccountDetails table {
border-collapse: seperate
}
```
You will also need to remove the borders from the tr to the td
```
#editAccountDetails td {
border-bottom:1px solid #CDD3E0;
border-top:1px solid #FFFFFF;
}
```
And the selector for the first row is:
```
#editAccountDetails tr:first-child {color:blue}
```
And the selector for the last row is: (last row doesnt work in ie)
```
#editAccountDetails tr:last-child {color:blue}
``` | ```
table {
border-collapse: collapse
}
```
try this |
4,203,607 | I have stuck in a point when I convert a psd to html/css
The page is this : <http://valogiannis.com/freelancer/neurosport/editdetails.html>
Below the title "Edit Account Details" I have a table to show the user data.
I have I have the following rule for the rows
```
#editAccountDetails tr {
border-bottom:#cdd3e0 solid 1px;
border-top:#fff solid 1px;
line-height:3;
}
```
As you can see in the page the blue bottom-border overlap the white border-top. I get the same result in all browser so I suppose is normal behavior and it's something that I can't understand.
What I want to achieve is the border-bottom to be exactly above the white border-top. Any suggestion?
P.S Something else that would help me if you know. How can I make the border-bottom don't appear for the latest row and border-top for the first row? I think it's something like `tr + tr {... }` but I don't remember exactly. | 2010/11/17 | [
"https://Stackoverflow.com/questions/4203607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407382/"
] | ```
table {
border-collapse: collapse
}
```
try this | Simply put borders on the TD instead of TR and all will be well :-)
```
#editAccountDetails tr td {
border-bottom:#cdd3e0 solid 1px;
border-top:#fff solid 1px;
line-height:3;
}
``` |
4,203,607 | I have stuck in a point when I convert a psd to html/css
The page is this : <http://valogiannis.com/freelancer/neurosport/editdetails.html>
Below the title "Edit Account Details" I have a table to show the user data.
I have I have the following rule for the rows
```
#editAccountDetails tr {
border-bottom:#cdd3e0 solid 1px;
border-top:#fff solid 1px;
line-height:3;
}
```
As you can see in the page the blue bottom-border overlap the white border-top. I get the same result in all browser so I suppose is normal behavior and it's something that I can't understand.
What I want to achieve is the border-bottom to be exactly above the white border-top. Any suggestion?
P.S Something else that would help me if you know. How can I make the border-bottom don't appear for the latest row and border-top for the first row? I think it's something like `tr + tr {... }` but I don't remember exactly. | 2010/11/17 | [
"https://Stackoverflow.com/questions/4203607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407382/"
] | The reason you cant see your borders is because this is in your reset.css
```
table {
border-collapse: collapse
}
```
add in this to your css
```
#editAccountDetails table {
border-collapse: seperate
}
```
You will also need to remove the borders from the tr to the td
```
#editAccountDetails td {
border-bottom:1px solid #CDD3E0;
border-top:1px solid #FFFFFF;
}
```
And the selector for the first row is:
```
#editAccountDetails tr:first-child {color:blue}
```
And the selector for the last row is: (last row doesnt work in ie)
```
#editAccountDetails tr:last-child {color:blue}
``` | Simply put borders on the TD instead of TR and all will be well :-)
```
#editAccountDetails tr td {
border-bottom:#cdd3e0 solid 1px;
border-top:#fff solid 1px;
line-height:3;
}
``` |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | Plain old C doesn't actually support exceptions natively.
You can use alternative error handling strategies, such as:
* returning an error code
* returning `FALSE` and using a `last_error` variable or function.
See <http://en.wikibooks.org/wiki/C_Programming/Error_handling>. | In C we can't use try case to handle the error.
but if you can use Windows.h so you can:
```
#include <stdio.h>
#include <Windows.h>
#include <setjmp.h>
jmp_buf Buf;
NTAPI Error_Handler(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
printf("co loi roi ban oi.!!!\r\n");
longjmp(Buf, 1);
}
void main()
{
AddVectoredExceptionHandler(1, Error_Handler);
int x = 0;
printf("start main\r\n");
if (setjmp(Buf) == 0)
{
int y = 1 / x;
}
printf("end main\r\n");
}
``` |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | In C you could use the combination of the `setjmp()` and `longjmp()` functions, defined in `setjmp.h`. [Example from Wikipedia](http://en.wikipedia.org/wiki/Setjmp.h)
```
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp
// was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main"); // prints
}
return 0;
}
```
**Note:** I would actually advise you **not** to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead. | C is able to throw C++ exceptions. It is machine code anyway.
For example, in file *bar.c*:
```
#include <stdlib.h>
#include <stdint.h>
extern void *__cxa_allocate_exception(size_t thrown_size);
extern void __cxa_throw (void *thrown_exception, void* *tinfo, void (*dest) (void *) );
extern void * _ZTIl; // typeinfo of long
int bar1()
{
int64_t * p = (int64_t*)__cxa_allocate_exception(8);
*p = 1976;
__cxa_throw(p, &_ZTIl, 0);
return 10;
}
```
In file *a.cc*,
```
#include <stdint.h>
#include <cstdio>
extern "C" int bar1();
void foo()
{
try
{
bar1();
}
catch(int64_t x)
{
printf("good %ld", x);
}
}
int main(int argc, char *argv[])
{
foo();
return 0;
}
```
To compile it:
```none
gcc -o bar.o -c bar.c && g++ a.cc bar.o && ./a.out
```
### Output
```none
good 1976
```
<https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html> has more detail info about `__cxa_throw`.
I am not sure whether it is portable or not, and I test it with 'gcc-4.8.2' on Linux. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | There's no *built-in* exception mechanism in C; you need to *simulate* exceptions and their semantics. This is usually achieved by relying on `setjmp` and `longjmp`.
There are quite a few libraries around, and I'm implementing yet another one. It's called [exceptions4c](http://code.google.com/p/exceptions4c/); it's portable and free. You may take a look at it, and compare it against [other alternatives](http://code.google.com/p/exceptions4c/wiki/alternatives) to see which fits you most. | On Windows with **Microsoft Visual C++** (MSVC) there's `__try ... __except ...`, but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | Plain old C doesn't actually support exceptions natively.
You can use alternative error handling strategies, such as:
* returning an error code
* returning `FALSE` and using a `last_error` variable or function.
See <http://en.wikibooks.org/wiki/C_Programming/Error_handling>. | On Windows with **Microsoft Visual C++** (MSVC) there's `__try ... __except ...`, but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | This question is super old, but I just stumbled across it and thought I'd share a technique: divide by zero, or dereference a null pointer.
The question is simply "how to throw", not how to catch, or even how to throw a specific type of exception. I had a situation ages ago where we needed to trigger an exception from C to be caught in C++. Specifically, we had occasional reports of "pure virtual function call" errors, and needed to convince the C runtime's \_purecall function to throw something. So we added our own \_purecall function that divided by zero, and boom, we got an exception that we could catch on C++, and even use some stack fun to see where things went wrong. | If you write code with the *[happy path](https://en.wikipedia.org/wiki/Happy_path)* design pattern (for example, for an embedded device) you may simulate exception error processing (AKA deffering or finally emulation) with operator "goto".
```
int process(int port)
{
int rc;
int fd1;
int fd2;
fd1 = open("/dev/...", ...);
if (fd1 == -1) {
rc = -1;
goto out;
}
fd2 = open("/dev/...", ...);
if (fd2 == -1) {
rc = -1;
goto out;
}
// Do some with fd1 and fd2 for example write(f2, read(fd1))
rc = 0;
out:
//if (rc != 0) {
(void)close(fd1);
(void)close(fd2);
//}
return rc;
}
```
It is not actually an exception handler, but it takes you a way to handle error at function exit.
P.S.: You should be careful to use goto only from the same or more deep scopes and never jump a variable declaration. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | In C you could use the combination of the `setjmp()` and `longjmp()` functions, defined in `setjmp.h`. [Example from Wikipedia](http://en.wikipedia.org/wiki/Setjmp.h)
```
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp
// was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main"); // prints
}
return 0;
}
```
**Note:** I would actually advise you **not** to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead. | C doesn't have exceptions.
There are various hacky implementations that try to do it (one example at: <http://adomas.org/excc/>). |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | In C you could use the combination of the `setjmp()` and `longjmp()` functions, defined in `setjmp.h`. [Example from Wikipedia](http://en.wikipedia.org/wiki/Setjmp.h)
```
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("second\n"); // prints
longjmp(buf,1); // jumps back to where setjmp
// was called - making setjmp now return 1
}
void first(void) {
second();
printf("first\n"); // does not print
}
int main() {
if ( ! setjmp(buf) ) {
first(); // when executed, setjmp returns 0
} else { // when longjmp jumps back, setjmp returns 1
printf("main"); // prints
}
return 0;
}
```
**Note:** I would actually advise you **not** to use them as they work awful with C++ (destructors of local objects wouldn't get called) and it is really hard to understand what is going on. Return some kind of error instead. | This question is super old, but I just stumbled across it and thought I'd share a technique: divide by zero, or dereference a null pointer.
The question is simply "how to throw", not how to catch, or even how to throw a specific type of exception. I had a situation ages ago where we needed to trigger an exception from C to be caught in C++. Specifically, we had occasional reports of "pure virtual function call" errors, and needed to convince the C runtime's \_purecall function to throw something. So we added our own \_purecall function that divided by zero, and boom, we got an exception that we could catch on C++, and even use some stack fun to see where things went wrong. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | There are no exceptions in C. In C the errors are notified by the returned value of the function, the exit value of the process, signals to the process ([Program Error Signals (GNU libc)](http://www.gnu.org/software/libc/manual/html_node/Program-Error-Signals.html)) or the CPU hardware interruption (or other notification error form the CPU if there is)([How processor handles the case of division by zero](https://stackoverflow.com/questions/23878400/how-processor-handles-case-of-division-by-zero)).
Exceptions are defined in C++ and other languages though. Exception handling in C++ is specified in the C++ standard "S.15 Exception handling", there is no equivalent section in the C standard. | Plain old C doesn't actually support exceptions natively.
You can use alternative error handling strategies, such as:
* returning an error code
* returning `FALSE` and using a `last_error` variable or function.
See <http://en.wikibooks.org/wiki/C_Programming/Error_handling>. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | C is able to throw C++ exceptions. It is machine code anyway.
For example, in file *bar.c*:
```
#include <stdlib.h>
#include <stdint.h>
extern void *__cxa_allocate_exception(size_t thrown_size);
extern void __cxa_throw (void *thrown_exception, void* *tinfo, void (*dest) (void *) );
extern void * _ZTIl; // typeinfo of long
int bar1()
{
int64_t * p = (int64_t*)__cxa_allocate_exception(8);
*p = 1976;
__cxa_throw(p, &_ZTIl, 0);
return 10;
}
```
In file *a.cc*,
```
#include <stdint.h>
#include <cstdio>
extern "C" int bar1();
void foo()
{
try
{
bar1();
}
catch(int64_t x)
{
printf("good %ld", x);
}
}
int main(int argc, char *argv[])
{
foo();
return 0;
}
```
To compile it:
```none
gcc -o bar.o -c bar.c && g++ a.cc bar.o && ./a.out
```
### Output
```none
good 1976
```
<https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html> has more detail info about `__cxa_throw`.
I am not sure whether it is portable or not, and I test it with 'gcc-4.8.2' on Linux. | As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to <https://github.com/psevon/exceptions-and-raii-in-c>
This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly. |
2,891,766 | I typed this into Google, but I only found how-tos in C++.
How can I do it in C? | 2010/05/23 | [
"https://Stackoverflow.com/questions/2891766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335325/"
] | On Windows with **Microsoft Visual C++** (MSVC) there's `__try ... __except ...`, but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions. | In C we can't use try case to handle the error.
but if you can use Windows.h so you can:
```
#include <stdio.h>
#include <Windows.h>
#include <setjmp.h>
jmp_buf Buf;
NTAPI Error_Handler(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
printf("co loi roi ban oi.!!!\r\n");
longjmp(Buf, 1);
}
void main()
{
AddVectoredExceptionHandler(1, Error_Handler);
int x = 0;
printf("start main\r\n");
if (setjmp(Buf) == 0)
{
int y = 1 / x;
}
printf("end main\r\n");
}
``` |
41,060 | In [this question](https://chinese.stackexchange.com/q/34152/4709), we can clearly see the origin of 巨 is 矩, which is originally formed from 工 + 大 (corrupted into 矢). However, nowadays 巨 has lost the left hand side of 工, and so naturally the radical appears to be "匚".
Some dictionaries list 巨 as having `工`, and some as `匚` radical. For example, Hanping (using CC-EDICT) says it's 工, but Baidu (obviously not authoritative) and Pleco say it's 匚. Even some native speakers I talked to cannot agree whether it's 工 or 匚, and some say they were taught that it is 匚 very early in education.
Is there a fairly authoritative, widely accepted source on which radical 巨 falls under? | 2020/09/04 | [
"https://chinese.stackexchange.com/questions/41060",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/4709/"
] | Since radicals are dictionary headers, "what is the radical of X" is dependent on the dictionary you're looking at.
The most internationally-agreed-upon dictionary radicals for Chinese characters would be the [Kangxi Dictionary](https://en.wikipedia.org/wiki/Kangxi_Dictionary), which lists it under 「工」. Thankfully, most dictionaries have [sets of radicals which are derived from the Kangxi list](https://en.wikipedia.org/wiki/Kangxi_radical), and most dictionaries are in agreement with Kangxi's classification.
[](https://i.stack.imgur.com/6x19O.jpg)
---
My edition of Pleco doesn't list the radical as 「匚」.
[](https://i.stack.imgur.com/CQdBnm.png) | first of all, **don’t fixated on regular script (楷書)**, read and think on bronze script or seal script; please.
look at the [components semantic tree (部件樹):](http://humanum.arts.cuhk.edu.hk/Lexis/lexi-mf/search.php?word=%E7%9F%A9)
矩 is 大 + 人 + 工
[](https://i.stack.imgur.com/vAm7V.png)[](https://i.stack.imgur.com/AqF2t.png)
in the same page, the 漢語多功能字庫 stated clearly that
>
> 後來「大」形與「工」形分開,「大」(人形)的手部與「工」相連,形成「巨」字形
>
>
>
roughly, the “大” separated from “工”, only the “手” is connect to “工”; which make the character “巨”
[](https://i.stack.imgur.com/KGjfM.png)
this picture shown such separation :)
>
> 巨 has lost the left hand side of 工, and so naturally the radical appears to be "匚".
>
>
>
>
> Baidu (obviously not authoritative) and Pleco say it's 匚
>
>
>
only in regular script, that 巨 would appear belong to radical 匚 (radical 22), or 匸 (radical 23).
巨 in bronze script:
[](https://i.stack.imgur.com/IjUtU.png)
巨 in seal script:
[](https://i.stack.imgur.com/xDwvJ.png)
[](https://i.stack.imgur.com/1jjp5.png)
these three clearly shown the “工“ in the character “巨”
>
> Is there a fairly authoritative, widely accepted source on which radical 巨 falls under?
>
>
>
as droooze said, the authoritative dictionary is 康熙字典
another one using 540 radicals is 說文解字. you may guess it, “巨” is in volume 5, (工, radical 147)
[](https://i.stack.imgur.com/C3l38.jpg)
last, authoritative resources for etymology:
[漢語多功能字庫](http://humanum.arts.cuhk.edu.hk/Lexis/lexi-mf/)
[小學堂](https://xiaoxue.iis.sinica.edu.tw/)
use the 漢語多功能字庫 first, compare the “pictures” of different scripts. **read** the etymologies (形義通解); these’re experts’ explanations in one place.
imo, it’s enough for novices, even advance users.
if one need a bigger pictures of characters in particular scripts, shift to 小學堂
have fun :) |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | This happens because once you hit enter in the omnibox, the focus turns to the page. If you tried the same thing with `onkeydown`, the omnibox would change nothing, because as you said, it isn't a part of the document. One way to filter the omnibox's false event out would be to check that every `keyup` has a pair keydown.
```
<script>
var down = false;
document.addEventListener('keydown', function (){
down = true;
}, false);
document.addEventListener('keyup', function (){
if(down === true){
alert('It was from the page!');
}
else{
alert('Omnibox. Ignore it.');
}
down = false;
}, false);
</script>
```
[Demo.](http://pastehtml.com/raw/c9d7kwd2j.html#typeHereAndHitEnter)
Make your own HTML page and try it preferably, because PasteHTML.com stuffs it into an iframe. For it to work correctly there, click on the text first to give the iframe focus.
[Demo.](http://dl.dropbox.com/u/32930499/chromeOmniEnter.html#TypeHereAndHitEnter)
Remember to use your mouse to focus on the omnibox and type, not a keyboard shortcut. (That fires the onkeydown event, creating a false positive)
**Update:** As of Chrome 35, this doesn't happen anymore. I don't know which version they fixed it on, however. | You could filter for the keycode ...if that helps...13 is enter key
```
$(document).on('keyup', function(event){
if( parseInt(event.keyCode,10) !== 13 ){
alert("Hey");
}
});
``` |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | The solution for Chrome is simple: use `keypress` instead of `keyup`. This doesn't work in all cases (IE), so you may have to add a conditional to switch the type depending on the browser. However, this will solve your issue.
Note that looking for a specific keycode may negate your issue. Good luck. | You could filter for the keycode ...if that helps...13 is enter key
```
$(document).on('keyup', function(event){
if( parseInt(event.keyCode,10) !== 13 ){
alert("Hey");
}
});
``` |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | You could filter for the keycode ...if that helps...13 is enter key
```
$(document).on('keyup', function(event){
if( parseInt(event.keyCode,10) !== 13 ){
alert("Hey");
}
});
``` | A possible solution is to slightly delay the "keyup" event handler registration. This will skip the first "spurious" trigger that seems to happen in Chrome and Safari.
```
$(function() {
setTimeout(
function() {
console.log("Delayed event attachment");
$(document).bind('keyup', log);
}, 10);
});
function log(e) {
console.log(e.target.localName);
}
``` |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | This happens because once you hit enter in the omnibox, the focus turns to the page. If you tried the same thing with `onkeydown`, the omnibox would change nothing, because as you said, it isn't a part of the document. One way to filter the omnibox's false event out would be to check that every `keyup` has a pair keydown.
```
<script>
var down = false;
document.addEventListener('keydown', function (){
down = true;
}, false);
document.addEventListener('keyup', function (){
if(down === true){
alert('It was from the page!');
}
else{
alert('Omnibox. Ignore it.');
}
down = false;
}, false);
</script>
```
[Demo.](http://pastehtml.com/raw/c9d7kwd2j.html#typeHereAndHitEnter)
Make your own HTML page and try it preferably, because PasteHTML.com stuffs it into an iframe. For it to work correctly there, click on the text first to give the iframe focus.
[Demo.](http://dl.dropbox.com/u/32930499/chromeOmniEnter.html#TypeHereAndHitEnter)
Remember to use your mouse to focus on the omnibox and type, not a keyboard shortcut. (That fires the onkeydown event, creating a false positive)
**Update:** As of Chrome 35, this doesn't happen anymore. I don't know which version they fixed it on, however. | The solution for Chrome is simple: use `keypress` instead of `keyup`. This doesn't work in all cases (IE), so you may have to add a conditional to switch the type depending on the browser. However, this will solve your issue.
Note that looking for a specific keycode may negate your issue. Good luck. |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | This happens because once you hit enter in the omnibox, the focus turns to the page. If you tried the same thing with `onkeydown`, the omnibox would change nothing, because as you said, it isn't a part of the document. One way to filter the omnibox's false event out would be to check that every `keyup` has a pair keydown.
```
<script>
var down = false;
document.addEventListener('keydown', function (){
down = true;
}, false);
document.addEventListener('keyup', function (){
if(down === true){
alert('It was from the page!');
}
else{
alert('Omnibox. Ignore it.');
}
down = false;
}, false);
</script>
```
[Demo.](http://pastehtml.com/raw/c9d7kwd2j.html#typeHereAndHitEnter)
Make your own HTML page and try it preferably, because PasteHTML.com stuffs it into an iframe. For it to work correctly there, click on the text first to give the iframe focus.
[Demo.](http://dl.dropbox.com/u/32930499/chromeOmniEnter.html#TypeHereAndHitEnter)
Remember to use your mouse to focus on the omnibox and type, not a keyboard shortcut. (That fires the onkeydown event, creating a false positive)
**Update:** As of Chrome 35, this doesn't happen anymore. I don't know which version they fixed it on, however. | A possible solution is to slightly delay the "keyup" event handler registration. This will skip the first "spurious" trigger that seems to happen in Chrome and Safari.
```
$(function() {
setTimeout(
function() {
console.log("Delayed event attachment");
$(document).bind('keyup', log);
}, 10);
});
function log(e) {
console.log(e.target.localName);
}
``` |
11,991,062 | In chrome browser, when using this snippet:
```
$(document).on('keyup', function(){
alert("Hey");
});
```
Every time I press `enter` in the url bar (for example when I cut and paste the url of the page itself) the event listener fires.
Why does it happen?
**EDIT:**
It surprised me because url bar is not in `document` (maybe in `window`?) and firefox does not have this behaviour. When I look for `e.target`, Chrome Inspector shows `body`.
I thought this could be caused by event bubbling so I tried this:
```
$(document).on('keyup', function(e){
e.stopPropagation();
alert("Hey");
});
```
But it doesn't work.
How can I prevent it from being triggered? | 2012/08/16 | [
"https://Stackoverflow.com/questions/11991062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240338/"
] | The solution for Chrome is simple: use `keypress` instead of `keyup`. This doesn't work in all cases (IE), so you may have to add a conditional to switch the type depending on the browser. However, this will solve your issue.
Note that looking for a specific keycode may negate your issue. Good luck. | A possible solution is to slightly delay the "keyup" event handler registration. This will skip the first "spurious" trigger that seems to happen in Chrome and Safari.
```
$(function() {
setTimeout(
function() {
console.log("Delayed event attachment");
$(document).bind('keyup', log);
}, 10);
});
function log(e) {
console.log(e.target.localName);
}
``` |
30,961,582 | I am doing a project for Data Structures. I need to have the user input Strings into a doubly linked list using bufferedReader, where -1 terminates the stream and displays the list. Here is what I have so far. Every input I enter is throwing an exception and closing the Stream. Where am I going wrong?
```
public class Main {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int count;
String inputString;
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
DoublyLinkedList list = new DoublyLinkedList();//does this go in the loop?
while ((inputString = in.readLine()) != null)
{
System.out.println("Enter a String, then press enter.");
if (inputString.equals(-1) {
displayList();
} else {
list.insertFirst(inputString);
}
count++
in.close();
}
/**
*
*/
public static void displayList()
{
Node first = null;
Node node = first;
while(node != null){
node.displayNode();
System.out.println("Next Link: " + node.next);
node = node.next;
System.out.println();
}
}
}
```
Node Class:
```
public class Node {
public String dData; // data item
public Node next; // next node in list
public Node previous; // previous node in list
/**
*
* @param d
*/
public Node(String d) // constructor
{
dData = d;
}
public void displayNode() // display this link
{
System.out.print(dData + " ");
}
}// end class Node
```
Doubly-linked-list Class:
```
public class DoublyLinkedList {
public Node first; // ref to first item
/**
*
*/
public Node last; // ref to last item
public DoublyLinkedList() // constructor
{
first = null; // no items on list yet
last = null;
}
public boolean isEmpty() // true if no links
{
return first == null;
}
public void insertFirst(String dd) // insert at front of list
{
Node newNode = new Node(dd); // make new link
if (isEmpty()) // if empty list,
{
last = newNode; // newLink <-- last
} else {
first.previous = newNode; // newLink <-- old first
}
newNode.next = first; // newLink --> old first
first = newNode; // first --> newLink
}
public void insertLast(String dd) // insert at end of list
{
Node newNode = new Node(dd); // make new link
if (isEmpty()) // if empty list,
{
first = newNode; // first --> newLink
} else {
last.next = newNode; // old last --> newLink
newNode.previous = last; // old last <-- newLink
}
last = newNode; // newLink <-- last
}
public Node deleteFirst() // delete first link
{ // (assumes non-empty list)
Node temp = first;
if (first.next == null) // if only one item
{
last = null; // null <-- last
} else {
first.next.previous = null; // null <-- old next
}
first = first.next; // first --> old next
return temp;
}
public Node deleteLast() // delete last link
{ // (assumes non-empty list)
Node temp = last;
if (first.next == null) // if only one item
{
first = null; // first --> null
} else {
last.previous.next = null; // old previous --> null
}
last = last.previous; // old previous <-- last
return temp;
}
// insert dd just after key
public boolean insertAfter(String key, String dd) { // (assumes non-empty list)
Node current = first; // start at beginning
while (!current.dData.equals(key)) // until match is found,
{
current = current.next; // move to next link
if (current == null) {
return false; // didn’t find it
}
}
Node newNode = new Node(dd); // make new link
if (current == last) // if last link,
{
newNode.next = null; // newLink --> null
last = newNode; // newLink <-- last
} else // not last link,
{
newNode.next = current.next; // newLink --> old next
// newLink <-- old next
current.next.previous = newNode;
}
newNode.previous = current; // old current <-- newLink
current.next = newNode; // old current --> newLink
return true; // found it, did insertion
}
/**
*
* @param key
* @return
*/
public Node deleteKey(String key) // delete item w/ given key
{ // (assumes non-empty list)
Node current = first; // start at beginning
while (!current.dData.equals(key)) // until match is found,
{
current = current.next; // move to next link
if (current == null) {
return null; // didn’t find it
}
}
if (current == first) // found it; first item?
{
first = current.next; // first --> old next
} else // not first
// old previous --> old next
{
current.previous.next = current.next;
}
if (current == last) // last item?
{
last = current.previous; // old previous <-- last
} else // not last
// old previous <-- old next
{
current.next.previous = current.previous;
}
return current; // return value
}
public void displayForward() {
System.out.print("List(first-- > last): ");
Node current = first; // start at beginning
while (current != null) // until end of list,
{
current.displayNode(); // display data
current = current.next; // move to next link
}
System.out.println("");
}
public void displayBackward() {
System.out.print("List(last-- > first): ");
Node current = last; // start at end
while (current != null) // until start of list,
{
current.displayNode(); // display data
current = current.previous; // move to previous link
}
System.out.println("");
}
} // end class DoublyLinkedList
``` | 2015/06/21 | [
"https://Stackoverflow.com/questions/30961582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959353/"
] | Here you go, you had a bunch of mistakes,
1. Missing out a brace.
2. Closing the stream inside the loop. (How are you going to read input in the next iteration?)
3. `displayList` did not take any arguments (How will print the `LinkedList` if it doesn’t have any references to it?
4. Last but not the least, you didn’t even call displayList.
The `Node` and `LinkedList` classes are fine. I also made some other minor changes.
```
import java.io.*;
class Main {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException
{
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DoublyLinkedList list = new DoublyLinkedList();//does this go in the loop?
System.out.println("Enter a String, then press enter.");
String inputString = br.readLine();
while ((inputString != null) )
{
if (inputString.equals("-1"))
{
break;
}
else
{
list.insertFirst(inputString);
}
inputString =br.readLine();
count++;
}
displayList(list);
br.close();
}
public static void displayList(DoublyLinkedList d)
{
Node node = d.first;
while(node != null)
{
node.displayNode();
//System.out.println("Next Link: " + node.next);
node = node.next;
System.out.println();
}
}
}
``` | Your while should look like this:
```
System.out.println("Enter a String, then press enter.");
while (!(inputString = in.readLine()).equals("-1")) {
if (in.readLine().equals("")) { // filter empty lines, user probably hit enter twice
continue;
}
// add inputString to the list
System.out.println("Enter a String, then press enter.");
}
// print list
``` |
30,961,582 | I am doing a project for Data Structures. I need to have the user input Strings into a doubly linked list using bufferedReader, where -1 terminates the stream and displays the list. Here is what I have so far. Every input I enter is throwing an exception and closing the Stream. Where am I going wrong?
```
public class Main {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
int count;
String inputString;
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(reader);
DoublyLinkedList list = new DoublyLinkedList();//does this go in the loop?
while ((inputString = in.readLine()) != null)
{
System.out.println("Enter a String, then press enter.");
if (inputString.equals(-1) {
displayList();
} else {
list.insertFirst(inputString);
}
count++
in.close();
}
/**
*
*/
public static void displayList()
{
Node first = null;
Node node = first;
while(node != null){
node.displayNode();
System.out.println("Next Link: " + node.next);
node = node.next;
System.out.println();
}
}
}
```
Node Class:
```
public class Node {
public String dData; // data item
public Node next; // next node in list
public Node previous; // previous node in list
/**
*
* @param d
*/
public Node(String d) // constructor
{
dData = d;
}
public void displayNode() // display this link
{
System.out.print(dData + " ");
}
}// end class Node
```
Doubly-linked-list Class:
```
public class DoublyLinkedList {
public Node first; // ref to first item
/**
*
*/
public Node last; // ref to last item
public DoublyLinkedList() // constructor
{
first = null; // no items on list yet
last = null;
}
public boolean isEmpty() // true if no links
{
return first == null;
}
public void insertFirst(String dd) // insert at front of list
{
Node newNode = new Node(dd); // make new link
if (isEmpty()) // if empty list,
{
last = newNode; // newLink <-- last
} else {
first.previous = newNode; // newLink <-- old first
}
newNode.next = first; // newLink --> old first
first = newNode; // first --> newLink
}
public void insertLast(String dd) // insert at end of list
{
Node newNode = new Node(dd); // make new link
if (isEmpty()) // if empty list,
{
first = newNode; // first --> newLink
} else {
last.next = newNode; // old last --> newLink
newNode.previous = last; // old last <-- newLink
}
last = newNode; // newLink <-- last
}
public Node deleteFirst() // delete first link
{ // (assumes non-empty list)
Node temp = first;
if (first.next == null) // if only one item
{
last = null; // null <-- last
} else {
first.next.previous = null; // null <-- old next
}
first = first.next; // first --> old next
return temp;
}
public Node deleteLast() // delete last link
{ // (assumes non-empty list)
Node temp = last;
if (first.next == null) // if only one item
{
first = null; // first --> null
} else {
last.previous.next = null; // old previous --> null
}
last = last.previous; // old previous <-- last
return temp;
}
// insert dd just after key
public boolean insertAfter(String key, String dd) { // (assumes non-empty list)
Node current = first; // start at beginning
while (!current.dData.equals(key)) // until match is found,
{
current = current.next; // move to next link
if (current == null) {
return false; // didn’t find it
}
}
Node newNode = new Node(dd); // make new link
if (current == last) // if last link,
{
newNode.next = null; // newLink --> null
last = newNode; // newLink <-- last
} else // not last link,
{
newNode.next = current.next; // newLink --> old next
// newLink <-- old next
current.next.previous = newNode;
}
newNode.previous = current; // old current <-- newLink
current.next = newNode; // old current --> newLink
return true; // found it, did insertion
}
/**
*
* @param key
* @return
*/
public Node deleteKey(String key) // delete item w/ given key
{ // (assumes non-empty list)
Node current = first; // start at beginning
while (!current.dData.equals(key)) // until match is found,
{
current = current.next; // move to next link
if (current == null) {
return null; // didn’t find it
}
}
if (current == first) // found it; first item?
{
first = current.next; // first --> old next
} else // not first
// old previous --> old next
{
current.previous.next = current.next;
}
if (current == last) // last item?
{
last = current.previous; // old previous <-- last
} else // not last
// old previous <-- old next
{
current.next.previous = current.previous;
}
return current; // return value
}
public void displayForward() {
System.out.print("List(first-- > last): ");
Node current = first; // start at beginning
while (current != null) // until end of list,
{
current.displayNode(); // display data
current = current.next; // move to next link
}
System.out.println("");
}
public void displayBackward() {
System.out.print("List(last-- > first): ");
Node current = last; // start at end
while (current != null) // until start of list,
{
current.displayNode(); // display data
current = current.previous; // move to previous link
}
System.out.println("");
}
} // end class DoublyLinkedList
``` | 2015/06/21 | [
"https://Stackoverflow.com/questions/30961582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959353/"
] | Here you go, you had a bunch of mistakes,
1. Missing out a brace.
2. Closing the stream inside the loop. (How are you going to read input in the next iteration?)
3. `displayList` did not take any arguments (How will print the `LinkedList` if it doesn’t have any references to it?
4. Last but not the least, you didn’t even call displayList.
The `Node` and `LinkedList` classes are fine. I also made some other minor changes.
```
import java.io.*;
class Main {
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException
{
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DoublyLinkedList list = new DoublyLinkedList();//does this go in the loop?
System.out.println("Enter a String, then press enter.");
String inputString = br.readLine();
while ((inputString != null) )
{
if (inputString.equals("-1"))
{
break;
}
else
{
list.insertFirst(inputString);
}
inputString =br.readLine();
count++;
}
displayList(list);
br.close();
}
public static void displayList(DoublyLinkedList d)
{
Node node = d.first;
while(node != null)
{
node.displayNode();
//System.out.println("Next Link: " + node.next);
node = node.next;
System.out.println();
}
}
}
``` | You need to make 2 changes:
1. Change:
```
inputString.equals(-1) // A String cannot be equal to an integer.
```
to
```
inputString.equals("-1")
```
2. To break out of the loop if user enters `-1`, add a `break;` statement after `displayList()`.
### Then you asked
```
DoublyLinkedList list = new DoublyLinkedList();//does this go in the loop?
```
### Answer:
No. It doesn't enter a loop. Why do you think it does? It just calls the constructor of `class DoublyLinkedList` whici initializes `first` and `last` equal to `null` |
21,612,120 | I am trying to create 3 different .png images in R and save them to 3 different files - all at once.
The following code creates 1 image and then stops. Why not the other 2 images?
**“MatrixFunction”** is my own function that requires a df, column numbers, title. Each test type is also the name of a data frame.
Thank you.
```
testtype <- list("Grade4TopBottom", "Grade8TopBottom", "HSPATopBottom")
for(i in testtype){
mypath <- paste("testing", testtype)
png(mypath, width=1336, height=656)
MatrixFunction(get(i), 8:19, "Title")
dev.off()
}
``` | 2014/02/06 | [
"https://Stackoverflow.com/questions/21612120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3130947/"
] | You are overwriting your file over and over again. There's an obvious typo: `mypath <- paste("testing", i)`. In that case, you will create tree separate files instead of one. | Avoid `for`-loops in `R`. They are notorious slow.
If you create your method as a function, it is easier to check for errors and you can apply `lapply` or `sapply` to it,
```
testtype <- list("Grade4TopBottom", "Grade8TopBottom", "HSPATopBottom")
make.image <- function(n) {
obj <- mget(n, ifnotfound=NA)[[1]]
if (is.na(obj)) return(FALSE)
mypath <- paste("testing", n)
png(mypath, width=1336, height=656)
MatrixFunction(obj, 8:19, "Title")
dev.off()
return(TRUE)
}
# test:
make.image('Grade4TopBottom') # should return TRUE
make.image('Nope') # should return FALSE
sapply(testtype, make.image)
``` |
2,964,913 | I've made an MSBuild project that simply does an msbuild task with our solution file as parameter. I've defined a BeforeBuild target where I set some properties, and a Build target that executes the msbuild task.
I've confirmed that no errors occured when building the msbuild script in the command line console. However, when I use it in the msbuild task in my CCNET project, I keep getting the following error:
>
> C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
> (483,9): error: The OutputPath
> property is not set for project
> 'MyProject.msbuild'. Please check to
> make sure that you have specified a
> valid combination of Configuration and
> Platform for this project.
> Configuration='Debug'
> Platform='AnyCPU'. You may be seeing
> this message because you are trying to
> build a project without a solution
> file, and have specified a non-default
> Configuration or Platform that doesn't
> exist for this project.
>
>
>
I checked the build log and it seems that the error occurs during \_CheckForInvalidConfigurationAndPlatform. It wasn't even able to continue to my Build task! Since the script is only intended to build the solution under Debug/Release and AnyCPU as platform, I tried to add the following lines to my msbuild project:
```
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>.\bin\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>.\bin\Release\</OutputPath>
</PropertyGroup>
```
I could still build the project without errors in the command line, but CCNET is returning the same error mentioned above.
I don't understand why CCNET keeps getting the error, and I don't know what else to try.
Please help. | 2010/06/03 | [
"https://Stackoverflow.com/questions/2964913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357333/"
] | I found I had a similar situation (but using TeamCity as my CI environment). In my particular case, the project was a Command Line application. To solve it, I had to manually edit my project file.
Find these lines:
```
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
```
Change the second line to:
```
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
```
The find the other platform-specific lines in the project file and change them. Example:
```
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
```
becomes:
```
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
```
My suspicion is our build servers are 64-bit and the Console Application project type in Studio won't let you make the project fit an AnyCPU platform...
After these changes, TeamCity had no problem with my build script. | The answer from David helped me. But later I found the actual source of the issue for my computer. The **PLATFORM** environment variable is added on HP machines and does impact a number of different scenarios with Visual Studio.
Go into Environment Variables-> System Variables and remove the "PLATFORM" from the list.
See additional details here: <http://blogs.msdn.com/b/jnak/archive/2010/03/24/outputpath-property-is-not-set-for-project-error-when-building-a-windows-azure-cloud-service-in-vs-2010.aspx> |
516,817 | I am trying to make a tax calculator for an invoice template and the idea is to pass the variable `subcost` to the command `\taxcalc`.
```
\newcommand*{\taxcalc}[2]{%
\pgfmathparse{#1/(1.0-#2)-#1}%
\pgfmathprintnumber{\pgfmathresult}%
}
\newcommand{\vatTotal}{
& & & {\bf BTW 21\%} & {\bf {\bf \euro\taxcalc{subcost}{0.21}}}
\\*[1.5ex]
}
```
The problem is, no matter what I try to do to `subcost`, the compiler keeps complaining:
>
> Package PGF Math Error: Unknown function `subcost' (in 'subcost/(1.0-0.21)-subcost').'
>
>
>
It works perfectly for the following:
```
\newcommand*{\total}[1]{\FPdiv{\t}{\arabic{#1}}{1000}\formatNumber{\t}}
\newcommand{\subTotal}{
& & & {\bf Subtotaal (excl. btw)} & {\bf \euro\total{subcost}}
\\*[1.5ex]
}
```
Can anyone help me? I've been googling for hours now in order to find how to correctly pass variables to functions in this language but no matter what I try, it only works if I hardcode a number.
`subcost` is defined as follows:
```
\newcounter{hours} \newcounter{subhours}
\newcounter{cost} \newcounter{subcost}
\newcounter{vat}
``` | 2019/11/17 | [
"https://tex.stackexchange.com/questions/516817",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/201545/"
] | Use `alignat`, that makes pairs of “right aligned/left aligned” columns with no intervening space (that you can add yourself).
```latex
\documentclass{article}
\usepackage{amsmath}
\newcommand{\ceilset}{\mathsf{Ceil}}
\newcommand{\ceilf}[1]{\lceil #1 \rceil}
\begin{document}
Define the following two functions
\begin{alignat*}{3}
&\wedge \colon \ceilset \times \ceilset \longrightarrow \ceilset
&\qquad\text{and}\qquad &&
\vee \colon \ceilset \times \ceilset \longrightarrow \ceilset \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset$ by the assignments}
&\wedge \colon (A, B) \longmapsto A \cap B
&\qquad\text{and}\qquad &&
\vee \colon (A, B) \longmapsto \ceilf{A \cup B} \makebox[0pt][l]{.}
\end{alignat*}
These functions will be used shortly.
\end{document}
```
I set the period hanging right, so the symbols are aligned.
[](https://i.stack.imgur.com/yesxD.png)
You should also considering aligning at the wedge and vee:
```latex
\documentclass{article}
\usepackage{amsmath}
\newcommand{\ceilset}{\mathsf{Ceil}}
\newcommand{\ceilf}[1]{\lceil #1 \rceil}
\begin{document}
Define the following two functions
\begin{alignat*}{2}
&\wedge \colon \ceilset \times \ceilset \longrightarrow \ceilset
&\qquad\text{and}\qquad &
\vee \colon \ceilset \times \ceilset \longrightarrow \ceilset \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset$ by the assignments}
&\wedge \colon (A, B) \longmapsto A \cap B
&\qquad\text{and}\qquad &
\vee \colon (A, B) \longmapsto \ceilf{A \cup B} .
\end{alignat*}
These functions will be used shortly.
\end{document}
```
[](https://i.stack.imgur.com/jiyzE.png)
Notes.
1. I only left the package `amsmath` that's essential for the code.
2. The colon after “functions” is wrong. | Define `\ceilset` and `\ceilif` according to your needs and try the following
```
\documentclass[paper=letter,twoside,fontsize=12pt,leqno]{scrbook}
\usepackage{mathtools}
\begin{document}
\noindent Define the following two functions:
\begin{align*}
&\wedge \colon \ceilset \times \ceilset \longrightarrow \ceilset & & \text{and} & \vee \colon \ceilset \times \ceilset \longrightarrow \ceilset & \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset $ by the assignments}
&\wedge \colon (A, B) \longmapsto A \cap B && \text{and} & \vee \colon (A, B) \longmapsto \ceilf{A \cup B} &\text{.}
\end{align*}
\end{document}
``` |
516,817 | I am trying to make a tax calculator for an invoice template and the idea is to pass the variable `subcost` to the command `\taxcalc`.
```
\newcommand*{\taxcalc}[2]{%
\pgfmathparse{#1/(1.0-#2)-#1}%
\pgfmathprintnumber{\pgfmathresult}%
}
\newcommand{\vatTotal}{
& & & {\bf BTW 21\%} & {\bf {\bf \euro\taxcalc{subcost}{0.21}}}
\\*[1.5ex]
}
```
The problem is, no matter what I try to do to `subcost`, the compiler keeps complaining:
>
> Package PGF Math Error: Unknown function `subcost' (in 'subcost/(1.0-0.21)-subcost').'
>
>
>
It works perfectly for the following:
```
\newcommand*{\total}[1]{\FPdiv{\t}{\arabic{#1}}{1000}\formatNumber{\t}}
\newcommand{\subTotal}{
& & & {\bf Subtotaal (excl. btw)} & {\bf \euro\total{subcost}}
\\*[1.5ex]
}
```
Can anyone help me? I've been googling for hours now in order to find how to correctly pass variables to functions in this language but no matter what I try, it only works if I hardcode a number.
`subcost` is defined as follows:
```
\newcounter{hours} \newcounter{subhours}
\newcounter{cost} \newcounter{subcost}
\newcounter{vat}
``` | 2019/11/17 | [
"https://tex.stackexchange.com/questions/516817",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/201545/"
] | Use `alignat`, that makes pairs of “right aligned/left aligned” columns with no intervening space (that you can add yourself).
```latex
\documentclass{article}
\usepackage{amsmath}
\newcommand{\ceilset}{\mathsf{Ceil}}
\newcommand{\ceilf}[1]{\lceil #1 \rceil}
\begin{document}
Define the following two functions
\begin{alignat*}{3}
&\wedge \colon \ceilset \times \ceilset \longrightarrow \ceilset
&\qquad\text{and}\qquad &&
\vee \colon \ceilset \times \ceilset \longrightarrow \ceilset \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset$ by the assignments}
&\wedge \colon (A, B) \longmapsto A \cap B
&\qquad\text{and}\qquad &&
\vee \colon (A, B) \longmapsto \ceilf{A \cup B} \makebox[0pt][l]{.}
\end{alignat*}
These functions will be used shortly.
\end{document}
```
I set the period hanging right, so the symbols are aligned.
[](https://i.stack.imgur.com/yesxD.png)
You should also considering aligning at the wedge and vee:
```latex
\documentclass{article}
\usepackage{amsmath}
\newcommand{\ceilset}{\mathsf{Ceil}}
\newcommand{\ceilf}[1]{\lceil #1 \rceil}
\begin{document}
Define the following two functions
\begin{alignat*}{2}
&\wedge \colon \ceilset \times \ceilset \longrightarrow \ceilset
&\qquad\text{and}\qquad &
\vee \colon \ceilset \times \ceilset \longrightarrow \ceilset \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset$ by the assignments}
&\wedge \colon (A, B) \longmapsto A \cap B
&\qquad\text{and}\qquad &
\vee \colon (A, B) \longmapsto \ceilf{A \cup B} .
\end{alignat*}
These functions will be used shortly.
\end{document}
```
[](https://i.stack.imgur.com/jiyzE.png)
Notes.
1. I only left the package `amsmath` that's essential for the code.
2. The colon after “functions” is wrong. | If you also want to align the operators:
```
\documentclass[paper=letter,twoside,fontsize=12pt,leqno]{scrbook}
\usepackage{mathtools}
\usepackage{showframe}
\let\ceilset=\relax
\let\ceilf=\relax
\begin{document}
Define the following two functions:
\begin{align*}
&\wedge \colon \ceilset \times \ceilset &&\longrightarrow \ceilset && \text{and} && \vee \colon \ceilset \times \ceilset &&\longrightarrow \\
\intertext{for each $(A, B) \in \ceilset \times \ceilset$ by the assignments}
&\wedge \colon (A, B) &&\longmapsto A \cap B && \text{and} && \vee \colon (A, B) &&\longmapsto \ceilf{A \cup B} \quad\text{.} \\
\end{align*}
\end{document}
```
[](https://i.stack.imgur.com/MFGhA.png) |
635,697 | Does the union of intervals form a set? I mean the union of $(0,1)$ and $(1,2)$ is a set and if yes, then how? | 2014/01/12 | [
"https://math.stackexchange.com/questions/635697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | A set is a collection of elements. In this case, all elements are real numbers.
Any interval $(a,b)$ *is a set* (the set of those real numbers $x$ which satisfy $a<x<b$.)
The union of any two sets is still a collection of elements, i.e. **is a set**. | It is because each interval is set and union of two sets is set. |
635,697 | Does the union of intervals form a set? I mean the union of $(0,1)$ and $(1,2)$ is a set and if yes, then how? | 2014/01/12 | [
"https://math.stackexchange.com/questions/635697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | A set is just a collection of elements, therefore, you have a set, since you have a collection of real numbers. | It is because each interval is set and union of two sets is set. |
635,697 | Does the union of intervals form a set? I mean the union of $(0,1)$ and $(1,2)$ is a set and if yes, then how? | 2014/01/12 | [
"https://math.stackexchange.com/questions/635697",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | As "explicit" sets these intervals are written:
$$(0,1)=\{x:0<x<1,\space x \in \mathbb{R}\}, (1,2)=\{x:1<x<2,\space x \in \mathbb{R}\}$$
So the union is:
$$(0,1) \cup (1,2)=\{x:0<x<2,\space x\neq 1,\space x \in \mathbb{R}\}$$ | It is because each interval is set and union of two sets is set. |
19,564,670 | I can generate html from a file on the fly and return like this:
```
from django.http import HttpResponse
response = HttpResponse(mimetype="text/html")
content = "".join(open(filename).readlines())
response._set_content(content)
return response
```
but is there a better, built in way, in Django 1.5? | 2013/10/24 | [
"https://Stackoverflow.com/questions/19564670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210801/"
] | The following code is a better method for making a file available for download or viewing, short of streaming (which has some downsides, such as not having a known size).
```
from django.http import HttpResponse
def serve_file(filename):
response = HttpResponse(mimetype="text/html")
for line in open(filename):
response.write(line)
return response
``` | Django is an MVC framework (well, arguably it's MTV, but the basic principle is similar), so you should be [creating templates](https://docs.djangoproject.com/en/1.5/ref/templates/) for that kind of task. |
19,564,670 | I can generate html from a file on the fly and return like this:
```
from django.http import HttpResponse
response = HttpResponse(mimetype="text/html")
content = "".join(open(filename).readlines())
response._set_content(content)
return response
```
but is there a better, built in way, in Django 1.5? | 2013/10/24 | [
"https://Stackoverflow.com/questions/19564670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/210801/"
] | The following code is a better method for making a file available for download or viewing, short of streaming (which has some downsides, such as not having a known size).
```
from django.http import HttpResponse
def serve_file(filename):
response = HttpResponse(mimetype="text/html")
for line in open(filename):
response.write(line)
return response
``` | You should configure your webserver to [serve static files](https://docs.djangoproject.com/en/1.5/howto/static-files/deployment/) directly.
If you absolutely have to do it through django you could use [static views](https://docs.djangoproject.com/en/1.5/howto/static-files/). |
23,323,637 | Want to start function if user clicked on `id^="mark_paid_used"` or value changed in class `paid_used_amount_for_below_header_debit`
such codes works
```
$('[id^="mark_paid_used"]').click(function(){
//do something
});
```
.
```
$('.paid_used_amount_for_below_header_debit').change(function() {
//do the same as above
});
```
but this does not work
```
$('.paid_used_amount_for_below_header_debit').change || $('[id^="mark_paid_used"]').click(function() {
});
```
What would be correct code? | 2014/04/27 | [
"https://Stackoverflow.com/questions/23323637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118559/"
] | You can create a function, As I have in example. After that you can pass it to event handler
```
var yourFunction = function () {
//do something
};
$('[id^="mark_paid_used"]').click(yourFunction);
$('.paid_used_amount_for_below_header_debit').change(yourFunction);
``` | Call a function then add it as an event
```
var getfunction = function(){
};
$('[id^="mark_paid_used"]').click(getfunction);
$('.paid_used_amount_for_below_header_debit').change(getfunction);
``` |
23,323,637 | Want to start function if user clicked on `id^="mark_paid_used"` or value changed in class `paid_used_amount_for_below_header_debit`
such codes works
```
$('[id^="mark_paid_used"]').click(function(){
//do something
});
```
.
```
$('.paid_used_amount_for_below_header_debit').change(function() {
//do the same as above
});
```
but this does not work
```
$('.paid_used_amount_for_below_header_debit').change || $('[id^="mark_paid_used"]').click(function() {
});
```
What would be correct code? | 2014/04/27 | [
"https://Stackoverflow.com/questions/23323637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118559/"
] | You can create a function, As I have in example. After that you can pass it to event handler
```
var yourFunction = function () {
//do something
};
$('[id^="mark_paid_used"]').click(yourFunction);
$('.paid_used_amount_for_below_header_debit').change(yourFunction);
``` | Define a function, and execute it when something happens.
```
function anyname(){
// your code
}
$('.paid_used_amount_for_below_header_debit').change(function(){anyname();});
$('[id^="mark_paid_used"]').click(function(){anyname()});
``` |
23,323,637 | Want to start function if user clicked on `id^="mark_paid_used"` or value changed in class `paid_used_amount_for_below_header_debit`
such codes works
```
$('[id^="mark_paid_used"]').click(function(){
//do something
});
```
.
```
$('.paid_used_amount_for_below_header_debit').change(function() {
//do the same as above
});
```
but this does not work
```
$('.paid_used_amount_for_below_header_debit').change || $('[id^="mark_paid_used"]').click(function() {
});
```
What would be correct code? | 2014/04/27 | [
"https://Stackoverflow.com/questions/23323637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2118559/"
] | Call a function then add it as an event
```
var getfunction = function(){
};
$('[id^="mark_paid_used"]').click(getfunction);
$('.paid_used_amount_for_below_header_debit').change(getfunction);
``` | Define a function, and execute it when something happens.
```
function anyname(){
// your code
}
$('.paid_used_amount_for_below_header_debit').change(function(){anyname();});
$('[id^="mark_paid_used"]').click(function(){anyname()});
``` |
51,105,311 | I have a webpage with rows of 'cards' which each contain an img, some text below, and an link styled as a button. The text varies in length but I want each card to be of equal length and the buttons to be aligned toward the bottom of each card.
```
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-lg-3 col-md-12 mb-4">
<!--Card-->
<div class="card">
<!--Card image-->
<div class="view overlay">
<img src="img/bb/didyouknow.jpg" class="card-img-top" alt="">
<a href="didyouknow.html" onclick="trackOutboundLink(this, 'Internal Links', 'Did You Know'); return false;">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Did you know?</h4>
<!--Text-->
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="didyouknow.html" class="btn btn-primary" onclick="trackOutboundLink(this, 'Internal Links', 'Did You Know'); return false;">More</a>
<!--<button id="didyouknow" type="button" onclick="window.open('didyouknow.html','_self'); trackOutboundLink(this, 'Internal Links', 'Did You Know'); return false;" class="btn btn-primary">More</button>-->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-lg-3 col-md-6 mb-4">
<!--Card-->
<div class="card">
<!--Card image-->
<div class="view overlay">
<img src="img/bb/tipsntricks.jpg" class="card-img-top" alt="">
<a href="staysmokefree.html" onclick="trackOutboundLink(this, 'Internal Links', 'Stay Smoke Free'); return false;">
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Stay smoke free</h4>
<!--Text-->
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content. Lots of text. Lots of text. Lots of text. Lots of text. Lots of text.</p>
<a href="staysmokefree.html" class="btn btn-primary" onclick="trackOutboundLink(this, 'Internal Links', 'Stay Smoke Free'); return false;">More</a>
<!--<button type="button" onclick="window.open('staysmokefree.html','_self');" class="btn btn-primary">More</button>-->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid column-->
</div>
<!--Grid row-->
```
This CSS makes each card the same height by making the cards height fill the parent div:
```
.row {
display: flex; /* equal height of the children */
position:relative;
}
.card{
height: 100%;/* fill parent div height*/
}
```
The problem I have is that the buttons are not horizontally aligned because they just sit below where the text finishes. If I do this:
```
.card-body a {
position: absolute;
bottom: 10px;
}
```
the buttons are aligned at the bottom of the cards but they overlap and cover the text. How can I get the buttons to appear below the text and align across cards?
EDIT: I've made a jsfiddle that demonstrates the problem: <https://jsfiddle.net/captncanary/m156dqeu/> | 2018/06/29 | [
"https://Stackoverflow.com/questions/51105311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3410340/"
] | You can just pass the column names as parameters to the function:
```
q)tab:([]x:1 2 3;y:4 5 6)
q)func:{[x;y] x+y}
q)
q)select res:func[x;y]from tab
res
---
5
7
9
```
Alternatively you could use functional form to turn that query into a function:
```
q){?[x;();0b;enlist[`res]!enlist(`func;y;z)]}[tab;`x;`y]
res
---
5
7
9
``` | Since `+` is overloaded to work with both atom and list , `res:func[x;y]` will work perfectly fine; however in cases when a dyadic function only accepts the arguments as atoms rather than lists then `each-both` will do the trick:
```
q)select res:func'[x;y] from tab // using each-both func'[x;y]
res
---
5
7
9
```
e.g To select as many charecters as `c` from column `s`
```
tab2:([] c:1 2 3;s:("123";"1234";"123456"))
q)update res:#'[c;s] from tab2 //func'[x;y]
c s res
-----------------------
1 "123" enlist "1"
2 "1234" "12"
3 "123456" "123"
``` |
14,065,106 | I can't seem to figure out how to take the year from say `Rogue Assassin 2007` and return:
```
moviename = "Rogue Assassin" 'Whitespace doesn't matter
movieyear = "2007" 'Whitespace doesn't matter
```
However, I can't get it to work. I have been trying the following:
```
If System.Text.RegularExpressions.Regex.IsMatch(fn, "[0-9][0-9][0-9][0-9]") Then 'Is this right?
Dim mtemp As String() = fn.Split(" ") 'Movie temp array
myear(0) = mtemp.Last 'Attempting to set year to the last split
For Each z As String In mtemp 'Adding the other elements in mtemp together to remake the title
If z IsNot mtemp.Last Then
mtitle(0) = z & " " 'Movie title
Else
Exit For
End If
Next
...
Else
...
End If
```
Any help greatly appreciated! | 2012/12/28 | [
"https://Stackoverflow.com/questions/14065106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1808539/"
] | You could get the name of the variable inside the function ("str"), but you cannot get the name of the variable that was passed into the function unless you pass it in as a second parameter.
It doesn't make sense to get the name of the variable passed to the function because there may not have even been a variable if a literal was passed such as `AddVariable("test variable")`. | You don't need parameter name (possible from reflection) but rather a variable name that has been passed as a parameter. AFAIK, for all practical purpose, this is not possible for the code within the function.
On the other hand, it's as such possible to do the code analysis of all assemblies loaded in the app-domain and find all invocations to your method and then do the stack-walk to determine possible invocation so that you may able to nail the variable name in the calling method (again if there can be many invocations in calling method, making it difficult to guess the variable name and you have to then rely on IL offset etc) but its just too convoluted.
Perhaps, you can state the reason for such requirements, there can be some alternative. For example, you can get and log stack trace within your method code that can be used for say trouble-shooting. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Since IIS7 uses .net from the top down there would not be any performance overhead of using an HttpModule, In fact there are several Managed HttpModules that are always used on every request. When the BeginRequest event is fired, the SessionStateModule may not have been added to the Modules collection, so if you try to handle the request during this event no session state info will be available. Setting the HttpContext.Handler property will initialize the session state if the requested handler needs it, so you can just set the handler to your fancy 404 page that implements IRequiresSessionState. The code below should do the trick, though you may need to write a different implementation for the IsMissing() method:
```
using System.Web;
using System.Web.UI;
class Smart404Module : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.BeginRequest += new System.EventHandler(DoMapping);
}
void DoMapping(object sender, System.EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (IsMissing(app.Context))
app.Context.Handler = PageParser.GetCompiledPageInstance(
"~/404.aspx", app.Request.MapPath("~/404.aspx"), app.Context);
}
bool IsMissing(HttpContext context)
{
string path = context.Request.MapPath(context.Request.Url.AbsolutePath);
if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path)
&& System.IO.File.Exists(System.IO.Path.Combine(path, "default.aspx"))))
return true;
return false;
}
}
```
Edit: I added an implementation of IsMissing()
Note: On IIS7, The session state module does not run globally by default. There are two options: Enable the session state module for all requests (see my comment above regarding running managed modules for all request types), or you could use reflection to access internal members inside System.Web.dll. | Just a guess: the handler specified in IIS7's %windir%\system32\inetsrv\config\applicationhost.config which is handling your request is not allowing the POST verb to get through at all, and it is evaluating that rule before determining whether the URL doesn't exist. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Microsoft released a hotfix for this :
[<http://support.microsoft.com/default.aspx/kb/956578>](http://support.microsoft.com/default.aspx/kb/956578) | Just a guess: the handler specified in IIS7's %windir%\system32\inetsrv\config\applicationhost.config which is handling your request is not allowing the POST verb to get through at all, and it is evaluating that rule before determining whether the URL doesn't exist. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | The problem in IIS 7 of post variables not being passed through to custom error handlers is fixed in service pack 2 for Vista. Haven't tried it on Windows Server but I'm sure it will be fixed there too. | Just a guess: the handler specified in IIS7's %windir%\system32\inetsrv\config\applicationhost.config which is handling your request is not allowing the POST verb to get through at all, and it is evaluating that rule before determining whether the URL doesn't exist. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Since IIS7 uses .net from the top down there would not be any performance overhead of using an HttpModule, In fact there are several Managed HttpModules that are always used on every request. When the BeginRequest event is fired, the SessionStateModule may not have been added to the Modules collection, so if you try to handle the request during this event no session state info will be available. Setting the HttpContext.Handler property will initialize the session state if the requested handler needs it, so you can just set the handler to your fancy 404 page that implements IRequiresSessionState. The code below should do the trick, though you may need to write a different implementation for the IsMissing() method:
```
using System.Web;
using System.Web.UI;
class Smart404Module : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.BeginRequest += new System.EventHandler(DoMapping);
}
void DoMapping(object sender, System.EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (IsMissing(app.Context))
app.Context.Handler = PageParser.GetCompiledPageInstance(
"~/404.aspx", app.Request.MapPath("~/404.aspx"), app.Context);
}
bool IsMissing(HttpContext context)
{
string path = context.Request.MapPath(context.Request.Url.AbsolutePath);
if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path)
&& System.IO.File.Exists(System.IO.Path.Combine(path, "default.aspx"))))
return true;
return false;
}
}
```
Edit: I added an implementation of IsMissing()
Note: On IIS7, The session state module does not run globally by default. There are two options: Enable the session state module for all requests (see my comment above regarding running managed modules for all request types), or you could use reflection to access internal members inside System.Web.dll. | Yes, I would definitely recommend URL rewriting (using Microsoft's IIS7 one or one of the many alternatives). This is specifically designed for providing friendly URLs, whereas error documents are a last-ditch backstop for failures, which tends to munge the incoming data so it may not be what you expect. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Microsoft released a hotfix for this :
[<http://support.microsoft.com/default.aspx/kb/956578>](http://support.microsoft.com/default.aspx/kb/956578) | Since IIS7 uses .net from the top down there would not be any performance overhead of using an HttpModule, In fact there are several Managed HttpModules that are always used on every request. When the BeginRequest event is fired, the SessionStateModule may not have been added to the Modules collection, so if you try to handle the request during this event no session state info will be available. Setting the HttpContext.Handler property will initialize the session state if the requested handler needs it, so you can just set the handler to your fancy 404 page that implements IRequiresSessionState. The code below should do the trick, though you may need to write a different implementation for the IsMissing() method:
```
using System.Web;
using System.Web.UI;
class Smart404Module : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.BeginRequest += new System.EventHandler(DoMapping);
}
void DoMapping(object sender, System.EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (IsMissing(app.Context))
app.Context.Handler = PageParser.GetCompiledPageInstance(
"~/404.aspx", app.Request.MapPath("~/404.aspx"), app.Context);
}
bool IsMissing(HttpContext context)
{
string path = context.Request.MapPath(context.Request.Url.AbsolutePath);
if (System.IO.File.Exists(path) || (System.IO.Directory.Exists(path)
&& System.IO.File.Exists(System.IO.Path.Combine(path, "default.aspx"))))
return true;
return false;
}
}
```
Edit: I added an implementation of IsMissing()
Note: On IIS7, The session state module does not run globally by default. There are two options: Enable the session state module for all requests (see my comment above regarding running managed modules for all request types), or you could use reflection to access internal members inside System.Web.dll. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Microsoft released a hotfix for this :
[<http://support.microsoft.com/default.aspx/kb/956578>](http://support.microsoft.com/default.aspx/kb/956578) | Yes, I would definitely recommend URL rewriting (using Microsoft's IIS7 one or one of the many alternatives). This is specifically designed for providing friendly URLs, whereas error documents are a last-ditch backstop for failures, which tends to munge the incoming data so it may not be what you expect. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | The problem in IIS 7 of post variables not being passed through to custom error handlers is fixed in service pack 2 for Vista. Haven't tried it on Windows Server but I'm sure it will be fixed there too. | Yes, I would definitely recommend URL rewriting (using Microsoft's IIS7 one or one of the many alternatives). This is specifically designed for providing friendly URLs, whereas error documents are a last-ditch backstop for failures, which tends to munge the incoming data so it may not be what you expect. |
102,846 | OK, this might sound a bit confusing and complicated, so bear with me.
We've written a framework that allows us to define friendly URLs. If you surf to any arbitrary URL, IIS tries to display a 404 error (or, in some cases, 403;14 or 405). However, IIS is set up so that anything directed to those specific errors is sent to an .aspx file. This allows us to implement an HttpHandler to handle the request and do stuff, which involves finding the an associated template and then executing whatever's associated with it.
Now, this all works in IIS 5 and 6 and, to an extent, on IIS7 - but for one catch, which happens when you post a form.
See, when you post a form to a non-existent URL, IIS says "ah, but that url doesn't exist" and throws a 405 "method not allowed" error. Since we're telling IIS to redirect those errors to our .aspx page and therefore handling it with our HttpHandler, this normally isn't a problem. But as of IIS7, all POST information has gone missing after being redirected to the 405. And so you can no longer do the most trivial of things involving forms.
To solve this we've tried using a HttpModule, which preserves POST data but appears to not have an initialized Session at the right time (when it's needed). We also tried using a HttpModule for all requests, not just the missing requests that hit 404/403;14/405, but that means stuff like images, css, js etc are being handled by .NET code, which is terribly inefficient.
Which brings me to the actual question: has anyone ever encountered this, and does anyone have any advice or know what to do to get things working again? So far someone has suggested using Microsoft's own [URL Rewriting module](http://learn.iis.net/page.aspx/460/using-url-rewrite-module/). Would this help solve our problem?
Thanks. | 2008/09/19 | [
"https://Stackoverflow.com/questions/102846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16308/"
] | Microsoft released a hotfix for this :
[<http://support.microsoft.com/default.aspx/kb/956578>](http://support.microsoft.com/default.aspx/kb/956578) | The problem in IIS 7 of post variables not being passed through to custom error handlers is fixed in service pack 2 for Vista. Haven't tried it on Windows Server but I'm sure it will be fixed there too. |
49,326,164 | I am trying to work with jupyter notebook, but when I open a file I receive the following error:
The kernel has died, and the automatic restart has failed. It is possible the kernel cannot be restarted. If you are not able to restart the kernel, you will still be able to save the notebook, but running code will no longer work until the notebook is reopened.
In the CMD I see the following:
```
(base) C:\Users\Dan Eran>jupyter notebook
[W 19:05:33.006 NotebookApp] Error loading server extension jupyterlab
Traceback (most recent call last):
File "C:\Users\Dan Eran\AppData\Roaming\Python\Python36\site-packages\notebook\notebookapp.py", line 1451, in init_server_extensions
mod = importlib.import_module(modulename)
File "C:\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'jupyterlab'
[I 19:05:33.122 NotebookApp] Serving notebooks from local directory: C:\Users\Dan Eran
[I 19:05:33.122 NotebookApp] 0 active kernels
[I 19:05:33.122 NotebookApp] The Jupyter Notebook is running at:
[I 19:05:33.122 NotebookApp] http://localhost:8888/?token=99a355c23c6617857e387f53d0af607ae26b89c20598336e
[I 19:05:33.122 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 19:05:33.122 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://localhost:8888/?token=99a355c23c6617857e387f53d0af607ae26b89c20598336e
[I 19:05:33.247 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[I 19:05:42.699 NotebookApp] Creating new notebook in
[I 19:05:43.563 NotebookApp] Kernel started: 1433cbbf-f4b9-4dd3-be19-e91d7ee3d82f
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "C:\Anaconda3\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
from .connect import *
File "C:\Anaconda3\lib\site-packages\ipykernel\connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
ModuleNotFoundError: No module named 'IPython'
[I 19:05:46.555 NotebookApp] KernelRestarter: restarting kernel (1/5), new random ports
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "C:\Anaconda3\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
from .connect import *
File "C:\Anaconda3\lib\site-packages\ipykernel\connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
ModuleNotFoundError: No module named 'IPython'
[I 19:05:49.591 NotebookApp] KernelRestarter: restarting kernel (2/5), new random ports
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "C:\Anaconda3\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
from .connect import *
File "C:\Anaconda3\lib\site-packages\ipykernel\connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
ModuleNotFoundError: No module named 'IPython'
[I 19:05:52.620 NotebookApp] KernelRestarter: restarting kernel (3/5), new random ports
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "C:\Anaconda3\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
from .connect import *
File "C:\Anaconda3\lib\site-packages\ipykernel\connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
ModuleNotFoundError: No module named 'IPython'
[W 19:05:53.595 NotebookApp] Timeout waiting for kernel_info reply from 1433cbbf-f4b9-4dd3-be19-e91d7ee3d82f
[I 19:05:55.632 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports
WARNING:root:kernel 1433cbbf-f4b9-4dd3-be19-e91d7ee3d82f restarted
Traceback (most recent call last):
File "C:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
from ipykernel import kernelapp as app
File "C:\Anaconda3\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
from .connect import *
File "C:\Anaconda3\lib\site-packages\ipykernel\connect.py", line 13, in <module>
from IPython.core.profiledir import ProfileDir
ModuleNotFoundError: No module named 'IPython'
[W 19:05:58.671 NotebookApp] KernelRestarter: restart failed
[W 19:05:58.671 NotebookApp] Kernel 1433cbbf-f4b9-4dd3-be19-e91d7ee3d82f died, removing from map.
ERROR:root:kernel 1433cbbf-f4b9-4dd3-be19-e91d7ee3d82f restarted failed!
[W 19:05:58.705 NotebookApp] 410 DELETE /api/sessions/fd456273-adb3-48cd-92f8-d531c9b8f7a8 (::1): Kernel deleted before session
[W 19:05:58.709 NotebookApp] Kernel deleted before session
[W 19:05:58.709 NotebookApp] 410 DELETE /api/sessions/fd456273-adb3-48cd-92f8-d531c9b8f7a8 (::1) 4.00ms referer=http://localhost:8888/notebooks/Untitled11.ipynb?kernel_name=python3
```
I have tried to uninstall and then reinstall some modules. However, I was not able to solve the problem. any ideas? THANKS!! | 2018/03/16 | [
"https://Stackoverflow.com/questions/49326164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9351684/"
] | It seems like there is something wrong with the jupyter installation. I recommend upgrading anaconda to v5, which should install jupyter by default(not sure if that is the case for v3, which is what seems to be used in this case). Try installing the missing modules using conda install if you want to stick with conda v3.
```
conda install -c conda-forge jupyterlab
conda install -c anaconda ipython
```
[IPython](https://anaconda.org/anaconda/ipython), [Jupyterlab](https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html) | I got the same error. Its because we haven't given administrator privilege. You have to install anaconda using administrator. Or run the app as administrator.
Just right click on jupyter or spyder then select run as administrator.
Or while installing anaconda select install as administrator |
38,980 | I have a Dell PowerEdge 2850 with a PERC 4 controller and SCSI drives. I need to clone that to a PE2950 with a PERC6i with SAS drives. I've used the DKMS package along with the latest driver on Dells website to create a driver disk and successfully installed by hand so I know that it will install but I need a good suggestion for cloning options. I've tried clonezilla but it does not recognize the hard drives and I'm no expert in debian based distros so I'm unable to manipulate it.
Does anyone know of a reliable way to clone this server? I imagine that if I can find a method to transfer the image then I will install the SAS driver on the source box before cloning it and it should be able to boot to the destination box.
Thanks all! | 2009/07/10 | [
"https://serverfault.com/questions/38980",
"https://serverfault.com",
"https://serverfault.com/users/7067/"
] | I've used SystemImager to move RHEL4 from 2850 to 2950.
RHEL4 did not recognize the drive controller on the 2950, so I booted using a rescuse disk and re-created the initrd. | If you've got the new box partitioned and setup the way you want it, and just need to get the "soul" of the old box over, you've got nothing to lose by trying a quick and dirty method.
I'd boot the RHEL 4.3 rescue CD on the new box using the driver disk and verify that you've got working network drivers and an IP address. Once you do that, make a directory somewhere on the new box in a mount that has enough space to accept the old box's data, cd to it, and do a:
```
nc -l -p 8989 | tar x
```
On the old box, do a:
```
tar cf - /* | nc (receiving host ip address) 8989
```
That'll ship the contents of the source box over to a directory on the destination box over the network.
In theory, you should be able to use diff to find the differences between /etc and other folders between the source box and destination box and "combine" them together into one box.
Really, you can probably get away with untarring the old box right over top of the root of the new box, since the new kernel and modules will be in a different path and shouldn't be overwritten. If you do that, you might put a "--exclude=boot" on the sending tar command line, like so, to keep the grub configuration from being overwritten on the new box:
```
tar cf - --exclude=boot /* | nc (receiving host ip address) 8989
``` |
38,980 | I have a Dell PowerEdge 2850 with a PERC 4 controller and SCSI drives. I need to clone that to a PE2950 with a PERC6i with SAS drives. I've used the DKMS package along with the latest driver on Dells website to create a driver disk and successfully installed by hand so I know that it will install but I need a good suggestion for cloning options. I've tried clonezilla but it does not recognize the hard drives and I'm no expert in debian based distros so I'm unable to manipulate it.
Does anyone know of a reliable way to clone this server? I imagine that if I can find a method to transfer the image then I will install the SAS driver on the source box before cloning it and it should be able to boot to the destination box.
Thanks all! | 2009/07/10 | [
"https://serverfault.com/questions/38980",
"https://serverfault.com",
"https://serverfault.com/users/7067/"
] | I've used SystemImager to move RHEL4 from 2850 to 2950.
RHEL4 did not recognize the drive controller on the 2950, so I booted using a rescuse disk and re-created the initrd. | I've had success with similar moves using a procedure like this (I mostly did this for moving from physical servers to VMs). Where I say "Knoppix", any Linux Live CD should work:
1. boot both with Knoppix; or boot the OLD server in single-user mode. "knoppix 2" for text-only might be a good idea.
2. Get networking going on both, with different IPs, of course.
3. On the OLD server, run: `dd if=/dev/sda | gzip -c | nc -l -p 3000`
4. On the NEW server, run: `nc $IP 3000 | gunzip -c | dd of=/dev/sda`
5. wait 1 to 3 hours, approximately (depends, of course)
6. turn off OLD server
7. following steps on the NEW server:
1. poke around and figure out which partitions are which. In my example, sda2 is / and sda1 is /boot
2. `mount -o dev /mnt/sda2`
3. `mount /dev/sda1 /mnt/sda2/boot`
4. `chroot /mnt/sda2`
5. `mount /proc`
6. edit /etc/modules.conf and change the scsi\_hostadapter to the right thing (looking at what knoppix has loaded using `lsmod` should help)
7. `module_upgrade`
8. `mkkerneldoth`
9. `rpm -qa | grep kernel`
10. `new-kernel-pkg --mkinitrd --depmod --install 2.4.21-40.EL` (version is from the previous; `rpm -q --scripts kernel` and emulate the post script)
11. `exit` (from chroot)
12. `shutdown -rf now`
8. When NEW machine boots up pick the same kernel that you modified, do the kudzu thing about acknowledging hardware that's gone and hardware that's added.
9. Verify that everything's working okay. Might have to adjust network settings, etc... |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | There are a number of things going on in the regular expression you're starting from:
```
^ # beginning of line
(?!.*\.\.) # negative lookahead that effectively prevents double periods
(?!.*\.$) # negative lookahead that prevents a period as the last character
[^\W] # first character must be a word character
[\w.]{0,29} # from 0 to 29 word characters or periods
$ # end of line
```
Additionally, based on what I'm seeing in that link, it has three flags applied: `i`, `g` and `m`. The only one of consequence really is `i`, because that means case-insensitive search. If you're trying to modify it to be case sensitive, the first thing you'll need to do is remove that.
The `\w` or word metacharacter matches `a-z`, `A-Z`, `0-9`, and `_`. So if you want to restrict that, replace it explicitly with the characters you want to allow, resulting in:
```
^(?!.*\.\.)(?!.*\.$)[^\W][a-z_.]{0,29}$
```
Now, it mostly works except that the first character can still be a capital letter. The `[^\W]` portion essentially matches "NOT NOT a word character" or.. "a word character", which includes uppercase letters. I'm honestly not sure the rationale behind this. But if it's no difference to you, you can probably just remove it and increase the remaining character range to 30 to still allow for up to 30 characters leaving us finally with:
```
^(?!.*\.\.)(?!.*\.$)[a-z_.]{0,30}$
```
**Edit**:
As noted by David, I did not catch your requirement to disallow multiple underscores.. be sure to include his added backreference to account for this:
```
^(?!.*\.\.)(?!.*__)(?!.*\.$)[a-z_.]{0,30}$
``` | Try this regex:
```
^(?!.*\.\.)(?!.*__)(?!.*[A-Z])(?!.*\.$)[^\W][\w.]{0,29}$
```
[RegExr demo](https://regexr.com/453us)
I've added this negative lookahead to disallow uppercase characters:
```
(?!.*[A-Z])
```
And this one to disallow double underscores:
```
(?!.*__)
```
---
One other important thing to remember is to uncheck the case insensitive flag.
[](https://i.stack.imgur.com/imOfP.png) |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | There are a number of things going on in the regular expression you're starting from:
```
^ # beginning of line
(?!.*\.\.) # negative lookahead that effectively prevents double periods
(?!.*\.$) # negative lookahead that prevents a period as the last character
[^\W] # first character must be a word character
[\w.]{0,29} # from 0 to 29 word characters or periods
$ # end of line
```
Additionally, based on what I'm seeing in that link, it has three flags applied: `i`, `g` and `m`. The only one of consequence really is `i`, because that means case-insensitive search. If you're trying to modify it to be case sensitive, the first thing you'll need to do is remove that.
The `\w` or word metacharacter matches `a-z`, `A-Z`, `0-9`, and `_`. So if you want to restrict that, replace it explicitly with the characters you want to allow, resulting in:
```
^(?!.*\.\.)(?!.*\.$)[^\W][a-z_.]{0,29}$
```
Now, it mostly works except that the first character can still be a capital letter. The `[^\W]` portion essentially matches "NOT NOT a word character" or.. "a word character", which includes uppercase letters. I'm honestly not sure the rationale behind this. But if it's no difference to you, you can probably just remove it and increase the remaining character range to 30 to still allow for up to 30 characters leaving us finally with:
```
^(?!.*\.\.)(?!.*\.$)[a-z_.]{0,30}$
```
**Edit**:
As noted by David, I did not catch your requirement to disallow multiple underscores.. be sure to include his added backreference to account for this:
```
^(?!.*\.\.)(?!.*__)(?!.*\.$)[a-z_.]{0,30}$
``` | I found your issue:
The flags you have selected `igm` include the `case insensitive` flag.
To make your regex exclude uppercase letters, disable that and try again with `^[a-z]...`
This should sort it out for you, but do comment if you can't get it to work, I'll try to help. |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | There are a number of things going on in the regular expression you're starting from:
```
^ # beginning of line
(?!.*\.\.) # negative lookahead that effectively prevents double periods
(?!.*\.$) # negative lookahead that prevents a period as the last character
[^\W] # first character must be a word character
[\w.]{0,29} # from 0 to 29 word characters or periods
$ # end of line
```
Additionally, based on what I'm seeing in that link, it has three flags applied: `i`, `g` and `m`. The only one of consequence really is `i`, because that means case-insensitive search. If you're trying to modify it to be case sensitive, the first thing you'll need to do is remove that.
The `\w` or word metacharacter matches `a-z`, `A-Z`, `0-9`, and `_`. So if you want to restrict that, replace it explicitly with the characters you want to allow, resulting in:
```
^(?!.*\.\.)(?!.*\.$)[^\W][a-z_.]{0,29}$
```
Now, it mostly works except that the first character can still be a capital letter. The `[^\W]` portion essentially matches "NOT NOT a word character" or.. "a word character", which includes uppercase letters. I'm honestly not sure the rationale behind this. But if it's no difference to you, you can probably just remove it and increase the remaining character range to 30 to still allow for up to 30 characters leaving us finally with:
```
^(?!.*\.\.)(?!.*\.$)[a-z_.]{0,30}$
```
**Edit**:
As noted by David, I did not catch your requirement to disallow multiple underscores.. be sure to include his added backreference to account for this:
```
^(?!.*\.\.)(?!.*__)(?!.*\.$)[a-z_.]{0,30}$
``` | You could try something like
`^(?:[a-z]|([._])(?!\1))+$`
Explained
```
^ # BOS
(?: # Repeat many times
[a-z] # a - z
| # or,
( [._] ) # (1), dot or underscore
(?! \1 ) # not followed by same
)+
$ # EOS
``` |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | Try this regex:
```
^(?!.*\.\.)(?!.*__)(?!.*[A-Z])(?!.*\.$)[^\W][\w.]{0,29}$
```
[RegExr demo](https://regexr.com/453us)
I've added this negative lookahead to disallow uppercase characters:
```
(?!.*[A-Z])
```
And this one to disallow double underscores:
```
(?!.*__)
```
---
One other important thing to remember is to uncheck the case insensitive flag.
[](https://i.stack.imgur.com/imOfP.png) | I found your issue:
The flags you have selected `igm` include the `case insensitive` flag.
To make your regex exclude uppercase letters, disable that and try again with `^[a-z]...`
This should sort it out for you, but do comment if you can't get it to work, I'll try to help. |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | Try this regex:
```
^(?!.*\.\.)(?!.*__)(?!.*[A-Z])(?!.*\.$)[^\W][\w.]{0,29}$
```
[RegExr demo](https://regexr.com/453us)
I've added this negative lookahead to disallow uppercase characters:
```
(?!.*[A-Z])
```
And this one to disallow double underscores:
```
(?!.*__)
```
---
One other important thing to remember is to uncheck the case insensitive flag.
[](https://i.stack.imgur.com/imOfP.png) | You could try something like
`^(?:[a-z]|([._])(?!\1))+$`
Explained
```
^ # BOS
(?: # Repeat many times
[a-z] # a - z
| # or,
( [._] ) # (1), dot or underscore
(?! \1 ) # not followed by same
)+
$ # EOS
``` |
53,824,824 | I'm sorry, I'm sure this will get marked as duplicate but I can not get my regex to work properly.
I want my regex to only allow lowercase letters, periods, and underscores. I'm using the instagram regex from the community patterns found here <https://regexr.com/3cg7r>
The pattern looks like `^(?!.*\.\.)(?!.*\.$)[^\W][\w.]{0,29}$`
Figured I could add `[a-z]` at the beginning of the pattern right after the carrot "^" but that didn't do anything. I tried various other ways like `[^A-Z]` which I thought would work but didn't.
Can someone steer me in the right direction?
Edit:
I want to match:
`test_handle`
`test.handle`
`testhandle`
`test_._handle`
Don't want to match:
`Test_handle`
`test_Handle`
`test__handle`
`test..handle`
`TESTHANDLE`
an | 2018/12/18 | [
"https://Stackoverflow.com/questions/53824824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8545437/"
] | I found your issue:
The flags you have selected `igm` include the `case insensitive` flag.
To make your regex exclude uppercase letters, disable that and try again with `^[a-z]...`
This should sort it out for you, but do comment if you can't get it to work, I'll try to help. | You could try something like
`^(?:[a-z]|([._])(?!\1))+$`
Explained
```
^ # BOS
(?: # Repeat many times
[a-z] # a - z
| # or,
( [._] ) # (1), dot or underscore
(?! \1 ) # not followed by same
)+
$ # EOS
``` |
298,296 | First, how do you define "exhibit"? To you, would this mean you need to prove that your bijection is 1-1 and onto? If so, I think I've got the 1-1 part, but am struggling with showing it is onto. The examples of a linear function being shown as onto just seem too elementary, and I'm not sure they work when mapping naturals to integers.
I'm saying $f(n)=2n+13$. To show 1-1, I've let $f(x)=f(y)$, substituted through, and came out with $x=y$. I'm sure there needs to be more detail given, but for now, I'm just trying to remember how to show a function is onto. From what I've been able to find examples of, I basically solve my proposed function for $y$ getting $(y-13)/2$, then plug that in? Does that really show anything?! Does this work when going from $\mathbb{N} \rightarrow\mathbb{Z}$? | 2013/02/08 | [
"https://math.stackexchange.com/questions/298296",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/60834/"
] | Your $f$ is a bijection $\Bbb N\to \{1,3,5,7,\dots\}$. This should be shifted with $12$ (if $13$ is included in the target set, and by $14$ if that starts with $15$), and you're there:
$$g(n):=f(n)+12=2n+13$$
will do it. | Suppose that $n\in \mathbb Z$ is odd and that $n>13$.
Then we can write $n=2z+1$ for some $z \in \mathbb Z$.
Then $n= 2z+1 =2z+1 +(13-13) = 2z-12 +13 = 2(z-6)+13$.
Hence $f(z-6) = n$.
Now we need to show that $z-6 \in \mathbb N$. But since $2z+1 > 13$ then $2z >12$ and $z>6$ and finally $z-6>0$.
Obviously all the greater than's can be greater than or equal to, according to whether or not $0\in \mathbb N$ for you. |
8,711,958 | I have been struggling with CellFormatting event, it's so slow.
I have a DataGridView something like this:

I have written a function that fires when you click the checkbox in the header and it makes all the check boxes to check in that column....
```
private void checkboxHeader_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
}
//dataGridView1.EndEdit();
}
```
And this function is working when I have something like 10 rows it works perfectly, but when I have 300 rows something that I should have... there is a something like 9 seconds delay for making all the checkboxes checked, and I found out that it's due to CellFormating event.
My CellFormating event code is:
```
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewCellStyle _myStyle = new DataGridViewCellStyle();
int index = gdv_row.FindIndex(p => p.log == (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value);
if (index != -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn && e.RowIndex != -1)
{
//e.CellStyle = _myStyle;
_myStyle.Font = gdv_row[index].font;
_myStyle.BackColor = gdv_row[index].backgroundcolor_color;
_myStyle.ForeColor = gdv_row[index].foregroundcolor_color;
dataGridView1.Rows[e.RowIndex].Cells[1].Style = _myStyle;
}
}
```
and I have used [DoubleBuffering for DataGridView](https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens). Now I don't have any idea what should I do with this CellFormatting event... | 2012/01/03 | [
"https://Stackoverflow.com/questions/8711958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1002584/"
] | Did you already try [SuspendLayout()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout%28v=VS.100%29.aspx) and [ResumeLayout()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resumelayout.aspx)?
This temporarily suspends the layout logic for the control, so that there is no redraw of the grid while you are populating it.
If you use DoubleBuffering the Grid still redrows itself which ist still slow. But if you do not redraw at all while you populate the Grid, this should give a dramatic impovement.
Your first function might then look like this:
```
private void checkboxHeader_CheckedChanged(object sender, EventArgs e)
{
dataGridView1.SuspendLayout();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
}
dataGridView1.ResumeLayout();
}
```
**[Edit 1]**
Added code sample.
**[Edit 2]**
To minimise the necessary drawing of the rows, instead of creating a new `DataGridViewCellStyle` object for each row, try setting the properties of the existing style directly:
```
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int index = gdv_row.FindIndex(p => p.log == (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value);
if (index != -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn && e.RowIndex != -1)
{
dataGridView1.Rows[e.RowIndex].Cells[1].Style.Font = gdv_row[index].font;
dataGridView1.Rows[e.RowIndex].Cells[1].Style.BackColor = gdv_row[index].backgroundcolor_color;
dataGridView1.Rows[e.RowIndex].Cells[1].Style.ForeColor = gdv_row[index].foregroundcolor_color;
}
}
```
Finally, looking for some solution, I found this MSDN article document:
[Best Practices for Scaling the Windows Forms DataGridView Control](http://msdn.microsoft.com/de-de/library/ha5xt0d9.aspx)
**[EDIT 3] (Response to Ehsan's comment below)**
This is because "a" is a value that is instantly there to display in the Grid while the original line does some significant work:
\* Performs a search for the desired value, including all child controls
\* Creates an Array with the found results
\* Makes a Cast from object to CheckBox
\* It does all of this per each and every single line in your Grid
It becomes obvious that this becomes more time consuming the more items you have in your DataGridView.
If I understood your code correctly it should help you to change the method into this:
```
CheckBox headerBox = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]);
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = headerBox.Checked;
}
```
By doing this you only perform the search once. | If you want to stop painting the control when you're checking all the rows, you should take a look at the `DrawingControl` class from this post: [https://stackoverflow.com/questions/487661/...](https://stackoverflow.com/questions/487661/how-do-i-suspend-painting-for-a-control-and-its-children) |
8,711,958 | I have been struggling with CellFormatting event, it's so slow.
I have a DataGridView something like this:

I have written a function that fires when you click the checkbox in the header and it makes all the check boxes to check in that column....
```
private void checkboxHeader_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
}
//dataGridView1.EndEdit();
}
```
And this function is working when I have something like 10 rows it works perfectly, but when I have 300 rows something that I should have... there is a something like 9 seconds delay for making all the checkboxes checked, and I found out that it's due to CellFormating event.
My CellFormating event code is:
```
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewCellStyle _myStyle = new DataGridViewCellStyle();
int index = gdv_row.FindIndex(p => p.log == (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value);
if (index != -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn && e.RowIndex != -1)
{
//e.CellStyle = _myStyle;
_myStyle.Font = gdv_row[index].font;
_myStyle.BackColor = gdv_row[index].backgroundcolor_color;
_myStyle.ForeColor = gdv_row[index].foregroundcolor_color;
dataGridView1.Rows[e.RowIndex].Cells[1].Style = _myStyle;
}
}
```
and I have used [DoubleBuffering for DataGridView](https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens). Now I don't have any idea what should I do with this CellFormatting event... | 2012/01/03 | [
"https://Stackoverflow.com/questions/8711958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1002584/"
] | Did you already try [SuspendLayout()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout%28v=VS.100%29.aspx) and [ResumeLayout()](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resumelayout.aspx)?
This temporarily suspends the layout logic for the control, so that there is no redraw of the grid while you are populating it.
If you use DoubleBuffering the Grid still redrows itself which ist still slow. But if you do not redraw at all while you populate the Grid, this should give a dramatic impovement.
Your first function might then look like this:
```
private void checkboxHeader_CheckedChanged(object sender, EventArgs e)
{
dataGridView1.SuspendLayout();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
}
dataGridView1.ResumeLayout();
}
```
**[Edit 1]**
Added code sample.
**[Edit 2]**
To minimise the necessary drawing of the rows, instead of creating a new `DataGridViewCellStyle` object for each row, try setting the properties of the existing style directly:
```
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int index = gdv_row.FindIndex(p => p.log == (string)dataGridView1.Rows[e.RowIndex].Cells[1].Value);
if (index != -1 && dataGridView1.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn && e.RowIndex != -1)
{
dataGridView1.Rows[e.RowIndex].Cells[1].Style.Font = gdv_row[index].font;
dataGridView1.Rows[e.RowIndex].Cells[1].Style.BackColor = gdv_row[index].backgroundcolor_color;
dataGridView1.Rows[e.RowIndex].Cells[1].Style.ForeColor = gdv_row[index].foregroundcolor_color;
}
}
```
Finally, looking for some solution, I found this MSDN article document:
[Best Practices for Scaling the Windows Forms DataGridView Control](http://msdn.microsoft.com/de-de/library/ha5xt0d9.aspx)
**[EDIT 3] (Response to Ehsan's comment below)**
This is because "a" is a value that is instantly there to display in the Grid while the original line does some significant work:
\* Performs a search for the desired value, including all child controls
\* Creates an Array with the found results
\* Makes a Cast from object to CheckBox
\* It does all of this per each and every single line in your Grid
It becomes obvious that this becomes more time consuming the more items you have in your DataGridView.
If I understood your code correctly it should help you to change the method into this:
```
CheckBox headerBox = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]);
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1[0, i].Value = headerBox.Checked;
}
```
By doing this you only perform the search once. | In my case the problem was caused by DataGridView property **AutoSizeColumnsMode=AllCells**. Probably after cell formatting all other cells in column and header cell had to be redrawn to fit theirs dimensions to the new cell dimensions. After I was changed property value to it default value "None", grid is painted immediately. |
36,399,834 | In mvc4 application I used datetime format `dd.MM.YYYY HH:mm`
*EditorTemplates > DateTime.cshtml*
```
@Html.TextBoxFor(model => model, "{0:dd.MM.yyyy HH:mm}", ViewData["htmlAttributes"])
```
and I parsed it like this
```
DateTime.ParseExact(myDate, "dd.MM.yyyy", CultureInfo.InvariantCulture);
```
where myDate is passed as parameter ofcourse.
Inside jquery datetime picker I used code (abbreviated inside function)
```
... format('DD.MM.YYYY HH:mm')
```
how can I change this code to use following datetime format
```
2016-04-04 23:05
```
I tried with
```
@Html.TextBoxFor(model => model, "{0:YYYY-MM-DD HH:mm}", ViewData["htmlAttributes"])
```
and parsing like
```
DateTime.ParseExact(myDate, "YYYY-MM-DD", CultureInfo.InvariantCulture)
```
and inside js
```
... format('YYYY-MM-DD HH:mm')
```
but I'm getting year as `YYYY` instead of `2016`. | 2016/04/04 | [
"https://Stackoverflow.com/questions/36399834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765862/"
] | [Custom Date and Time Format Strings](https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx) are case sensitive. There is no `YYYY` or `DD` as a specifiers. That's why those strings will be in *as* they are when you get it's string representation.
From docs;
>
> Any other character.
>
>
> The character is copied to the result string unchanged.
>
>
>
Your format should be as `yyyy-MM-dd`. | Try it with `"yyyy-MM-dd"` instead of `"YYYY-MM-DD"`. |
35,249,962 | I have two assignments/variables in my code:
```
OUTPUT1="/Users/check/1.html"
OUTPUT2="/Users/check/2.html"
```
When I use one of the above, for instance, I write `c = open(OUTPUT1)`.
However, I think the correct approach for this would be to have something like a generic:
`OUTPUT="/Users/check/$var.html"` and then while using, I should first assign:
```
$var = 1.html
then open(OUTPUT)
```
This way I open `1.html`.
How do you do this in Python? | 2016/02/07 | [
"https://Stackoverflow.com/questions/35249962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111128/"
] | Use string interpolation like so:
```
var = "1.html"
path = "/Users/check/{}".format(var)
open(path)
```
You may also want to use a more common pattern:
```
import os
var = "1.html"
path = os.path.join("/Users/check/", var)
open(path)
``` | Perhaps you would consider using a tuple:
```
OUTPUT_PATHS = (
'/Users/check/1.html',
'/Users/check/2.html',
'/tmp/3.html'
)
```
Then you can simply index them, starting with 0:
```
outnum = random(0, 3)
c = open(outnum)
``` |
35,249,962 | I have two assignments/variables in my code:
```
OUTPUT1="/Users/check/1.html"
OUTPUT2="/Users/check/2.html"
```
When I use one of the above, for instance, I write `c = open(OUTPUT1)`.
However, I think the correct approach for this would be to have something like a generic:
`OUTPUT="/Users/check/$var.html"` and then while using, I should first assign:
```
$var = 1.html
then open(OUTPUT)
```
This way I open `1.html`.
How do you do this in Python? | 2016/02/07 | [
"https://Stackoverflow.com/questions/35249962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111128/"
] | If you wanted to put it in a function:
```
def getPath(var):
return "/Users/check/" + str(var) + ".html"
print(getPath(1))
print(getPath(2))
``` | Perhaps you would consider using a tuple:
```
OUTPUT_PATHS = (
'/Users/check/1.html',
'/Users/check/2.html',
'/tmp/3.html'
)
```
Then you can simply index them, starting with 0:
```
outnum = random(0, 3)
c = open(outnum)
``` |
40,318,778 | Given a base-**10** integer,**n** , convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1's in **n**'s binary representation.
Here is the code I wrote for it
```
#!/bin/python
import sys
k=0
m=0
i=0
n = int(raw_input().strip())
x=bin(n)[2:]
while x[i] :
if x[i]==1:
m=m+1
else :
if k<m:
k=m
m=0
i+=1
print(k)
```
I am getting the following error
```
Traceback (most recent call last):
File "solution.py", line 9, in <module>
while x[i] :
IndexError: string index out of range
``` | 2016/10/29 | [
"https://Stackoverflow.com/questions/40318778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6243763/"
] | Your while loop increments `i` but never checks when it has gone past the end of the string `x`. Your test `while x[i]` does not check for the string's end, it just checks each character if is empty. Since no character in a string is empty (and your string contains only `'0'` and `'1'`), your loop just continues. Note that the string `'0'` does not test to `False`: it is a perfectly valid string and evaluates to `True`.
If you want that structure, instead use the check
```
while i < len(x):
```
but it would be more pythonic to restructure your code and use
```
for c in x:
```
which looks at each character `c` in string `x`. | Your condition `while x[i]` is wrong since it will never evaluate to `False` for any character. Are you used to C's null-terminated strings?
Also, you are comparing a `str` to an `int` here:
```
if x[i]==1:
```
The proper way to do this would be to use a for-each loop:
```
import sys
k = 0
m = 0
i = 0
n = int(raw_input().strip())
x = bin(n)[2:]
for c in x:
if c == '1':
m += 1
else:
if k < m:
k = m
m = 0
# check whether the last run is greater than the current maximum
if k < m:
k = m
print(k)
``` |
56,119,014 | I have a school project in which I need to create a communication between a USB HID keyboard and Nexys4DDR in VHDL using Vivado 2018.3 . I have used the Nexys 4 keyboard demo from [here](https://reference.digilentinc.com/learn/programmable-logic/tutorials/nexys-4-ddr-keyboard-demo/start) which I wrote in VHDL and to which I have added a DCD in order to decode the values and to output the correct letter. My issue is with the bit stream generation. The error I get is only when running the bit stream generation and it does not appear in synthesis or implementation.
>
> WARNING: [Constraints 18-5210] No constraints selected for write.
> Resolution: This message can indicate that there are no constraints for the design, or it can indicate that the used\_in flags are set such that the constraints are ignored. This later case is used when running synth\_design to not write synthesis constraints to the resulting checkpoint. Instead, project constraints are read when the synthesized design is opened.
>
>
>
I have used the same constraint file as it is specified on the program from diligent.
I am unsure where the issue is.
My constraint file is :
```
## Clock signal
set_property -dict { PACKAGE_PIN E3 IOSTANDARD LVCMOS33 } [get_ports { Clk }]; #IO_L12P_T1_MRCC_35 Sch=clk100mhz
create_clock -add -name sys_clk_pin -period 10.00 -waveform {0 5} [get_ports {Clk}];
##Switches
#set_property -dict { PACKAGE_PIN J15 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }]; #IO_L24N_T3_RS0_15 Sch=sw[0]
#set_property -dict { PACKAGE_PIN L16 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }]; #IO_L3N_T0_DQS_EMCCLK_14 Sch=sw[1]
#set_property -dict { PACKAGE_PIN M13 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }]; #IO_L6N_T0_D08_VREF_14 Sch=sw[2]
#set_property -dict { PACKAGE_PIN R15 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }]; #IO_L13N_T2_MRCC_14 Sch=sw[3]
#set_property -dict { PACKAGE_PIN R17 IOSTANDARD LVCMOS33 } [get_ports { SW[4] }]; #IO_L12N_T1_MRCC_14 Sch=sw[4]
#set_property -dict { PACKAGE_PIN T18 IOSTANDARD LVCMOS33 } [get_ports { SW[5] }]; #IO_L7N_T1_D10_14 Sch=sw[5]
#set_property -dict { PACKAGE_PIN U18 IOSTANDARD LVCMOS33 } [get_ports { SW[6] }]; #IO_L17N_T2_A13_D29_14 Sch=sw[6]
#set_property -dict { PACKAGE_PIN R13 IOSTANDARD LVCMOS33 } [get_ports { SW[7] }]; #IO_L5N_T0_D07_14 Sch=sw[7]
#set_property -dict { PACKAGE_PIN T8 IOSTANDARD LVCMOS18 } [get_ports { SW[8] }]; #IO_L24N_T3_34 Sch=sw[8]
#set_property -dict { PACKAGE_PIN U8 IOSTANDARD LVCMOS18 } [get_ports { SW[9] }]; #IO_25_34 Sch=sw[9]
#set_property -dict { PACKAGE_PIN R16 IOSTANDARD LVCMOS33 } [get_ports { SW[10] }]; #IO_L15P_T2_DQS_RDWR_B_14 Sch=sw[10]
#set_property -dict { PACKAGE_PIN T13 IOSTANDARD LVCMOS33 } [get_ports { SW[11] }]; #IO_L23P_T3_A03_D19_14 Sch=sw[11]
#set_property -dict { PACKAGE_PIN H6 IOSTANDARD LVCMOS33 } [get_ports { SW[12] }]; #IO_L24P_T3_35 Sch=sw[12]
#set_property -dict { PACKAGE_PIN U12 IOSTANDARD LVCMOS33 } [get_ports { SW[13] }]; #IO_L20P_T3_A08_D24_14 Sch=sw[13]
#set_property -dict { PACKAGE_PIN U11 IOSTANDARD LVCMOS33 } [get_ports { SW[14] }]; #IO_L19N_T3_A09_D25_VREF_14 Sch=sw[14]
#set_property -dict { PACKAGE_PIN V10 IOSTANDARD LVCMOS33 } [get_ports { SW[15] }]; #IO_L21P_T3_DQS_14 Sch=sw[15]
## LEDs
#set_property -dict { PACKAGE_PIN H17 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }]; #IO_L18P_T2_A24_15 Sch=led[0]
#set_property -dict { PACKAGE_PIN K15 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }]; #IO_L24P_T3_RS1_15 Sch=led[1]
#set_property -dict { PACKAGE_PIN J13 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }]; #IO_L17N_T2_A25_15 Sch=led[2]
#set_property -dict { PACKAGE_PIN N14 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }]; #IO_L8P_T1_D11_14 Sch=led[3]
#set_property -dict { PACKAGE_PIN R18 IOSTANDARD LVCMOS33 } [get_ports { LED[4] }]; #IO_L7P_T1_D09_14 Sch=led[4]
#set_property -dict { PACKAGE_PIN V17 IOSTANDARD LVCMOS33 } [get_ports { LED[5] }]; #IO_L18N_T2_A11_D27_14 Sch=led[5]
#set_property -dict { PACKAGE_PIN U17 IOSTANDARD LVCMOS33 } [get_ports { LED[6] }]; #IO_L17P_T2_A14_D30_14 Sch=led[6]
#set_property -dict { PACKAGE_PIN U16 IOSTANDARD LVCMOS33 } [get_ports { LED[7] }]; #IO_L18P_T2_A12_D28_14 Sch=led[7]
#set_property -dict { PACKAGE_PIN V16 IOSTANDARD LVCMOS33 } [get_ports { LED[8] }]; #IO_L16N_T2_A15_D31_14 Sch=led[8]
#set_property -dict { PACKAGE_PIN T15 IOSTANDARD LVCMOS33 } [get_ports { LED[9] }]; #IO_L14N_T2_SRCC_14 Sch=led[9]
#set_property -dict { PACKAGE_PIN U14 IOSTANDARD LVCMOS33 } [get_ports { LED[10] }]; #IO_L22P_T3_A05_D21_14 Sch=led[10]
#set_property -dict { PACKAGE_PIN T16 IOSTANDARD LVCMOS33 } [get_ports { LED[11] }]; #IO_L15N_T2_DQS_DOUT_CSO_B_14 Sch=led[11]
#set_property -dict { PACKAGE_PIN V15 IOSTANDARD LVCMOS33 } [get_ports { LED[12] }]; #IO_L16P_T2_CSI_B_14 Sch=led[12]
#set_property -dict { PACKAGE_PIN V14 IOSTANDARD LVCMOS33 } [get_ports { LED[13] }]; #IO_L22N_T3_A04_D20_14 Sch=led[13]
#set_property -dict { PACKAGE_PIN V12 IOSTANDARD LVCMOS33 } [get_ports { LED[14] }]; #IO_L20N_T3_A07_D23_14 Sch=led[14]
#set_property -dict { PACKAGE_PIN V11 IOSTANDARD LVCMOS33 } [get_ports { LED[15] }]; #IO_L21N_T3_DQS_A06_D22_14 Sch=led[15]
#set_property -dict { PACKAGE_PIN R12 IOSTANDARD LVCMOS33 } [get_ports { LED16_B }]; #IO_L5P_T0_D06_14 Sch=led16_b
#set_property -dict { PACKAGE_PIN M16 IOSTANDARD LVCMOS33 } [get_ports { LED16_G }]; #IO_L10P_T1_D14_14 Sch=led16_g
#set_property -dict { PACKAGE_PIN N15 IOSTANDARD LVCMOS33 } [get_ports { LED16_R }]; #IO_L11P_T1_SRCC_14 Sch=led16_r
#set_property -dict { PACKAGE_PIN G14 IOSTANDARD LVCMOS33 } [get_ports { LED17_B }]; #IO_L15N_T2_DQS_ADV_B_15 Sch=led17_b
#set_property -dict { PACKAGE_PIN R11 IOSTANDARD LVCMOS33 } [get_ports { LED17_G }]; #IO_0_14 Sch=led17_g
#set_property -dict { PACKAGE_PIN N16 IOSTANDARD LVCMOS33 } [get_ports { LED17_R }]; #IO_L11N_T1_SRCC_14 Sch=led17_r
##7 segment display
set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { SEG[0] }]; #IO_L24N_T3_A00_D16_14 Sch=ca
set_property -dict { PACKAGE_PIN R10 IOSTANDARD LVCMOS33 } [get_ports { SEG[1] }]; #IO_25_14 Sch=cb
set_property -dict { PACKAGE_PIN K16 IOSTANDARD LVCMOS33 } [get_ports { SEG[2] }]; #IO_25_15 Sch=cc
set_property -dict { PACKAGE_PIN K13 IOSTANDARD LVCMOS33 } [get_ports { SEG[3] }]; #IO_L17P_T2_A26_15 Sch=cd
set_property -dict { PACKAGE_PIN P15 IOSTANDARD LVCMOS33 } [get_ports { SEG[4] }]; #IO_L13P_T2_MRCC_14 Sch=ce
set_property -dict { PACKAGE_PIN T11 IOSTANDARD LVCMOS33 } [get_ports { SEG[5] }]; #IO_L19P_T3_A10_D26_14 Sch=cf
set_property -dict { PACKAGE_PIN L18 IOSTANDARD LVCMOS33 } [get_ports { SEG[6] }]; #IO_L4P_T0_D04_14 Sch=cg
set_property -dict { PACKAGE_PIN H15 IOSTANDARD LVCMOS33 } [get_ports { DP }]; #IO_L19N_T3_A21_VREF_15 Sch=dp
set_property -dict { PACKAGE_PIN J17 IOSTANDARD LVCMOS33 } [get_ports { AN[0] }]; #IO_L23P_T3_FOE_B_15 Sch=an[0]
set_property -dict { PACKAGE_PIN J18 IOSTANDARD LVCMOS33 } [get_ports { AN[1] }]; #IO_L23N_T3_FWE_B_15 Sch=an[1]
set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { AN[2] }]; #IO_L24P_T3_A01_D17_14 Sch=an[2]
set_property -dict { PACKAGE_PIN J14 IOSTANDARD LVCMOS33 } [get_ports { AN[3] }]; #IO_L19P_T3_A22_15 Sch=an[3]
set_property -dict { PACKAGE_PIN P14 IOSTANDARD LVCMOS33 } [get_ports { AN[4] }]; #IO_L8N_T1_D12_14 Sch=an[4]
set_property -dict { PACKAGE_PIN T14 IOSTANDARD LVCMOS33 } [get_ports { AN[5] }]; #IO_L14P_T2_SRCC_14 Sch=an[5]
set_property -dict { PACKAGE_PIN K2 IOSTANDARD LVCMOS33 } [get_ports { AN[6] }]; #IO_L23P_T3_35 Sch=an[6]
set_property -dict { PACKAGE_PIN U13 IOSTANDARD LVCMOS33 } [get_ports { AN[7] }]; #IO_L23N_T3_A02_D18_14 Sch=an[7]
##Buttons
#set_property -dict { PACKAGE_PIN C12 IOSTANDARD LVCMOS33 } [get_ports { CPU_RESETN }]; #IO_L3P_T0_DQS_AD1P_15 Sch=cpu_resetn
set_property -dict { PACKAGE_PIN N17 IOSTANDARD LVCMOS33 } [get_ports { Rst }]; #IO_L9P_T1_DQS_14 Sch=btnc(Rst)
#set_property -dict { PACKAGE_PIN M18 IOSTANDARD LVCMOS33 } [get_ports { BTNU }]; #IO_L4N_T0_D05_14 Sch=btnu
#set_property -dict { PACKAGE_PIN P17 IOSTANDARD LVCMOS33 } [get_ports { BTNL }]; #IO_L12P_T1_MRCC_14 Sch=btnl
#set_property -dict { PACKAGE_PIN M17 IOSTANDARD LVCMOS33 } [get_ports { BTNR }]; #IO_L10N_T1_D15_14 Sch=btnr
#set_property -dict { PACKAGE_PIN P18 IOSTANDARD LVCMOS33 } [get_ports { BTND }]; #IO_L9N_T1_DQS_D13_14 Sch=btnd
##Pmod Headers
##Pmod Header JA
#set_property -dict { PACKAGE_PIN C17 IOSTANDARD LVCMOS33 } [get_ports { JA[1] }]; #IO_L20N_T3_A19_15 Sch=ja[1]
#set_property -dict { PACKAGE_PIN D18 IOSTANDARD LVCMOS33 } [get_ports { JA[2] }]; #IO_L21N_T3_DQS_A18_15 Sch=ja[2]
#set_property -dict { PACKAGE_PIN E18 IOSTANDARD LVCMOS33 } [get_ports { JA[3] }]; #IO_L21P_T3_DQS_15 Sch=ja[3]
#set_property -dict { PACKAGE_PIN G17 IOSTANDARD LVCMOS33 } [get_ports { JA[4] }]; #IO_L18N_T2_A23_15 Sch=ja[4]
#set_property -dict { PACKAGE_PIN D17 IOSTANDARD LVCMOS33 } [get_ports { JA[7] }]; #IO_L16N_T2_A27_15 Sch=ja[7]
#set_property -dict { PACKAGE_PIN E17 IOSTANDARD LVCMOS33 } [get_ports { JA[8] }]; #IO_L16P_T2_A28_15 Sch=ja[8]
#set_property -dict { PACKAGE_PIN F18 IOSTANDARD LVCMOS33 } [get_ports { JA[9] }]; #IO_L22N_T3_A16_15 Sch=ja[9]
#set_property -dict { PACKAGE_PIN G18 IOSTANDARD LVCMOS33 } [get_ports { JA[10] }]; #IO_L22P_T3_A17_15 Sch=ja[10]
##Pmod Header JB
#set_property -dict { PACKAGE_PIN D14 IOSTANDARD LVCMOS33 } [get_ports { JB[1] }]; #IO_L1P_T0_AD0P_15 Sch=jb[1]
#set_property -dict { PACKAGE_PIN F16 IOSTANDARD LVCMOS33 } [get_ports { JB[2] }]; #IO_L14N_T2_SRCC_15 Sch=jb[2]
#set_property -dict { PACKAGE_PIN G16 IOSTANDARD LVCMOS33 } [get_ports { JB[3] }]; #IO_L13N_T2_MRCC_15 Sch=jb[3]
#set_property -dict { PACKAGE_PIN H14 IOSTANDARD LVCMOS33 } [get_ports { JB[4] }]; #IO_L15P_T2_DQS_15 Sch=jb[4]
#set_property -dict { PACKAGE_PIN E16 IOSTANDARD LVCMOS33 } [get_ports { JB[7] }]; #IO_L11N_T1_SRCC_15 Sch=jb[7]
#set_property -dict { PACKAGE_PIN F13 IOSTANDARD LVCMOS33 } [get_ports { JB[8] }]; #IO_L5P_T0_AD9P_15 Sch=jb[8]
#set_property -dict { PACKAGE_PIN G13 IOSTANDARD LVCMOS33 } [get_ports { JB[9] }]; #IO_0_15 Sch=jb[9]
#set_property -dict { PACKAGE_PIN H16 IOSTANDARD LVCMOS33 } [get_ports { JB[10] }]; #IO_L13P_T2_MRCC_15 Sch=jb[10]
##Pmod Header JC
#set_property -dict { PACKAGE_PIN K1 IOSTANDARD LVCMOS33 } [get_ports { JC[1] }]; #IO_L23N_T3_35 Sch=jc[1]
#set_property -dict { PACKAGE_PIN F6 IOSTANDARD LVCMOS33 } [get_ports { JC[2] }]; #IO_L19N_T3_VREF_35 Sch=jc[2]
#set_property -dict { PACKAGE_PIN J2 IOSTANDARD LVCMOS33 } [get_ports { JC[3] }]; #IO_L22N_T3_35 Sch=jc[3]
#set_property -dict { PACKAGE_PIN G6 IOSTANDARD LVCMOS33 } [get_ports { JC[4] }]; #IO_L19P_T3_35 Sch=jc[4]
#set_property -dict { PACKAGE_PIN E7 IOSTANDARD LVCMOS33 } [get_ports { JC[7] }]; #IO_L6P_T0_35 Sch=jc[7]
#set_property -dict { PACKAGE_PIN J3 IOSTANDARD LVCMOS33 } [get_ports { JC[8] }]; #IO_L22P_T3_35 Sch=jc[8]
#set_property -dict { PACKAGE_PIN J4 IOSTANDARD LVCMOS33 } [get_ports { JC[9] }]; #IO_L21P_T3_DQS_35 Sch=jc[9]
#set_property -dict { PACKAGE_PIN E6 IOSTANDARD LVCMOS33 } [get_ports { JC[10] }]; #IO_L5P_T0_AD13P_35 Sch=jc[10]
##Pmod Header JD
#set_property -dict { PACKAGE_PIN H4 IOSTANDARD LVCMOS33 } [get_ports { JD[1] }]; #IO_L21N_T3_DQS_35 Sch=jd[1]
#set_property -dict { PACKAGE_PIN H1 IOSTANDARD LVCMOS33 } [get_ports { JD[2] }]; #IO_L17P_T2_35 Sch=jd[2]
#set_property -dict { PACKAGE_PIN G1 IOSTANDARD LVCMOS33 } [get_ports { JD[3] }]; #IO_L17N_T2_35 Sch=jd[3]
#set_property -dict { PACKAGE_PIN G3 IOSTANDARD LVCMOS33 } [get_ports { JD[4] }]; #IO_L20N_T3_35 Sch=jd[4]
#set_property -dict { PACKAGE_PIN H2 IOSTANDARD LVCMOS33 } [get_ports { JD[7] }]; #IO_L15P_T2_DQS_35 Sch=jd[7]
#set_property -dict { PACKAGE_PIN G4 IOSTANDARD LVCMOS33 } [get_ports { JD[8] }]; #IO_L20P_T3_35 Sch=jd[8]
#set_property -dict { PACKAGE_PIN G2 IOSTANDARD LVCMOS33 } [get_ports { JD[9] }]; #IO_L15N_T2_DQS_35 Sch=jd[9]
#set_property -dict { PACKAGE_PIN F3 IOSTANDARD LVCMOS33 } [get_ports { JD[10] }]; #IO_L13N_T2_MRCC_35 Sch=jd[10]
##Pmod Header JXADC
#set_property -dict { PACKAGE_PIN A14 IOSTANDARD LVDS } [get_ports { XA_N[1] }]; #IO_L9N_T1_DQS_AD3N_15 Sch=xa_n[1]
#set_property -dict { PACKAGE_PIN A13 IOSTANDARD LVDS } [get_ports { XA_P[1] }]; #IO_L9P_T1_DQS_AD3P_15 Sch=xa_p[1]
#set_property -dict { PACKAGE_PIN A16 IOSTANDARD LVDS } [get_ports { XA_N[2] }]; #IO_L8N_T1_AD10N_15 Sch=xa_n[2]
#set_property -dict { PACKAGE_PIN A15 IOSTANDARD LVDS } [get_ports { XA_P[2] }]; #IO_L8P_T1_AD10P_15 Sch=xa_p[2]
#set_property -dict { PACKAGE_PIN B17 IOSTANDARD LVDS } [get_ports { XA_N[3] }]; #IO_L7N_T1_AD2N_15 Sch=xa_n[3]
#set_property -dict { PACKAGE_PIN B16 IOSTANDARD LVDS } [get_ports { XA_P[3] }]; #IO_L7P_T1_AD2P_15 Sch=xa_p[3]
#set_property -dict { PACKAGE_PIN A18 IOSTANDARD LVDS } [get_ports { XA_N[4] }]; #IO_L10N_T1_AD11N_15 Sch=xa_n[4]
#set_property -dict { PACKAGE_PIN B18 IOSTANDARD LVDS } [get_ports { XA_P[4] }]; #IO_L10P_T1_AD11P_15 Sch=xa_p[4]
##VGA Connector
#set_property -dict { PACKAGE_PIN A3 IOSTANDARD LVCMOS33 } [get_ports { VGA_R[0] }]; #IO_L8N_T1_AD14N_35 Sch=vga_r[0]
#set_property -dict { PACKAGE_PIN B4 IOSTANDARD LVCMOS33 } [get_ports { VGA_R[1] }]; #IO_L7N_T1_AD6N_35 Sch=vga_r[1]
#set_property -dict { PACKAGE_PIN C5 IOSTANDARD LVCMOS33 } [get_ports { VGA_R[2] }]; #IO_L1N_T0_AD4N_35 Sch=vga_r[2]
#set_property -dict { PACKAGE_PIN A4 IOSTANDARD LVCMOS33 } [get_ports { VGA_R[3] }]; #IO_L8P_T1_AD14P_35 Sch=vga_r[3]
#set_property -dict { PACKAGE_PIN C6 IOSTANDARD LVCMOS33 } [get_ports { VGA_G[0] }]; #IO_L1P_T0_AD4P_35 Sch=vga_g[0]
#set_property -dict { PACKAGE_PIN A5 IOSTANDARD LVCMOS33 } [get_ports { VGA_G[1] }]; #IO_L3N_T0_DQS_AD5N_35 Sch=vga_g[1]
#set_property -dict { PACKAGE_PIN B6 IOSTANDARD LVCMOS33 } [get_ports { VGA_G[2] }]; #IO_L2N_T0_AD12N_35 Sch=vga_g[2]
#set_property -dict { PACKAGE_PIN A6 IOSTANDARD LVCMOS33 } [get_ports { VGA_G[3] }]; #IO_L3P_T0_DQS_AD5P_35 Sch=vga_g[3]
#set_property -dict { PACKAGE_PIN B7 IOSTANDARD LVCMOS33 } [get_ports { VGA_B[0] }]; #IO_L2P_T0_AD12P_35 Sch=vga_b[0]
#set_property -dict { PACKAGE_PIN C7 IOSTANDARD LVCMOS33 } [get_ports { VGA_B[1] }]; #IO_L4N_T0_35 Sch=vga_b[1]
#set_property -dict { PACKAGE_PIN D7 IOSTANDARD LVCMOS33 } [get_ports { VGA_B[2] }]; #IO_L6N_T0_VREF_35 Sch=vga_b[2]
#set_property -dict { PACKAGE_PIN D8 IOSTANDARD LVCMOS33 } [get_ports { VGA_B[3] }]; #IO_L4P_T0_35 Sch=vga_b[3]
#set_property -dict { PACKAGE_PIN B11 IOSTANDARD LVCMOS33 } [get_ports { VGA_HS }]; #IO_L4P_T0_15 Sch=vga_hs
#set_property -dict { PACKAGE_PIN B12 IOSTANDARD LVCMOS33 } [get_ports { VGA_VS }]; #IO_L3N_T0_DQS_AD1N_15 Sch=vga_vs
##Micro SD Connector
#set_property -dict { PACKAGE_PIN E2 IOSTANDARD LVCMOS33 } [get_ports { SD_RESET }]; #IO_L14P_T2_SRCC_35 Sch=sd_reset
#set_property -dict { PACKAGE_PIN A1 IOSTANDARD LVCMOS33 } [get_ports { SD_CD }]; #IO_L9N_T1_DQS_AD7N_35 Sch=sd_cd
#set_property -dict { PACKAGE_PIN B1 IOSTANDARD LVCMOS33 } [get_ports { SD_SCK }]; #IO_L9P_T1_DQS_AD7P_35 Sch=sd_sck
#set_property -dict { PACKAGE_PIN C1 IOSTANDARD LVCMOS33 } [get_ports { SD_CMD }]; #IO_L16N_T2_35 Sch=sd_cmd
#set_property -dict { PACKAGE_PIN C2 IOSTANDARD LVCMOS33 } [get_ports { SD_DAT[0] }]; #IO_L16P_T2_35 Sch=sd_dat[0]
#set_property -dict { PACKAGE_PIN E1 IOSTANDARD LVCMOS33 } [get_ports { SD_DAT[1] }]; #IO_L18N_T2_35 Sch=sd_dat[1]
#set_property -dict { PACKAGE_PIN F1 IOSTANDARD LVCMOS33 } [get_ports { SD_DAT[2] }]; #IO_L18P_T2_35 Sch=sd_dat[2]
#set_property -dict { PACKAGE_PIN D2 IOSTANDARD LVCMOS33 } [get_ports { SD_DAT[3] }]; #IO_L14N_T2_SRCC_35 Sch=sd_dat[3]
##Accelerometer
#set_property -dict { PACKAGE_PIN E15 IOSTANDARD LVCMOS33 } [get_ports { ACL_MISO }]; #IO_L11P_T1_SRCC_15 Sch=acl_miso
#set_property -dict { PACKAGE_PIN F14 IOSTANDARD LVCMOS33 } [get_ports { ACL_MOSI }]; #IO_L5N_T0_AD9N_15 Sch=acl_mosi
#set_property -dict { PACKAGE_PIN F15 IOSTANDARD LVCMOS33 } [get_ports { ACL_SCLK }]; #IO_L14P_T2_SRCC_15 Sch=acl_sclk
#set_property -dict { PACKAGE_PIN D15 IOSTANDARD LVCMOS33 } [get_ports { ACL_CSN }]; #IO_L12P_T1_MRCC_15 Sch=acl_csn
#set_property -dict { PACKAGE_PIN B13 IOSTANDARD LVCMOS33 } [get_ports { ACL_INT[1] }]; #IO_L2P_T0_AD8P_15 Sch=acl_int[1]
#set_property -dict { PACKAGE_PIN C16 IOSTANDARD LVCMOS33 } [get_ports { ACL_INT[2] }]; #IO_L20P_T3_A20_15 Sch=acl_int[2]
##Temperature Sensor
#set_property -dict { PACKAGE_PIN C14 IOSTANDARD LVCMOS33 } [get_ports { TMP_SCL }]; #IO_L1N_T0_AD0N_15 Sch=tmp_scl
#set_property -dict { PACKAGE_PIN C15 IOSTANDARD LVCMOS33 } [get_ports { TMP_SDA }]; #IO_L12N_T1_MRCC_15 Sch=tmp_sda
#set_property -dict { PACKAGE_PIN D13 IOSTANDARD LVCMOS33 } [get_ports { TMP_INT }]; #IO_L6N_T0_VREF_15 Sch=tmp_int
#set_property -dict { PACKAGE_PIN B14 IOSTANDARD LVCMOS33 } [get_ports { TMP_CT }]; #IO_L2N_T0_AD8N_15 Sch=tmp_ct
##Omnidirectional Microphone
#set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { M_CLK }]; #IO_25_35 Sch=m_clk
#set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { M_DATA }]; #IO_L24N_T3_35 Sch=m_data
#set_property -dict { PACKAGE_PIN F5 IOSTANDARD LVCMOS33 } [get_ports { M_LRSEL }]; #IO_0_35 Sch=m_lrsel
##PWM Audio Amplifier
#set_property -dict { PACKAGE_PIN A11 IOSTANDARD LVCMOS33 } [get_ports { AUD_PWM }]; #IO_L4N_T0_15 Sch=aud_pwm
#set_property -dict { PACKAGE_PIN D12 IOSTANDARD LVCMOS33 } [get_ports { AUD_SD }]; #IO_L6P_T0_15 Sch=aud_sd
##USB-RS232 Interface
#set_property -dict { PACKAGE_PIN C4 IOSTANDARD LVCMOS33 } [get_ports { UART_TXD_IN }]; #IO_L7P_T1_AD6P_35 Sch=uart_txd_in
set_property -dict { PACKAGE_PIN D4 IOSTANDARD LVCMOS33 } [get_ports { UART_TXD }]; #IO_L11N_T1_SRCC_35 Sch=uart_rxd_out
#set_property -dict { PACKAGE_PIN D3 IOSTANDARD LVCMOS33 } [get_ports { UART_CTS }]; #IO_L12N_T1_MRCC_35 Sch=uart_cts
#set_property -dict { PACKAGE_PIN E5 IOSTANDARD LVCMOS33 } [get_ports { UART_RTS }]; #IO_L5N_T0_AD13N_35 Sch=uart_rts
##USB HID (PS/2)
set_property -dict { PACKAGE_PIN F4 IOSTANDARD LVCMOS33 } [get_ports { PS2_clk }]; #IO_L13P_T2_MRCC_35 Sch=ps2_clk
set_property -dict { PACKAGE_PIN B2 IOSTANDARD LVCMOS33 } [get_ports { PS2_data }]; #IO_L10N_T1_AD15N_35 Sch=ps2_data
```
The main program is connected to a PS2 receiver, decoder and a 7 segment display.
```
entity top is
Port (
Clk: in std_logic;
Rst: in std_logic;
PS2_clk: in std_logic;
PS2_data: in std_logic;
SEG: out std_logic_vector(7 downto 0);
AN: out std_logic_vector(7 downto 0);
DP: out std_logic;
UART_TXD: out std_logic
);
end top;
architecture Behavioral of top is
signal smallerCLK:std_logic:='0';
signal keycode: std_logic_vector(31 downto 0);
component PS2RECEIVER is
Port ( clk : in STD_LOGIC;
kclk : in STD_LOGIC;
kdata : in STD_LOGIC;
outData : out STD_LOGIC_VECTOR (31 downto 0));
end component;
component DCD is
Port (
input: in std_logic_vector(31 downto 0);
CLK: in std_logic;
output: out std_logic_vector(31 downto 0)
);
end component DCD;
signal output: std_logic_vector(31 downto 0);
begin
process(clk)
begin
smallerCLK<=NOT smallerCLK;
end process;
PS2: PS2RECEIVER port map (smallerCLK,PS2_CLK,PS2_DATA,keycode);
DC:DCD port map(keycode,smallerCLK,output);
display: entity WORK.displ7seg
port map(Clk => Clk,
Rst => Rst,
Data => output,
An => An,
Seg => Seg);
end Behavioral;
```
The PS2 receiver which is connected to a debouncer:
```
entity PS2Receiver is
Port ( clk : in STD_LOGIC;
kclk : in STD_LOGIC;
kdata : in STD_LOGIC;
outData : out STD_LOGIC_VECTOR (31 downto 0));
end PS2Receiver;
architecture Behavioral of PS2Receiver is
signal kclkf: std_logic;
signal kdataf: std_logic;
signal datacur: std_logic_vector(7 downto 0);
signal dataprev: std_logic_vector(7 downto 0);
signal cnt: std_logic_vector(3 downto 0):="0000";
signal keycode: std_logic_vector(31 downto 0):= (Others => '0');
signal flag: std_logic:='0';
component debouncer is
port(CLK: in std_logic;
I0: in std_logic;
I1: in std_logic;
O0: out std_logic;
O1:out std_logic );
end component;
begin
Deb: debouncer port map(clk=>clk,I0=>kclk,I1=>kdata,O0=>kclkf,O1=>kdataf);
process(clk)
begin
if falling_edge(kclkf) then
case cnt is
when "0000" => null ; --do nothing is the starting bit--0
when "0001" => datacur<=datacur(7 downto 1) & kdataf;--1
when "0010" => datacur<=datacur(7 downto 2) & kdataf & datacur(0);--2
when "0011" => datacur<=datacur(7 downto 3) & kdataf & datacur(1 downto 0);--3
when "0100" => datacur<=datacur(7 downto 4) & kdataf & datacur(2 downto 0);--4
when "0101" => datacur<=datacur(7 downto 5) & kdataf & datacur(3 downto 0);---5
when "0110" => datacur<=datacur(7 downto 6) & kdataf & datacur(4 downto 0);--6
when "0111" => datacur<=datacur(7) & kdataf & datacur(5 downto 0);--7
when "1000" => datacur<= kdataf & datacur(6 downto 0);--8
when "1001" => flag<='1';--9
when "1010" => flag<='0';--10
when others=> NULL;
end case;
if(cnt <= 9) then cnt<= cnt+1;
elsif cnt=10 then cnt<=(Others => '0');
end if;
end if;
end process;
process(flag)
begin
if rising_edge(flag) then
if NOT(dataprev = datacur) then
keycode(31 downto 24)<= keycode(23 downto 16);
keycode(23 downto 16)<= keycode(15 downto 8);
keycode(15 downto 8)<= dataprev;
keycode(7 downto 0)<= datacur;
dataprev<= datacur;
end if;
end if;
end process;
outData<=keycode;
end Behavioral;
entity Debouncer is
Port (
CLK: in std_logic;
I0: in std_logic;
I1: in std_logic;
O0: out std_logic;
O1:out std_logic );
end Debouncer;
architecture Behavioral of Debouncer is
signal cnt0: std_logic_vector(4 downto 0):="00000";
signal cnt1: std_logic_vector(4 downto 0):="00000";
signal Iv1: std_logic:='0';
signal Iv0: std_logic:='0';
signal out0:std_logic;
signal out1: std_logic;
begin
process(clk)
begin
if rising_edge(clk) then
if(I0=Iv0)then
if cnt0="10011" then O0<=I0;
else cnt0<=cnt0+"00001";
end if;
else
cnt0<="00000";
Iv0<= I0;
end if;
if(I1=Iv1)then
if cnt1="10011" then O1<=I1;
else cnt1<=cnt1+"00001";
end if;
else
cnt1<="00000";
Iv1<= I1;
end if;
end if;
end process;
end Behavioral;
```
And the DCD is :
```
entity DCD is
Port (
input: in std_logic_vector(31 downto 0);
CLK: in std_logic;
output: out std_logic_vector(31 downto 0)
);
end DCD;
architecture Behavioral of DCD is
signal AUX : std_logic_vector(31 downto 0);
begin
process(clk)
begin
case input is
when "00000000000000000000000001000101"=> AUX <="00000000000000000000000011000000"; --0
when "00000000000000000000000000010110"=> AUX <="00000000000000000000000011111001"; --1
when "00000000000000000000000000011110"=> AUX <="00000000000000000000000010100100"; --2
when "00000000000000000000000000100110"=> AUX <="00000000000000000000000010110000"; --3
when "00000000000000000000000000100101"=> AUX <="00000000000000000000000010011011"; --4
when "00000000000000000000000000101110"=> AUX <="00000000000000000000000010010010"; --5
when "00000000000000000000000000110110"=> AUX <="00000000000000000000000010000010"; --6
when "00000000000000000000000000111101"=> AUX <="00000000000000000000000011111000"; --7
when "00000000000000000000000000111110"=> AUX <="00000000000000000000000010000000"; --8
when "00000000000000000000000001000110"=> AUX <="00000000000000000000000010010000"; --9
when "00000000000000000000000000011100"=> AUX <="00000000000000000000000010001000"; --A
when "00000000000000000000000000110010"=> AUX <="00000000000000000000000010000011"; --b
when "00000000000000000000000000100001"=> AUX <="00000000000000000000000011000110"; --C
when "00000000000000000000000000100011"=> AUX <="00000000000000000000000010100001"; --d
when "00000000000000000000000000100100"=> AUX <="00000000000000000000000010000110"; --E
when "00000000000000000000000000101011"=> AUX <="00000000000000000000000010001110"; --F
when "00000000000000000000000000110100"=> AUX <="00000000000000000000000010000010"; --G
when "00000000000000000000000000110011"=> AUX <="00000000000000000000000010001001"; --H
when "00000000000000000000000001000011"=> AUX <="00000000000000000000000011001111"; --I
when "00000000000000000000000000111011"=> AUX <="00000000000000000000000011110001"; --J
when "00000000000000000000000001000010"=> AUX <="00000000000000000000000010001111"; --K
when "00000000000000000000000001001011"=> AUX <="00000000000000000000000011000111"; --L
when "00000000000000000000000000111010"=> AUX <="00000000000000000000000011001000"; --M
when "00000000000000000000000000110001"=> AUX <="00000000000000000000000010101011"; --N
when "00000000000000000000000001000100"=> AUX <="00000000000000000000000011000000"; --O
when "00000000000000000000000001001101"=> AUX <="00000000000000000000000010001100"; --P
when "00000000000000000000000000010101"=> AUX <="00000000000000000000000010100001"; --Q
when "00000000000000000000000000101101"=> AUX <="00000000000000000000000010101111"; --r
when "00000000000000000000000000011011"=> AUX <="00000000000000000000000010010010"; --S
when "00000000000000000000000000101100"=> AUX <="00000000000000000000000010000111"; --t
when "00000000000000000000000000111100"=> AUX <="00000000000000000000000011000001"; --U
when "00000000000000000000000000101010"=> AUX <="00000000000000000000000011010101"; --V
when "00000000000000000000000000011101"=> AUX <="00000000000000000000000010011001"; --Y
when "00000000000000000000000000011010"=> AUX <="00000000000000000000000010100100"; --Z
when "00000000000000000000000000101001"=> AUX <="00000000000000000000000001110111"; -- Spaceend case
when others=> NULL;
end case;
end process;
output<=AUX;
end Behavioral;
```
Has somebody else run into this problem and has a solution ?
Thank you! | 2019/05/13 | [
"https://Stackoverflow.com/questions/56119014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9076867/"
] | Not sure if this helps but I have a similar setup (Vivado 2019.2 and Nexys 4 (not DDR). I had a very similar issue; I was unable to generate a bitstream. Closer inspection showed that I had this error too after Synthesis. What worked for me was this solution, posted here with the solution by user hongh: [Here](https://forums.xilinx.com/t5/Synthesis/Meaning-of-synthesis-warning-Constraints-18-5210-No-constraint/td-p/881007)
>
> When you generate the synth.dcp with the below method, the warning
> disappears and no constraints are missing:
>
>
> <1>. Open synthesized design
>
>
> <2>. write\_checkpoint synth.dcp
> (type that command in the TCL console)
>
>
>
After doing these 2 simple steps, I was able to run Implementation and generate a bitstream successfully, as well as program my board. I hope this helps, and good luck with your project! | One possible cause is that there's an error in your constraint file, so Vivado didn't load it properly. Check log for any warnings mentioning your constraint file. |
2,618,694 | The first print shows the member value to be false, and the other two prints show it as true. Why does the first output differ from the last two?
```
#include <vector>
#include <iostream>
using namespace std;
class MyClass
{
public:
bool value;
bool stuff;
};
class Container
{
public:
vector<MyClass> my_classes;
Container()
{
MyClass c;
cout << c.value << endl;
my_classes.push_back(c);
}
};
int main (int argc , char* argv[] )
{
MyClass mc;
cout << mc.value << endl;
Container con;
cout << con.my_classes[0].value << endl;
return 0;
}
``` | 2010/04/11 | [
"https://Stackoverflow.com/questions/2618694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145058/"
] | The two members are primitive (non-class) objects and thus uninitialized. That means that their values will be arbitrary at runtime. You must initialize them in the constructor:
```
class MyClass {
public:
bool value;
bool stuff;
MyClass(): value(false), stuff(false) { }
};
``` | You are not initializing members to any value. They will just have any value that was in that place of memory before. |
2,618,694 | The first print shows the member value to be false, and the other two prints show it as true. Why does the first output differ from the last two?
```
#include <vector>
#include <iostream>
using namespace std;
class MyClass
{
public:
bool value;
bool stuff;
};
class Container
{
public:
vector<MyClass> my_classes;
Container()
{
MyClass c;
cout << c.value << endl;
my_classes.push_back(c);
}
};
int main (int argc , char* argv[] )
{
MyClass mc;
cout << mc.value << endl;
Container con;
cout << con.my_classes[0].value << endl;
return 0;
}
``` | 2010/04/11 | [
"https://Stackoverflow.com/questions/2618694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145058/"
] | The two members are primitive (non-class) objects and thus uninitialized. That means that their values will be arbitrary at runtime. You must initialize them in the constructor:
```
class MyClass {
public:
bool value;
bool stuff;
MyClass(): value(false), stuff(false) { }
};
``` | The objects you are declaring in main(..) are automatic hence allocated on the stack of the running thread. Since you don't initialize the objects, they are simply filled with the data that was previously in this very part of the stack.
If you processor is of intel x86 architecture, the assembly language code for a typical function would look something like this (AT&T syntax)
```
pushl %ebp
movl %esp, %ebp
subl $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp
...
<function code goes here>
<that is how we read variable values>
movl -4(%ebp), %ebx
...
addl $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp
popl %ebp
```
As you see, we simply add and substract the necessary number of bytes from the stack pointer, leaving the old data where it was. |
2,618,694 | The first print shows the member value to be false, and the other two prints show it as true. Why does the first output differ from the last two?
```
#include <vector>
#include <iostream>
using namespace std;
class MyClass
{
public:
bool value;
bool stuff;
};
class Container
{
public:
vector<MyClass> my_classes;
Container()
{
MyClass c;
cout << c.value << endl;
my_classes.push_back(c);
}
};
int main (int argc , char* argv[] )
{
MyClass mc;
cout << mc.value << endl;
Container con;
cout << con.my_classes[0].value << endl;
return 0;
}
``` | 2010/04/11 | [
"https://Stackoverflow.com/questions/2618694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145058/"
] | You are not initializing members to any value. They will just have any value that was in that place of memory before. | The objects you are declaring in main(..) are automatic hence allocated on the stack of the running thread. Since you don't initialize the objects, they are simply filled with the data that was previously in this very part of the stack.
If you processor is of intel x86 architecture, the assembly language code for a typical function would look something like this (AT&T syntax)
```
pushl %ebp
movl %esp, %ebp
subl $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp
...
<function code goes here>
<that is how we read variable values>
movl -4(%ebp), %ebx
...
addl $LOCAL_VARIABLES_NUM * WORD_SIZE, %esp
popl %ebp
```
As you see, we simply add and substract the necessary number of bytes from the stack pointer, leaving the old data where it was. |
19,640,762 | I am trying to sum every other digit in the card number by doing this:
```
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
```
All I get is 6. The sum I am looking for is supposed to be 37. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924177/"
] | You're breaking out of the loop on the very first iteration only. So, you won't go past to another iteration.
However, removing the `break` too won't solve your problem. `number % 10` will always give you the last digit of the number, and not every alternate number. You should follow this approach:
* `num % 10` - Will give you last digit.
* Then update the `num` by trimming off the last 2 digits.
* Repeat | Here is updated code in which i have removed logic of flag.This is shorter and easier to understand.
```
public static int sumOfOddDigits(long number){
int sum = 0;
String newString = new StringBuilder(String.valueOf(number)).reverse().toString();
number = Long.parseLong(newString);
while (number != 0){
sum = (int) (sum + number % 10);
number = number / 100;
}
return sum;
}
``` |
19,640,762 | I am trying to sum every other digit in the card number by doing this:
```
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
```
All I get is 6. The sum I am looking for is supposed to be 37. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924177/"
] | You're breaking out of the loop on the very first iteration only. So, you won't go past to another iteration.
However, removing the `break` too won't solve your problem. `number % 10` will always give you the last digit of the number, and not every alternate number. You should follow this approach:
* `num % 10` - Will give you last digit.
* Then update the `num` by trimming off the last 2 digits.
* Repeat | I haven't seen the minimum solution yet, so here goes:
```
public static int sumOddDigits(long input) {
int sum = 0;
for (long temp = input; temp > 0; temp /= 100) {
sum += temp % 10;
}
return sum;
}
```
You don't need to divide by 10 and check if it's an even number, you can just divide by 100 every time.
Demo: <http://ideone.com/sDZfpU> |
19,640,762 | I am trying to sum every other digit in the card number by doing this:
```
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
```
All I get is 6. The sum I am looking for is supposed to be 37. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924177/"
] | Try this ... this should work for you
```
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 != 0)
{
sum = (sum + (int)(number % 10));
number = number/10;
}else {
number = number/10;
}
}
return sum;
}
```
What I have done here is if `i` is odd, I take a mod of the number so I get the last digit of the number and then add it to sum and then I get rid of the last digit by dividing it with 10 and if the number is even I just get rid of the digit in the `i`th position.
Here I am collecting the digits in odd places in reverse order. | Here is updated code in which i have removed logic of flag.This is shorter and easier to understand.
```
public static int sumOfOddDigits(long number){
int sum = 0;
String newString = new StringBuilder(String.valueOf(number)).reverse().toString();
number = Long.parseLong(newString);
while (number != 0){
sum = (int) (sum + number % 10);
number = number / 100;
}
return sum;
}
``` |
19,640,762 | I am trying to sum every other digit in the card number by doing this:
```
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
```
All I get is 6. The sum I am looking for is supposed to be 37. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924177/"
] | Try this ... this should work for you
```
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 != 0)
{
sum = (sum + (int)(number % 10));
number = number/10;
}else {
number = number/10;
}
}
return sum;
}
```
What I have done here is if `i` is odd, I take a mod of the number so I get the last digit of the number and then add it to sum and then I get rid of the last digit by dividing it with 10 and if the number is even I just get rid of the digit in the `i`th position.
Here I am collecting the digits in odd places in reverse order. | I haven't seen the minimum solution yet, so here goes:
```
public static int sumOddDigits(long input) {
int sum = 0;
for (long temp = input; temp > 0; temp /= 100) {
sum += temp % 10;
}
return sum;
}
```
You don't need to divide by 10 and check if it's an even number, you can just divide by 100 every time.
Demo: <http://ideone.com/sDZfpU> |
19,640,762 | I am trying to sum every other digit in the card number by doing this:
```
/*
Return the sum of the odd-place digits.
*/
public static int sumOfoddPlace(long number)
{
int maxDigitLength = 16;
int sum = 0;
for (int i = 1; i <= maxDigitLength; i++)
{
if (i % 2 == 1)
{
sum = sum + (int)(number % 10);
}
break;
}
return sum;
}
```
All I get is 6. The sum I am looking for is supposed to be 37. | 2013/10/28 | [
"https://Stackoverflow.com/questions/19640762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2924177/"
] | I haven't seen the minimum solution yet, so here goes:
```
public static int sumOddDigits(long input) {
int sum = 0;
for (long temp = input; temp > 0; temp /= 100) {
sum += temp % 10;
}
return sum;
}
```
You don't need to divide by 10 and check if it's an even number, you can just divide by 100 every time.
Demo: <http://ideone.com/sDZfpU> | Here is updated code in which i have removed logic of flag.This is shorter and easier to understand.
```
public static int sumOfOddDigits(long number){
int sum = 0;
String newString = new StringBuilder(String.valueOf(number)).reverse().toString();
number = Long.parseLong(newString);
while (number != 0){
sum = (int) (sum + number % 10);
number = number / 100;
}
return sum;
}
``` |
16,062 | Short:
I want DHCP server to assign a preconfigured IP address based on a port (on a switch, ideally) a device is connected to.
Long:
My situation:
I am building an automated indoor farm (for growing tomatoes). The farm is composed of many (12 for now, but will grow to hundreds) identical 7"x7" rooms. Each room will have an Ethernet port, and into this port an environment control system will be plugged in. Note that each room needs to be controlled individually.
Rooms are arranged in rows of 12, so I was thinking I will have a switch per row, and connect these switches to a router.
I could program each environmental controller with a static IP, so that I can associate a controller to a particular room on the server, but I think it would be easier if I could assign an IP address to each room, which would also make controllers interchangeable and hot swap-able with no need for manual configuration.
InB4: I am also considering using ZigBee network for this application, but I may need to transmit diagnostic images, and with hundreds of units ZigBee may be inadequate.
**Question:** is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this? | 2015/01/09 | [
"https://networkengineering.stackexchange.com/questions/16062",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/13301/"
] | >
> is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this?
>
>
>
You can use a Cisco switch and an IOS that supports [DHCP Server Port-Based Address Allocation](http://www.cisco.com/en/US/docs/switches/lan/catalyst2960/software/release/12.2_55_se/configuration/guide/swdhcp82.html#wp1320905) on your switch; you also must issue DHCP from your switch. Assume that you have got `Fa0/1` and `Fa0/2` in Vlan120.
```
ip dhcp use subscriber-id client-id
ip dhcp subscriber-id interface-name
ip dhcp excluded-address 192.0.2.1 192.0.2.10
!
ip dhcp pool VLAN120
network 192.0.2.0 255.255.255.0
default-router 192.0.2.1
dns-server 192.0.2.5
reserved-only
address 192.0.2.101 client-id "Fa0/1" ascii
address 192.0.2.102 client-id "Fa0/2" ascii
```
This configuration reserves addresses for fa0/1 and fa0/2. The same address will always be assigned to those ports. | If you want "hot swappable," the device names will have to be independent of their location. You'll need to keep track of device MAC addresses on a chart with an easy corresponding Minion name like "Bob." Then configure the device with that name or description "Bob." This way when network monitoring reports issues only the description or name matters to check the chart. You just have to keep track on the chart where you put the devices.
Switches are more concerned with physical addresses than ip addresses. However, each floor could use its own vlan with its own dhcp server. Then you can create a named vlan for each floor like "grow\_rooms\_1-12" with /28 subnet mask. You can also give each port a description like "to grow room 1." These are great management aids if you are watching your network via command line.
You can also alter size of rooms to improve efficiency of lighting, humidity, and temperature which could also reduce monitoring devices. |
16,062 | Short:
I want DHCP server to assign a preconfigured IP address based on a port (on a switch, ideally) a device is connected to.
Long:
My situation:
I am building an automated indoor farm (for growing tomatoes). The farm is composed of many (12 for now, but will grow to hundreds) identical 7"x7" rooms. Each room will have an Ethernet port, and into this port an environment control system will be plugged in. Note that each room needs to be controlled individually.
Rooms are arranged in rows of 12, so I was thinking I will have a switch per row, and connect these switches to a router.
I could program each environmental controller with a static IP, so that I can associate a controller to a particular room on the server, but I think it would be easier if I could assign an IP address to each room, which would also make controllers interchangeable and hot swap-able with no need for manual configuration.
InB4: I am also considering using ZigBee network for this application, but I may need to transmit diagnostic images, and with hundreds of units ZigBee may be inadequate.
**Question:** is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this? | 2015/01/09 | [
"https://networkengineering.stackexchange.com/questions/16062",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/13301/"
] | >
> is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this?
>
>
>
You can use a Cisco switch and an IOS that supports [DHCP Server Port-Based Address Allocation](http://www.cisco.com/en/US/docs/switches/lan/catalyst2960/software/release/12.2_55_se/configuration/guide/swdhcp82.html#wp1320905) on your switch; you also must issue DHCP from your switch. Assume that you have got `Fa0/1` and `Fa0/2` in Vlan120.
```
ip dhcp use subscriber-id client-id
ip dhcp subscriber-id interface-name
ip dhcp excluded-address 192.0.2.1 192.0.2.10
!
ip dhcp pool VLAN120
network 192.0.2.0 255.255.255.0
default-router 192.0.2.1
dns-server 192.0.2.5
reserved-only
address 192.0.2.101 client-id "Fa0/1" ascii
address 192.0.2.102 client-id "Fa0/2" ascii
```
This configuration reserves addresses for fa0/1 and fa0/2. The same address will always be assigned to those ports. | I was able to do what you wanted using Cisco IOS DHCP and option 82 snooping. I may not be using the right terms. But, basically I needed to assign IP addresses to kitchen printers based on the station in the kitchen they were at. If one of these printers died during a dinner shift, the store manager would need to be able to put a new printer configured with DHCP in and have it be configured with the same address as the printer removed. I also needed all 8 printers to be in the same broadcast domain and I could not use helper to send to a windows 2012 server as the store needed to continue to work even if my wan went down.
I did this with the following command on each switch port:
`ip dhcp snooping vlan 3 information option format-type circuit-id override string broil` (or whatever is relevant to you)
Use an ASCII to hex converter and convert your string to hex
Then on the DHCP server be it a switch or a router set up a DHCP class. For my broil above it is this
```
ip dhcp class broil
relay agent information
relay-information hex 010562726f696c*
```
it is `010 <number of characters in your string so 5 since broil is 5 characters><whatever your string converts to>`
Here is how my pool is set up.
```
ip dhcp pool Kitchen
network 10.102.1.0 255.255.255.0
default-router 10.102.1.1
lease infinite
class broil
address range 10.102.1.160 10.102.1.160
```
And finally in order to make this address available to another device should the one in that switch port fail, I set up a kron job to issue `clear ip dhcp bind *` every 5 minutes.
I believe for ALL of this to work I needed the following additional commands on my ios switch that is my dhcp server
```
ip dhcp relay information trust-all ip dhcp subscriber-id
interface-name
ip dhcp snooping vlan 3 (our vlan of course) ip dhcp snooping
information option allow-untrusted ip dhcp snooping
```
and on any port linking your DHCP server switch to any other switches that may be used for this (along with that switches uplink to your DHCP server switch)
```
ip dhcp snooping trust
```
Thats basically it. Works like a charm and FINALLY allowed us to get off of IP to serial printing which was a train wreck. |
16,062 | Short:
I want DHCP server to assign a preconfigured IP address based on a port (on a switch, ideally) a device is connected to.
Long:
My situation:
I am building an automated indoor farm (for growing tomatoes). The farm is composed of many (12 for now, but will grow to hundreds) identical 7"x7" rooms. Each room will have an Ethernet port, and into this port an environment control system will be plugged in. Note that each room needs to be controlled individually.
Rooms are arranged in rows of 12, so I was thinking I will have a switch per row, and connect these switches to a router.
I could program each environmental controller with a static IP, so that I can associate a controller to a particular room on the server, but I think it would be easier if I could assign an IP address to each room, which would also make controllers interchangeable and hot swap-able with no need for manual configuration.
InB4: I am also considering using ZigBee network for this application, but I may need to transmit diagnostic images, and with hundreds of units ZigBee may be inadequate.
**Question:** is it possible to assign a preconfigured IP address based on a port a device is connected to? What devices do I need for this? | 2015/01/09 | [
"https://networkengineering.stackexchange.com/questions/16062",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/13301/"
] | I was able to do what you wanted using Cisco IOS DHCP and option 82 snooping. I may not be using the right terms. But, basically I needed to assign IP addresses to kitchen printers based on the station in the kitchen they were at. If one of these printers died during a dinner shift, the store manager would need to be able to put a new printer configured with DHCP in and have it be configured with the same address as the printer removed. I also needed all 8 printers to be in the same broadcast domain and I could not use helper to send to a windows 2012 server as the store needed to continue to work even if my wan went down.
I did this with the following command on each switch port:
`ip dhcp snooping vlan 3 information option format-type circuit-id override string broil` (or whatever is relevant to you)
Use an ASCII to hex converter and convert your string to hex
Then on the DHCP server be it a switch or a router set up a DHCP class. For my broil above it is this
```
ip dhcp class broil
relay agent information
relay-information hex 010562726f696c*
```
it is `010 <number of characters in your string so 5 since broil is 5 characters><whatever your string converts to>`
Here is how my pool is set up.
```
ip dhcp pool Kitchen
network 10.102.1.0 255.255.255.0
default-router 10.102.1.1
lease infinite
class broil
address range 10.102.1.160 10.102.1.160
```
And finally in order to make this address available to another device should the one in that switch port fail, I set up a kron job to issue `clear ip dhcp bind *` every 5 minutes.
I believe for ALL of this to work I needed the following additional commands on my ios switch that is my dhcp server
```
ip dhcp relay information trust-all ip dhcp subscriber-id
interface-name
ip dhcp snooping vlan 3 (our vlan of course) ip dhcp snooping
information option allow-untrusted ip dhcp snooping
```
and on any port linking your DHCP server switch to any other switches that may be used for this (along with that switches uplink to your DHCP server switch)
```
ip dhcp snooping trust
```
Thats basically it. Works like a charm and FINALLY allowed us to get off of IP to serial printing which was a train wreck. | If you want "hot swappable," the device names will have to be independent of their location. You'll need to keep track of device MAC addresses on a chart with an easy corresponding Minion name like "Bob." Then configure the device with that name or description "Bob." This way when network monitoring reports issues only the description or name matters to check the chart. You just have to keep track on the chart where you put the devices.
Switches are more concerned with physical addresses than ip addresses. However, each floor could use its own vlan with its own dhcp server. Then you can create a named vlan for each floor like "grow\_rooms\_1-12" with /28 subnet mask. You can also give each port a description like "to grow room 1." These are great management aids if you are watching your network via command line.
You can also alter size of rooms to improve efficiency of lighting, humidity, and temperature which could also reduce monitoring devices. |
2,058,877 | I am trying to add trusted sites to Mac OS X's firewall via command-line. I understand that previously, we were able to use **ipfw** to configure the firewall on a packet level by using port numbers or IPs. In Leopard (10.5) and on, there is a new feature to add a trusted application to a list. This can be accomplished using the UI:
*System Preferences > Security > Firewall*
As well as using the command-line: **socketfilterfw**
```
%sudo /usr/libexec/ApplicationFirewall/socketfilterfw -t "[binary path of application]"
```
However, I am having problems when I execute the above command, the utility "hangs" and doesn't seem to do anything. This is the output I would receive, and then does nothing:
```
kyue:/usr/libexec/ApplicationFirewall> sudo ./socketfilterfw -t \~/[my binary path]\
adding ~/[my binary path] to the list of trusted applications
GetSignException: creator ‘BNUp’
GetSignException: creator ‘BNu2′
GetSignException: creator ‘SWar’
GetSignException: creator ‘StCm’
GetSignException: creator ‘Dbl2′
GetSignException: creator ‘PJ03′
GetSignException: creator ‘PJ07′
GetSignException: creator ‘FP98′
```
There was great guidance from this article:
<http://krypted.com/mac-os-x/command-line-alf-on-mac-os-x/comment-page-1/#comment-547>
Just wondering if anyone here may know why it doesn't seem to be working.
Kat | 2010/01/13 | [
"https://Stackoverflow.com/questions/2058877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132429/"
] | Have 2 tables, Team and Game, where Team has a team name, and a team ID, and game has 2 team IDs (team 1 and team 2) and the score of the game. Then, you have foreign keys (for integrity) between the Game and Team tables. This will reflect who played who and what the score was with a minimal schema and a very simple structure.
```
Team
|-------------------------|
| Primary (int)| id |
| (chr)| name |
|-------------------------|
Game
|-------------------------|
| Primary (int)| team1 |
| Primary (int)| team2 |
| (int)| score1 |
| (int)| score2 |
|-------------------------|
```
So, some sample data would look like:
```
Team
|------------------|
| id | name |
|------------------|
| 1 | Blue Devils |
| 2 | Cardinals |
| 3 | Fish |
| 4 | Lemmings |
|------------------|
Game
|---------------------------------|
| team1 | team2 | score1 | score2 |
|---------------------------------|
| 1 | 2 | 7 | 8 |
| 1 | 4 | 2 | 25 |
| 2 | 3 | 8 | 2 |
| 3 | 4 | 17 | 18 |
|---------------------------------|
```
This data indicates that team 1 (Blue Devils) played team 2 (Cardinals) with a score of 7 to 8. The rest of the data is similar.
If you do not need to track the team names, you can leave that field out, but this is often useful information.
So, with this schema, you would get the scores for a particular team with a query like
```
SELECT * FROM Game g
INNER JOIN Team t on t.team1 = g.id
```
You could then also add additional information if you need to, like when the game took place (date), and any other information, such as other statistics about the game or team. | The first response is correct. If you organize your data into relations, and create one table for each relation, the data will be a lot easier to work with. The background learning you need to do in relational database design will teach you more about this.
If you use the Team and Game structure from the response, you can still convert that structure into the kind of structure you imagined in your question. This process is called "crosstabulating" or "pivoting" and it's well documented in the tutorials.
While it's easy to move from a relational structure to a crosstabulated one, it's monstruously difficult to go the other way. It's also difficult to compose other queries against crosstabulated data. An example might be finding the highest score scored against each team. If you put your data in a database, sooner or later you are ging to want to do more than one thing with it. |
33,524,696 | I was under the impression that this syntax:
```
import Router from 'react-router';
var {Link} = Router;
```
has the same final result as this:
```
import {Link} from 'react-router';
```
Can someone explain what the difference is?
(I originally thought it was a [React Router Bug](https://github.com/rackt/react-router/issues/2468).) | 2015/11/04 | [
"https://Stackoverflow.com/questions/33524696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | ```
import {Link} from 'react-router';
```
imports a **named export** from `react-router`, i.e. something like
```
export const Link = 42;
```
---
```
import Router from 'react-router';
const {Link} = Router;
```
pulls out the property `Link` from the **default export**, assuming it is an object, e.g.
```
export default {
Link: 42
};
```
(the default export is actually nothing but a standardized named export with the name "default").
See also [`export` on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
Complete example:
```
// react-router.js
export const Link = 42;
export default {
Link: 21,
};
// something.js
import {Link} from './react-router';
import Router from './react-router';
const {Link: Link2} = Router;
console.log(Link); // 42
console.log(Link2); // 21
```
---
With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes. | To do this:
```
import {purple, grey} from 'themeColors';
```
*Without repeating `export const` for each symbol*, just do:
```
export const
purple = '#BADA55',
grey = '#l0l',
gray = grey,
default = 'this line actually causes an error';
``` |
33,524,696 | I was under the impression that this syntax:
```
import Router from 'react-router';
var {Link} = Router;
```
has the same final result as this:
```
import {Link} from 'react-router';
```
Can someone explain what the difference is?
(I originally thought it was a [React Router Bug](https://github.com/rackt/react-router/issues/2468).) | 2015/11/04 | [
"https://Stackoverflow.com/questions/33524696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | ```
import {Link} from 'react-router';
```
imports a **named export** from `react-router`, i.e. something like
```
export const Link = 42;
```
---
```
import Router from 'react-router';
const {Link} = Router;
```
pulls out the property `Link` from the **default export**, assuming it is an object, e.g.
```
export default {
Link: 42
};
```
(the default export is actually nothing but a standardized named export with the name "default").
See also [`export` on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export).
Complete example:
```
// react-router.js
export const Link = 42;
export default {
Link: 21,
};
// something.js
import {Link} from './react-router';
import Router from './react-router';
const {Link: Link2} = Router;
console.log(Link); // 42
console.log(Link2); // 21
```
---
With Babel 5 and below I believe they have been interchangeable because of the way ES6 modules have been transpiled to CommonJS. But those are two different constructs as far as the language goes. | Except for different exports, it may also lead to
different bundled code by WebPack when using two variant ways to destruct ESM modules:
```js
// react-router
export function Link(str) { /* ... */ }
```
1. Destruct within the `import` statement:
```js
import {Link} from 'react-router';
Link('1');
Link('2');
```
```js
// WebPack output
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('1');
(0,util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__.Link)('2');
```
2. Use destructuring syntax:
```js
import * as Router from 'react-router';
const {Link} = Router;
Link('1');
Link('2');
```
```js
// WebPack output:
var util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
const {Link} = util_mobileValidator__WEBPACK_IMPORTED_MODULE_3__;
Link(1);
Link(2);
```
As you can see in the output example above where there is redundant code, which is not good for optimization when trying to uglify via `UglifyJS`, or `Terser`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.