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
|
---|---|---|---|---|---|
72,862,776 | I am trying to put together a diagram in CSS of a flow chart. I have attached below a picture. Is there a simple way to do this? I've been Googling around quite a bit looking for examples, but I don't know what to call this.
Can you please let me know how to do this? Or if this is something common, what I can Google to find more information.
[](https://i.stack.imgur.com/K2QXT.png) | 2022/07/04 | [
"https://Stackoverflow.com/questions/72862776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7053813/"
] | By using [CSS Flex](https://developer.mozilla.org/en-US/docs/Web/CSS/flex) you could achieve something like:
```css
body {font: 16px/1.4 sans-serif;}
.chart-row,
.chart-col {
display: flex;
gap: 1em;
}
.chart-row {
flex-direction: row;
}
.chart-col {
flex-direction: column;
}
.chart-pill,
.chart-rect{
padding: 1em;
text-align: center;
border: 2px solid #999;
}
.chart-pill {
flex: 1;
border-radius: 1em;
border-style: dashed;
}
.chart-rect{
flex: 0;
margin: auto 0;
background: #eee;
}
.chart-line-h {
height: 2px;
min-width: 3em;
background: #999;
margin: auto -1em;
}
```
```html
<div class="chart-row">
<div class="chart-pill chart-col">
<div class="chart-rect">alpha</div>
</div>
<div class="chart-line-h"></div>
<div class="chart-pill chart-col">
<div class="chart-rect">beta</div>
<div class="chart-rect">gamma</div>
<div class="chart-rect">delta</div>
</div>
<div class="chart-line-h"></div>
<div class="chart-pill chart-col">
<div class="chart-rect">gamma</div>
</div>
</div>
``` | I'll just add an answer because I can't write any comments yet, although I'm not new at CSS...
Yes, you can use Flexbox but I will also add CSS Grid, as the combination of both can give you more flexibility if you're planning on making bigger charts...
Once you get it working, it's pretty easy to use...
Copy and paste this code in your code editor and display it in your browser.
( if you use VSCode you can use the liveServer extension)
Then go to the dev tools inside your browser (Ctrl+Shift+i) and click the icon to select an element (the one on top at the very left hand side).
Then, inside the first div, you will see a label with the word grid, click it and you'll see the grid on your screen.
Finally, you just have to fill the rows and columns with the figures as in one of those old battleship games, or a 2D Cartesian Coordinate System.
Keep in mind that when placing your items on the Grid, it's better to use the lines instead of the areas of the rows and columns, as it's much easier to understand it this way.
[](https://i.stack.imgur.com/wokB7.png)
So for instance, in this case, connector1 goes from vertical line 9 to vertical line 10, or the first figure fills the space between line 5 and line 9, and so on.
Hope it helps!
By the way, I changed colours as it's easier for the explanation..
HTML :
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<!-- GRID FLOWCHART -->
<div class="flowchart">
<!-- FIRST FIGURE -->
<div class="set" id="set1">
<div class="box"><p>alpha</p></div>
</div>
<!-- FIRST CONNECTOR -->
<div class="connector" id="connector1"></div>
<!-- SECOND FIGURE -->
<div class="set" id="set2">
<div class="box"><p>beta</p></div>
<div class="box"><p>gamma</p></div>
<div class="box"><p>delta</p></div>
</div>
<!-- SECOND CONNECTOR -->
<div class="connector" id="connector2"></div>
<!-- THIRD FIGURE -->
<div class="set" id="set3">
<div class="box"><p>gamma</p></div>
</div>
</div>
</body>
</html>
```
CSS :
```
body {
width: 100vw;
height: 100vh;
background-color: #d3d3d3;
}
/* ****** GENERIC SHAPES : ********** */
.flowchart {
display: grid;
grid-template-columns: repeat(24, 1fr);
grid-template-rows: repeat(12, 1fr);
width: fit-content;
height: fit-content;
grid-gap: 2px;
}
.set {
min-width: 100px;
min-height: 100px;
border: 2px dashed blue;
border-radius: 15px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.box {
width: 80%;
height: 15%;
background-color: rgb(255, 255, 255);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin: 4%;
padding: 6%;
border: 1px solid black;
/* border-radius: 5px; */
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 0.9em;
}
.connector {
width: 120%;
max-height: 3px;
background-color: black;
transform: translateX(-6%);
}
/* ************* FIGURES : ************* */
#set1 {
grid-column: 5/9;
grid-row: 5/12;
}
#set2 {
grid-column: 10/14;
grid-row: 5/12;
}
#set3 {
grid-column:15/19;
grid-row: 5/12;
}
/* ******** CONNECTORS : *********** */
#connector1 {
grid-column: 9/10;
grid-row: 8/9;
}
#connector2 {
grid-column: 14/15;
grid-row: 8/9;
}
``` |
41,318,581 | I'm using a random number generator and IF Statements to switch between activities. It iterates through the first if statement and stops there. I don't think my random number generator is generating any random numbers. Thanks in advance.
```
package app.com.example.android.oraclethedeciscionmaker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.Random;
public class HomeScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
}
public void onClick(View view){
Random guess = new Random();
int guesser0 = guess.nextInt(0) + 1;
int guesser1 = guess.nextInt(0) + 1;
int guesser2 = guess.nextInt(0) + 1;
int guesser3 = guess.nextInt(0) + 1;
int guesser4 = guess.nextInt(0) + 1;
int result = guesser0 + guesser1 + guesser2 + guesser3 + guesser4;
// 0 out of 0
if(result == 0){
Intent intent = new Intent(HomeScreen.this, ZeroOfFive.class);
startActivity(intent);
// If this statement is true go to this activity
}
// 1 out of 5
else if(result == 1){
Intent intent = new Intent(HomeScreen.this, OneOfFive.class);
startActivity(intent);
// If this statement is true go to this activity
}
//2 out of 5
else if(result == 2){
Intent intent = new Intent(HomeScreen.this, TwoOfFive.class);
startActivity(intent);
// If this statement is true go to this activity
}
//3 out of 5
else if(result == 3){
Intent intent = new Intent(HomeScreen.this, ThreeOfFive.class);
startActivity(intent);
// If this statement is true go to this activity
}
//4 out of 5
else if(result == 4){
Intent intent = new Intent(HomeScreen.this, FourOfFive.class);
startActivity(intent);
// If this statement is true go to this activity
}
//5 out of 5
else {
Intent intent = new Intent(HomeScreen.this, FiveOfFive.class);
startActivity(intent);
}
}
}
``` | 2016/12/25 | [
"https://Stackoverflow.com/questions/41318581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6191311/"
] | The only thing I did was instead of using a path like
```
c:\xyz\desktop\practice
```
and starting http-server, I did the following:
step 1:
```
c:\
```
step 2:
```
http-server c:\xyz\desktop\practice
```
It started working. Thanks for everyone's help. | Instead of
```
127.0.0.1 8081
```
Use this:
```
http://127.0.0.1:8081/wamp/www/Angular_1/contactapp/
``` |
1,451,281 | I'm just starting, and yes, i haven't written any tests yet (I'm not a fundamentalist, I don't like compile errors just because there is no test), but I'm wondering where to get started on doing a project that parses fixed length flat file records according to an XML mapping, into a class that represents the superset of all file layouts, before writing (with transformation) the class details to a DB table.
There are so many external factors, and I don't want to mock them all, so where or how would be a good way to start test driving this project? | 2009/09/20 | [
"https://Stackoverflow.com/questions/1451281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | It's all about decomposing the problem into parts. Some examples:
* File/stream reader
* Input mapper
* Input mapper loader
* File layout
* File layout collection
* Data access layer
Try to give each class a single responsibility, determine its dependencies, and inject those in. That, with the help of mocks/stubs, will permit you to test each class in isolation. | Well, you want to do testing but you don't want to mock. I believe that it leaves you to write [integration tests](http://en.wikipedia.org/wiki/Integration_testing) or [acceptance tests](http://en.wikipedia.org/wiki/Acceptance_test). It means that you have to do a lot of setup in your tests that probably will make your test brittle and hard to maintain.
I would really recommend to mock your external dependencies. It will make your application loosely couple and I believed it's going to be easier maintain in the future. Plus your tests are going to be much more manageable.
There are lot of [Mock Frameworks](http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx) out there that can help you. I have to admit that if you never done that before there's some learning curve. But we are in software development business and there's always something new to learn.
In case you decided to invest some time to learn testing with mock, you can start with [this article](http://vkreynin.wordpress.com/2008/12/04/tutorial-to-tdd-using-rhino-mocks-and-systemwrapper/).
Good luck. |
1,451,281 | I'm just starting, and yes, i haven't written any tests yet (I'm not a fundamentalist, I don't like compile errors just because there is no test), but I'm wondering where to get started on doing a project that parses fixed length flat file records according to an XML mapping, into a class that represents the superset of all file layouts, before writing (with transformation) the class details to a DB table.
There are so many external factors, and I don't want to mock them all, so where or how would be a good way to start test driving this project? | 2009/09/20 | [
"https://Stackoverflow.com/questions/1451281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | Two techniques I've found useful for testing IO-based classes:
* Where possible, talk in general terms like `StreamReader` and `Stream` rather than filenames. It's easy to create a `StringReader` or a `MemoryStream` in tests and provide the data that way.
* Sometimes you need more data than you really want to embed in literals in the code. In that case, add test files (sometimes both input and expected output) as embedded resources, and use `Assembly.GetManifestResourceStream` to get the data at execution time.
Beyond those general points, TrueWill's advice sounds very good. If you can split up the bigger task, writing the unit test for each individual bit sounds like it'll probably be easy - with the exception of the database access, which is usually a pain. If you can make the database part as small as possible, providing all the data from another easy-to-test class, that should make life simpler. | Well, you want to do testing but you don't want to mock. I believe that it leaves you to write [integration tests](http://en.wikipedia.org/wiki/Integration_testing) or [acceptance tests](http://en.wikipedia.org/wiki/Acceptance_test). It means that you have to do a lot of setup in your tests that probably will make your test brittle and hard to maintain.
I would really recommend to mock your external dependencies. It will make your application loosely couple and I believed it's going to be easier maintain in the future. Plus your tests are going to be much more manageable.
There are lot of [Mock Frameworks](http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx) out there that can help you. I have to admit that if you never done that before there's some learning curve. But we are in software development business and there's always something new to learn.
In case you decided to invest some time to learn testing with mock, you can start with [this article](http://vkreynin.wordpress.com/2008/12/04/tutorial-to-tdd-using-rhino-mocks-and-systemwrapper/).
Good luck. |
1,451,281 | I'm just starting, and yes, i haven't written any tests yet (I'm not a fundamentalist, I don't like compile errors just because there is no test), but I'm wondering where to get started on doing a project that parses fixed length flat file records according to an XML mapping, into a class that represents the superset of all file layouts, before writing (with transformation) the class details to a DB table.
There are so many external factors, and I don't want to mock them all, so where or how would be a good way to start test driving this project? | 2009/09/20 | [
"https://Stackoverflow.com/questions/1451281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | It's all about decomposing the problem into parts. Some examples:
* File/stream reader
* Input mapper
* Input mapper loader
* File layout
* File layout collection
* Data access layer
Try to give each class a single responsibility, determine its dependencies, and inject those in. That, with the help of mocks/stubs, will permit you to test each class in isolation. | Two techniques I've found useful for testing IO-based classes:
* Where possible, talk in general terms like `StreamReader` and `Stream` rather than filenames. It's easy to create a `StringReader` or a `MemoryStream` in tests and provide the data that way.
* Sometimes you need more data than you really want to embed in literals in the code. In that case, add test files (sometimes both input and expected output) as embedded resources, and use `Assembly.GetManifestResourceStream` to get the data at execution time.
Beyond those general points, TrueWill's advice sounds very good. If you can split up the bigger task, writing the unit test for each individual bit sounds like it'll probably be easy - with the exception of the database access, which is usually a pain. If you can make the database part as small as possible, providing all the data from another easy-to-test class, that should make life simpler. |
71,793,245 | Is there a standard algorithm in the library that does the job of the following for-loop?
```
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main( )
{
const char oldFillCharacter { '-' };
std::vector<char> vec( 10, oldFillCharacter ); // construct with 10 chars
// modify some of the elements
vec[1] = 'e';
vec[7] = 'x';
vec[9] = '{';
const char newFillCharacter { '#' };
for ( auto& elem : vec ) // change the fill character of the container
{
if ( elem == oldFillCharacter )
{
elem = newFillCharacter;
}
}
// output to stdout
std::copy( std::begin( vec ), std::end( vec ),
std::ostream_iterator<char>( std::cout, " " ) );
std::cout << '\n';
/* prints: # e # # # # # x # { */
}
```
I want to replace the above *range-based for-loop* with a **one-liner** if possible. Is there any function that does this? I looked at [std::for\_each](https://en.cppreference.com/w/cpp/algorithm/for_each) but I guess it's not suitable for such a scenario. | 2022/04/08 | [
"https://Stackoverflow.com/questions/71793245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13407802/"
] | This loop will replace every occurrence of `oldFillCharacter` with `newFillCharacter`. If you don't want to do something more fancy [`std::replace`](https://en.cppreference.com/w/cpp/algorithm/replace) looks good:
```
std::replace(std::begin(vec), std::end(vec), oldFillCharacter, newFillCharacter);
```
Or a bit simpler with [`std::ranges::replace`](https://en.cppreference.com/w/cpp/algorithm/ranges/replace):
```
std::ranges::replace(vec, oldFillCharacter, newFillCharacter);
``` | You can use `std::for_each`.
```
std::for_each(vec.begin(), vec.end(), [](char& elem) {
if ( elem == oldFillCharacter ) elem = newFillCharacter;
});
``` |
71,793,245 | Is there a standard algorithm in the library that does the job of the following for-loop?
```
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main( )
{
const char oldFillCharacter { '-' };
std::vector<char> vec( 10, oldFillCharacter ); // construct with 10 chars
// modify some of the elements
vec[1] = 'e';
vec[7] = 'x';
vec[9] = '{';
const char newFillCharacter { '#' };
for ( auto& elem : vec ) // change the fill character of the container
{
if ( elem == oldFillCharacter )
{
elem = newFillCharacter;
}
}
// output to stdout
std::copy( std::begin( vec ), std::end( vec ),
std::ostream_iterator<char>( std::cout, " " ) );
std::cout << '\n';
/* prints: # e # # # # # x # { */
}
```
I want to replace the above *range-based for-loop* with a **one-liner** if possible. Is there any function that does this? I looked at [std::for\_each](https://en.cppreference.com/w/cpp/algorithm/for_each) but I guess it's not suitable for such a scenario. | 2022/04/08 | [
"https://Stackoverflow.com/questions/71793245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13407802/"
] | This loop will replace every occurrence of `oldFillCharacter` with `newFillCharacter`. If you don't want to do something more fancy [`std::replace`](https://en.cppreference.com/w/cpp/algorithm/replace) looks good:
```
std::replace(std::begin(vec), std::end(vec), oldFillCharacter, newFillCharacter);
```
Or a bit simpler with [`std::ranges::replace`](https://en.cppreference.com/w/cpp/algorithm/ranges/replace):
```
std::ranges::replace(vec, oldFillCharacter, newFillCharacter);
``` | ```
std::replace(vec.begin(), vec.end(), '_', '#');
``` |
1,648,939 | i ran jconsole, i see some live threads count and daemon threads count .... i run no other java app/classes .... i could see the list of live threads but not daemon thread .... is there a way to know what is the list of deamon threads ? | 2009/10/30 | [
"https://Stackoverflow.com/questions/1648939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can create a thread dump (using the `jstack` tool), which will show for each thread whether it is a daemon or not.
Instead of using `jstack` on the command line, you can also trigger a thread dump using visualvm (<http://visualvm.dev.java.net>), and look at the threads over time. | The daemon are included in live threads.
Both in the counter and list.
I don't think jconsole has an option to show only daemon threads.
Must of the "built-in" if not all but the "main" thread are daemon threads. |
64,601,439 | I am new to HTML and CSS. I want to achieve rounded-corner for my table and it is not working. Any ideas how can I make it work?
Here is my CSS for table:
```
table {
border: 1px solid #CCC;
border-collapse: collapse;
font-size:13px;
color:white;
}
td {
border: none;
}
```
Currently, it looks like this:
[](https://i.stack.imgur.com/Ce5NO.png)
And I want the corner of the table to be rounded.
Many thanks. | 2020/10/30 | [
"https://Stackoverflow.com/questions/64601439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11471461/"
] | You can make the rounded table using the `border-radius` CSS attribute based on `border-collapse: separate` as follows.
```css
table {
border: 1px solid #CCC;
font-size: 13px;
color: white;
background: red;
border-collapse: separate;
border-radius: 10px;
-moz-border-radius: 10px;
}
td {
border: none;
}
```
```html
<table border="1">
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
</table>
``` | Use border radius on the table.
```
table {
border: 1px solid #CCC;
border-collapse: collapse;
border-radius: 20%;
font-size:13px;
color:white;
}
td {
border: none;
}
``` |
64,601,439 | I am new to HTML and CSS. I want to achieve rounded-corner for my table and it is not working. Any ideas how can I make it work?
Here is my CSS for table:
```
table {
border: 1px solid #CCC;
border-collapse: collapse;
font-size:13px;
color:white;
}
td {
border: none;
}
```
Currently, it looks like this:
[](https://i.stack.imgur.com/Ce5NO.png)
And I want the corner of the table to be rounded.
Many thanks. | 2020/10/30 | [
"https://Stackoverflow.com/questions/64601439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11471461/"
] | You can make the rounded table using the `border-radius` CSS attribute based on `border-collapse: separate` as follows.
```css
table {
border: 1px solid #CCC;
font-size: 13px;
color: white;
background: red;
border-collapse: separate;
border-radius: 10px;
-moz-border-radius: 10px;
}
td {
border: none;
}
```
```html
<table border="1">
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
<tr>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<td>Hello World</td>
<tr>
</table>
``` | you need to give `border-radius` to make table border rounded so try this :
```
table {
border: 1px solid #CCC;
border-radius:50px;
border-collapse: collapse;
font-size:13px;
color:white;
}
td {
border: none;
}
``` |
16,875,356 | I am successfully detecting faces using JavaCV, it's not totally accurate but good enough for the moment.
However, for testing purposes and with a look at the future (this is only part of a bigger group project), I want to write rectangles onto the faces using BufferedImage and Graphics.drawRect().
I am aware of the fact that you can draw rects to faces using JavaCV with the static methods, but it's not what I need / want to do.
If I, after the scanning process, try to load the image using ImageIO and try to write rects to it, the application ends with a native error.
**Is there any way I can command openCV to "release" the image (because I think that's the soruce of the problem, that opencv does not release the image file.) ?**
Thanks in advance
edit: error code:
```
# A fatal error has been detected by the Java Runtime Environment:
#
# SIGSEGV (0xb) at pc=0x00007fc705dafac4, pid=8216, tid=140493568964352
#
# JRE version: 7.0_21-b02
# Java VM: OpenJDK 64-Bit Server VM (23.7-b01 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [libjpeg.so.8+0x1eac4] jpeg_save_markers+0x84
```
edit:
```
cvReleaseImage(inputImage);
cvReleaseImage(grayImage);
cvClearMemStorage(storage);
```
didnt help too | 2013/06/01 | [
"https://Stackoverflow.com/questions/16875356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342579/"
] | Quoting from the [paperjs.org tutorial on rasters](http://paperjs.org/tutorials/images/working-with-rasters/):
>
> Images need to already be loaded when they are added to a Paper.js project. Working with local images or images hosted on other websites may throw security exceptions on certain browsers.
>
>
>
So you need an image somewhere that is preferably [visually hidden](https://github.com/h5bp/html5-boilerplate/blob/a20a3c76d541d40ffb75a8f02c8c0f7b05773e51/css/main.css#L127-L136):
```
<img id="mona" class="visuallyhidden" src="mona.jpg" width="320" height="491">
```
And the [PaperScript](http://paperjs.org/tutorials/getting-started/working-with-paper-js/) code could look like this:
```
// Create a raster item using the image tag with id="mona"
var raster = new Raster('mona');
```
Then you can reposition, scale or rotate like so:
```
// Move the raster to the center of the view
raster.position = view.center;
// Scale the raster by 50%
raster.scale(0.5);
// Rotate the raster by 45 degrees:
raster.rotate(45);
```
And here is a [paperjs.org sketch](http://sketch.paperjs.org/#S/VY9BbwIhEIX/yoSkcZtU8KAXG0/GYy965YIw3UV3gcDoxjT97wXWbmK48Jj3vnn8MKcGZFt2uiLpjn0w7U3RdxXBDi3swHh9G9AR1xEV4aHHohrJ8liy90/p8oWnqLNXso4obIUIKmC8JO5jK+hGPlrVJ2EH1WISo49X69rlaKlbRpUIYxKDd4pfQkY+idZUYHmXTLq5xtmbB1choDP7zvamyebSohwhYF9bgoIJDJZwgFvK+4A6hFoBSLVQtoM1u0XZsJCu/PiZ2YHDEY5VNNN82pD5X/6OlfT0kq9K52pZ+e+q7hZH6SYHDz5Zst5lbHnnk/Wfd9KqfwGeH7BZvc3pVObNim/mBkdP5YevkfUGDLYRMW3naKzGZp2j7PcP) to play with. | First, If you want to work with JavaScript directly look at [this tutorial](http://paperjs.org/tutorials/getting-started/using-javascript-directly/).
Once you understand it, you would have something like this to load image in raster
```
paper.install(window);
window.onload = function() {
// Setup directly from canvas id:
paper.setup('myCanvas');
var raster = new paper.Raster({source: 'Chrysanthemum.jpg', position: view.center});
}
``` |
12,907,167 | >
> **Possible Duplicate:**
>
> [How can I pass command-line arguments in IronPython?](https://stackoverflow.com/questions/5949735/how-can-i-pass-command-line-arguments-in-ironpython)
>
>
>
I am new to ironpython and sharpdevelop and I am trying to run the following code,
```
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
```
How do I pass the arguments to the command line ? | 2012/10/16 | [
"https://Stackoverflow.com/questions/12907167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/523960/"
] | In [SharpDevelop](http://www.icsharpcode.net/opensource/sd/) you
* *right-click* on the python *project*
* choose *Properties* in the context-menu
* choose the *Debug*-tab
* append your arguments in the *Command line arguments* field | Does [this article](https://stackoverflow.com/questions/5949735/how-can-i-pass-command-line-arguments-in-ironpython) help you at all?
>
> You need to set the values of sys.argv.
>
>
>
> ```
> engine.Sys.argv = List.Make(args);
>
> ```
>
> |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | To do web-based databases, the best practice\*\*\* is to use HTTP requests to a PHP script. That way you will not have to establish a database connection from the app, leaving Usernames and Passwords excluded from the actual project. Create some PHP scripts that will do what you need by sending POST and GET variables.
\*\*\*In my experience and preference | You need to build out API end points for all the actions that are possible.
E.g posts/view posts/edit posts/add
A popular and well documented architecture to use would be REST
<http://en.wikipedia.org/wiki/Representational_state_transfer>
If you are using a PHP framework there are often helper libraries for creating the API
This tutorial should help you understand it
<http://net.tutsplus.com/tutorials/php/creating-an-api-centric-web-application/> |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | To do web-based databases, the best practice\*\*\* is to use HTTP requests to a PHP script. That way you will not have to establish a database connection from the app, leaving Usernames and Passwords excluded from the actual project. Create some PHP scripts that will do what you need by sending POST and GET variables.
\*\*\*In my experience and preference | I am a newbie to iphone development and have been working on Iphone for a month or so. Would like to give some tips on this:
1) First read up on Objective-C since you are making an Iphone app and how Xcode in general works
2) Next the connecting to the web API, you could use AFNetworking. Here is a [Tutorial](http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/) to get started. You need to know what is the API to get the data.
3) Next you need to parse the data depending whether it is an JSON or XML data from the API. This will allow you to get the data.
4)You can now display in the Xcode using the UI |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | To do web-based databases, the best practice\*\*\* is to use HTTP requests to a PHP script. That way you will not have to establish a database connection from the app, leaving Usernames and Passwords excluded from the actual project. Create some PHP scripts that will do what you need by sending POST and GET variables.
\*\*\*In my experience and preference | Your app can connect to your service by issuing HTTP requests to URLs on your server. You can use whatever backend you like, I have personally used PHP with MySQL since virtually all hosting services will support these tools. You form queries by defining URLs that perform a function. Generally, you want to use POST requests when you're changing data on the server, and GET requests when you're making read-only requests for information.
You have to be careful to design your URLs and your server to prevent unauthorized access, I won't describe the details here but the web is full of good advice about this. I'll focus here on how you connect to your service using URLs.
I recommend using a library that aids in sending requests and receiving responses. Back (a year or so ago) when I was actively working on an app that did this, I used the AsiHTTPRequest library, which is available for free, but I see now that the author has discontinued support for it. My $0.02: it worked well for my app: <http://allseeing-i.com/ASIHTTPRequest/>
There are two parts: 1) send request, and 2) receive and process response. You generally want to make sure your requests are issued asynchronously so that your app doesn't freeze while the request is making its way over the internet, the server processes the request, and you receive the response.
For convenience in parsing the results, have your web app backend send the responses in apple plist format. Or you could use XML, but I like plist because support for it is baked in to the SDK.
Here's code from my app that does this:
```
// this allows you to switch between the "live" web service and a local development copy
#ifndef _USE_LOCAL_SERVER_
#define kAppCustomerInfoURL @"https://mysite.com/path/to_my/service/"
#else
#define kAppCustomerInfoURL @"http://localhost/path/to_my/service/"
#endif
NSURL *url = [NSURL URLWithString:kAppCustomerInfoURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// udm is my singleton that holds properties for the current user
[request setPostValue:[udm getProperty:kNameProperty] forKey:@"name"];
[request setPostValue:[udm getProperty:kPhoneProperty] forKey:@"phone"];
[request setPostValue:[udm getProperty:kEmailProperty] forKey:@"email"];
[request setPostValue:[udm getProperty:kCityProperty] forKey:@"city"];
[request setPostValue:[udm getProperty:kAddressProperty] forKey:@"address"];
[request setPostValue:[udm getProperty:kDeliveryNotesProperty] forKey:@"comments"];
[request setPostValue:[NSString stringWithFormat:@"%u", arc4random()] forKey:@"random"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
```
Your object needs to implement the requestFinished: and requestFailed: methods:
```
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
NSData* plistData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSPropertyListFormat format;
NSString *errorStr;
NSDictionary* plist = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&errorStr];
if ( ! plist )
{
// NSLog( @"Error: %@", errorStr );
[errorStr release];
return;
}
for ( NSString *key in [plist allKeys] )
{
if ( [key isEqualToString:@"result"] )
{
NSString *resultStr = [plist objectForKey:@"result"];
if ( ! [resultStr isEqualToString:@"ok"] )
{
// set an error
}
}
// more cases
}
}
```
Here's my response failed method, it sets some app state and sends a notification that the request has finished, that other parts of the app may use to update themselves upon a request finishing:
```
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog( @"update customer info failed: %@", [error localizedDescription] );
self.syncDataToServerOK = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:kUserDataSyncFinishedNotification object:nil];
}
``` |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | To do web-based databases, the best practice\*\*\* is to use HTTP requests to a PHP script. That way you will not have to establish a database connection from the app, leaving Usernames and Passwords excluded from the actual project. Create some PHP scripts that will do what you need by sending POST and GET variables.
\*\*\*In my experience and preference | You just setup a [RESTful webservice](http://www.slimframework.com/), then access to it on Obj-C via [Restkit](http://restkit.org/).
EDIT: btw if you haven't got fancy app needs, just [make your website responsive](http://en.wikipedia.org/wiki/Responsive_web_design) and you'l be done. |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | You need to build out API end points for all the actions that are possible.
E.g posts/view posts/edit posts/add
A popular and well documented architecture to use would be REST
<http://en.wikipedia.org/wiki/Representational_state_transfer>
If you are using a PHP framework there are often helper libraries for creating the API
This tutorial should help you understand it
<http://net.tutsplus.com/tutorials/php/creating-an-api-centric-web-application/> | I am a newbie to iphone development and have been working on Iphone for a month or so. Would like to give some tips on this:
1) First read up on Objective-C since you are making an Iphone app and how Xcode in general works
2) Next the connecting to the web API, you could use AFNetworking. Here is a [Tutorial](http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/) to get started. You need to know what is the API to get the data.
3) Next you need to parse the data depending whether it is an JSON or XML data from the API. This will allow you to get the data.
4)You can now display in the Xcode using the UI |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | You need to build out API end points for all the actions that are possible.
E.g posts/view posts/edit posts/add
A popular and well documented architecture to use would be REST
<http://en.wikipedia.org/wiki/Representational_state_transfer>
If you are using a PHP framework there are often helper libraries for creating the API
This tutorial should help you understand it
<http://net.tutsplus.com/tutorials/php/creating-an-api-centric-web-application/> | Your app can connect to your service by issuing HTTP requests to URLs on your server. You can use whatever backend you like, I have personally used PHP with MySQL since virtually all hosting services will support these tools. You form queries by defining URLs that perform a function. Generally, you want to use POST requests when you're changing data on the server, and GET requests when you're making read-only requests for information.
You have to be careful to design your URLs and your server to prevent unauthorized access, I won't describe the details here but the web is full of good advice about this. I'll focus here on how you connect to your service using URLs.
I recommend using a library that aids in sending requests and receiving responses. Back (a year or so ago) when I was actively working on an app that did this, I used the AsiHTTPRequest library, which is available for free, but I see now that the author has discontinued support for it. My $0.02: it worked well for my app: <http://allseeing-i.com/ASIHTTPRequest/>
There are two parts: 1) send request, and 2) receive and process response. You generally want to make sure your requests are issued asynchronously so that your app doesn't freeze while the request is making its way over the internet, the server processes the request, and you receive the response.
For convenience in parsing the results, have your web app backend send the responses in apple plist format. Or you could use XML, but I like plist because support for it is baked in to the SDK.
Here's code from my app that does this:
```
// this allows you to switch between the "live" web service and a local development copy
#ifndef _USE_LOCAL_SERVER_
#define kAppCustomerInfoURL @"https://mysite.com/path/to_my/service/"
#else
#define kAppCustomerInfoURL @"http://localhost/path/to_my/service/"
#endif
NSURL *url = [NSURL URLWithString:kAppCustomerInfoURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// udm is my singleton that holds properties for the current user
[request setPostValue:[udm getProperty:kNameProperty] forKey:@"name"];
[request setPostValue:[udm getProperty:kPhoneProperty] forKey:@"phone"];
[request setPostValue:[udm getProperty:kEmailProperty] forKey:@"email"];
[request setPostValue:[udm getProperty:kCityProperty] forKey:@"city"];
[request setPostValue:[udm getProperty:kAddressProperty] forKey:@"address"];
[request setPostValue:[udm getProperty:kDeliveryNotesProperty] forKey:@"comments"];
[request setPostValue:[NSString stringWithFormat:@"%u", arc4random()] forKey:@"random"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
```
Your object needs to implement the requestFinished: and requestFailed: methods:
```
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
NSData* plistData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSPropertyListFormat format;
NSString *errorStr;
NSDictionary* plist = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&errorStr];
if ( ! plist )
{
// NSLog( @"Error: %@", errorStr );
[errorStr release];
return;
}
for ( NSString *key in [plist allKeys] )
{
if ( [key isEqualToString:@"result"] )
{
NSString *resultStr = [plist objectForKey:@"result"];
if ( ! [resultStr isEqualToString:@"ok"] )
{
// set an error
}
}
// more cases
}
}
```
Here's my response failed method, it sets some app state and sends a notification that the request has finished, that other parts of the app may use to update themselves upon a request finishing:
```
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog( @"update customer info failed: %@", [error localizedDescription] );
self.syncDataToServerOK = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:kUserDataSyncFinishedNotification object:nil];
}
``` |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | You just setup a [RESTful webservice](http://www.slimframework.com/), then access to it on Obj-C via [Restkit](http://restkit.org/).
EDIT: btw if you haven't got fancy app needs, just [make your website responsive](http://en.wikipedia.org/wiki/Responsive_web_design) and you'l be done. | I am a newbie to iphone development and have been working on Iphone for a month or so. Would like to give some tips on this:
1) First read up on Objective-C since you are making an Iphone app and how Xcode in general works
2) Next the connecting to the web API, you could use AFNetworking. Here is a [Tutorial](http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/) to get started. You need to know what is the API to get the data.
3) Next you need to parse the data depending whether it is an JSON or XML data from the API. This will allow you to get the data.
4)You can now display in the Xcode using the UI |
13,728,084 | I have made a website (php) and it connects to a database so it can have users and post material. Imagine it like a forum. Now how would I go about making an iPhone app that connects to the same database. I am already teaching myself c++ to make the app, but am not sure how I will connect it to the database. | 2012/12/05 | [
"https://Stackoverflow.com/questions/13728084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879764/"
] | You just setup a [RESTful webservice](http://www.slimframework.com/), then access to it on Obj-C via [Restkit](http://restkit.org/).
EDIT: btw if you haven't got fancy app needs, just [make your website responsive](http://en.wikipedia.org/wiki/Responsive_web_design) and you'l be done. | Your app can connect to your service by issuing HTTP requests to URLs on your server. You can use whatever backend you like, I have personally used PHP with MySQL since virtually all hosting services will support these tools. You form queries by defining URLs that perform a function. Generally, you want to use POST requests when you're changing data on the server, and GET requests when you're making read-only requests for information.
You have to be careful to design your URLs and your server to prevent unauthorized access, I won't describe the details here but the web is full of good advice about this. I'll focus here on how you connect to your service using URLs.
I recommend using a library that aids in sending requests and receiving responses. Back (a year or so ago) when I was actively working on an app that did this, I used the AsiHTTPRequest library, which is available for free, but I see now that the author has discontinued support for it. My $0.02: it worked well for my app: <http://allseeing-i.com/ASIHTTPRequest/>
There are two parts: 1) send request, and 2) receive and process response. You generally want to make sure your requests are issued asynchronously so that your app doesn't freeze while the request is making its way over the internet, the server processes the request, and you receive the response.
For convenience in parsing the results, have your web app backend send the responses in apple plist format. Or you could use XML, but I like plist because support for it is baked in to the SDK.
Here's code from my app that does this:
```
// this allows you to switch between the "live" web service and a local development copy
#ifndef _USE_LOCAL_SERVER_
#define kAppCustomerInfoURL @"https://mysite.com/path/to_my/service/"
#else
#define kAppCustomerInfoURL @"http://localhost/path/to_my/service/"
#endif
NSURL *url = [NSURL URLWithString:kAppCustomerInfoURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
// udm is my singleton that holds properties for the current user
[request setPostValue:[udm getProperty:kNameProperty] forKey:@"name"];
[request setPostValue:[udm getProperty:kPhoneProperty] forKey:@"phone"];
[request setPostValue:[udm getProperty:kEmailProperty] forKey:@"email"];
[request setPostValue:[udm getProperty:kCityProperty] forKey:@"city"];
[request setPostValue:[udm getProperty:kAddressProperty] forKey:@"address"];
[request setPostValue:[udm getProperty:kDeliveryNotesProperty] forKey:@"comments"];
[request setPostValue:[NSString stringWithFormat:@"%u", arc4random()] forKey:@"random"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
```
Your object needs to implement the requestFinished: and requestFailed: methods:
```
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
NSData* plistData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSPropertyListFormat format;
NSString *errorStr;
NSDictionary* plist = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&errorStr];
if ( ! plist )
{
// NSLog( @"Error: %@", errorStr );
[errorStr release];
return;
}
for ( NSString *key in [plist allKeys] )
{
if ( [key isEqualToString:@"result"] )
{
NSString *resultStr = [plist objectForKey:@"result"];
if ( ! [resultStr isEqualToString:@"ok"] )
{
// set an error
}
}
// more cases
}
}
```
Here's my response failed method, it sets some app state and sends a notification that the request has finished, that other parts of the app may use to update themselves upon a request finishing:
```
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog( @"update customer info failed: %@", [error localizedDescription] );
self.syncDataToServerOK = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:kUserDataSyncFinishedNotification object:nil];
}
``` |
133,107 | How can I reduce the size of a `\psdiabox`, for instance:
```
\documentclass[10pt,a4paper,twoside]{scrbook}
\usepackage{pstricks}
\usepackage{pst-all}
\begin{document}
\psset{unit=0.35}
\begin{pspicture}(9.261250,-52.662503)(52.977702,-0.950000)
\begin{psmatrix}[rowsep=1cm,colsep=.5cm]
& \rput[tc](30.5,-19.5){\psdiabox
{ \begin{tabular}{c}
?`$Pueden \, estar \, repetidos$ \\
$los \, p \, que \, vaya \, a \, tomar?$ \\
\end{tabular} }}
\end{psmatrix}
\end{pspicture}
\end{document}
```
 | 2013/09/13 | [
"https://tex.stackexchange.com/questions/133107",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/35541/"
] | Your best bet would be to convert the pdf to a series of images probably using [imagemagick](http://www.imagemagick.org/script/index.php)'s convert routine, then use [ffmpeg](http://www.ffmpeg.org/) to assemble them into a video. Both tools are free and cross-platform.
[Stack Overflow has more detail](https://stackoverflow.com/a/10612261/2583476) - you could basically run the contents of the 2 php `exec` commands in the answer from the command line.
**Edit:**
I think it would be necessary to use a script to figure out where to insert the video - either:
* In my limited use of Beamer (simple static slides) I would be able to count the `\begin{frame}`s to count the slides, then look out for the command that includes the video. You could then use this to drive `ffmpeg`.
* It also looks possible to parse the `.nav` file - this may be simpler, but I can't get `media9` working here at the moment, so don't know whether it inserts anything into the `.nav` or the `.aux`.
The common point is that ffpmeg can do the heavy lifting by combining images and (dissimilar) video files.
However, if this was a one-off, without too many videos, I would be inclined to split the PDF, and use ffmpeg to combine PDF1, video1, PDF2, video2 etc. by hand, despite my inclination to script as much as possible. | This is perhaps a bit of a "hacky" solution, but you could try using a screen recording application as you manually play back the PDF (at full screen) at your desired speed and timings. Quicktime X on Mac OS X is excellent, and there is a Linux program `simplescreenrecorder` which looks to do much the same thing.
Don't forget to set your screen resolution to the resolution of the Smart TV, if you can (presumably 1920x1080), to maximize quality. YMMV though, if you have an older machine it may struggle to record embedded video at that resolution. |
2,333,897 | **EDIT** - Rewrote my original question to give a bit more information
---
**Background info**
At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects.
I can't name our exact setup/formula, because I think our company wouldn't approve that...
**What's a customer / project?**
Our company provides management information for our customers on a yearly (or other interval) basis.
In our systems a customer/contract consists of:
* one Account: information about the Company
* per Account, one or more Products: the bundle of management information we'll provide
* per Product, one or more Measurements: a period of time, in which we gather and report the data
**Extranet site setup**
Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites:
* Company site: provides an overview of Account information and the Products
* Measurement site: after selecting a Measurement, detailed information on that period of time
The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research.
Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things).
**What kind of roles?**
The following users (read: roles) will be using the system:
* *Admins: development users :) (not customer related, full access)*
* *Employees: employees of our company (not customer related, full access)*
* Customer SuperUser: top level managers (full access to their account/measurement)
* Customer ContactPerson: primary contact (full access to their measurement(s))
* Customer Manager: a department manager (limited access, specific data of a measurement)
**What about ASP.Net users?**
The system will have many ASP.Net users, let's focus on the customer users:
* Users are not shared between Accounts
* SuperUser X automatically has access to all (and new) measurements
* User Y could be Primary contact for Measurement 1, but have no role for Measurement 2
* User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2
* The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2.
**URL structure**
These are typical urls in our application:
* <http://host/login> - the login screen
* <http://host/project> - the account/product overview screen (measurement selection)
* <http://host/project/1000> - measurement (id:1000) details
* <http://host/project/1000/planning> - planning overview (for primary contact/superuser)
* <http://host/project/1000/reports> - report downloads (manager department X can only access report X)
We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document.
**What's the problem? (finally ;))**
Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000.
Summarized:
1. How can we limit users to their accounts/measurements?
(remember superusers see all measurements, some managers only specific measurements)
2. How can we apply roles at a product/measurement level?
(user X could be primarycontact for measurement 1, but just a manager for measurement 2)
3. How can we limit manager access to the reports screen and only to their department's reports?
All with the magic of asp.net classes, perhaps with a custom roleprovider implementation.
**Similar Stackoverflow question/problem**
[ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles) | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136819/"
] | What you are seeking from the various posts that I see, is a custom role mechanism or said another way, a custom Authorization mechanism. Authentication can still use the standard SqlMembershipProvider.
I'm not sure that the standard role provider will provide you with what you want as authorization requires that you have the context of the Project. However, you might investigate writing a custom RoleProvider to see if you can create some custom methods that would do that. Still, for the purposes of answering the question, I'm going to assume you cannot use the SqlRoleProvider.
So, here's some potential schema:
```
Create Table Companies
(
Id int not null Primary Key
, ...
)
Create Table Projects
(
Id int not null Primary Key
, PrimaryContactUserId uniqueidentifier
, ...
, Constraint FK_Projects_aspnet_Users
Foreign Key ( PrimaryContactUserId )
References dbo.aspnet_Users ( UserId )
)
Create Table Roles
(
Name nvarchar(100) not null Primary Key
, ...
)
Create Table ProjectCompanyRoles
(
CompanyId int not null
, ProjectId int not null
, RoleName nvarchar(100) not null
, Constraint FK_...
)
```
As I said before, the reason for including PrimaryContact in the Projects table is to ensure that there is only one for a given project. If you include it as a role, you would have to include a bunch of hoop jumping code to ensure that a project is not assigned more than one PrimaryContact. If that were the case, then take out the PrimaryContactUserId from the Projects table and make it a role.
Authorization checks would entail queries against the ProjectCompanyRoles. Again, the addition of the contexts of Project and Company make using the default role providers problematic. If you wanted to use the .NET mechanism for roles as well as authentication, then you will have to implement your own custom RoleProvider. | Store a value in the profile potentially. Setup a profile entry in the config file and use that to store the value.
More realistically, you may want to store this outside of the ASP.NET tables for ease of use and for ease of accessing the value (maybe outside of the web environment if you need to)...
Not sure what all your requirements are. |
2,333,897 | **EDIT** - Rewrote my original question to give a bit more information
---
**Background info**
At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects.
I can't name our exact setup/formula, because I think our company wouldn't approve that...
**What's a customer / project?**
Our company provides management information for our customers on a yearly (or other interval) basis.
In our systems a customer/contract consists of:
* one Account: information about the Company
* per Account, one or more Products: the bundle of management information we'll provide
* per Product, one or more Measurements: a period of time, in which we gather and report the data
**Extranet site setup**
Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites:
* Company site: provides an overview of Account information and the Products
* Measurement site: after selecting a Measurement, detailed information on that period of time
The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research.
Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things).
**What kind of roles?**
The following users (read: roles) will be using the system:
* *Admins: development users :) (not customer related, full access)*
* *Employees: employees of our company (not customer related, full access)*
* Customer SuperUser: top level managers (full access to their account/measurement)
* Customer ContactPerson: primary contact (full access to their measurement(s))
* Customer Manager: a department manager (limited access, specific data of a measurement)
**What about ASP.Net users?**
The system will have many ASP.Net users, let's focus on the customer users:
* Users are not shared between Accounts
* SuperUser X automatically has access to all (and new) measurements
* User Y could be Primary contact for Measurement 1, but have no role for Measurement 2
* User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2
* The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2.
**URL structure**
These are typical urls in our application:
* <http://host/login> - the login screen
* <http://host/project> - the account/product overview screen (measurement selection)
* <http://host/project/1000> - measurement (id:1000) details
* <http://host/project/1000/planning> - planning overview (for primary contact/superuser)
* <http://host/project/1000/reports> - report downloads (manager department X can only access report X)
We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document.
**What's the problem? (finally ;))**
Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000.
Summarized:
1. How can we limit users to their accounts/measurements?
(remember superusers see all measurements, some managers only specific measurements)
2. How can we apply roles at a product/measurement level?
(user X could be primarycontact for measurement 1, but just a manager for measurement 2)
3. How can we limit manager access to the reports screen and only to their department's reports?
All with the magic of asp.net classes, perhaps with a custom roleprovider implementation.
**Similar Stackoverflow question/problem**
[ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles) | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136819/"
] | This is exactly the kind of scenario that calls for a custom RoleProvider. You design the database schema to support your case (you might want to create a table called ProjectRole and a table called CompanyRole).
Here are a couple of things to get you started (with links to help at the bottom):
Add this section to your web.config:
```
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add name="MyRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly, Version=1.0.0.0" description="My Custom Role Provider." enableSearchMethods="false" applicationName="MyApplicationName"/>
</providers>
</roleManager>
```
Then this is what the `MyRoleProvider` class looks like (more or less):
(NOTE: your class must inherit from `System.Web.Security.RoleProvider`)
```
namespace MyNamespace
{
...
public class MyRoleProvider : System.Web.Security.RoleProvider
{
private string _applicationName;
public MyRoleProvider()
{
}
public override string ApplicationName
{
get
{
return _applicationName;
}
set
{
_applicationName = value;
}
}
...
}
}
```
Then you just need to override some methods to provide your application with the information it needs:
At a minimum, I would override these 2 methods:
* GetRolesForUser
* IsUserInRole
But you can also override these methods if you want to:
* AddUsersToRoles
* RemoveUsersFromRoles
* FindUsersInRole
* GetUsersInRole
* GetAllRoles
* CreateRole
* DeleteRole
* RoleExists
Nor here are the links I promised:
* [Implementing a Role Provider](http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx)
* [Create Custom RoleProvider for ASP.NET Role Permissions and Security](http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx)
* [Sample Role-Provider Implementation](http://msdn.microsoft.com/en-us/library/tksy7hd7(VS.80).aspx) | Store a value in the profile potentially. Setup a profile entry in the config file and use that to store the value.
More realistically, you may want to store this outside of the ASP.NET tables for ease of use and for ease of accessing the value (maybe outside of the web environment if you need to)...
Not sure what all your requirements are. |
2,333,897 | **EDIT** - Rewrote my original question to give a bit more information
---
**Background info**
At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects.
I can't name our exact setup/formula, because I think our company wouldn't approve that...
**What's a customer / project?**
Our company provides management information for our customers on a yearly (or other interval) basis.
In our systems a customer/contract consists of:
* one Account: information about the Company
* per Account, one or more Products: the bundle of management information we'll provide
* per Product, one or more Measurements: a period of time, in which we gather and report the data
**Extranet site setup**
Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites:
* Company site: provides an overview of Account information and the Products
* Measurement site: after selecting a Measurement, detailed information on that period of time
The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research.
Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things).
**What kind of roles?**
The following users (read: roles) will be using the system:
* *Admins: development users :) (not customer related, full access)*
* *Employees: employees of our company (not customer related, full access)*
* Customer SuperUser: top level managers (full access to their account/measurement)
* Customer ContactPerson: primary contact (full access to their measurement(s))
* Customer Manager: a department manager (limited access, specific data of a measurement)
**What about ASP.Net users?**
The system will have many ASP.Net users, let's focus on the customer users:
* Users are not shared between Accounts
* SuperUser X automatically has access to all (and new) measurements
* User Y could be Primary contact for Measurement 1, but have no role for Measurement 2
* User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2
* The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2.
**URL structure**
These are typical urls in our application:
* <http://host/login> - the login screen
* <http://host/project> - the account/product overview screen (measurement selection)
* <http://host/project/1000> - measurement (id:1000) details
* <http://host/project/1000/planning> - planning overview (for primary contact/superuser)
* <http://host/project/1000/reports> - report downloads (manager department X can only access report X)
We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document.
**What's the problem? (finally ;))**
Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000.
Summarized:
1. How can we limit users to their accounts/measurements?
(remember superusers see all measurements, some managers only specific measurements)
2. How can we apply roles at a product/measurement level?
(user X could be primarycontact for measurement 1, but just a manager for measurement 2)
3. How can we limit manager access to the reports screen and only to their department's reports?
All with the magic of asp.net classes, perhaps with a custom roleprovider implementation.
**Similar Stackoverflow question/problem**
[ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles) | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136819/"
] | DISCLAIMER: Pursuant to the exchange in comments, in which I make a complete asshat of myself, an *almost out of the box* solution has been arrived at and this answer has been purged of all asshattery and now contains only a *tested* scenario that may or may not address the OP problem. ;-)
Kudos to Thomas for keeping his cool and not giving up.
---
Z- tell me if I understand you:
You want a central membership provider for all apps/projects and a distinct role silo for each app/project?
You may not need to implement custom providers. The standard stack may suffice with a ***minor stored procedure modification***. It is always best to try and sweet talk the baked-in systems to do what you want. It leads to less work and more sleep.
The salient facets of the proposed solution:
* A common database and connection string,
* A common membership application name,
* A common machineKey section so that each site will use the common forms ticket.
* A **UNIQUE** role provider application name (or projectId, as you say).
* A modified `aspnet_Users_DeleteUser` sproc.
The modification to aspnet\_Users\_DeleteUser involves cleaning up the user references in aspnet\_users that are dynamically created by the Roles and Profile providers and carries a condition that a particular aspnet\_db instance is *owned* by the common MembershipProvider, and only the sites that use that common Membership provider should connect to it.
To map this solution to the OP scenario:
Each Account/Company would have a distinct aspnet\_db instance and the 'ProjectId' would be mapped to the applicationName attribute of the RoleManager provider element.
As projects are 'migrated' they are assigned a new ProjectId (applicationName) and in doing so, the companies users can authenticate against the migrated project by virtue of the common membership provider but the roles from the original project do not carry over by virtue of distinct role providers.
All standard membership management strategies, e.g. AspNet configuration tool, Login controls, createuser wizards, Membership functions (especially Membership.DeleteUser() - thank you Thomas) will behave as expected with no modifications.
Profiles may be implemented in either direction, using the applicationId of the Membership provider will allow profile data to follow a user to any of the associated projects. Using the distinct ProjectId (applicationName) of the Role provider will allow seperate profiles for each user in each project.
Some more detail and the tests are **[here](http://skysanders.net/subtext/archive/2010/03/05/multiple-asp.net-apps-with-common-sqlmembershipprovider-and-unique-sqlroleprovidersqlprofileprovider.aspx)**.
The salient configuration sections are listed below and the modified sproc follows.
**Web.config**
```
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="testDb" providerName="System.Data.SqlClient" connectionString="Data Source=(local);Initial Catalog=__SingleAuthMultiRole;Integrated Security=True"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
<!-- this key is common all your apps - generate a new one @ http://www.developmentnow.com/articles/machinekey_generator.aspx -->
<machineKey validationKey="841FEF8E55CD7963CE9EAFED329724667D62F4412F635815DFDDBE7D2D8D15819AE0FDF70CEF8F72792DBD7BF661F163B01134092CBCB80D7D71EAA42DFBF0A9" decryptionKey="FC9B0626224B0CF0DA68C558577F3E37723BB09AACE795498C4069A490690669" validation="SHA1" decryption="AES"/>
<authorization>
<deny users="?"/>
</authorization>
<authentication mode="Forms" />
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="testDb"
applicationName="Common" /> <!-- membership applicationName is common to all projects -->
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SqlRoleManager" cacheRolesInCookie="true">
<providers>
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="testDb"
applicationName="WebApplication1"/> <!-- roleManager applicationName is unique to each projects -->
</providers>
</roleManager>
</system.web>
</configuration>
```
**Usage**:
After provisioning your Aspnet\_db with aspnet\_regsql.exe, run this script to modify the aspnet\_Users\_DeleteUser sproc.
```
/*************************************************************/
/*************************************************************/
--- Modified DeleteUser SP
IF (EXISTS (SELECT name
FROM sysobjects
WHERE (name = N'aspnet_Users_DeleteUser')
AND (type = 'P')))
DROP PROCEDURE [dbo].aspnet_Users_DeleteUser
GO
CREATE PROCEDURE [dbo].[aspnet_Users_DeleteUser]
@ApplicationName nvarchar(256),
@UserName nvarchar(256),
@TablesToDeleteFrom int,
@NumTablesDeletedFrom int OUTPUT
AS
BEGIN
-- holds all user id for username
DECLARE @UserIds TABLE(UserId UNIQUEIDENTIFIER)
SELECT @NumTablesDeletedFrom = 0
DECLARE @TranStarted bit
SET @TranStarted = 0
IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0
DECLARE @ErrorCode int
DECLARE @RowCount int
SET @ErrorCode = 0
SET @RowCount = 0
-- get all userid for username
INSERT INTO @UserIds
SELECT UserId
FROM dbo.aspnet_Users
WHERE LoweredUserName = LOWER(@UserName)
DECLARE @tmp int
SELECT @tmp = COUNT(*) FROM @UserIds
IF NOT EXISTS(SELECT * FROM @UserIds)
GOTO Cleanup
-- Delete from Membership table if (@TablesToDeleteFrom & 1) is set
IF ((@TablesToDeleteFrom & 1) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
BEGIN
DELETE FROM dbo.aspnet_Membership WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_UsersInRoles table if (@TablesToDeleteFrom & 2) is set
IF ((@TablesToDeleteFrom & 2) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_UsersInRoles') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_UsersInRoles WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_Profile table if (@TablesToDeleteFrom & 4) is set
IF ((@TablesToDeleteFrom & 4) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_Profiles') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_Profile WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_PersonalizationPerUser table if (@TablesToDeleteFrom & 8) is set
IF ((@TablesToDeleteFrom & 8) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_WebPartState_User') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_PersonalizationPerUser WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_Users table if (@TablesToDeleteFrom & 1,2,4 & 8) are all set
IF ((@TablesToDeleteFrom & 1) <> 0 AND
(@TablesToDeleteFrom & 2) <> 0 AND
(@TablesToDeleteFrom & 4) <> 0 AND
(@TablesToDeleteFrom & 8) <> 0 AND
(EXISTS (SELECT UserId FROM dbo.aspnet_Users WHERE UserId IN (SELECT UserId from @UserIds))))
BEGIN
DELETE FROM dbo.aspnet_Users WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END
RETURN 0
Cleanup:
SET @NumTablesDeletedFrom = 0
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END
RETURN @ErrorCode
END
GO
``` | Store a value in the profile potentially. Setup a profile entry in the config file and use that to store the value.
More realistically, you may want to store this outside of the ASP.NET tables for ease of use and for ease of accessing the value (maybe outside of the web environment if you need to)...
Not sure what all your requirements are. |
2,333,897 | **EDIT** - Rewrote my original question to give a bit more information
---
**Background info**
At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects.
I can't name our exact setup/formula, because I think our company wouldn't approve that...
**What's a customer / project?**
Our company provides management information for our customers on a yearly (or other interval) basis.
In our systems a customer/contract consists of:
* one Account: information about the Company
* per Account, one or more Products: the bundle of management information we'll provide
* per Product, one or more Measurements: a period of time, in which we gather and report the data
**Extranet site setup**
Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites:
* Company site: provides an overview of Account information and the Products
* Measurement site: after selecting a Measurement, detailed information on that period of time
The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research.
Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things).
**What kind of roles?**
The following users (read: roles) will be using the system:
* *Admins: development users :) (not customer related, full access)*
* *Employees: employees of our company (not customer related, full access)*
* Customer SuperUser: top level managers (full access to their account/measurement)
* Customer ContactPerson: primary contact (full access to their measurement(s))
* Customer Manager: a department manager (limited access, specific data of a measurement)
**What about ASP.Net users?**
The system will have many ASP.Net users, let's focus on the customer users:
* Users are not shared between Accounts
* SuperUser X automatically has access to all (and new) measurements
* User Y could be Primary contact for Measurement 1, but have no role for Measurement 2
* User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2
* The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2.
**URL structure**
These are typical urls in our application:
* <http://host/login> - the login screen
* <http://host/project> - the account/product overview screen (measurement selection)
* <http://host/project/1000> - measurement (id:1000) details
* <http://host/project/1000/planning> - planning overview (for primary contact/superuser)
* <http://host/project/1000/reports> - report downloads (manager department X can only access report X)
We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document.
**What's the problem? (finally ;))**
Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000.
Summarized:
1. How can we limit users to their accounts/measurements?
(remember superusers see all measurements, some managers only specific measurements)
2. How can we apply roles at a product/measurement level?
(user X could be primarycontact for measurement 1, but just a manager for measurement 2)
3. How can we limit manager access to the reports screen and only to their department's reports?
All with the magic of asp.net classes, perhaps with a custom roleprovider implementation.
**Similar Stackoverflow question/problem**
[ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles) | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136819/"
] | What you are seeking from the various posts that I see, is a custom role mechanism or said another way, a custom Authorization mechanism. Authentication can still use the standard SqlMembershipProvider.
I'm not sure that the standard role provider will provide you with what you want as authorization requires that you have the context of the Project. However, you might investigate writing a custom RoleProvider to see if you can create some custom methods that would do that. Still, for the purposes of answering the question, I'm going to assume you cannot use the SqlRoleProvider.
So, here's some potential schema:
```
Create Table Companies
(
Id int not null Primary Key
, ...
)
Create Table Projects
(
Id int not null Primary Key
, PrimaryContactUserId uniqueidentifier
, ...
, Constraint FK_Projects_aspnet_Users
Foreign Key ( PrimaryContactUserId )
References dbo.aspnet_Users ( UserId )
)
Create Table Roles
(
Name nvarchar(100) not null Primary Key
, ...
)
Create Table ProjectCompanyRoles
(
CompanyId int not null
, ProjectId int not null
, RoleName nvarchar(100) not null
, Constraint FK_...
)
```
As I said before, the reason for including PrimaryContact in the Projects table is to ensure that there is only one for a given project. If you include it as a role, you would have to include a bunch of hoop jumping code to ensure that a project is not assigned more than one PrimaryContact. If that were the case, then take out the PrimaryContactUserId from the Projects table and make it a role.
Authorization checks would entail queries against the ProjectCompanyRoles. Again, the addition of the contexts of Project and Company make using the default role providers problematic. If you wanted to use the .NET mechanism for roles as well as authentication, then you will have to implement your own custom RoleProvider. | This is exactly the kind of scenario that calls for a custom RoleProvider. You design the database schema to support your case (you might want to create a table called ProjectRole and a table called CompanyRole).
Here are a couple of things to get you started (with links to help at the bottom):
Add this section to your web.config:
```
<roleManager defaultProvider="MyRoleProvider" enabled="true">
<providers>
<add name="MyRoleProvider" type="MyNamespace.MyRoleProvider, MyAssembly, Version=1.0.0.0" description="My Custom Role Provider." enableSearchMethods="false" applicationName="MyApplicationName"/>
</providers>
</roleManager>
```
Then this is what the `MyRoleProvider` class looks like (more or less):
(NOTE: your class must inherit from `System.Web.Security.RoleProvider`)
```
namespace MyNamespace
{
...
public class MyRoleProvider : System.Web.Security.RoleProvider
{
private string _applicationName;
public MyRoleProvider()
{
}
public override string ApplicationName
{
get
{
return _applicationName;
}
set
{
_applicationName = value;
}
}
...
}
}
```
Then you just need to override some methods to provide your application with the information it needs:
At a minimum, I would override these 2 methods:
* GetRolesForUser
* IsUserInRole
But you can also override these methods if you want to:
* AddUsersToRoles
* RemoveUsersFromRoles
* FindUsersInRole
* GetUsersInRole
* GetAllRoles
* CreateRole
* DeleteRole
* RoleExists
Nor here are the links I promised:
* [Implementing a Role Provider](http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx)
* [Create Custom RoleProvider for ASP.NET Role Permissions and Security](http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx)
* [Sample Role-Provider Implementation](http://msdn.microsoft.com/en-us/library/tksy7hd7(VS.80).aspx) |
2,333,897 | **EDIT** - Rewrote my original question to give a bit more information
---
**Background info**
At my work I'm working on a ASP.Net web application for our customers. In our implementation we use technologies like Forms authentication with MembershipProviders and RoleProviders. All went well until I ran into some difficulties with configuring the roles, because the roles aren't system-wide, but related to the customer accounts and projects.
I can't name our exact setup/formula, because I think our company wouldn't approve that...
**What's a customer / project?**
Our company provides management information for our customers on a yearly (or other interval) basis.
In our systems a customer/contract consists of:
* one Account: information about the Company
* per Account, one or more Products: the bundle of management information we'll provide
* per Product, one or more Measurements: a period of time, in which we gather and report the data
**Extranet site setup**
Eventually we want all customers to be able to access their management information with our online system. The extranet consists of two sites:
* Company site: provides an overview of Account information and the Products
* Measurement site: after selecting a Measurement, detailed information on that period of time
The measurement site is the most interesting part of the extranet. We will create submodules for new overviews, reports, managing and maintaining resources that are important for the research.
Our Visual Studio solution consists of a number of projects. One web application named Portal for the basis. The sites and modules are virtual directories within that application (makes it easier to share MasterPages among things).
**What kind of roles?**
The following users (read: roles) will be using the system:
* *Admins: development users :) (not customer related, full access)*
* *Employees: employees of our company (not customer related, full access)*
* Customer SuperUser: top level managers (full access to their account/measurement)
* Customer ContactPerson: primary contact (full access to their measurement(s))
* Customer Manager: a department manager (limited access, specific data of a measurement)
**What about ASP.Net users?**
The system will have many ASP.Net users, let's focus on the customer users:
* Users are not shared between Accounts
* SuperUser X automatically has access to all (and new) measurements
* User Y could be Primary contact for Measurement 1, but have no role for Measurement 2
* User Y could be Primary contact for Measurement 1, but have a Manager role for Measurement 2
* The department managers are many individual users (per Measurement), if Manager Z had a login for Measurement 1, we would like to use that login again if he participates in Measurement 2.
**URL structure**
These are typical urls in our application:
* <http://host/login> - the login screen
* <http://host/project> - the account/product overview screen (measurement selection)
* <http://host/project/1000> - measurement (id:1000) details
* <http://host/project/1000/planning> - planning overview (for primary contact/superuser)
* <http://host/project/1000/reports> - report downloads (manager department X can only access report X)
We will also create a document url, where you can request a specific document by it's GUID. The system will have to check if the user has rights to the document. The document is related to a Measurement, the User or specific roles have specific rights to the document.
**What's the problem? (finally ;))**
Roles aren't enough to determine what a user is allowed to see/access/download a specific item. It's not enough to say that a certain navigation item is accessible to Managers. When the user requests Measurement 1000, we have to check that the user not only has a Manager role, but a Manager role for Measurement 1000.
Summarized:
1. How can we limit users to their accounts/measurements?
(remember superusers see all measurements, some managers only specific measurements)
2. How can we apply roles at a product/measurement level?
(user X could be primarycontact for measurement 1, but just a manager for measurement 2)
3. How can we limit manager access to the reports screen and only to their department's reports?
All with the magic of asp.net classes, perhaps with a custom roleprovider implementation.
**Similar Stackoverflow question/problem**
[ASP.NET, how to manage users with different types of roles](https://stackoverflow.com/questions/1367483/asp-net-how-to-manage-users-with-different-types-of-roles) | 2010/02/25 | [
"https://Stackoverflow.com/questions/2333897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/136819/"
] | What you are seeking from the various posts that I see, is a custom role mechanism or said another way, a custom Authorization mechanism. Authentication can still use the standard SqlMembershipProvider.
I'm not sure that the standard role provider will provide you with what you want as authorization requires that you have the context of the Project. However, you might investigate writing a custom RoleProvider to see if you can create some custom methods that would do that. Still, for the purposes of answering the question, I'm going to assume you cannot use the SqlRoleProvider.
So, here's some potential schema:
```
Create Table Companies
(
Id int not null Primary Key
, ...
)
Create Table Projects
(
Id int not null Primary Key
, PrimaryContactUserId uniqueidentifier
, ...
, Constraint FK_Projects_aspnet_Users
Foreign Key ( PrimaryContactUserId )
References dbo.aspnet_Users ( UserId )
)
Create Table Roles
(
Name nvarchar(100) not null Primary Key
, ...
)
Create Table ProjectCompanyRoles
(
CompanyId int not null
, ProjectId int not null
, RoleName nvarchar(100) not null
, Constraint FK_...
)
```
As I said before, the reason for including PrimaryContact in the Projects table is to ensure that there is only one for a given project. If you include it as a role, you would have to include a bunch of hoop jumping code to ensure that a project is not assigned more than one PrimaryContact. If that were the case, then take out the PrimaryContactUserId from the Projects table and make it a role.
Authorization checks would entail queries against the ProjectCompanyRoles. Again, the addition of the contexts of Project and Company make using the default role providers problematic. If you wanted to use the .NET mechanism for roles as well as authentication, then you will have to implement your own custom RoleProvider. | DISCLAIMER: Pursuant to the exchange in comments, in which I make a complete asshat of myself, an *almost out of the box* solution has been arrived at and this answer has been purged of all asshattery and now contains only a *tested* scenario that may or may not address the OP problem. ;-)
Kudos to Thomas for keeping his cool and not giving up.
---
Z- tell me if I understand you:
You want a central membership provider for all apps/projects and a distinct role silo for each app/project?
You may not need to implement custom providers. The standard stack may suffice with a ***minor stored procedure modification***. It is always best to try and sweet talk the baked-in systems to do what you want. It leads to less work and more sleep.
The salient facets of the proposed solution:
* A common database and connection string,
* A common membership application name,
* A common machineKey section so that each site will use the common forms ticket.
* A **UNIQUE** role provider application name (or projectId, as you say).
* A modified `aspnet_Users_DeleteUser` sproc.
The modification to aspnet\_Users\_DeleteUser involves cleaning up the user references in aspnet\_users that are dynamically created by the Roles and Profile providers and carries a condition that a particular aspnet\_db instance is *owned* by the common MembershipProvider, and only the sites that use that common Membership provider should connect to it.
To map this solution to the OP scenario:
Each Account/Company would have a distinct aspnet\_db instance and the 'ProjectId' would be mapped to the applicationName attribute of the RoleManager provider element.
As projects are 'migrated' they are assigned a new ProjectId (applicationName) and in doing so, the companies users can authenticate against the migrated project by virtue of the common membership provider but the roles from the original project do not carry over by virtue of distinct role providers.
All standard membership management strategies, e.g. AspNet configuration tool, Login controls, createuser wizards, Membership functions (especially Membership.DeleteUser() - thank you Thomas) will behave as expected with no modifications.
Profiles may be implemented in either direction, using the applicationId of the Membership provider will allow profile data to follow a user to any of the associated projects. Using the distinct ProjectId (applicationName) of the Role provider will allow seperate profiles for each user in each project.
Some more detail and the tests are **[here](http://skysanders.net/subtext/archive/2010/03/05/multiple-asp.net-apps-with-common-sqlmembershipprovider-and-unique-sqlroleprovidersqlprofileprovider.aspx)**.
The salient configuration sections are listed below and the modified sproc follows.
**Web.config**
```
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="testDb" providerName="System.Data.SqlClient" connectionString="Data Source=(local);Initial Catalog=__SingleAuthMultiRole;Integrated Security=True"/>
</connectionStrings>
<system.web>
<compilation debug="true"/>
<!-- this key is common all your apps - generate a new one @ http://www.developmentnow.com/articles/machinekey_generator.aspx -->
<machineKey validationKey="841FEF8E55CD7963CE9EAFED329724667D62F4412F635815DFDDBE7D2D8D15819AE0FDF70CEF8F72792DBD7BF661F163B01134092CBCB80D7D71EAA42DFBF0A9" decryptionKey="FC9B0626224B0CF0DA68C558577F3E37723BB09AACE795498C4069A490690669" validation="SHA1" decryption="AES"/>
<authorization>
<deny users="?"/>
</authorization>
<authentication mode="Forms" />
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="testDb"
applicationName="Common" /> <!-- membership applicationName is common to all projects -->
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SqlRoleManager" cacheRolesInCookie="true">
<providers>
<add name="SqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="testDb"
applicationName="WebApplication1"/> <!-- roleManager applicationName is unique to each projects -->
</providers>
</roleManager>
</system.web>
</configuration>
```
**Usage**:
After provisioning your Aspnet\_db with aspnet\_regsql.exe, run this script to modify the aspnet\_Users\_DeleteUser sproc.
```
/*************************************************************/
/*************************************************************/
--- Modified DeleteUser SP
IF (EXISTS (SELECT name
FROM sysobjects
WHERE (name = N'aspnet_Users_DeleteUser')
AND (type = 'P')))
DROP PROCEDURE [dbo].aspnet_Users_DeleteUser
GO
CREATE PROCEDURE [dbo].[aspnet_Users_DeleteUser]
@ApplicationName nvarchar(256),
@UserName nvarchar(256),
@TablesToDeleteFrom int,
@NumTablesDeletedFrom int OUTPUT
AS
BEGIN
-- holds all user id for username
DECLARE @UserIds TABLE(UserId UNIQUEIDENTIFIER)
SELECT @NumTablesDeletedFrom = 0
DECLARE @TranStarted bit
SET @TranStarted = 0
IF( @@TRANCOUNT = 0 )
BEGIN
BEGIN TRANSACTION
SET @TranStarted = 1
END
ELSE
SET @TranStarted = 0
DECLARE @ErrorCode int
DECLARE @RowCount int
SET @ErrorCode = 0
SET @RowCount = 0
-- get all userid for username
INSERT INTO @UserIds
SELECT UserId
FROM dbo.aspnet_Users
WHERE LoweredUserName = LOWER(@UserName)
DECLARE @tmp int
SELECT @tmp = COUNT(*) FROM @UserIds
IF NOT EXISTS(SELECT * FROM @UserIds)
GOTO Cleanup
-- Delete from Membership table if (@TablesToDeleteFrom & 1) is set
IF ((@TablesToDeleteFrom & 1) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
BEGIN
DELETE FROM dbo.aspnet_Membership WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_UsersInRoles table if (@TablesToDeleteFrom & 2) is set
IF ((@TablesToDeleteFrom & 2) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_UsersInRoles') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_UsersInRoles WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_Profile table if (@TablesToDeleteFrom & 4) is set
IF ((@TablesToDeleteFrom & 4) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_Profiles') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_Profile WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_PersonalizationPerUser table if (@TablesToDeleteFrom & 8) is set
IF ((@TablesToDeleteFrom & 8) <> 0 AND
(EXISTS (SELECT name FROM sysobjects WHERE (name = N'vw_aspnet_WebPartState_User') AND (type = 'V'))) )
BEGIN
DELETE FROM dbo.aspnet_PersonalizationPerUser WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
-- Delete from aspnet_Users table if (@TablesToDeleteFrom & 1,2,4 & 8) are all set
IF ((@TablesToDeleteFrom & 1) <> 0 AND
(@TablesToDeleteFrom & 2) <> 0 AND
(@TablesToDeleteFrom & 4) <> 0 AND
(@TablesToDeleteFrom & 8) <> 0 AND
(EXISTS (SELECT UserId FROM dbo.aspnet_Users WHERE UserId IN (SELECT UserId from @UserIds))))
BEGIN
DELETE FROM dbo.aspnet_Users WHERE UserId IN (SELECT UserId from @UserIds)
SELECT @ErrorCode = @@ERROR,
@RowCount = @@ROWCOUNT
IF( @ErrorCode <> 0 )
GOTO Cleanup
IF (@RowCount <> 0)
SELECT @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
END
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
COMMIT TRANSACTION
END
RETURN 0
Cleanup:
SET @NumTablesDeletedFrom = 0
IF( @TranStarted = 1 )
BEGIN
SET @TranStarted = 0
ROLLBACK TRANSACTION
END
RETURN @ErrorCode
END
GO
``` |
57,972,255 | I'm convinced someone else must have had this same issue before but I just can't find anything.
Given a table of data:
```
DECLARE @Table TABLE
(
[COL_NAME] nvarchar(30) NOT NULL,
[COL_AGE] int NOT NULL
);
INSERT INTO @Table
SELECT N'Column 1', 4 UNION ALL
SELECT N'Col2', 2 UNION ALL
SELECT N'Col 3', 56 UNION ALL
SELECT N'Column Four', 8 UNION ALL
SELECT N'Column Number 5', 12 UNION ALL
SELECT N'Column Number Six', 9;
```
If I use SSMS and set my output to text, running this script:
```
SELECT [COL_AGE], [COL_NAME] AS [MyCol] FROM @Table
```
Produces this:
```
COL_AGE MyCol
----------- -----------------
4 Column 1
2 Col2
56 Col 3
8 Column Four
12 Column Number 5
9 Column Number Six
```
Note that the data is neatly formatted and spaced.
I want to display the contents like SQL does when you post your results to text:
```
'Column 1 '
'Col2 '
'Col 3 '
'Column Four '
'Column Number 5 '
'Column Number Six'
```
The following is just to describe what I want, I understand it's obviously a horrible piece of script and should never make its way into production:
```
SELECT
N'''' + LEFT(
[COL_NAME] + SPACE( ( SELECT MAX(LEN([COL_NAME])) FROM @Table ) )
, ( SELECT MAX(LEN([COL_NAME])) FROM @Table )
) + N''''
FROM @Table
```
Originally, I tried this script, which is what I'm trying to get right:
```
SELECT
N'''' + LEFT(
[COL_NAME] + SPACE(MAX(LEN([COL_NAME])))
, MAX(LEN([COL_NAME]))
) + N''''
FROM @Table
```
But it returns the following error:
>
> Msg 8120, Level 16, State 1, Line 28 Column '@Table.COL\_NAME' is
> invalid in the select list because it is not contained in either an
> aggregate function or the GROUP BY clause.
>
>
>
The script is part of a much bigger script and it all has to happen within the SELECT statement, I can't use external variables to first look up the MAX(LEN()) because the bigger script iterates through other tables.
Any help would be appreciated. | 2019/09/17 | [
"https://Stackoverflow.com/questions/57972255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538480/"
] | I just used a quick CROSS APPLY to get the length of the buffer you want to use:
```
select
N'''' + LEFT(
[COL_NAME] + SPACE( t2.MLEN )
, t2.MLEN
) + N''''
from @Table
CROSS APPLY ( SELECT MAX(LEN([COL_NAME])) MLEN FROM @Table ) t2
``` | I don't really get, what you are trying to achieve, but I think, this might be what you need:
```
DECLARE @Table TABLE
(
[COL_NAME] nvarchar(30) NOT NULL
);
INSERT INTO @Table
SELECT N'Column 1' UNION ALL
SELECT N'Col2' UNION ALL
SELECT N'Col 3' UNION ALL
SELECT N'Column Four' UNION ALL
SELECT N'Column Number 5' UNION ALL
SELECT N'Column Number Six';
```
--The query
```
WITH ComputeMaxLength(ml) AS(SELECT MAX(LEN(t.COL_NAME)) FROM @Table t)
SELECT LEFT(CONCAT(tbl.COL_NAME,REPLICATE('.',ml)),ml)
FROM ComputeMaxLength
CROSS JOIN @Table tbl;
```
The result
```
Column 1.........
Col2.............
Col 3............
Column Four......
Column Number 5..
Column Number Six
```
The idea in short:
We use a CTE to compute the needed value.
Then we `CROSS JOIN` this with the source table. As the CTE will return just one row in any case, this will not add rows to our result. But it will add a column to our result, which we can use to compute a padding...
Hint: I used a dot instead of a blank to make the effect visible
UPDATE *Cannot use a `WITH` / CTE*
----------------------------------
You can shift the computation into an `APPLY` like here
```
SELECT CONCAT('''',LEFT(CONCAT([COL_NAME],SPACE(ml)),ml),'''')
FROM @Table
CROSS APPLY(SELECT MAX(LEN([COL_NAME])) FROM @Table) A(ml);
```
The engine should be smart enough to execute this just once...
UPDATE 2: If you cannot use an APPLY either
-------------------------------------------
Your own code, which is *obviously a horrible piece of script and should never make its way into production*, is not bad (just ugly :-) )
I'd put it like this
```
SELECT CONCAT(''''
,LEFT(CONCAT([COL_NAME]
,SPACE((SELECT MAX(LEN([COL_NAME])) FROM @Table)))
,(SELECT MAX(LEN([COL_NAME])) FROM @Table))
,'''')
FROM @Table;
```
The engine should be smart enough to reuse the result in this case too (and avoid multiple executions of the `SELECT MAX()...`... |
27,188,342 | I have a random crash in UIKit that happend a couple of times already.
It crashes with `EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x0000000d`
```
Thread : Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x30e08f46 objc_msgSend + 5
1 UIKit 0x26d1790d -[_UIWebViewScrollViewDelegateForwarder forwardInvocation:] + 140
2 CoreFoundation 0x23654def ___forwarding___ + 354
3 CoreFoundation 0x23586df8 _CF_forwarding_prep_0 + 24
4 UIKit 0x26b5a6fd -[UIScrollView _getDelegateZoomView] + 84
5 UIKit 0x26b5a635 -[UIScrollView _zoomScaleFromPresentationLayer:] + 24
6 UIKit 0x26b5a5ed -[UIWebDocumentView _zoomedDocumentScale] + 64
7 UIKit 0x26b5a13d -[UIWebDocumentView _layoutRectForFixedPositionObjects] + 104
8 UIKit 0x26b59f97 -[UIWebDocumentView _updateFixedPositionedObjectsLayoutRectUsingWebThread:synchronize:] + 38
9 UIKit 0x26b5c3e5 -[UIWebDocumentView _updateFixedPositioningObjectsLayoutAfterScroll] + 28
10 UIKit 0x26b5c3c1 -[UIWebBrowserView _updateFixedPositioningObjectsLayoutAfterScroll] + 56
11 CoreFoundation 0x2360a281 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
12 CoreFoundation 0x2356652d _CFXNotificationPost + 1784
13 Foundation 0x24296189 -[NSNotificationCenter postNotificationName:object:userInfo:] + 72
14 UIKit 0x27171dd7 -[UIInputWindowController postEndNotifications:withInfo:] + 554
15 UIKit 0x271732ed __77-[UIInputWindowController moveFromPlacement:toPlacement:starting:completion:]_block_invoke595 + 368
16 UIKit 0x26b44b05 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 308
17 UIKit 0x26b4471d -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 184
18 UIKit 0x26b4462f -[UIViewAnimationState animationDidStop:finished:] + 66
19 QuartzCore 0x2653d2d9 CA::Layer::run_animation_callbacks(void*) + 236
20 libdispatch.dylib 0x3135c7a7 _dispatch_client_callout + 22
21 libdispatch.dylib 0x3135ffa3 _dispatch_main_queue_callback_4CF + 718
22 CoreFoundation 0x236179d1 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
23 CoreFoundation 0x236160d1 __CFRunLoopRun + 1512
24 CoreFoundation 0x23564211 CFRunLoopRunSpecific + 476
25 CoreFoundation 0x23564023 CFRunLoopRunInMode + 106
26 GraphicsServices 0x2a95d0a9 GSEventRunModal + 136
27 UIKit 0x26b701d1 UIApplicationMain + 1440
28 MY_PROJECT 0x000842cf main (main.m:16)
```
It looks like it is related to UIWebView, but I have no clue what happened - any help is appreciated
The crash seems to be known in China ... | 2014/11/28 | [
"https://Stackoverflow.com/questions/27188342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4206060/"
] | I think that
```
height: auto;
```
in you CSS declaration could do what you want.
Updated fiddle: <http://jsfiddle.net/3122mts4/4/> | If you don't give height property then it will take height automatically. When you give height to any img tag then image also get distorted so never give fix height to images except some rare condition. Just give width property.
```css
img{
width: 19%;
margin: 0.5%;
background-color:black;
}
```
```html
<img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg"><img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg"><img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg"><img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg"><img src="http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg">
``` |
27,188,342 | I have a random crash in UIKit that happend a couple of times already.
It crashes with `EXC_BAD_ACCESS KERN_INVALID_ADDRESS at 0x0000000d`
```
Thread : Crashed: com.apple.main-thread
0 libobjc.A.dylib 0x30e08f46 objc_msgSend + 5
1 UIKit 0x26d1790d -[_UIWebViewScrollViewDelegateForwarder forwardInvocation:] + 140
2 CoreFoundation 0x23654def ___forwarding___ + 354
3 CoreFoundation 0x23586df8 _CF_forwarding_prep_0 + 24
4 UIKit 0x26b5a6fd -[UIScrollView _getDelegateZoomView] + 84
5 UIKit 0x26b5a635 -[UIScrollView _zoomScaleFromPresentationLayer:] + 24
6 UIKit 0x26b5a5ed -[UIWebDocumentView _zoomedDocumentScale] + 64
7 UIKit 0x26b5a13d -[UIWebDocumentView _layoutRectForFixedPositionObjects] + 104
8 UIKit 0x26b59f97 -[UIWebDocumentView _updateFixedPositionedObjectsLayoutRectUsingWebThread:synchronize:] + 38
9 UIKit 0x26b5c3e5 -[UIWebDocumentView _updateFixedPositioningObjectsLayoutAfterScroll] + 28
10 UIKit 0x26b5c3c1 -[UIWebBrowserView _updateFixedPositioningObjectsLayoutAfterScroll] + 56
11 CoreFoundation 0x2360a281 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
12 CoreFoundation 0x2356652d _CFXNotificationPost + 1784
13 Foundation 0x24296189 -[NSNotificationCenter postNotificationName:object:userInfo:] + 72
14 UIKit 0x27171dd7 -[UIInputWindowController postEndNotifications:withInfo:] + 554
15 UIKit 0x271732ed __77-[UIInputWindowController moveFromPlacement:toPlacement:starting:completion:]_block_invoke595 + 368
16 UIKit 0x26b44b05 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 308
17 UIKit 0x26b4471d -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 184
18 UIKit 0x26b4462f -[UIViewAnimationState animationDidStop:finished:] + 66
19 QuartzCore 0x2653d2d9 CA::Layer::run_animation_callbacks(void*) + 236
20 libdispatch.dylib 0x3135c7a7 _dispatch_client_callout + 22
21 libdispatch.dylib 0x3135ffa3 _dispatch_main_queue_callback_4CF + 718
22 CoreFoundation 0x236179d1 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 8
23 CoreFoundation 0x236160d1 __CFRunLoopRun + 1512
24 CoreFoundation 0x23564211 CFRunLoopRunSpecific + 476
25 CoreFoundation 0x23564023 CFRunLoopRunInMode + 106
26 GraphicsServices 0x2a95d0a9 GSEventRunModal + 136
27 UIKit 0x26b701d1 UIApplicationMain + 1440
28 MY_PROJECT 0x000842cf main (main.m:16)
```
It looks like it is related to UIWebView, but I have no clue what happened - any help is appreciated
The crash seems to be known in China ... | 2014/11/28 | [
"https://Stackoverflow.com/questions/27188342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4206060/"
] | I think that
```
height: auto;
```
in you CSS declaration could do what you want.
Updated fiddle: <http://jsfiddle.net/3122mts4/4/> | If you want to save `height`, change `img` to `div` blocks with `background-image`
**HTML**
```
<div style="background-image: url('http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg');"></div>
<div style="background-image: url('http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg');"></div>
<div style="background-image: url('http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg');"></div>
<div style="background-image: url('http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg');"></div>
<div style="background-image: url('http://doc.jsfiddle.net/_downloads/jsfiddle-logo-white.svg');"></div>
```
**CSS**
```
img{
width: 19%;
height: 200px;
margin: 0.5%;
background-color:black;
background-size: cover;
}
div
{
width:19%;
height:200px;
margin:0.5%;
background-color:black;
background-size: cover;
display:inline-block;
background-position:50% 50%;
}
```
in [JSFiddle](http://jsfiddle.net/om7L5nL8/) |
12,992,432 | thanks for looking at my question.
Basically what I'm trying to do is find all images that look like the first and the third image here: <http://imgur.com/a/IhHEC>
and remove all the ones that don't look like that (2,4).
I've tried several libraries to no avail.
Another acceptable way to do this is to check if the images contain "Code:", as that string is in each one that I have to sort out.
Thank you,
Steve
EDIT: Although the 1st and 3rd images seem like they are the same size, they are not. | 2012/10/20 | [
"https://Stackoverflow.com/questions/12992432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/679184/"
] | If those are the actual images you're going to use, it looks like histogram similarity will do the job. The first and third are very contrasty, the second and fourth, especially the fourth, have a wide range of different intensities.
You could easily make a histogram of the shades of grey in the image and then apply thresholds to the shape of the histogram to classify them.
EDIT: To actually do this: you can iterate through every pixel and create an array of pixel value => number of times found. As it's greyscale you can take either the R, G or B channel. Then divide each number by the number of pixels in the image to normalise, so it will work for any size. Each entry in the histogram will then be a fraction of the number of pixels used. You can then measure the number of values above a certain threshold. If there are lots of greys, you'll get a large number of small values. If there aren't, you'll get a small number of large values. | Due to my background in working more with text from images than image objects, I would do this in post-OCR process, by searching the text content for 'keywords' or checking for 'regular expression' representing your desired data. This means that the entire job needs to be separated into two stages: image-to-text OCR (free or cheap, software or cloud), and actual separation process (simple programming). |
1,952,126 | How do I prove that
$\displaystyle{\sum\_{i=1}^{\infty}{\frac{2^n(n!)^2}{(2n)!}}=1+\frac{\pi}{2}}$ | 2016/10/03 | [
"https://math.stackexchange.com/questions/1952126",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/166193/"
] | Challenging question. You may notice that $\frac{n!^2}{(2n)!}=\binom{2n}{n}^{-1}$, then prove that by integration by parts and induction we have
$$ \int\_{0}^{\pi/2}\sin(x)^{2n-1}\,dx = \frac{4^n}{2n\binom{2n}{n}} \tag{1}$$
It follows that
$$ S=\sum\_{n\geq 1}2^n\binom{2n}{n}^{-1} = \int\_{0}^{\pi/2}\sum\_{n\geq 1}\frac{2n}{2^n}\sin(x)^{2n-1}\,dx = \int\_{0}^{\pi/2}\frac{4\sin(x)}{(2-\sin^2 x)^2}\,dx.\tag{2}$$
Now it is not difficult to check that the last integral equals $\frac{\pi+2}{2}$: for instance, by integration by parts, since it equals:
$$ S = \int\_{0}^{1}\frac{4\,dt}{(1+t^2)^2}.\tag{3}$$ | We have that
$$\sum\_{n=1}^{\infty}\frac{2^n(n!)^2}{(2n)!}=\sum\_{n=1}^{\infty}\frac{4^n (1/2)^n}{\binom{2n}{n}}=\sum\_{n=0}^{\infty}\frac{4^n (1/2)^n}{\binom{2n}{n}}-1\\=Z(1/2)-1=\left(2\cdot\frac{\pi}{4}+2\right)-1=\frac{\pi}{2}+1$$
where we used the fact that for $|t|<1$,
$$Z(t)=\sum\_{n=0}^{\infty}\frac{4^n t^n}{\binom{2n}{n}}=
\frac{1}{1-t}\sqrt{\frac{t}{1-t}}\arctan \sqrt{\frac{t}{1-t}}+\frac{1}{1-t}.$$
A proof is given by Theorem 2.1 [here](https://www.emis.de/journals/INTEGERS/papers/g27/g27.pdf). |
1,952,126 | How do I prove that
$\displaystyle{\sum\_{i=1}^{\infty}{\frac{2^n(n!)^2}{(2n)!}}=1+\frac{\pi}{2}}$ | 2016/10/03 | [
"https://math.stackexchange.com/questions/1952126",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/166193/"
] | One way to deal with this is notice the factor in the summand is proportional
to a [Beta function](https://en.wikipedia.org/wiki/Beta_function).
$$\frac{n!^2}{(2n)!} = \frac{n}{2}\frac{\Gamma(n)\Gamma(n)}{\Gamma(2n)}
= \frac{n}{2}\int\_0^1 t^{n-1}(1-t)^{n-1} dt$$
This leads to
$$\sum\_{n=1}^\infty \frac{2^n n!^2}{(2n)!}
= \int\_0^1 \left(\sum\_{n=1}^\infty n (2t(1-t))^{n-1}\right) dt
= \int\_0^1 \frac{dt}{(1-2t(1-t))^2}
= 4\int\_0^1 \frac{dt}{(1+(2t-1)^2)^2}
$$
Change variable to $2t-1 = \tan\theta$, the series reduces to
$$2\int\_{-\pi/4}^{\pi/4} \frac{d\theta}{1+\tan^2\theta}
= \int\_{-\pi/4}^{\pi/4} (1 + \cos2\theta) d\theta
= \left[\theta + \frac12\sin(2\theta)\right]\_{-\pi/4}^{\pi/4}
= \frac{\pi}{2} + 1
$$ | We have that
$$\sum\_{n=1}^{\infty}\frac{2^n(n!)^2}{(2n)!}=\sum\_{n=1}^{\infty}\frac{4^n (1/2)^n}{\binom{2n}{n}}=\sum\_{n=0}^{\infty}\frac{4^n (1/2)^n}{\binom{2n}{n}}-1\\=Z(1/2)-1=\left(2\cdot\frac{\pi}{4}+2\right)-1=\frac{\pi}{2}+1$$
where we used the fact that for $|t|<1$,
$$Z(t)=\sum\_{n=0}^{\infty}\frac{4^n t^n}{\binom{2n}{n}}=
\frac{1}{1-t}\sqrt{\frac{t}{1-t}}\arctan \sqrt{\frac{t}{1-t}}+\frac{1}{1-t}.$$
A proof is given by Theorem 2.1 [here](https://www.emis.de/journals/INTEGERS/papers/g27/g27.pdf). |
1,952,126 | How do I prove that
$\displaystyle{\sum\_{i=1}^{\infty}{\frac{2^n(n!)^2}{(2n)!}}=1+\frac{\pi}{2}}$ | 2016/10/03 | [
"https://math.stackexchange.com/questions/1952126",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/166193/"
] | Challenging question. You may notice that $\frac{n!^2}{(2n)!}=\binom{2n}{n}^{-1}$, then prove that by integration by parts and induction we have
$$ \int\_{0}^{\pi/2}\sin(x)^{2n-1}\,dx = \frac{4^n}{2n\binom{2n}{n}} \tag{1}$$
It follows that
$$ S=\sum\_{n\geq 1}2^n\binom{2n}{n}^{-1} = \int\_{0}^{\pi/2}\sum\_{n\geq 1}\frac{2n}{2^n}\sin(x)^{2n-1}\,dx = \int\_{0}^{\pi/2}\frac{4\sin(x)}{(2-\sin^2 x)^2}\,dx.\tag{2}$$
Now it is not difficult to check that the last integral equals $\frac{\pi+2}{2}$: for instance, by integration by parts, since it equals:
$$ S = \int\_{0}^{1}\frac{4\,dt}{(1+t^2)^2}.\tag{3}$$ | One way to deal with this is notice the factor in the summand is proportional
to a [Beta function](https://en.wikipedia.org/wiki/Beta_function).
$$\frac{n!^2}{(2n)!} = \frac{n}{2}\frac{\Gamma(n)\Gamma(n)}{\Gamma(2n)}
= \frac{n}{2}\int\_0^1 t^{n-1}(1-t)^{n-1} dt$$
This leads to
$$\sum\_{n=1}^\infty \frac{2^n n!^2}{(2n)!}
= \int\_0^1 \left(\sum\_{n=1}^\infty n (2t(1-t))^{n-1}\right) dt
= \int\_0^1 \frac{dt}{(1-2t(1-t))^2}
= 4\int\_0^1 \frac{dt}{(1+(2t-1)^2)^2}
$$
Change variable to $2t-1 = \tan\theta$, the series reduces to
$$2\int\_{-\pi/4}^{\pi/4} \frac{d\theta}{1+\tan^2\theta}
= \int\_{-\pi/4}^{\pi/4} (1 + \cos2\theta) d\theta
= \left[\theta + \frac12\sin(2\theta)\right]\_{-\pi/4}^{\pi/4}
= \frac{\pi}{2} + 1
$$ |
5,841,740 | I am trying to do some **method inspection** (in Squeak - Smalltalk).
I wanted to ask what is the way **to check if a method is an abstract method**?
Meaning I want to write,
A method which gets a **class** and a **symbol** and will check if there is such a symbol in
the list of methods in an object which is of this class type and if found will return true if abstract (else not).
**How can I check if a method is an abstract method or not?**
*Thanks in advance.* | 2011/04/30 | [
"https://Stackoverflow.com/questions/5841740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550413/"
] | A method is abstract (in the sense Java or C++ people mean) if it looks like this:
```
myMethod
self subclassResponsibility.
```
So all you need to do to answer "is `MyObject>>#myMethod` abstract?" is to answer "is `MyObject>>#myMethod` a sender of `#subclassResponsibility`?"
You can answer *that* question by adding this method to Object:
```
isMethodAbstract: aSelector on: aClass
^ (self systemNavigation allCallsOn: #subclassResponsibility)
anySatisfy: [:each | each selector == aSelector
and: [each classSymbol == aClass name]]
```
or simply evaluating this in a Workspace (with suitable replacements for `#samplesPerFrame` and `SoundCodec` of course):
```
(SystemNavigation default allCallsOn: #subclassResponsibility)
anySatisfy: [:each | each selector == #samplesPerFrame
and: [each classSymbol == SoundCodec name]]
``` | You can use
>
> (aClass>>aMethod) isAbstract
>
>
>
but it only works if aClass actually contains the method aMethod, and does not work for superclasses.
So you'll have to check it recursively, similarly to how canUnderstand: works. |
5,841,740 | I am trying to do some **method inspection** (in Squeak - Smalltalk).
I wanted to ask what is the way **to check if a method is an abstract method**?
Meaning I want to write,
A method which gets a **class** and a **symbol** and will check if there is such a symbol in
the list of methods in an object which is of this class type and if found will return true if abstract (else not).
**How can I check if a method is an abstract method or not?**
*Thanks in advance.* | 2011/04/30 | [
"https://Stackoverflow.com/questions/5841740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550413/"
] | A method is abstract (in the sense Java or C++ people mean) if it looks like this:
```
myMethod
self subclassResponsibility.
```
So all you need to do to answer "is `MyObject>>#myMethod` abstract?" is to answer "is `MyObject>>#myMethod` a sender of `#subclassResponsibility`?"
You can answer *that* question by adding this method to Object:
```
isMethodAbstract: aSelector on: aClass
^ (self systemNavigation allCallsOn: #subclassResponsibility)
anySatisfy: [:each | each selector == aSelector
and: [each classSymbol == aClass name]]
```
or simply evaluating this in a Workspace (with suitable replacements for `#samplesPerFrame` and `SoundCodec` of course):
```
(SystemNavigation default allCallsOn: #subclassResponsibility)
anySatisfy: [:each | each selector == #samplesPerFrame
and: [each classSymbol == SoundCodec name]]
``` | While I don't know what your ultimate goal is, the Pharo code critics will identify methods where subclass responsibility is not defined. This may already be what you want to do. On the other hand, it's also worth checking out how that test is implemented to see whether you can use some or all of the existing code. |
5,841,740 | I am trying to do some **method inspection** (in Squeak - Smalltalk).
I wanted to ask what is the way **to check if a method is an abstract method**?
Meaning I want to write,
A method which gets a **class** and a **symbol** and will check if there is such a symbol in
the list of methods in an object which is of this class type and if found will return true if abstract (else not).
**How can I check if a method is an abstract method or not?**
*Thanks in advance.* | 2011/04/30 | [
"https://Stackoverflow.com/questions/5841740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550413/"
] | You can use
>
> (aClass>>aMethod) isAbstract
>
>
>
but it only works if aClass actually contains the method aMethod, and does not work for superclasses.
So you'll have to check it recursively, similarly to how canUnderstand: works. | While I don't know what your ultimate goal is, the Pharo code critics will identify methods where subclass responsibility is not defined. This may already be what you want to do. On the other hand, it's also worth checking out how that test is implemented to see whether you can use some or all of the existing code. |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | Couple suggestions:
1) Ensure the Reading Pane is enabled for the Tasks/To-Do view. Check *View* tab -> *Reading Pane* -> Ensure it's set to something other than "*Off*".
2) Try *View* tab -> *Reset View* while looking a the Tasks/To-Do list. | on windows 10 go to:
"View"
"To-Do Bar"
select "tasks"
you will now be able to see your flagged emails on the right of your screen. |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | Couple suggestions:
1) Ensure the Reading Pane is enabled for the Tasks/To-Do view. Check *View* tab -> *Reading Pane* -> Ensure it's set to something other than "*Off*".
2) Try *View* tab -> *Reset View* while looking a the Tasks/To-Do list. | If you are using Outlook Office 365, you can just click the Filter button up and to the right of your email list. Then choose Flagged. It shows all your Flagged emails. Other options to Filter are: Unread, To me, Flagged, Mentions, Attachments and Sort. |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | Couple suggestions:
1) Ensure the Reading Pane is enabled for the Tasks/To-Do view. Check *View* tab -> *Reading Pane* -> Ensure it's set to something other than "*Off*".
2) Try *View* tab -> *Reset View* while looking a the Tasks/To-Do list. | Click View- Click Arrange BY. go down to view settings. click sort by. change the first to flag status, and the second sort to by received decending. Flagged emails will now be at the top |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | on windows 10 go to:
"View"
"To-Do Bar"
select "tasks"
you will now be able to see your flagged emails on the right of your screen. | If you are using Outlook Office 365, you can just click the Filter button up and to the right of your email list. Then choose Flagged. It shows all your Flagged emails. Other options to Filter are: Unread, To me, Flagged, Mentions, Attachments and Sort. |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | on windows 10 go to:
"View"
"To-Do Bar"
select "tasks"
you will now be able to see your flagged emails on the right of your screen. | Click View- Click Arrange BY. go down to view settings. click sort by. change the first to flag status, and the second sort to by received decending. Flagged emails will now be at the top |
1,089,644 | I've just upgraded from Outlook 2013. When I opened my To-Do List view, all flagged emails were displayed in a narrow list on the left hand side. The currently selected email were opened in a reading pane on the right hand side.
Now, after the upgrade to Outlook 2016, the previously narrow list view takes up the whole screen unnecessarily. I don't get to see any of my emails.
[](https://i.stack.imgur.com/EVbc8.png)
How can I regain my reading pane on this page? | 2016/06/15 | [
"https://superuser.com/questions/1089644",
"https://superuser.com",
"https://superuser.com/users/389544/"
] | If you are using Outlook Office 365, you can just click the Filter button up and to the right of your email list. Then choose Flagged. It shows all your Flagged emails. Other options to Filter are: Unread, To me, Flagged, Mentions, Attachments and Sort. | Click View- Click Arrange BY. go down to view settings. click sort by. change the first to flag status, and the second sort to by received decending. Flagged emails will now be at the top |
44,881,991 | Currently I'm coding a project which has a BunifuProgressBar, but I'm having trouble coding it. Basically it says: `'Increment' is not a member of 'BunifuProgressBar'`, any ideas how to fix that issue (Please put the code in the comment section, which will make it so I don't get that error and the prog bar will work.)
CODE:
```
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BunifuProgressBar1.Increment(1)
If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then
End Sub
```
Regards,
-Zualux
P.S
Like I always say, just comment if you need more information.. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44881991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7898892/"
] | `BunifuProgressBar` does not have a `Increment` method,see the [reference page](https://devtools.bunifu.co.ke/bunifu-ui-winforms-docs/). What it does have is a `Value` property, so what you probably need to do is just:
```
BunifuProgressBar1.Value+=1
``` | According to [Here](https://devtools.bunifu.co.ke/bunifu-ui-winforms-docs/), It only has
>
> Value – the progress value
>
> MaximumValue – the maximum allowed progress
>
> value ProgressColor – the color of the progress bar
>
> BorderRadius – the roundness of the corners
>
>
>
You probably want to increment Value, set MaximumValue to whatever you want |
44,881,991 | Currently I'm coding a project which has a BunifuProgressBar, but I'm having trouble coding it. Basically it says: `'Increment' is not a member of 'BunifuProgressBar'`, any ideas how to fix that issue (Please put the code in the comment section, which will make it so I don't get that error and the prog bar will work.)
CODE:
```
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BunifuProgressBar1.Increment(1)
If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then
End Sub
```
Regards,
-Zualux
P.S
Like I always say, just comment if you need more information.. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44881991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7898892/"
] | `BunifuProgressBar` does not have a `Increment` method,see the [reference page](https://devtools.bunifu.co.ke/bunifu-ui-winforms-docs/). What it does have is a `Value` property, so what you probably need to do is just:
```
BunifuProgressBar1.Value+=1
``` | ```
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BunifuProgressBar1.Value+=1
If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then
```
End Sub |
44,881,991 | Currently I'm coding a project which has a BunifuProgressBar, but I'm having trouble coding it. Basically it says: `'Increment' is not a member of 'BunifuProgressBar'`, any ideas how to fix that issue (Please put the code in the comment section, which will make it so I don't get that error and the prog bar will work.)
CODE:
```
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BunifuProgressBar1.Increment(1)
If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then
End Sub
```
Regards,
-Zualux
P.S
Like I always say, just comment if you need more information.. | 2017/07/03 | [
"https://Stackoverflow.com/questions/44881991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7898892/"
] | According to [Here](https://devtools.bunifu.co.ke/bunifu-ui-winforms-docs/), It only has
>
> Value – the progress value
>
> MaximumValue – the maximum allowed progress
>
> value ProgressColor – the color of the progress bar
>
> BorderRadius – the roundness of the corners
>
>
>
You probably want to increment Value, set MaximumValue to whatever you want | ```
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
BunifuProgressBar1.Value+=1
If BunifuProgressBar1.Value = BunifuProgressBar1.Maxium Then
```
End Sub |
6,301,506 | I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?)
Yes, I know that it is impossible, and yes I know that it is a bad practice.
Yes, I also know that I am an idiot. But I need this solution for some specific purposes.
Thanks! | 2011/06/10 | [
"https://Stackoverflow.com/questions/6301506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | the only real way to do it is probably to encrypt the images in a flash file or something, but no matter how much time you spend jumping through hoops the user can still just press printscreen. there is no reason to even try doing this. | <http://javascript.about.com/library/blnoright.htm>
```
<body oncontextmenu="return false;">
```
Or...
```
document.body.oncontextmenu = function(){
return false;
}
```
<http://jsfiddle.net/EEMsm/> |
6,301,506 | I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?)
Yes, I know that it is impossible, and yes I know that it is a bad practice.
Yes, I also know that I am an idiot. But I need this solution for some specific purposes.
Thanks! | 2011/06/10 | [
"https://Stackoverflow.com/questions/6301506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | You could try to replace all the `<img>` elements with `<div>` elements that have the same size and use the image as a background:
```
$('img').each(function() {
var $img = $(this);
var $div = $('<div>').css({
width: $img.width(),
height: $img.height(),
backgroundImage: 'url(' + $img.attr('src') + ')',
display: 'inline-block'
});
$img.after($div).remove();
});
```
I'm using jQuery because DOM manipulation like this is a bit of a nightmare in raw JavaScript (and because this isn't a free code writing service). This won't stop anyone but it will keep them from dragging the images off your page or doing a "Save As..." from the context menu. This sort of thing also won't do anything if your users disable JavaScript.
Example: <http://jsfiddle.net/ambiguous/4Hca3/>
I'll leave translating this to whatever JavaScript libraries (if any) you're using as an exercise for the reader.
You can try disabling the context menu but not all browsers (such as Firefox) will pay attention to that sort of chicanery. | <http://javascript.about.com/library/blnoright.htm>
```
<body oncontextmenu="return false;">
```
Or...
```
document.body.oncontextmenu = function(){
return false;
}
```
<http://jsfiddle.net/EEMsm/> |
6,301,506 | I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?)
Yes, I know that it is impossible, and yes I know that it is a bad practice.
Yes, I also know that I am an idiot. But I need this solution for some specific purposes.
Thanks! | 2011/06/10 | [
"https://Stackoverflow.com/questions/6301506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | You could try to replace all the `<img>` elements with `<div>` elements that have the same size and use the image as a background:
```
$('img').each(function() {
var $img = $(this);
var $div = $('<div>').css({
width: $img.width(),
height: $img.height(),
backgroundImage: 'url(' + $img.attr('src') + ')',
display: 'inline-block'
});
$img.after($div).remove();
});
```
I'm using jQuery because DOM manipulation like this is a bit of a nightmare in raw JavaScript (and because this isn't a free code writing service). This won't stop anyone but it will keep them from dragging the images off your page or doing a "Save As..." from the context menu. This sort of thing also won't do anything if your users disable JavaScript.
Example: <http://jsfiddle.net/ambiguous/4Hca3/>
I'll leave translating this to whatever JavaScript libraries (if any) you're using as an exercise for the reader.
You can try disabling the context menu but not all browsers (such as Firefox) will pay attention to that sort of chicanery. | the only real way to do it is probably to encrypt the images in a flash file or something, but no matter how much time you spend jumping through hoops the user can still just press printscreen. there is no reason to even try doing this. |
6,301,506 | I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?)
Yes, I know that it is impossible, and yes I know that it is a bad practice.
Yes, I also know that I am an idiot. But I need this solution for some specific purposes.
Thanks! | 2011/06/10 | [
"https://Stackoverflow.com/questions/6301506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | the only real way to do it is probably to encrypt the images in a flash file or something, but no matter how much time you spend jumping through hoops the user can still just press printscreen. there is no reason to even try doing this. | One non-js way to make it harder for people is to absolutely position and size a clear png/gif on top of anything you want to make hard to download with a right click. When they try to save the image, they'll just get the clear one.
EDIT
I just saw this question which is related
[How does Flickr prevent people from downloading images from the site?](https://stackoverflow.com/questions/2129404/how-does-flickr-prevent-people-from-downloading-images-from-the-site) |
6,301,506 | I need a working script for prohibiting users from saving images on their machine. (Is it only possible through disabling right-click?)
Yes, I know that it is impossible, and yes I know that it is a bad practice.
Yes, I also know that I am an idiot. But I need this solution for some specific purposes.
Thanks! | 2011/06/10 | [
"https://Stackoverflow.com/questions/6301506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194076/"
] | You could try to replace all the `<img>` elements with `<div>` elements that have the same size and use the image as a background:
```
$('img').each(function() {
var $img = $(this);
var $div = $('<div>').css({
width: $img.width(),
height: $img.height(),
backgroundImage: 'url(' + $img.attr('src') + ')',
display: 'inline-block'
});
$img.after($div).remove();
});
```
I'm using jQuery because DOM manipulation like this is a bit of a nightmare in raw JavaScript (and because this isn't a free code writing service). This won't stop anyone but it will keep them from dragging the images off your page or doing a "Save As..." from the context menu. This sort of thing also won't do anything if your users disable JavaScript.
Example: <http://jsfiddle.net/ambiguous/4Hca3/>
I'll leave translating this to whatever JavaScript libraries (if any) you're using as an exercise for the reader.
You can try disabling the context menu but not all browsers (such as Firefox) will pay attention to that sort of chicanery. | One non-js way to make it harder for people is to absolutely position and size a clear png/gif on top of anything you want to make hard to download with a right click. When they try to save the image, they'll just get the clear one.
EDIT
I just saw this question which is related
[How does Flickr prevent people from downloading images from the site?](https://stackoverflow.com/questions/2129404/how-does-flickr-prevent-people-from-downloading-images-from-the-site) |
65,224,241 | It is my first time using PHP. I am using XAMPP on a mac.
MySQL, Apache, and localhost:8080 are all working right now.
I created this file called test.php and saved it inside lampp/htdocs:
```
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connection</title>
</head>
<body>
<?php
$servername = "localhost:8080";
$username = "root";
$password = "root";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error($conn));
}
else
{
echo "Connected successfully";
}
?>
</body>
</html>
```
However, when I go to localhose:8080/test.php a blank page opens but nothing shows up | 2020/12/09 | [
"https://Stackoverflow.com/questions/65224241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14545805/"
] | Okay, partially my bad.
I did re-compile the **EMPTY** sample project and found that despite the compiler error, the solution does build.
```
1>------ Rebuild All started: Project: Microdesk.BIMrxCommon.Infrastructure, Configuration: Debug2020 Any CPU ------
1> Microdesk.BIMrxCommon.Infrastructure -> C:\Work\Microdesk.BIMrx\bin\Debug2020\Microdesk.BIMrxCommon.Infrastructure.dll
2>------ Rebuild All started: Project: Microdesk.BIMrxCommon.DbApp, Configuration: Debug2020 Any CPU ------
2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1720,5): error : Internal MSBuild error: Non-CrossTargeting GetTargetFrameworks target should not be used in cross targeting (outer) build
2> Microdesk.BIMrxCommon.DbApp -> C:\Work\Microdesk.BIMrx\bin\Debug2020\Microdesk.BIMrxCommon.DbApp.dll
========== Rebuild All: 2 succeeded, 0 failed, 0 skipped ==========
```
**BUT** if you try to USE anything from the Infrastructure project in the referencing DbApp project then the Solution will NOT compile
```
Rebuild started...
1>------ Rebuild All started: Project: Microdesk.BIMrxCommon.Infrastructure, Configuration: Debug2020 Any CPU ------
2>------ Rebuild All started: Project: Microdesk.BIMrxCommon.DbApp, Configuration: Debug2020 Any CPU ------
2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1720,5): error : Internal MSBuild error: Non-CrossTargeting GetTargetFrameworks target should not be used in cross targeting (outer) build
2>C:\Work\Microdesk.BIMrx\BIMrxCommon\Microdesk.BIMrxCommon.DbApp\DerivedClass.cs(1,29,1,4
): error CS0234: The type or namespace name 'Infrastructure' does not exist in the namespace 'Microdesk.BIMrxCommon' (are you missing an assembly reference?)
2>C:\Work\Microdesk.BIMrx\BIMrxCommon\Microdesk.BIMrxCommon.DbApp\DerivedClass.cs(5,33,5,42): error CS0246: The type or namespace name 'BaseClass' could not be found (are you missing a using directive or an assembly reference?)
========== Rebuild All: 1 succeeded, 1 failed, 0 skipped ==========
```
I did upload a second sample project named "Microdesk.BIMrx (2).zip" to the previous OneDrive directory | When I test your issue in your side, I did not face the same behaviors as you described. So I guess that there is some issues on your current vs environment due to the update. And maybe the update broke some tools of VS.
[](https://i.stack.imgur.com/odZR7.png)
So please try the following steps to troubleshoot it:
**Suggestions**
**1)** disable any third party installed extensions under **Extensions**-->**Manage Extensions**-->**Installed**
**2)** close VS, delete `.vs` hidden folder, every `bin` and `obj` folder of your project.
and also delete all cache files under `C:\Users\xxx(current user)\AppData\Local\Microsoft\VisualStudio\16.0_xxx\ComponentModelCache`
**Then**, restart VS to test again.
**3)** or create a new project and then migrate the content from the old into the new one to test whether the issue is related to your VS or the special project itself.
**4)** If this does not work, do an initialization operation on your VS.
**Close VS**, delete the whole user folder under `C:\Users\xxx(current user)\AppData\Local\Microsoft\VisualStudio\16.0_xxx` and then restart VS to test again.
**5)** [repair vs](https://learn.microsoft.com/en-us/visualstudio/install/repair-visual-studio?view=vs-2019) from the vs\_installer |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | The default for position is `position: static;` | The [`initial`](http://www.w3.org/TR/css3-cascade/#initial) keyword was introduced in 2011 in the [Cascading and Inheritance Module](http://www.w3.org/TR/css3-cascade/) -- it's supported in FF 19+, Chrome, Safari, Opera 15+ but is currently [not supported](http://msdn.microsoft.com/en-us/library/hh781508(v=vs.85).aspx#keywords) in any version of IE. |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | The default for position is `position: static;` | Even IE 11 gives me the 'squiggles' for this one. Changing to `static` gave me the desired behavior.

Chrome actually suggests it as an acceptable property in its dropdown
 |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | The default for position is `position: static;` | I was having the same issue as `position: unset;` wasn't working for me in IE. I changed `position: static;` and it worked as expected as IE doesn't have unset behavior. |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | The [`initial`](http://www.w3.org/TR/css3-cascade/#initial) keyword was introduced in 2011 in the [Cascading and Inheritance Module](http://www.w3.org/TR/css3-cascade/) -- it's supported in FF 19+, Chrome, Safari, Opera 15+ but is currently [not supported](http://msdn.microsoft.com/en-us/library/hh781508(v=vs.85).aspx#keywords) in any version of IE. | Even IE 11 gives me the 'squiggles' for this one. Changing to `static` gave me the desired behavior.

Chrome actually suggests it as an acceptable property in its dropdown
 |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | The [`initial`](http://www.w3.org/TR/css3-cascade/#initial) keyword was introduced in 2011 in the [Cascading and Inheritance Module](http://www.w3.org/TR/css3-cascade/) -- it's supported in FF 19+, Chrome, Safari, Opera 15+ but is currently [not supported](http://msdn.microsoft.com/en-us/library/hh781508(v=vs.85).aspx#keywords) in any version of IE. | I was having the same issue as `position: unset;` wasn't working for me in IE. I changed `position: static;` and it worked as expected as IE doesn't have unset behavior. |
15,343,487 | I have a css conflict, so I have to go against an absolute positioning property that deals with some class `.myclass`. But in one case, I want a div with `.myclass` class to have a no absolute positioning. So I put `position: initial`, which works in Chrome, but is it cross-browser? I googled it and found nothing really precise. | 2013/03/11 | [
"https://Stackoverflow.com/questions/15343487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1275959/"
] | Even IE 11 gives me the 'squiggles' for this one. Changing to `static` gave me the desired behavior.

Chrome actually suggests it as an acceptable property in its dropdown
 | I was having the same issue as `position: unset;` wasn't working for me in IE. I changed `position: static;` and it worked as expected as IE doesn't have unset behavior. |
39,583,980 | I am making a listing system that updates checking new data from a json file every **3 seconds** by appending the **response.list[i].firstname** to document.getElementById("list"). but i am getting unlimited loop.
**output:**
name1
name2
name1
name2
name1
name2
(to infinity..)
```
<script>
list();
setInterval(list, 3000);
function list() {
$.getJSON('list.php',function(response){
for(var i = 0; i < response.list_count; i++){
var newElement = document.createElement('div');
newElement.innerHTML = response.list[i].firstname;
document.getElementById("list").appendChild(newElement);
}
document.getElementById("list_count").innerHTML = "" + response.list_count; + "";
});
};
``` | 2016/09/20 | [
"https://Stackoverflow.com/questions/39583980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6246854/"
] | This is happening because every 3 seconds you read JSON file and append it to the already rendered (with all the data appended in previous runs) list with
```
document.getElementById("list").appendChild(newElement);
```
If you want to show only the content of the file once, then you should clean the target list div with one of the methods described in here:
[Remove all child elements of a DOM node in JavaScript](https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript)
for example:
$('#list').empty();
Alternatively, you need to keep track of what you have already added to the list, and append only the new entries, but that might be a bit more tricky, if there is no unique identifiers in the json data that you render.
So, with the first solutioin it will be something like:
```
list();
setInterval(list, 3000);
function list() {
$.getJSON('list.php',function(response){
$('#list').empty();
for(var i = 0; i < response.list_count; i++){
var newElement = document.createElement('div');
newElement.innerHTML = response.list[i].firstname;
document.getElementById("list").appendChild(newElement);
}
document.getElementById("list_count").innerHTML = "" + response.list_count; + "";
});
};
``` | I have shared how to get length of JSON response.
```
var obj = JSON.parse(response);
var limit=Object.keys(obj).length;
for( var i = 0; i < limit; i++ ) {
}
```
I am not sure about response.**list\_count** you are using. Is that a finite number? |
36,572,968 | I'm trying to write a program to return the amount of rows and columns in a csv file. Below is the code I currently have:
```
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("ETF_Corrsv2.csv");
if (myfile.is_open())
{
int counter = 0;
while (getline(myfile, line)) { // To get the number of lines in the file
counter++;
cout << counter;
}
//int baz[5][5] = {};
while (getline(myfile, line, ','))
{
int count = 0;
cout << line;
for (int i = 0; i < line.size(); i++)
if (line[i] == ',')
count++;
cout << count;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
```
The first part works fine and counter returns the number of rows appropriately. However count does not return the correct amount of commas. When using `cout` to display the lines it shows that the commas seem to have been replaced by zeros however when I open the file with Notepad++ the commas are there. What is going on?
EDIT: Changed code to have all operations in one while loop:
```
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream myfile("ETF_Corrsv2.csv");
if (myfile.is_open())
{
int counter = 0;
while (getline(myfile, line, ',')) { // To get the number of lines in the file
counter++;
cout << counter;
int count = 0;
cout << line;
for (int i = 0; i < line.size(); i++)
if (line[i] == ',')
count++;
cout << count;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
```
Still however getting the issue that the commas are replaced by zeros though so count isn't returning the correct number of columns | 2016/04/12 | [
"https://Stackoverflow.com/questions/36572968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4845418/"
] | In fact you can reference the corresponding `ElementRef` using `@ViewChild`. Something like that:
```
@Component({
(...)
template: `
<div #someId>(...)</div>
`
})
export class Render {
@ViewChild('someId')
elt:ElementRef;
ngAfterViewInit() {
let domElement = this.elt.nativeElement;
}
}
```
`elt` will be set before the `ngAfterViewInit` callback is called. See this doc: <https://angular.io/docs/ts/latest/api/core/ViewChild-var.html>. | For HTML elements added statically to your components template you can use [`@ViewChild()`](https://angular.io/docs/ts/latest/api/core/ViewChild-var.html):
```
@Component({
...
template: `<div><span #item></span></div>`
})
export class SirRender {
@ViewChild('item') item;
ngAfterViewInit() {
passElement(this.item.nativeElement)
}
...
}
```
This doesn't work for dynamically generated HTML though.
but you can use
```
this.item.nativeElement.querySelector(...)
```
This is frowned upon though because it's direct DOM access, but if you generate the DOM dynamically already you're into this topic already anyway. |
73,787 | 1. I couldn't afford that **big a** car.
2. It was so **warm a** day that I could hardly work.
The sentences stated above have been taken from *Practical English Usage* by Michael Swan. If I write-
3. I couldn't afford that big car.
4. It was so warm day that I could hardly work.
These make sense. But placement of article *a* makes these sentences awkward to me. Please say why and when articles are placed after adjectives. And what are the differences among 1, 2 and 3, 4. | 2015/11/20 | [
"https://ell.stackexchange.com/questions/73787",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/-1/"
] | **Short answer**
----------------
If an adjective is being modified by a deictic degree adverb such as *so, too, as, this* or *that* then the adjective and adverb must go before, not after, the indefinite article. They can also appear as a postmodifier after the noun:
* a day so warm
**Full answer**
---------------
There are several grammatical points about this construction. Firstly, note that the adjective *precedes* the article here. The adjective is modifying a whole noun phrase, not a nominal (a nominal is just the smaller phrase within a noun phrase that occurs after the determiners or articles). So we see:
* so warm a day
and not:
* a so warm day
Secondly you will have noticed that this adjective is itself modified by an adverb. Now this adverb must (a) be an adverb of degree and (b) must be a deictic word, in other words it is understood by reference to the immediate environment of the speaker, or through some other element of the discourse itself. Simply using a normal degree adverb will not work here:
* \*He was very good a footballer as ...
* \*He was extremely good a footballer that ...
The adverbs that can be used like this are *so, too*, *as*, *this*, *that* as well as *how*. Some grammarians have also included *more, less* and *enough* in this list, but the grammar of these adverbs is in fact significantly different. Notice that *this* and *that* are adverbs here, not determiners.
The adverbs *so*, *too*, *as*, *how*, *this*, *that* and *how* are degree adverbs that cannot themselves give us any idea of actual *degree* or *extent* involved. We could think of them as a kind of 'pro - degree adverb'. These adverbs require some kind of benchmark for us to appreciate the actual degree involved. If this information is not provided by the context this normally entails there being a Complement phrase which indicates the actual extent or degree involved. We can consider such sentences in this way:
* It was (X)big a problem [that we gave up the whole project]
Here (X) represents the degree involved. On its own (X) does not tell us the actual degree of the bigness of the problem. It is the clause in brackets which explains the actual extent of the size of the problem.
The adverb involved will dictate what kind of phrase or clause can function as the Complement. The adverb *so* can take preposition phrases headed by the preposition *as* or finite clauses typically using the subordinator *that*. In the sentence above the only possible adverb we could use instead of (X) is the adverb *so*.
The adverb *as* typically takes phrases headed by *as*. It cannot take clauses headed by *that*.
The adverb *too* takes *to*-infinitival clauses, headed by *for* if they include a Subject:
* He was **so** big an idiot [that he wasn't allowed to speak in public without his advisors].
* It was **so** forceful a blow [as to fell his opponent].
* He is **as** great an actor [as has ever graced this stage].
* He is **as** good a footballer [as the next]'
* He was **too** valuable an asset [to let go].
* It was **too** dangerous a project [for us to take it on].
The preposition *as* (as opposed to the degree adverb) introduces equality with what follows it. More precisely it indicates some kind of benchmark which is met *or* exceeded.
Notice that the deictic degree adverbs *this*, *that* and *how* usually don't require a following phrase to provide the benchmark. It is normally clear from the discourse itself. However *that* sometimes takes finite clauses with *that* to provide a benchmark when it isn't available from the discourse:
* It was that big [that I couldn't fit it through the door].
Lastly, when *how* is interrogative as opposed to exclamative then it is not deictic - in the sense that the degree expressed is left unresolved and in direct questions may be expected to be supplied by the respondent:
* I wondered how long a journey it actually was.
* How long a rope do we need?
Notice that we cannot generally put adjectives before articles, the following are badly formed:
* \*big a footballer
* \*clever an idea
This only occurs when the adjective is being modified by a deictic degree adverb. Why? I don't know. I've been looking into this for quite a long time but haven't been able to find out.
**The Original Poster's Examples**:
Sentences (1) and (2) are grammatical. Sentence (3) is also grammatical, but this is because the adjective *big* is not being modified by any adverb. The word *that* here is a Determiner. Sentence (4) is completely ungrammatical. Because *day* is singular we must use a Determiner here. If we used an indefinite article then because *warm* is being modified by a deictic degree adverb, the adverb adjective combination should precede the article - as in sentence (2).
---
**Note**: Thanks to Edwin and fdb for helpful observations, which have been edited into the answer. | Regarding example (1), I think the emphasis of "that big a car" considerably differs from "that big car." "That big a car" could be rephrased as a "a car as big as that," which shows that you are comparing the car in question to some standard of a car that you have in your mind. "That big car" on the other hand seems to solely indicate that you're just pointing to a car that's right there, in person, in a magazine, whatever. Regarding (2) I'm not sure whether there's an issue -- or at least your example (4) is ungrammatical in English. You would need some sort of article before "day," so as it stands number (2) is the only acceptable of the two ways to express that thought (there could be others of course, but I haven't thought of them). |
73,286,085 | I want to create a simple plotly chart from a .csv file that I fetched from an API.
I import the library, pass the dataframe, and get the error:
```none
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
```
code:
```
import plotly.express as px
df=pd.read_csv('file.csv')
```
What might be the problem, and what does this error mean?
Full error traceback:
```none
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module>
1 from dash import Dash, dcc, html, Input, Output
----> 2 import plotly.express as px
3 import pandas as pd
~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module>
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module>
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
~\anaconda3\lib\site-packages\xarray\__init__.py in <module>
----> 1 from . import testing, tutorial
2 from .backends.api import (
3 load_dataarray,
4 load_dataset,
5 open_dataarray,
~\anaconda3\lib\site-packages\xarray\testing.py in <module>
7 import pandas as pd
8
----> 9 from xarray.core import duck_array_ops, formatting, utils
10 from xarray.core.dataarray import DataArray
11 from xarray.core.dataset import Dataset
~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module>
24 from numpy import where as _where
25
---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
27 from .nputils import nanfirst, nanlast
28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array
~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module>
70 List[Any],
71 # anything with a dtype attribute
---> 72 _SupportsDType[np.dtype],
73 ]
74 except ImportError:
~\anaconda3\lib\typing.py in inner(*args, **kwds)
273 except TypeError:
274 pass # All real errors (not unhashable args) are raised below.
--> 275 return func(*args, **kwds)
276 return inner
277
~\anaconda3\lib\typing.py in __class_getitem__(cls, params)
997 else:
998 # Subscripting a regular Generic subclass.
--> 999 _check_generic(cls, params, len(cls.__parameters__))
1000 return _GenericAlias(cls, params)
1001
~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen)
207 """
208 if not elen:
--> 209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
211 if alen != elen:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
``` | 2022/08/09 | [
"https://Stackoverflow.com/questions/73286085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15299852/"
] | I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error.
```
pip install numpy==1.21.6
``` | ```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4960/3694415272.py in <module>
----> 1 plotly.express.__version__
~\anaconda3\lib\site-packages\_plotly_utils\importers.py in __getattr__(import_name)
37 return getattr(class_module, class_name)
38
---> 39 raise AttributeError(
40 "module {__name__!r} has no attribute {name!r}".format(
41 name=import_name, __name__=parent_name
AttributeError: module 'plotly' has no attribute 'express'
``` |
73,286,085 | I want to create a simple plotly chart from a .csv file that I fetched from an API.
I import the library, pass the dataframe, and get the error:
```none
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
```
code:
```
import plotly.express as px
df=pd.read_csv('file.csv')
```
What might be the problem, and what does this error mean?
Full error traceback:
```none
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module>
1 from dash import Dash, dcc, html, Input, Output
----> 2 import plotly.express as px
3 import pandas as pd
~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module>
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module>
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
~\anaconda3\lib\site-packages\xarray\__init__.py in <module>
----> 1 from . import testing, tutorial
2 from .backends.api import (
3 load_dataarray,
4 load_dataset,
5 open_dataarray,
~\anaconda3\lib\site-packages\xarray\testing.py in <module>
7 import pandas as pd
8
----> 9 from xarray.core import duck_array_ops, formatting, utils
10 from xarray.core.dataarray import DataArray
11 from xarray.core.dataset import Dataset
~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module>
24 from numpy import where as _where
25
---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
27 from .nputils import nanfirst, nanlast
28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array
~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module>
70 List[Any],
71 # anything with a dtype attribute
---> 72 _SupportsDType[np.dtype],
73 ]
74 except ImportError:
~\anaconda3\lib\typing.py in inner(*args, **kwds)
273 except TypeError:
274 pass # All real errors (not unhashable args) are raised below.
--> 275 return func(*args, **kwds)
276 return inner
277
~\anaconda3\lib\typing.py in __class_getitem__(cls, params)
997 else:
998 # Subscripting a regular Generic subclass.
--> 999 _check_generic(cls, params, len(cls.__parameters__))
1000 return _GenericAlias(cls, params)
1001
~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen)
207 """
208 if not elen:
--> 209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
211 if alen != elen:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
``` | 2022/08/09 | [
"https://Stackoverflow.com/questions/73286085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15299852/"
] | I got the same error, it is dependency issue, plotly.express (5.9.0) is not working with numpy==1.20, if you upgrade numpy==1.21.6 it will solve your error.
```
pip install numpy==1.21.6
``` | I was having same issue when I updated xarray. I tried updating numpy but conda environment was restricting it. Updating the whole conda environment helped me resolve this error.
```
conda update --all
``` |
73,286,085 | I want to create a simple plotly chart from a .csv file that I fetched from an API.
I import the library, pass the dataframe, and get the error:
```none
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
```
code:
```
import plotly.express as px
df=pd.read_csv('file.csv')
```
What might be the problem, and what does this error mean?
Full error traceback:
```none
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9952/1054373791.py in <module>
1 from dash import Dash, dcc, html, Input, Output
----> 2 import plotly.express as px
3 import pandas as pd
~\anaconda3\lib\site-packages\plotly\express\__init__.py in <module>
13 )
14
---> 15 from ._imshow import imshow
16 from ._chart_types import ( # noqa: F401
17 scatter,
~\anaconda3\lib\site-packages\plotly\express\_imshow.py in <module>
9
10 try:
---> 11 import xarray
12
13 xarray_imported = True
~\anaconda3\lib\site-packages\xarray\__init__.py in <module>
----> 1 from . import testing, tutorial
2 from .backends.api import (
3 load_dataarray,
4 load_dataset,
5 open_dataarray,
~\anaconda3\lib\site-packages\xarray\testing.py in <module>
7 import pandas as pd
8
----> 9 from xarray.core import duck_array_ops, formatting, utils
10 from xarray.core.dataarray import DataArray
11 from xarray.core.dataset import Dataset
~\anaconda3\lib\site-packages\xarray\core\duck_array_ops.py in <module>
24 from numpy import where as _where
25
---> 26 from . import dask_array_compat, dask_array_ops, dtypes, npcompat, nputils
27 from .nputils import nanfirst, nanlast
28 from .pycompat import cupy_array_type, dask_array_type, is_duck_dask_array
~\anaconda3\lib\site-packages\xarray\core\npcompat.py in <module>
70 List[Any],
71 # anything with a dtype attribute
---> 72 _SupportsDType[np.dtype],
73 ]
74 except ImportError:
~\anaconda3\lib\typing.py in inner(*args, **kwds)
273 except TypeError:
274 pass # All real errors (not unhashable args) are raised below.
--> 275 return func(*args, **kwds)
276 return inner
277
~\anaconda3\lib\typing.py in __class_getitem__(cls, params)
997 else:
998 # Subscripting a regular Generic subclass.
--> 999 _check_generic(cls, params, len(cls.__parameters__))
1000 return _GenericAlias(cls, params)
1001
~\anaconda3\lib\typing.py in _check_generic(cls, parameters, elen)
207 """
208 if not elen:
--> 209 raise TypeError(f"{cls} is not a generic class")
210 alen = len(parameters)
211 if alen != elen:
TypeError: <class 'numpy.typing._dtype_like._SupportsDType'> is not a generic class
``` | 2022/08/09 | [
"https://Stackoverflow.com/questions/73286085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15299852/"
] | I was having same issue when I updated xarray. I tried updating numpy but conda environment was restricting it. Updating the whole conda environment helped me resolve this error.
```
conda update --all
``` | ```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4960/3694415272.py in <module>
----> 1 plotly.express.__version__
~\anaconda3\lib\site-packages\_plotly_utils\importers.py in __getattr__(import_name)
37 return getattr(class_module, class_name)
38
---> 39 raise AttributeError(
40 "module {__name__!r} has no attribute {name!r}".format(
41 name=import_name, __name__=parent_name
AttributeError: module 'plotly' has no attribute 'express'
``` |
41,354,972 | my MYSQL table is as below:
```
id record_nr timestamp
1 931 2014-02-15 6:21:00
2 577 2013-05-03 0:19:00
3 323 2012-08-07 11:26:00
```
in PHP I tried to retrieve a record by comparing time as below:
```
$dateTimeString = "2013-07-28 7:23:34";
$query = "SELECT * FROM mytable ";
$query .= "WHERE timestamp <= STR_TO_DATE('".$dateTimeString."', '%H:%i:%s')";
$query .= " ORDER BY timestamp DESC LIMIT 1";
```
This didn't work. How to retrieve the record #577? Timestamp is not the time the record was created. Rather, it is a date and time associated with that record. | 2016/12/28 | [
"https://Stackoverflow.com/questions/41354972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109581/"
] | You are sending an ajax request to update the record. So, you should not try to `render` a view or `redirect` user as the response of this request. Instead, you can send back a JSON object with some properties e.g. "status".
Then on client side, you check the returned JSON response and based on "status" parameter ( or any other you chose ), you can either update your data or reload the page using `window.reload` on client side. | Your db query says
```
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email]) ...
```
Shouldn't it be
```
db.none('update cands set name=$1, email=$2 where id=$8', [req.body.name, req.body.email, candID])
``` |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | Don't know if it works in Python 2.7, but in Python 3.4 `len(cap)` returns 0.
The FileCapture object is a generator, so what worked for me is `len([packet for packet in cap])` | A look at the [source code](https://github.com/KimiNewt/pyshark/blob/master/src/pyshark/capture/file_capture.py) reveals that `_packets` is a list containing packets and is only used internally:
When iterating through a `FileCapture` object with `keep_packets = True` packets are getting added to this list.
---
To get access to all packets in a `FileCapture` object you should iterate over it just like you did:
```
for packet in cap:
do_something(packet)
```
But to count the amount of packets just do this:
```
packet_amount = len(cap)
```
or use a counter like you did, but **don't use** `_packets` as it does not contain the complete packet list. |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | i too, len(cap) is 0, i thinks the answer is fail.
if you want know len(cap), please load packet before print it.
use: cap.load\_packets()
```
cap.load_packets()
packet_amount = len(cap)
print packet_amount
``` | A look at the [source code](https://github.com/KimiNewt/pyshark/blob/master/src/pyshark/capture/file_capture.py) reveals that `_packets` is a list containing packets and is only used internally:
When iterating through a `FileCapture` object with `keep_packets = True` packets are getting added to this list.
---
To get access to all packets in a `FileCapture` object you should iterate over it just like you did:
```
for packet in cap:
do_something(packet)
```
But to count the amount of packets just do this:
```
packet_amount = len(cap)
```
or use a counter like you did, but **don't use** `_packets` as it does not contain the complete packet list. |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | A look at the [source code](https://github.com/KimiNewt/pyshark/blob/master/src/pyshark/capture/file_capture.py) reveals that `_packets` is a list containing packets and is only used internally:
When iterating through a `FileCapture` object with `keep_packets = True` packets are getting added to this list.
---
To get access to all packets in a `FileCapture` object you should iterate over it just like you did:
```
for packet in cap:
do_something(packet)
```
But to count the amount of packets just do this:
```
packet_amount = len(cap)
```
or use a counter like you did, but **don't use** `_packets` as it does not contain the complete packet list. | Just adding another way using callback function. Also little bit faster approach.
```
length = 0
def count_callback(pkt):
global length
length = length + 1
cap.apply_on_packets(count_callback)
print(length)
``` |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | Don't know if it works in Python 2.7, but in Python 3.4 `len(cap)` returns 0.
The FileCapture object is a generator, so what worked for me is `len([packet for packet in cap])` | i too, len(cap) is 0, i thinks the answer is fail.
if you want know len(cap), please load packet before print it.
use: cap.load\_packets()
```
cap.load_packets()
packet_amount = len(cap)
print packet_amount
``` |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | Don't know if it works in Python 2.7, but in Python 3.4 `len(cap)` returns 0.
The FileCapture object is a generator, so what worked for me is `len([packet for packet in cap])` | Just adding another way using callback function. Also little bit faster approach.
```
length = 0
def count_callback(pkt):
global length
length = length + 1
cap.apply_on_packets(count_callback)
print(length)
``` |
27,025,827 | In this code with pyshark
```
import pyshark
cap = pyshark.FileCapture(filename)
i = 0
for idx, packet in enumerate(cap):
i += 1
print i
print len(cap._packets)
```
`i` and `len(cap._packets)` give two different results. Why is that? | 2014/11/19 | [
"https://Stackoverflow.com/questions/27025827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/464277/"
] | i too, len(cap) is 0, i thinks the answer is fail.
if you want know len(cap), please load packet before print it.
use: cap.load\_packets()
```
cap.load_packets()
packet_amount = len(cap)
print packet_amount
``` | Just adding another way using callback function. Also little bit faster approach.
```
length = 0
def count_callback(pkt):
global length
length = length + 1
cap.apply_on_packets(count_callback)
print(length)
``` |
31,962 | I am using this program. However, I am getting garbage values only.
Do revert as to how can I get proper values over my arduino.
```
/*****************************************************************************/
* PrinterCapturePoll.ino
* ------------------
* Monitor a parallel port printer output and capture each character. Output the
* character on the USB serial port so it can be captured in a terminal program.
*
* By............: Paul Jewell
* Date..........: 29th January 2015
* Version.......: 0.1a
*-------------------------------------------------------------------------- - ----
* Wiring Layout
* ------------ -
*
* Parallel Port Output Arduino Input
* -------------------- ------------ -
* Name Dir. Pin Name Pin
* ---- -- - ---- -- -
* nSTROBE > 1..........................2
* DATA BYTE > 2 - 9.......................3 - 10
* nACK < 10.........................11
* BUSY < 11.........................12
* OutofPaper < 12................GND
* Selected < 13.................5v
* GND <> 18 - 25................GND
*------------------------------------------------------------------------------ -
******************************************************************************** /
int nStrobe = 2;
int Data0 = 3;
int Data1 = 4;
int Data2 = 5;
int Data3 = 6;
int Data4 = 7;
int Data5 = 8;
int Data6 = 9;
int Data7 = 10;
int nAck = 11;
int Busy = 12;
int led = 13; // use as status led
void setup() {
// Configure pins
pinMode(nStrobe, INPUT_PULLUP);
for (int n = Data0; n < (Data7 + 1); n++)
pinMode(n, INPUT_PULLUP);
pinMode(nAck, OUTPUT);
pinMode(Busy, OUTPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
while (!Serial) {
Serial.println("Waiting to Initialise");
}
//State = READY;
delay(1000);
Serial.println("Initialised");
delay(1000);
}
void loop() {
while (digitalRead(nStrobe) == HIGH) {
digitalWrite(Busy, LOW);
digitalWrite(nAck, HIGH);
digitalWrite(led, HIGH);
ProcessChar();
}
digitalWrite(Busy, HIGH);
digitalWrite(led, LOW);
digitalWrite(nAck, LOW);
delay(5); //milliseconds. Specification minimum = 5 us
}
void ProcessChar() {
byte Char;
Char = digitalRead(Data0) +
(digitalRead(Data1) << 1) +
(digitalRead(Data2) << 2) +
(digitalRead(Data3) << 3) +
(digitalRead(Data4) << 4) +
(digitalRead(Data5) << 5) +
(digitalRead(Data6) << 6) +
(digitalRead(Data7) << 7);
Serial.print(char(Char));
}
``` | 2016/12/06 | [
"https://arduino.stackexchange.com/questions/31962",
"https://arduino.stackexchange.com",
"https://arduino.stackexchange.com/users/20151/"
] | I think I can see the problem - although I have no way to test it.
According to [Wikipedia](https://en.wikipedia.org/wiki/Parallel_port):
>
> When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.
>
>
>
That's not what you're doing - you are repeatedly reading while the strobe is HIGH.
Here's my attempt at your loop() which I hope will at least get you started:
```
void loop()
{
// Wait for strobe to go LOW, indicating a character is ready
while (digitalRead(nStrobe) == LOW) {
delay(1)
};
// Strobe is now LOW - a character is ready.
// Pull BUSY to high
// (NB: I don't know what you're doing with nAct and led)
digitalWrite(Busy, HIGH);
digitalWrite(led, LOW);
digitalWrite(nAck,LOW);
// Print the character
ProcessChar();
// Return BUSY to low again
// (NB: I don't know what you're doing with nAct and led)
digitalWrite(Busy, LOW);
digitalWrite(led, HIGH);
digitalWrite(nAck,HIGH);
// Wait for the strobe to go HIGH again
while (digitalRead(nStrobe) == LOW) {
delay(1)
};
}
```
You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state. I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it. | Do you know the printer is working properly?
You are trying to fix more than one thing at once and that's never a good idea. What I suggest you do is get a breadboard and make your own printer simulator. You need to connect and LED up to every output pin and a button to every input pin.
Then you can simulate data from the printer, i.e. just pressing the button for pin 3 and you should see 1 coming out on the serial monitor. OK I agree this "simulator" is rubbish, but you probably have the bits to knock it up now.
If you are still seeing 'junk' values then have a look and see if there is a pattern to the data. This would be helped by printing the values in hex.
Of course if the Arduino side works then the issue is that the printer is sending data that you are not expecting. It might help stick LEDs on every pin, both directions, it will help you see what is being sent.
Its possible that you are expecting 1 to indicate the bit is set and the printer is using 0. |
20,730,665 | I want use a common WebDriver instance across all my TestNG tests by extending my test class to use a base class as shown below but it doesn't seem to work :
```
public class Browser {
private static WebDriver driver = new FirefoxDriver();
public static WebDriver getDriver()
{
return driver;
}
public static void open(String url)
{
driver.get(url);
}
public static void close()
{
driver.close();
}
}
```
I want to use the WebDriver in my test class as shown below, but I get the error message :
**The method getDriver() is undefined for the type GoogleTest**:
```
public class GoogleTest extends Browser
{
@Test
public void GoogleSearch() {
WebElement query = getDriver().findElement(By.name("q"));
// Enter something to search for
query.sendKeys("Selenium");
// Now submit the form
query.submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 5 seconds
WebDriverWait wait = new WebDriverWait(getDriver(), 30);
// wait.Until((d) => { return d.Title.StartsWith("selenium"); });
//Check that the Title is what we are expecting
assertEquals("selenium - Google Search", getDriver().getTitle().toString());
}
}
``` | 2013/12/22 | [
"https://Stackoverflow.com/questions/20730665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2850361/"
] | The problem is that your `getDriver` method is **static**.
Solution #1: Make method non-static (this will either need to make the `driver` variable non-static as well, or use `return Browser.getDriver();` )
```
public WebDriver getDriver() {
return driver;
}
```
**Or,** call the `getDriver` method by using `Browser.getDriver`
```
WebElement query = Browser.getDriver().findElement(By.name("q"));
``` | You need to start your driver, one of many solution is to try @Before to add, Junit will autorun it for you.
```
public class Browser {
private WebDriver driver;
@Before
public void runDriver()
{
driver = new FirefoxDriver();
}
public WebDriver getDriver()
{
return driver;
}
public void open(String url)
{
driver.get(url);
}
public void close()
{
driver.close();
}
}
``` |
60,823,571 | I have a background image and a box with a title in it. How would I blur part of the image in the box? I tried using web kit filter but it blurred the title
[](https://i.stack.imgur.com/yWjPZ.png)
```
.title {
height: 90px;
margin: auto;
margin-top: 90px;
margin-left: 250px;
margin-right: 250px;
display: flex;
justify-content: center;
align-items: center;
border-width: 1px;
border-style: solid;
filter: blur(8px);
-webkit-filter: blur(8px);
}
```
```
.bgimage {
width: 100%;
height: 540px;
background-size: 100%;
background-repeat: no-repeat;
background-image: url("img");
}
```
```
<div className="bgimage">
<div className="title">Title</div>
</div>
``` | 2020/03/24 | [
"https://Stackoverflow.com/questions/60823571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7559119/"
] | You may need **[backdrop-filter](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter)**
>
> The backdrop-filter CSS property lets you apply graphical effects such as blurring or color shifting to the area behind an element. Because it applies to everything behind the element, to see the effect you must make the element or its background at least partially transparent.
>
>
>
```css
backdrop-filter: blur(20px);
```
An amazing online demo: <https://codepen.io/alphardex/pen/pooQMVp>
```css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
/* background: URL(); */
background-size: cover;
background-position: center;
}
.bgimage {
display: flex;
justify-content: center;
align-items: center;
width: 72vw;
height: 36vh;
/* box-shadow: ; */
backdrop-filter: blur(20px);
transition: 0.5s ease;
&:hover {
/* box-shadow: ; */
}
.title {
padding-left: 0.375em;
font-size: 3.6em;
font-family: Lato, sans-serif;
font-weight: 200;
letter-spacing: 0.75em;
color: white;
@media (max-width: 640px) {
font-size: 2em;
}
}
}
```
[](https://i.stack.imgur.com/rdx6i.jpg) | Add another blurred image with a pseudo-element and clip it:
```css
.example {
position: relative;
width: 400px;
height: 400px;
background: #000 url(https://picsum.photos/id/870/400/400) no-repeat center center scroll;
display: flex;
justify-content: center;
align-items: center;
}
.example::before {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: #000 url(https://picsum.photos/id/870/400/400) no-repeat center center scroll;
clip-path: inset(80px);
filter: blur(10px);
}
.example p {
font-size: 4rem;
position: relative;
z-index: 1;
}
```
```html
<div class="example">
<p>Title</p>
</div>
``` |
2,619,042 | Here's what i have so far...
I have yet to figure out how i'm going to handle the 11 / 1 situation with an ace, and when the player chooses an option for hit/stand, i get segfault.
HELP!!!
**updated code**
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define DECKSIZE 52
#define VALUE 9
#define FACE 4
#define HANDSIZE 26
typedef struct {
int value;
char* suit;
char* name;
}Card;
/*typedef struct {
int value;
char* suit;
char* name;
}dealerHand;
typedef struct {
int value;
char* suit;
char* name;
}playerHand;*/ //trying something different
Card cards[DECKSIZE];
/*dealerHand deal[HANDSIZE]; //trying something different
playerHand dealt[HANDSIZE];*/
char *faceName[]={"two","three", "four","five","six", "seven","eight","nine",
"ten", "jack","queen", "king","ace"};
char *suitName[]={"spades","diamonds","clubs","hearts"};
Card *deal[HANDSIZE];
Card *dealt[HANDSIZE];
void printDeck(){
int i;
for(i=0;i<DECKSIZE;i++){
printf("%s of %s value = %d\n ",cards[i].name,cards[i].suit,cards[i].value);
if((i+1)%13==0 && i!=0) printf("-------------------\n\n");
}
}
void shuffleDeck(){
srand(time(NULL));
int this;
int that;
Card temp;
int c;
for(c=0;c<10000;c++){ //c is the index for number of individual card shuffles should be set to c<10000 or more
this=rand()%DECKSIZE;
that=rand()%DECKSIZE;
temp=cards[this];
cards[this]=cards[that];
cards[that]=temp;
}
}
/*void hitStand(i,y){ // I dumped this because of a segfault i couldn't figure out.
int k;
printf(" Press 1 to HIT or press 2 to STAND:");
scanf("%d",k);
if(k=1){
dealt[y].suit=cards[i].suit;
dealt[y].name=cards[i].name;
dealt[y].value=cards[i].value;
y++;
i++;
}
}
*/
int main(){
int suitCount=0;
int faceCount=0;
int i;
int x;
int y;
int d;
int p;
int k;
for(i=0;i<DECKSIZE;i++){ //this for statement builds the deck
if(faceCount<9){
cards[i].value=faceCount+2;
}else{ //assigns face cards as value 10
cards[i].value=10;
}
cards[i].suit=suitName[suitCount];
cards[i].name=faceName[faceCount++];
if(faceCount==13){ //this if loop increments suit count once
cards[i].value=11; //all faces have been assigned, and also
suitCount++; //assigns the ace as 11
faceCount=0;
} //end building deck
}
/*printDeck(); //prints the deck in order
shuffleDeck(); //shuffles the deck
printDeck(); //prints the deck as shuffled
This was used in testing, commented out to keep the deck hidden!*/
shuffleDeck();
x=0;
y=0;
for(i=0;i<4;i++){ //this for loop deals the first 4 cards,
dealt[y]=&cards[i]; //first card to player, second to dealer, as per standard dealing practice.
i++;
y++;
deal[x]=&cards[i];
x++;
}
printf(" Dealer's hand is: %s of %s and XXXX of XXXX. (Second card is hidden!)\n",deal[0]->name,deal[0]->suit,deal[1]->name,deal[1]->suit);
printf(" Player's hand is: %s of %s and %s of %s.\n",dealt[0]->name,dealt[0]->suit,dealt[1]->name,dealt[1]->suit);
printf(" the current value of the index i=%d\n",i); //this line gave me the value of i for testing
d=deal[0]->value+deal[1]->value;
p=dealt[0]->value+dealt[1]->value;
if(d==21){
printf(" The Dealer has Blackjack! House win!\n");
}else{
if(d>21){
printf(" The dealer is Bust! You win!\n");
}else{
if(d>17){
printf(" Press 1 to HIT or 2 to STAND: ");
scanf("%d",&k);
if(k==1){
dealt[y]=&cards[i];
y++;
i++;
}
}else{
if(d<17){
printf(" Dealer Hits!");
deal[x]=&cards[i];
x++;
i++;
}
}
}
}
return 0;
}
``` | 2010/04/11 | [
"https://Stackoverflow.com/questions/2619042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314116/"
] | To fix your segfault, use `scanf("%d",&k);` instead of `scanf("%d",k);` (note the ampersand that I added. You need that because `scanf`'s second argument is a pointer to the location where it should store what gets read in. `k` by itself isn't a pointer--adding the `&` gets a pointer to `k`.
For handling aces, under what conditions do the aces go from valued at 11 to valued at 1? What line(s) in your code do you expect to have to touch to enable that? I can think of a way to implement it involving a variable that keeps track of how many aces went into computing a player's total score, or another way would be to recompute a score just in time to use it. | See [this question](https://stackoverflow.com/questions/837951/is-there-an-elegant-way-to-deal-with-the-ace-in-blackjack) on how to deal with the ace situation.
As a general tip about your code; you have essentially the same struct three times (Card, dealerHand, playerHand). It would suffice to define the struct once for the card and, for example, have pointers to the cards stored as the hands. |
2,619,042 | Here's what i have so far...
I have yet to figure out how i'm going to handle the 11 / 1 situation with an ace, and when the player chooses an option for hit/stand, i get segfault.
HELP!!!
**updated code**
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define DECKSIZE 52
#define VALUE 9
#define FACE 4
#define HANDSIZE 26
typedef struct {
int value;
char* suit;
char* name;
}Card;
/*typedef struct {
int value;
char* suit;
char* name;
}dealerHand;
typedef struct {
int value;
char* suit;
char* name;
}playerHand;*/ //trying something different
Card cards[DECKSIZE];
/*dealerHand deal[HANDSIZE]; //trying something different
playerHand dealt[HANDSIZE];*/
char *faceName[]={"two","three", "four","five","six", "seven","eight","nine",
"ten", "jack","queen", "king","ace"};
char *suitName[]={"spades","diamonds","clubs","hearts"};
Card *deal[HANDSIZE];
Card *dealt[HANDSIZE];
void printDeck(){
int i;
for(i=0;i<DECKSIZE;i++){
printf("%s of %s value = %d\n ",cards[i].name,cards[i].suit,cards[i].value);
if((i+1)%13==0 && i!=0) printf("-------------------\n\n");
}
}
void shuffleDeck(){
srand(time(NULL));
int this;
int that;
Card temp;
int c;
for(c=0;c<10000;c++){ //c is the index for number of individual card shuffles should be set to c<10000 or more
this=rand()%DECKSIZE;
that=rand()%DECKSIZE;
temp=cards[this];
cards[this]=cards[that];
cards[that]=temp;
}
}
/*void hitStand(i,y){ // I dumped this because of a segfault i couldn't figure out.
int k;
printf(" Press 1 to HIT or press 2 to STAND:");
scanf("%d",k);
if(k=1){
dealt[y].suit=cards[i].suit;
dealt[y].name=cards[i].name;
dealt[y].value=cards[i].value;
y++;
i++;
}
}
*/
int main(){
int suitCount=0;
int faceCount=0;
int i;
int x;
int y;
int d;
int p;
int k;
for(i=0;i<DECKSIZE;i++){ //this for statement builds the deck
if(faceCount<9){
cards[i].value=faceCount+2;
}else{ //assigns face cards as value 10
cards[i].value=10;
}
cards[i].suit=suitName[suitCount];
cards[i].name=faceName[faceCount++];
if(faceCount==13){ //this if loop increments suit count once
cards[i].value=11; //all faces have been assigned, and also
suitCount++; //assigns the ace as 11
faceCount=0;
} //end building deck
}
/*printDeck(); //prints the deck in order
shuffleDeck(); //shuffles the deck
printDeck(); //prints the deck as shuffled
This was used in testing, commented out to keep the deck hidden!*/
shuffleDeck();
x=0;
y=0;
for(i=0;i<4;i++){ //this for loop deals the first 4 cards,
dealt[y]=&cards[i]; //first card to player, second to dealer, as per standard dealing practice.
i++;
y++;
deal[x]=&cards[i];
x++;
}
printf(" Dealer's hand is: %s of %s and XXXX of XXXX. (Second card is hidden!)\n",deal[0]->name,deal[0]->suit,deal[1]->name,deal[1]->suit);
printf(" Player's hand is: %s of %s and %s of %s.\n",dealt[0]->name,dealt[0]->suit,dealt[1]->name,dealt[1]->suit);
printf(" the current value of the index i=%d\n",i); //this line gave me the value of i for testing
d=deal[0]->value+deal[1]->value;
p=dealt[0]->value+dealt[1]->value;
if(d==21){
printf(" The Dealer has Blackjack! House win!\n");
}else{
if(d>21){
printf(" The dealer is Bust! You win!\n");
}else{
if(d>17){
printf(" Press 1 to HIT or 2 to STAND: ");
scanf("%d",&k);
if(k==1){
dealt[y]=&cards[i];
y++;
i++;
}
}else{
if(d<17){
printf(" Dealer Hits!");
deal[x]=&cards[i];
x++;
i++;
}
}
}
}
return 0;
}
``` | 2010/04/11 | [
"https://Stackoverflow.com/questions/2619042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314116/"
] | In general: compiling with warnings enabled tends to be helpful (gcc doesn't help you out much by default!).
Compare:
```
$ gcc -o blackjack blackjack.c
$
```
with:
```
$ gcc -Wall -o blackjack blackjack.c
blackjack.c: In function 'main':
blackjack.c:124: warning: too many arguments for format
blackjack.c:139: warning: format '%d' expects type 'int *', but argument 2 has type 'int'
$
```
This spots the `scanf()` problem (and another one!) straight away. | See [this question](https://stackoverflow.com/questions/837951/is-there-an-elegant-way-to-deal-with-the-ace-in-blackjack) on how to deal with the ace situation.
As a general tip about your code; you have essentially the same struct three times (Card, dealerHand, playerHand). It would suffice to define the struct once for the card and, for example, have pointers to the cards stored as the hands. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I'd use observer design pattern and move the update logic to the observer class.
Don't mix logic and GUI. | I like option 4:
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
UpdateTotalCountLabel(totalCount);
}
}
```
Clear delineation of intent and scope, easy-to-follow logic -- what's not to love? |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I'd use observer design pattern and move the update logic to the observer class.
Don't mix logic and GUI. | *(Update: I misread the order of the options and had them reversed - EM)*
Since your code is "doing something" (setting the count label on an outside component), the first form is usually considered better.
However -- and OOP purists will disagree vehemently with me on this -- neither version is terribly wrong. I've done and seen both. I will not rewrite code that looks like #2 just for the heck of it.
In some contexts, the second alternative might actually be more sensible than the first. For example, if the code needs to track the counter for other reasons and sets and gets it a lot, it might make sense to think of the writing to the label as a View side-effect, and the setting/getting of the count property as the main artifact. In that case I would go for the property get/set pair.
UPDATE:
About the new third alternative:
I actually don't recommend that idea. Now you have separated, into two separate of code, two actions that always must happen together; that's a net loss. You risk forgetting doing one of them somewhere in the code. Either #1 or #2 are better than #3. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I think using the public accessors is better since it allows more maintanable code in case later on you need to change the way the total value is calculated. In that way, the users of the TotalValue property will not need to worry about your changes since these changes will not affect their code in any way. | I actually favor #1, since it clearly conveys that you are *doing* something, other than setting a field.
However, I agree with Mykola that your UI interaction **should not belong** to the same class that your backing logic does. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I think using the public accessors is better since it allows more maintanable code in case later on you need to change the way the total value is calculated. In that way, the users of the TotalValue property will not need to worry about your changes since these changes will not affect their code in any way. | I prefer the first or
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
The second one I dislike because it breaks Encapsulation. I would also modify the method name to be more descriptive such as 'UpdateTotalLabelCountAsync' since that is what the method is doing.
Since you are right now are working on the code you could get away with putting it in the property setter. However, when somebody else or even you later go to do maintenance work, you might not see how the label is set. With the method at least you know exactly how the label is set. Also a property is used to store data not updated a UI. It is also possible you might move the property out of the UI layer and store another location. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I think using the public accessors is better since it allows more maintanable code in case later on you need to change the way the total value is calculated. In that way, the users of the TotalValue property will not need to worry about your changes since these changes will not affect their code in any way. | I like option 4:
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
UpdateTotalCountLabel(totalCount);
}
}
```
Clear delineation of intent and scope, easy-to-follow logic -- what's not to love? |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I'd use observer design pattern and move the update logic to the observer class.
Don't mix logic and GUI. | I prefer the first or
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
The second one I dislike because it breaks Encapsulation. I would also modify the method name to be more descriptive such as 'UpdateTotalLabelCountAsync' since that is what the method is doing.
Since you are right now are working on the code you could get away with putting it in the property setter. However, when somebody else or even you later go to do maintenance work, you might not see how the label is set. With the method at least you know exactly how the label is set. Also a property is used to store data not updated a UI. It is also possible you might move the property out of the UI layer and store another location. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I think using the public accessors is better since it allows more maintanable code in case later on you need to change the way the total value is calculated. In that way, the users of the TotalValue property will not need to worry about your changes since these changes will not affect their code in any way. | *(Update: I misread the order of the options and had them reversed - EM)*
Since your code is "doing something" (setting the count label on an outside component), the first form is usually considered better.
However -- and OOP purists will disagree vehemently with me on this -- neither version is terribly wrong. I've done and seen both. I will not rewrite code that looks like #2 just for the heck of it.
In some contexts, the second alternative might actually be more sensible than the first. For example, if the code needs to track the counter for other reasons and sets and gets it a lot, it might make sense to think of the writing to the label as a View side-effect, and the setting/getting of the count property as the main artifact. In that case I would go for the property get/set pair.
UPDATE:
About the new third alternative:
I actually don't recommend that idea. Now you have separated, into two separate of code, two actions that always must happen together; that's a net loss. You risk forgetting doing one of them somewhere in the code. Either #1 or #2 are better than #3. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I'd use observer design pattern and move the update logic to the observer class.
Don't mix logic and GUI. | I actually favor #1, since it clearly conveys that you are *doing* something, other than setting a field.
However, I agree with Mykola that your UI interaction **should not belong** to the same class that your backing logic does. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I've always considered Properties to be the equivalent to get/set accessor methods. The rule of thumb for get/set accessors is that they are generally supposed to be for a public interface. If a class is calling it's own accessor methods, they should probably be in another class.
I'd consider it a code smell. | I actually favor #1, since it clearly conveys that you are *doing* something, other than setting a field.
However, I agree with Mykola that your UI interaction **should not belong** to the same class that your backing logic does. |
630,249 | I am working on a multi-threaded app. I'm processing reports and keeping track of the number of reports in the current batch as well as the total number of reports processed. Whenever I update the counters, I also need to update a label on the GUI which, since the process is on a separate thread, requires a call to a delegate. Which one of these is the better way to go?
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
or
```
private int totalCount;
public int TotalCount
{
get { return totalCount; }
set {
totalCount = value;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
}
```
**Edit:** Ok, third option.
```
private void UpdateTotalCountLabel()
{
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
// code elsewhere would look like this
totalCount++;
UpdateTotalCountLabel();
//or
totalCount+= curBatch.Length;
UpdateTotalCountLabel();
``` | 2009/03/10 | [
"https://Stackoverflow.com/questions/630249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19038/"
] | I prefer the first or
```
private void UpdateTotalCount(int newValue)
{
totalCount = newValue;
if (labelTotalCount.InvokeRequired)
BeginInvoke((MethodInvoker) delegate() {
labelTotalCount.Text = "Total reports:" + totalcount; });
else
labelTotalCount.Text = "Total reports:" + totalcount;
}
```
The second one I dislike because it breaks Encapsulation. I would also modify the method name to be more descriptive such as 'UpdateTotalLabelCountAsync' since that is what the method is doing.
Since you are right now are working on the code you could get away with putting it in the property setter. However, when somebody else or even you later go to do maintenance work, you might not see how the label is set. With the method at least you know exactly how the label is set. Also a property is used to store data not updated a UI. It is also possible you might move the property out of the UI layer and store another location. | I actually favor #1, since it clearly conveys that you are *doing* something, other than setting a field.
However, I agree with Mykola that your UI interaction **should not belong** to the same class that your backing logic does. |
17,610,594 | I'm developing an application to send SMS via AT commands, that part is OK. I have a list of contacts and I want to send a file (which changes in time) to all of my contacts. In order to do that I need to repeat the sending part every 30 minutes.
I found this code using a timer, but I'm not sure if it's useful in my case and how I can use it. Please help, any idea is appreciated.
```
private void btntime_Click(object sender, EventArgs e)
{
s_myTimer.Tick += new EventHandler(s_myTimer_Tick);
int tps = Convert.ToInt32(textBoxsettime.Text);
// 1 seconde = 1000 millisecondes
try
{
s_myTimer.Interval = tps * 60000;
}
catch
{
MessageBox.Show("Error");
}
s_myTimer.Start();
MessageBox.Show("Timer activated.");
}
// Méthode appelée pour l'évènement
static void s_myTimer_Tick(object sender, EventArgs e)
{
s_myCounter++;
MessageBox.Show("ns_myCounter is " + s_myCounter + ".");
if (s_myCounter >= 1)
{
// If the timer is on...
if (s_myTimer.Enabled)
{
s_myTimer.Stop();
MessageBox.Show("Timer stopped.");
}
else
{
MessageBox.Show("Timer already stopped.");
}
}
}
``` | 2013/07/12 | [
"https://Stackoverflow.com/questions/17610594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2335219/"
] | Whether this code is useful or not depends entirely what you want to do with it. It shows a very basic usage of the Timer-class in .NET, which is indeed one of the timers you can use if you want to implement a repeating action. [I suggest you look at the MSDN-guidance on all timers in .NET](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx) and pick the one that best fits your requirements. | This is simple but should work for you if you do not need a very accurate time span between firing.
Add a timer to your form (timer1), and a timer tick event .
```
private void btntime_Click(object sender, EventArgs e)
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 30 *1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
//fire you method to send the sms here
MessageBox.Show("fired");//take this away after test
timer1.Start();
}
``` |
17,610,594 | I'm developing an application to send SMS via AT commands, that part is OK. I have a list of contacts and I want to send a file (which changes in time) to all of my contacts. In order to do that I need to repeat the sending part every 30 minutes.
I found this code using a timer, but I'm not sure if it's useful in my case and how I can use it. Please help, any idea is appreciated.
```
private void btntime_Click(object sender, EventArgs e)
{
s_myTimer.Tick += new EventHandler(s_myTimer_Tick);
int tps = Convert.ToInt32(textBoxsettime.Text);
// 1 seconde = 1000 millisecondes
try
{
s_myTimer.Interval = tps * 60000;
}
catch
{
MessageBox.Show("Error");
}
s_myTimer.Start();
MessageBox.Show("Timer activated.");
}
// Méthode appelée pour l'évènement
static void s_myTimer_Tick(object sender, EventArgs e)
{
s_myCounter++;
MessageBox.Show("ns_myCounter is " + s_myCounter + ".");
if (s_myCounter >= 1)
{
// If the timer is on...
if (s_myTimer.Enabled)
{
s_myTimer.Stop();
MessageBox.Show("Timer stopped.");
}
else
{
MessageBox.Show("Timer already stopped.");
}
}
}
``` | 2013/07/12 | [
"https://Stackoverflow.com/questions/17610594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2335219/"
] | Whether this code is useful or not depends entirely what you want to do with it. It shows a very basic usage of the Timer-class in .NET, which is indeed one of the timers you can use if you want to implement a repeating action. [I suggest you look at the MSDN-guidance on all timers in .NET](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx) and pick the one that best fits your requirements. | You can start something like this. After all SMS are sent then after 30 seconds the SMS will be sent again.
```
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer1.Interval = (30 * 60 * 1000);
timer1.Tick += SendSMS;
}
private void SendSMS(object sender, EventArgs e)
{
timer1.Stop();
// Code to send SMS
timer1.Start();
}
```
Hope it helps. |
4,607,039 | We have around 3 people working on a project in TFS. Our company set our TFS project to single checkout. But Sometimes, we have 1 person checking out certain files, solution files, etc. Is it bad practice to have multiple checkout enabled and let the merging or diff tool handle the problem if we both accidentally overwrote someone else code?
I've read this somewhere that its all about good communication and allowing the diff tool to handle these problems but our employers suggest using single checkout.
2 questions. Should we enable multiple checkout? If so, how do we enable multiple checkout? | 2011/01/05 | [
"https://Stackoverflow.com/questions/4607039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400861/"
] | It is true that having multiple checkout disabled is simpler to work with, and it safeguards you against having to do manual merges and perhaps overwrite work.
However, it can also hinder productivity and development, especially on medium to large teams. If John can't get his feature done before Susan checks her version of a file in; some time is going to be wasted.
In my experience, multiple checkout with TFS works really well, and you should not be afraid to use it. The built-in merge tool sucks, but you can get a nice one such as [DiffMerge](http://www.sourcegear.com/diffmerge/) for free. If you make sure to communicate what each other is working on, and each of you make sure to Get Latest after each feature (or every morning), to avoid the possibility of working on stale versions, you should be fine. | I worked on a team of 3+ developers for a long time and shared checkout is fantastic. Your team will need the discipline to *communicate with each other* if they run into merge conflicts that aren't straightforward, but I have experienced nothing but upside in enabling shared checkout.
Make sure that you use a merge tool that supports three-way merge (such as [DiffMerge](http://www.sourcegear.com/diffmerge/)), as these tools make it much easier to determine the intent of each developer's changes. |
9,183 | I managed to get all traffic routed through tor using the following this [documentation](https://trac.torproject.org/projects/tor/wiki/doc/TransparentProxy).
I want now to know if it's possible to turn this on and off on command. I've tried reversing it with the following to no avail:
```
#!/bin/sh
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -F INPUT
iptables -F OUTPUT
iptables -F FORWARD
```
Does anyone know how this would be possible? | 2015/12/07 | [
"https://tor.stackexchange.com/questions/9183",
"https://tor.stackexchange.com",
"https://tor.stackexchange.com/users/10009/"
] | 1. You need to flush the NAT table too, as dingensundso suggests: `iptables -t nat -F`
2. You probably don't want to just `ACCEPT` all `INPUT`, `OUTPUT`, and `FORWARD` traffic, this would disable packet-filtering (your "firewall") entirely.
3. Just switching Tor on and off is a terrible plan for anonymity. Your applications will keep state between your usage inside and outside of Tor and this state will potentially link your Tor usage to your non-Tor usage, deanonymizing you. | Just bind it - if you're using IPTables - to the username. Create a username, let's say `clearnet` and allow all the traffic for it to be direct. |
12,234,050 | For the last 3 weeks we have been testing Nginx as load balance.
Currently, we're not succeeding to handle more than 1000 req/sec and 18K active connections.
When we get to the above numbers, Nginx starts to hang, and returns timeout codes.
The only way to get a response is to reduce the number of connection dramatically.
I must note that my servers can and does handle this amount of traffic on a daily basis and we currently use a simple round rubin DNS balancing.
We are using a dedicated server with the following HW:
* INTEL XEON E5620 CPU
* 16GB RAM
* 2T SATA HDD
* 1Gb/s connection
* OS: CentOS 5.8
We need to load balance 7 back servers running Tomcat6 and handling more than 2000 req/sec on peek times, handling HTTP and HTTPS requests.
While running Nginx's cpu consumption is around 15% and used RAM is about 100MB.
My questions are:
1. Has any one tried to load balance this kind of traffic using nginx?
2. Do you think nginx can handle such traffic?
3. Do you have any idea what can cause the hanging?
4. Am I missing something on my configurations?
Below are my configuration files:
nginx.conf:
-----------
```sh
user nginx;
worker_processes 10;
worker_rlimit_nofile 200000;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 10000;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log /var/log/nginx/access.log main;
access_log off;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
reset_timedout_connection on;
gzip on;
gzip_comp_level 1;
include /etc/nginx/conf.d/*.conf;
}
```
servers.conf:
-------------
```sh
#Set the upstream (servers to load balance)
#HTTP stream
upstream adsbar {
least_conn;
server xx.xx.xx.34 max_fails=2 fail_timeout=15s;
server xx.xx.xx.36 max_fails=2 fail_timeout=15s;
server xx.xx.xx.37 max_fails=2 fail_timeout=15s;
server xx.xx.xx.39 max_fails=2 fail_timeout=15s;
server xx.xx.xx.40 max_fails=2 fail_timeout=15s;
server xx.xx.xx.42 max_fails=2 fail_timeout=15s;
server xx.xx.xx.43 max_fails=2 fail_timeout=15s;
}
#HTTPS stream
upstream adsbar-ssl {
least_conn;
server xx.xx.xx.34:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.36:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.37:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.39:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.40:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.42:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.43:443 max_fails=2 fail_timeout=15s;
}
#HTTP
server {
listen xxx.xxx.xxx.xxx:8080;
server_name www.mycompany.com;
location / {
proxy_set_header Host $host;
# So the original HTTP Host header is preserved
proxy_set_header X-Real-IP $remote_addr;
# The IP address of the client (which might be a proxy itself)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://adsbar;
}
}
#HTTPS
server {
listen xxx.xxx.xxx.xxx:8443;
server_name www.mycompany.com;
ssl on;
ssl_certificate /etc/pki/tls/certs/mycompany.crt;
# Path to an SSL certificate;
ssl_certificate_key /etc/pki/tls/private/mycompany.key;
# Path to the key for the SSL certificate;
location / {
proxy_set_header Host $host;
# So the original HTTP Host header is preserved
proxy_set_header X-Real-IP $remote_addr;
# The IP address of the client (which might be a proxy itself)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://adsbar-ssl;
}
}
server {
listen xxx.xxx.xxx.xxx:61709;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
```
sysctl.conf:
------------
```sh
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values,
0 is disabled, 1 is enabled. See sysctl(8) and
# sysctl.conf(5) for more details.
# Controls IP packet forwarding
net.ipv4.ip_forward = 0
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 1
# Controls whether core dumps will append the PID to the core filename
# Useful for debugging multi-threaded applications
kernel.core_uses_pid = 1
# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1
# Controls the maximum size of a message, in bytes
kernel.msgmnb = 65536
# Controls the default maxmimum size of a mesage queue
kernel.msgmax = 65536
# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736
# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
fs.file-max = 120000
net.ipv4.ip_conntrack_max = 131072
net.ipv4.tcp_max_syn_backlog = 8196
net.ipv4.tcp_fin_timeout = 25
net.ipv4.tcp_keepalive_time = 3600
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_rmem = 4096 25165824 25165824
net.core.rmem_max = 25165824
net.core.rmem_default = 25165824
net.ipv4.tcp_wmem = 4096 65536 25165824
net.core.wmem_max = 25165824
net.core.wmem_default = 65536
net.core.optmem_max = 25165824
net.core.netdev_max_backlog = 2500
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
```
Any help, guidance, ideas will be highly appreciated. | 2012/09/02 | [
"https://Stackoverflow.com/questions/12234050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1520931/"
] | Here are some good references:
<http://dak1n1.com/blog/12-nginx-performance-tuning>
Server fault:
<https://serverfault.com/questions/221292/tips-for-maximizing-nginx-requests-sec>
A very well documented config from the dak1n1 link:
```
# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesn't benefit from more than one worker per CPU.)
worker_processes 24;
# Number of file descriptors used for Nginx. This is set in the OS with 'ulimit -n 200000'
# or using /etc/security/limits.conf
worker_rlimit_nofile 200000;
# only log critical errors
error_log /var/log/nginx/error.log crit
# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
# "Max clients" is also limited by the number of socket connections available on the system (~64k)
worker_connections 4000;
# essential for linux, optmized to serve many clients with each thread
use epoll;
# Accept as many connections as possible, after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
multi_accept on;
# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Buffer log writes to speed up IO, or disable them altogether
#access_log /var/log/nginx/access.log main buffer=16k;
access_log off;
# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring data to and from the user space.
sendfile on;
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers before calling sendfile,
# or for throughput optimization.
tcp_nopush on;
# don't buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time.
tcp_nodelay on;
# Timeout for keep-alive connections. Server will close connections after this time.
keepalive_timeout 30;
# Number of requests a client can make over the keep-alive connection. This is set high for testing.
keepalive_requests 100000;
# allow the server to close the connection after a client stops responding. Frees up socket-associated memory.
reset_timedout_connection on;
# send the client a "request timed out" if the body is not loaded by this time. Default 60.
client_body_timeout 10;
# If the client stops reading data, free up the stale client connection after this much time. Default 60.
send_timeout 2;
# Compression. Reduces the amount of data that needs to be transferred over the network
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
```
Also more info on linux system tuning for sysctl.conf:
```
# Increase system IP port limits to allow for more connections
net.ipv4.ip_local_port_range = 2000 65000
net.ipv4.tcp_window_scaling = 1
# number of packets to keep in backlog before the kernel starts dropping them
net.ipv4.tcp_max_syn_backlog = 3240000
# increase socket listen backlog
net.core.somaxconn = 3240000
net.ipv4.tcp_max_tw_buckets = 1440000
# Increase TCP buffer sizes
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = cubic
``` | nginx should definately be able to handle more then 1000 req/s (I get about 2800 req/s in nginx when playing around on my cheap laptop with jmeter using one and a halve of the 2 cores)
You're using epoll which is the optimal option on current linux kernel as I understand it.
You've turned acces\_log off, so you'r disc IO shouldn't be a bottleneck either (note: you could also set the access\_log to buffered mode with a large buffer where it only writes after each x kb, which avoids the disk io being constantly hammered, but keeps the logs for analysis)
My understanding is that in order to maximize nginx performance you normally set the number of worker\_processes equal to the number of core/cpu's, and then up the number of worker\_connections to allow more concurrent connections (along with the number of open files os limit). Yet in the data you posted above you have a quadcore cpu with 10 worker processes with 10k connections allowed each. Consequently on the nginx side I'd try something like:
```
worker_processes 4;
worker_rlimit_nofile 999999;
events {
worker_connections 32768;
use epoll;
multi_accept on;
}
```
On the kernel side I'd tune tcp read and write buffers differently, you want a small minimum, small default and large max.
You've upped the ephemeral port range already.
I'd up the number open files limit more, as you'll have lots of open sockets.
Which gives the following lines to add/change in your /etc/sysctl.conf
```
net.ipv4.tcp_rmem = 4096 4096 25165824
net.ipv4.tcp_wmem = 4096 4096 25165824
fs.file-max=999999
```
Hope that helps. |
12,234,050 | For the last 3 weeks we have been testing Nginx as load balance.
Currently, we're not succeeding to handle more than 1000 req/sec and 18K active connections.
When we get to the above numbers, Nginx starts to hang, and returns timeout codes.
The only way to get a response is to reduce the number of connection dramatically.
I must note that my servers can and does handle this amount of traffic on a daily basis and we currently use a simple round rubin DNS balancing.
We are using a dedicated server with the following HW:
* INTEL XEON E5620 CPU
* 16GB RAM
* 2T SATA HDD
* 1Gb/s connection
* OS: CentOS 5.8
We need to load balance 7 back servers running Tomcat6 and handling more than 2000 req/sec on peek times, handling HTTP and HTTPS requests.
While running Nginx's cpu consumption is around 15% and used RAM is about 100MB.
My questions are:
1. Has any one tried to load balance this kind of traffic using nginx?
2. Do you think nginx can handle such traffic?
3. Do you have any idea what can cause the hanging?
4. Am I missing something on my configurations?
Below are my configuration files:
nginx.conf:
-----------
```sh
user nginx;
worker_processes 10;
worker_rlimit_nofile 200000;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 10000;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
#access_log /var/log/nginx/access.log main;
access_log off;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
reset_timedout_connection on;
gzip on;
gzip_comp_level 1;
include /etc/nginx/conf.d/*.conf;
}
```
servers.conf:
-------------
```sh
#Set the upstream (servers to load balance)
#HTTP stream
upstream adsbar {
least_conn;
server xx.xx.xx.34 max_fails=2 fail_timeout=15s;
server xx.xx.xx.36 max_fails=2 fail_timeout=15s;
server xx.xx.xx.37 max_fails=2 fail_timeout=15s;
server xx.xx.xx.39 max_fails=2 fail_timeout=15s;
server xx.xx.xx.40 max_fails=2 fail_timeout=15s;
server xx.xx.xx.42 max_fails=2 fail_timeout=15s;
server xx.xx.xx.43 max_fails=2 fail_timeout=15s;
}
#HTTPS stream
upstream adsbar-ssl {
least_conn;
server xx.xx.xx.34:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.36:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.37:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.39:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.40:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.42:443 max_fails=2 fail_timeout=15s;
server xx.xx.xx.43:443 max_fails=2 fail_timeout=15s;
}
#HTTP
server {
listen xxx.xxx.xxx.xxx:8080;
server_name www.mycompany.com;
location / {
proxy_set_header Host $host;
# So the original HTTP Host header is preserved
proxy_set_header X-Real-IP $remote_addr;
# The IP address of the client (which might be a proxy itself)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://adsbar;
}
}
#HTTPS
server {
listen xxx.xxx.xxx.xxx:8443;
server_name www.mycompany.com;
ssl on;
ssl_certificate /etc/pki/tls/certs/mycompany.crt;
# Path to an SSL certificate;
ssl_certificate_key /etc/pki/tls/private/mycompany.key;
# Path to the key for the SSL certificate;
location / {
proxy_set_header Host $host;
# So the original HTTP Host header is preserved
proxy_set_header X-Real-IP $remote_addr;
# The IP address of the client (which might be a proxy itself)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass https://adsbar-ssl;
}
}
server {
listen xxx.xxx.xxx.xxx:61709;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}
```
sysctl.conf:
------------
```sh
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values,
0 is disabled, 1 is enabled. See sysctl(8) and
# sysctl.conf(5) for more details.
# Controls IP packet forwarding
net.ipv4.ip_forward = 0
# Controls source route verification
net.ipv4.conf.default.rp_filter = 1
# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 1
# Controls whether core dumps will append the PID to the core filename
# Useful for debugging multi-threaded applications
kernel.core_uses_pid = 1
# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1
# Controls the maximum size of a message, in bytes
kernel.msgmnb = 65536
# Controls the default maxmimum size of a mesage queue
kernel.msgmax = 65536
# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736
# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
fs.file-max = 120000
net.ipv4.ip_conntrack_max = 131072
net.ipv4.tcp_max_syn_backlog = 8196
net.ipv4.tcp_fin_timeout = 25
net.ipv4.tcp_keepalive_time = 3600
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_rmem = 4096 25165824 25165824
net.core.rmem_max = 25165824
net.core.rmem_default = 25165824
net.ipv4.tcp_wmem = 4096 65536 25165824
net.core.wmem_max = 25165824
net.core.wmem_default = 65536
net.core.optmem_max = 25165824
net.core.netdev_max_backlog = 2500
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
```
Any help, guidance, ideas will be highly appreciated. | 2012/09/02 | [
"https://Stackoverflow.com/questions/12234050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1520931/"
] | Here are some good references:
<http://dak1n1.com/blog/12-nginx-performance-tuning>
Server fault:
<https://serverfault.com/questions/221292/tips-for-maximizing-nginx-requests-sec>
A very well documented config from the dak1n1 link:
```
# This number should be, at maximum, the number of CPU cores on your system.
# (since nginx doesn't benefit from more than one worker per CPU.)
worker_processes 24;
# Number of file descriptors used for Nginx. This is set in the OS with 'ulimit -n 200000'
# or using /etc/security/limits.conf
worker_rlimit_nofile 200000;
# only log critical errors
error_log /var/log/nginx/error.log crit
# Determines how many clients will be served by each worker process.
# (Max clients = worker_connections * worker_processes)
# "Max clients" is also limited by the number of socket connections available on the system (~64k)
worker_connections 4000;
# essential for linux, optmized to serve many clients with each thread
use epoll;
# Accept as many connections as possible, after nginx gets notification about a new connection.
# May flood worker_connections, if that option is set too low.
multi_accept on;
# Caches information about open FDs, freqently accessed files.
# Changing this setting, in my environment, brought performance up from 560k req/sec, to 904k req/sec.
# I recommend using some varient of these options, though not the specific values listed below.
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# Buffer log writes to speed up IO, or disable them altogether
#access_log /var/log/nginx/access.log main buffer=16k;
access_log off;
# Sendfile copies data between one FD and other from within the kernel.
# More efficient than read() + write(), since the requires transferring data to and from the user space.
sendfile on;
# Tcp_nopush causes nginx to attempt to send its HTTP response head in one packet,
# instead of using partial frames. This is useful for prepending headers before calling sendfile,
# or for throughput optimization.
tcp_nopush on;
# don't buffer data-sends (disable Nagle algorithm). Good for sending frequent small bursts of data in real time.
tcp_nodelay on;
# Timeout for keep-alive connections. Server will close connections after this time.
keepalive_timeout 30;
# Number of requests a client can make over the keep-alive connection. This is set high for testing.
keepalive_requests 100000;
# allow the server to close the connection after a client stops responding. Frees up socket-associated memory.
reset_timedout_connection on;
# send the client a "request timed out" if the body is not loaded by this time. Default 60.
client_body_timeout 10;
# If the client stops reading data, free up the stale client connection after this much time. Default 60.
send_timeout 2;
# Compression. Reduces the amount of data that needs to be transferred over the network
gzip on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";
```
Also more info on linux system tuning for sysctl.conf:
```
# Increase system IP port limits to allow for more connections
net.ipv4.ip_local_port_range = 2000 65000
net.ipv4.tcp_window_scaling = 1
# number of packets to keep in backlog before the kernel starts dropping them
net.ipv4.tcp_max_syn_backlog = 3240000
# increase socket listen backlog
net.core.somaxconn = 3240000
net.ipv4.tcp_max_tw_buckets = 1440000
# Increase TCP buffer sizes
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_congestion_control = cubic
``` | I found that using the least connected algorithm was problematic. I switched to
```
hash $remote_addr consistent;
```
and found the service much quicker. |
10,438,034 | So, I'm writing a menu and I want it to stay a certain color based upon it being on that page.
I've added "class = 'active'" onto the page, and I've tried adding it to CSS, but it's not working. Any ideas?
PHP code:
```
<?php
$currentPage = basename($_SERVER['REQUEST_URI']);
print "<div id = 'submenu-container'>";
print "<div id = 'submenu'>";
print "<ul class = 'about'>";
print " <li><a href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>";
print " <li><a href='about.php#about_team.php'if($currentPage=='about.php#about_team.php') echo 'class='active''>Team</a></li>";
print " <li><a href='about.php#about_services.php' if($currentPage=='about.php#about_services.php') echo 'class='active'>Services</a></li>";
print " </ul>";
print "</div>";
print"</div>";
?>
```
CSS:
```
#submenu ul li a .active {
background:#FFF;
}
``` | 2012/05/03 | [
"https://Stackoverflow.com/questions/10438034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340238/"
] | I think instead of
```
$memberDisplayList = '<a href= (...etc)
```
you meant to type
```
$memberDisplayList .= '<a href= (...etc)
```
which would append the new links to your string.
Also you don't seem to be echoing your `$user_pic` and `$memberDisplayList` strings anywhere. | Where are you actually constructing the HTML? You're setting a bunch of variables in the code you presented, and that looks okay for what it is. So it's probably in the presentation logic. If that's in the loop, you're in good shape. But if it's outside of the loop, then I can't imagine where you'd ever display anything but the last row. |
10,438,034 | So, I'm writing a menu and I want it to stay a certain color based upon it being on that page.
I've added "class = 'active'" onto the page, and I've tried adding it to CSS, but it's not working. Any ideas?
PHP code:
```
<?php
$currentPage = basename($_SERVER['REQUEST_URI']);
print "<div id = 'submenu-container'>";
print "<div id = 'submenu'>";
print "<ul class = 'about'>";
print " <li><a href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>";
print " <li><a href='about.php#about_team.php'if($currentPage=='about.php#about_team.php') echo 'class='active''>Team</a></li>";
print " <li><a href='about.php#about_services.php' if($currentPage=='about.php#about_services.php') echo 'class='active'>Services</a></li>";
print " </ul>";
print "</div>";
print"</div>";
?>
```
CSS:
```
#submenu ul li a .active {
background:#FFF;
}
``` | 2012/05/03 | [
"https://Stackoverflow.com/questions/10438034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340238/"
] | I think instead of
```
$memberDisplayList = '<a href= (...etc)
```
you meant to type
```
$memberDisplayList .= '<a href= (...etc)
```
which would append the new links to your string.
Also you don't seem to be echoing your `$user_pic` and `$memberDisplayList` strings anywhere. | Its because your overwriting the variables on each iteration, you need to hold the data within an array then do another foreach loop where ever you output:
```
<?php
while($row = mysql_fetch_array($sql)){
/////// Mechanism to Display Pic. See if they have uploaded a pic or not //////////////////////////
$check_pic = "../../members/{$row['id']}/image01.jpg";
$default_pic = "../../members/0/image01.jpg";
if (file_exists($check_pic)) {
$user_pic = "<img src=\"$check_pic?$cacheBuster\" width=\"80px\" />";
} else {
$user_pic = "<img src=\"$default_pic\" width=\"80px\" />";
}
$user[] = array('id'=>$row['id'],
'firstname'=>$row["firstname"],
'lasname'=>$row["lastname"],
'user_pic'=>$user_pic,
'display_list'=>'<a href="http://www.pathtosite.com/friends_page.php?id='. $row['id'].'">' . $row["firstname"] .' '. $row["lastname"] .'</a><br />');
}
?>
``` |
10,438,034 | So, I'm writing a menu and I want it to stay a certain color based upon it being on that page.
I've added "class = 'active'" onto the page, and I've tried adding it to CSS, but it's not working. Any ideas?
PHP code:
```
<?php
$currentPage = basename($_SERVER['REQUEST_URI']);
print "<div id = 'submenu-container'>";
print "<div id = 'submenu'>";
print "<ul class = 'about'>";
print " <li><a href='about.php#about_intro.php'if($currentPage=='about.php#about_intro.php' || $currentPage=='about.php') echo 'class='active''>About</a></li>";
print " <li><a href='about.php#about_team.php'if($currentPage=='about.php#about_team.php') echo 'class='active''>Team</a></li>";
print " <li><a href='about.php#about_services.php' if($currentPage=='about.php#about_services.php') echo 'class='active'>Services</a></li>";
print " </ul>";
print "</div>";
print"</div>";
?>
```
CSS:
```
#submenu ul li a .active {
background:#FFF;
}
``` | 2012/05/03 | [
"https://Stackoverflow.com/questions/10438034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1340238/"
] | Its because your overwriting the variables on each iteration, you need to hold the data within an array then do another foreach loop where ever you output:
```
<?php
while($row = mysql_fetch_array($sql)){
/////// Mechanism to Display Pic. See if they have uploaded a pic or not //////////////////////////
$check_pic = "../../members/{$row['id']}/image01.jpg";
$default_pic = "../../members/0/image01.jpg";
if (file_exists($check_pic)) {
$user_pic = "<img src=\"$check_pic?$cacheBuster\" width=\"80px\" />";
} else {
$user_pic = "<img src=\"$default_pic\" width=\"80px\" />";
}
$user[] = array('id'=>$row['id'],
'firstname'=>$row["firstname"],
'lasname'=>$row["lastname"],
'user_pic'=>$user_pic,
'display_list'=>'<a href="http://www.pathtosite.com/friends_page.php?id='. $row['id'].'">' . $row["firstname"] .' '. $row["lastname"] .'</a><br />');
}
?>
``` | Where are you actually constructing the HTML? You're setting a bunch of variables in the code you presented, and that looks okay for what it is. So it's probably in the presentation logic. If that's in the loop, you're in good shape. But if it's outside of the loop, then I can't imagine where you'd ever display anything but the last row. |
13,740,912 | i have simple chrome extension that opens JQuery dialog box on each tab i open ,
the problem is when web page has iframe in it , the dialog box opens as many iframes are in the page .
i want to avoid this , all i need it open only and only 1 instance of the Dialog box for each page .
how can i avoid the iframes in the page ?
this is my content script :
```
var layerNode= document.createElement('div');
layerNode.setAttribute('id','dialog');
layerNode.setAttribute('title','Basic dialog');
var pNode= document.createElement('p');
console.log("msg var: "+massage);
pNode.innerHTML = massage;
layerNode.appendChild(pNode);
document.body.appendChild(layerNode);
jQuery("#dialog").dialog({
autoOpen: true,
draggable: true,
resizable: true,
height: 'auto',
width: 500,
zIndex:3999,
modal: false,
open: function(event, ui) {
$(event.target).parent().css('position','fixed');
$(event.target).parent().css('top', '5px');
$(event.target).parent().css('left', '10px');
}
});
``` | 2012/12/06 | [
"https://Stackoverflow.com/questions/13740912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/63898/"
] | How about wrapping all this with
```
if(window==window.top) {
// we're not in an iframe
// your code goes here
}
``` | As PAEz said in a comment, content scripts run in only the top frame by default. To make them run in subframes, you'd need to have '"all\_frames":true' in the [content\_scripts section of your manifest](https://developer.chrome.com/extensions/content_scripts.html). Similarly, if you're injecting script using [tabs.executeScript](https://developer.chrome.com/extensions/tabs.html#method-executeScript), you'd have to include '"allFrames":true' in the [InjectDetails](https://developer.chrome.com/extensions/tabs.html#type-InjectDetails) argument. |
101,759 | I was wondering if there are any ledgers to make such entries. I trade regularly and I would like to make a good record of it. | 2018/11/03 | [
"https://money.stackexchange.com/questions/101759",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/78593/"
] | Have a look at the Asset functionality of common accounting packages. It allows you to record prices and quantities of 'things' at purchase and sale. For shares, each stock code can be considered a separate 'thing' with buy and sell prices and quantities held in 'inventory'.
Each accounting package has its own processes and it takes awhile to become familiar with them. Here are some steps to get you started with gnucash, which is "[personal and small-business financial-accounting software, freely licensed under the GNU GPL](https://www.gnucash.org/)". (Disclaimer: I've starting using the software fairly recently, but I'm not otherwise knowingly affiliated with gnucash.)
1. Download and install [gnucash](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html).
2. Open gnucash and Select menu item File -> New File. If a dialog pops up asking you to save changes to the (default) file, select "Continue Without Saving". This brings up the New Account Hierarchy Setup dialog.
3. Fill in whatever you like until you reach "Choose accounts to create". Here, select "Investment Accounts" for some defaults to start you off. Carry on with the rest of the dialog.
4. You'll be asked to save the file. Pick a filename you like, such as "Shares 2018". Pick a location (directory or folder), but be aware that gnucash will save lots of temporary and backup files in the same location. The filename you pick will be the main file, and once you quit gnucash, the rest can usually be safely deleted. However, you might want to keep them as backups. Make sure you click "Save" often (see the menu ribbon below the "File" menu) to ensure that your main gnucash file is up to date.
5. After saving, you'll see the chart of accounts. Here's a [link](https://www.gnucash.org/docs/v3/C/gnucash-guide/chapter_invest.html) to the gnucash manual for the chapter called "Investments". Follow [the instructions](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html) to set up your investment portfolio, then use the manual for further instructions about buying and selling shares, recording dividends, and so on.
Have fun! | It's fairly easy to set up a spreadsheet that records trades and reconciles the gains and losses. It becomes more time consuming if you trade frequently and scale in and out of positions. And it gets onerous if your trading involves numerous wash sales.
AFAIK, US brokers provide Forms 1099-B and 8949 that break down of all of this. The few that I've dealt with provide a disclaimer to the effect of:
>
> This is important tax information and is being furnished to the Internal Revenue Service. This statement has been prepared in accordance with our records, is provided for information purposes only and is not intended to constitute tax advice which may be relied upon to avoid penalties under any federal, state, local or other tax statutes or regulations, and does not resolve any tax issues in your favor. Please review it carefully for errors. It may or may not represent the amount of gain or loss reportable by you for Federal and state income tax purposes. We recommend that you consult your tax adviser as to the correct reporting of these items on your income tax return.
>
>
>
So the gist of it is that your broker prepares these forms, reports the results to the IRS yet disavows accuracy. I can attest that if you're a frequent flier, broker reporting often contain errors. Some of the more well known software offering differing levels of expertise are Gainskeeper, Quicken, and Tradelog. |
101,759 | I was wondering if there are any ledgers to make such entries. I trade regularly and I would like to make a good record of it. | 2018/11/03 | [
"https://money.stackexchange.com/questions/101759",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/78593/"
] | Have a look at the Asset functionality of common accounting packages. It allows you to record prices and quantities of 'things' at purchase and sale. For shares, each stock code can be considered a separate 'thing' with buy and sell prices and quantities held in 'inventory'.
Each accounting package has its own processes and it takes awhile to become familiar with them. Here are some steps to get you started with gnucash, which is "[personal and small-business financial-accounting software, freely licensed under the GNU GPL](https://www.gnucash.org/)". (Disclaimer: I've starting using the software fairly recently, but I'm not otherwise knowingly affiliated with gnucash.)
1. Download and install [gnucash](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html).
2. Open gnucash and Select menu item File -> New File. If a dialog pops up asking you to save changes to the (default) file, select "Continue Without Saving". This brings up the New Account Hierarchy Setup dialog.
3. Fill in whatever you like until you reach "Choose accounts to create". Here, select "Investment Accounts" for some defaults to start you off. Carry on with the rest of the dialog.
4. You'll be asked to save the file. Pick a filename you like, such as "Shares 2018". Pick a location (directory or folder), but be aware that gnucash will save lots of temporary and backup files in the same location. The filename you pick will be the main file, and once you quit gnucash, the rest can usually be safely deleted. However, you might want to keep them as backups. Make sure you click "Save" often (see the menu ribbon below the "File" menu) to ensure that your main gnucash file is up to date.
5. After saving, you'll see the chart of accounts. Here's a [link](https://www.gnucash.org/docs/v3/C/gnucash-guide/chapter_invest.html) to the gnucash manual for the chapter called "Investments". Follow [the instructions](https://www.gnucash.org/docs/v3/C/gnucash-guide/invest-setup1.html) to set up your investment portfolio, then use the manual for further instructions about buying and selling shares, recording dividends, and so on.
Have fun! | Since softwares are being recommended I can post my comment as an answer:
The shareware software, KBH Investor Accounting, accounts both long and short positions and computes an overall mark-to-market accounting. The realized buy/sell transactions can be printed out in the form of an IRS 4797 but assumes that no long term positions are included to make that form. Most investors do not use a 4797 but might want the print-out.
For most investors, the overall mark-to-market accounting is not a tax accounting but a portfolio performance accounting.
Note that editing of an accounting is done by installing the back-up files. But the original files, with a time stamp, are also kept in the folder. |
31,173,307 | What are the differences between this:
```
if(a && b)
{
//code
}
```
and this:
```
if(a)
{
if(b)
{
//code
}
}
```
From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31173307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4714970/"
] | They get compiled to the same bytecode. No performance difference.
Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit.
---
I tried this out. Here's the code:
```
public class Test {
public static void main(String[] args) {
boolean a = 1>0;
boolean b = 0>1;
if (a && b)
System.out.println(5);
if (a)
if (b)
System.out.println(5);
}
}
```
This compiles to:
```
0: iconst_1
1: istore_1
2: iconst_0
3: istore_2
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
19: iload_1
20: ifeq 34
23: iload_2
24: ifeq 34
27: getstatic #2
30: iconst_5
31: invokevirtual #3
34: return
```
Note how this block repeats twice:
```
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
```
Same bytecode both times. | If there is nothing in between two `if` statements in your second example then definitely first one is more cleaner and more readable.
But if there is a piece of code that could fit in between the two if conditions then only way is second example. |
31,173,307 | What are the differences between this:
```
if(a && b)
{
//code
}
```
and this:
```
if(a)
{
if(b)
{
//code
}
}
```
From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31173307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4714970/"
] | It makes a difference if you have an **else** associated with each **if**.
```
if(a && b)
{
//do something if both a and b evaluate to true
} else {
//do something if either of a or b is false
}
```
and this:
```
if(a)
{
if(b)
{
//do something if both a and b are true
} else {
//do something if only a is true
}
} else {
if(b)
{
//do something if only b is true
} else {
//do something if both a and b are false
}
}
``` | If there is nothing in between two `if` statements in your second example then definitely first one is more cleaner and more readable.
But if there is a piece of code that could fit in between the two if conditions then only way is second example. |
31,173,307 | What are the differences between this:
```
if(a && b)
{
//code
}
```
and this:
```
if(a)
{
if(b)
{
//code
}
}
```
From what I know `b` will only get evaluated in the first code block if `a` is true, and the second code block would be the same thing.
Are there any benefits of using one over the other? Code execution time? memory? etc. | 2015/07/01 | [
"https://Stackoverflow.com/questions/31173307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4714970/"
] | They get compiled to the same bytecode. No performance difference.
Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit.
---
I tried this out. Here's the code:
```
public class Test {
public static void main(String[] args) {
boolean a = 1>0;
boolean b = 0>1;
if (a && b)
System.out.println(5);
if (a)
if (b)
System.out.println(5);
}
}
```
This compiles to:
```
0: iconst_1
1: istore_1
2: iconst_0
3: istore_2
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
19: iload_1
20: ifeq 34
23: iload_2
24: ifeq 34
27: getstatic #2
30: iconst_5
31: invokevirtual #3
34: return
```
Note how this block repeats twice:
```
4: iload_1
5: ifeq 19
8: iload_2
9: ifeq 19
12: getstatic #2
15: iconst_5
16: invokevirtual #3
```
Same bytecode both times. | there shouldn't be a difference, but in readability I would prefer the first one, because it is less verbose and less indented. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.