qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
10,572 | Consider a Robinson Crusoe economy. Let $c$ be consumption and let $l$ be leisure. Our utility function is defined as
$$U(c,l)$$
Geometrically, I think we can say his indifference curve should be concave up, so therefore $\frac{dc}{dl} >0$ and $\frac{d^2c}{dl^2} >0$.
Typically we have a production function $$y = f(\ell)$$
where $\ell$ is labor, $f'>0$,$f''<0$ and $c \leq y$. Also, I think $l = 1 - \ell$.
Also, note
$$MRS = MPL$$
-------------
**WHY INCREASING PRODUCTIVITY MIGHT INCREASE LABOR**
Suppose $f(\ell)=A \sqrt{\ell}$. Then
$$MPL = f'(\ell) = \frac{A}{2\sqrt{\ell}}$$
So then if $A \rightarrow \lambda A$, then for fixed $MPL$ we must have
$$MPL = \frac{\lambda A}{2\sqrt{\lambda^2 \ell}}$$
In other words, if $A$ increases, Crusoe works harder if we assume $MPL$ is fixed.
---
**WHY INCREASING PRODUCTIVITY MIGHT DECREASE LABOR**
But increasing $A$ would also mean essentially that Crusoe gets more production per unit of labor consumed. This gives him more $c$ available. This will mean his $MU\_c$ goes down.
Recall $$MRS = \frac {U\_l} {U\_c}$$ If we assume $MRS$ remains constant, then $MU\_l$ must go down to offset this change. This implies $l$ goes up and therefore, $\ell$ goes down.
So one could also argue changing $A$ results in $\ell$ going down.
---
**MY QUESTION**
What is the income effect and substitution effect in the case of changing $A$?
According to what my instructors have said (and I don't think they explain it well at all), the income effect is the latter change I described due to $A$ (i.e. decrease in $\ell$) whereas the substitution effect is due to the former change (increase in $\ell$).
But these don't match the income and substitution effects I learned about in my class on Marshallian and Hicksian demand functions. It seems very confused. Can someone define these explicitly or explain why my instructor has misused these two terms? | 2016/02/07 | [
"https://economics.stackexchange.com/questions/10572",
"https://economics.stackexchange.com",
"https://economics.stackexchange.com/users/2679/"
]
| The ratio of government debt to GDP is a useful indicator because, broadly, the larger a country's GDP, the larger is the tax revenue the government could *potentially* raise to service the debt while maintaining other government expenditure at an acceptable level. Thus a very high debt / GDP ratio would raise doubts about the government's ability to service the debt.
One reason why a larger GDP implies a larger potential tax revenue is that most of the transactions making up [GDP from an income perspective](https://en.wikipedia.org/wiki/Gross_domestic_product#Income_approach), eg wages and salaries, company profits, could be taxed. However, taxes could also be levied on items that are not part of GDP, eg capital values of property. The more fundamental point, therefore, is that a larger GDP, again from an income perspective, tends to imply a larger aggregate ability to pay, out of that income, such taxes as may be levied by the government.
The government's ability to tax is also influenced by political factors and by the effectiveness of its tax collection, so the debt / GDP ratio can only be a crude indicator of ability to service debt. | I believe your understanding of budget and GDP is a bit off. Comparing debt with GDP is more adequate, as GDP measures the country's production level, while budget is just an estimate. At least where I live, what is budgeted for the upcoming year is not always accomplished in the end, as there are gaps and things that missed the planning phase.
In that case, it makes a bit more sense to compare what the country owes (debt) with what it is **actually** producing, rather than with what it estimates to produce, don't you think?
I'm not exactly sure, but I believe GDP aggregates indirect revenues, while revenue size does not - hence *looking more serious*. |
63,568,813 | for example
```
public class Main
{
public static void main(String[] args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++)
{
arr[i] = Integer.parseInt(args[i]);
}
printarr pp = new printarr();
pp.pnt(arr);
}
}
public class printarr{
public int pnt(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println(+arr[i]);
}
return arr;
}
}
```
i dont know but something is wrong please help me out
when ever i compile it it gives
printarr.java:6: error: incompatible types: int[] cannot be converted to int
return arr;
^
1 error | 2020/08/24 | [
"https://Stackoverflow.com/questions/63568813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14160027/"
]
| You may check the string at [this link](https://r12a.github.io/uniview/?charlist=%F0%9D%95%BE%F0%9D%96%8D%F0%9D%96%8E%F0%9D%96%97%F0%9D%96%94%F0%9D%96%93#title) and you will see that the "" string consists of characters belonging to `\p{L}` category. Your regex starts with `[^А-я\w\d`, which means it matches any chars but Russian chars (except `ё` (that you define a bit later) and `Ё`), any Unicode letters (**any** because in Python 3, `\w` - by default - matches any Unicode alphanumeric chars and connector punctuation.
It appears you only want to remove Russian and English letters, so use the corresponding ranges:
```
r"[^А-ЯЁа-яёA-Za-z0-9\n ,.?!/@#:()]+"
```
It matches one or more chas other than
* `А-ЯЁа-яё` - Russian letters
* `A-Za-z` - ASCII letters
* `0-9` - ASCII digits
* `\n ,.?!/@#:()` - newline, space, comma, dot, question and exclamation marks, slash, ampersand, hash, colon and round parentheses. | You can make it so it only matches the type you need. Instead of the string type that you don't need.
This should work `[А-я\w\d\"+\"\n\"+\" ,.?!ё/@#:()]` |
401,950 | *I want to say up front, that this question involves minor modification (transient surge/current suppression) to the power supply side of a power tool. Usually I'd be the last to do anything like this (and never have). But in this case, my basic knowledge of electronics suggests that a trivial component inline with or across the mains supply, would have a very beneficial effect - no opening or changing of the tool itself is intended or would be acceptable. I think "anti surge" plugs also exist that do what I'm after, to underline that it's a safe intention. With that, on to my question.....*
I have a power tool. Actually it's [one of these](https://www.amazon.co.uk/Evolution-Electric-Concrete-2400W-230V/dp/B003OJAOPA), a 2400W 230V rotary concrete saw. I've had one of this model for years, and it's robust and reliable, with one design flaw. If the blade happens to stick, it's handled safely, from a mechanical/safety perspective. But there's clearly some kind of suppression missing or skimped in the design, because it typically also blows the 13A amp mains fuse in the plug.
Since this doesn't happen that often and replacing a fuse is trivial, I've satisfied myself with just keeping a bag of 10 fuses to hand, and replacing if it happens. It's cheaper than any alternative, which is typically an extra £200 for more rigorously built brands such as Makita, Husqvarna and the like - and 230V saws of this kind aren't easily found, so it's a limited market.
But today it clearly stuck bigger than usual because the motor itself has, after 4 years, shorted out. Swap fuse, press start button, 1/2 a second spin and fuse consistently blows. Admittedly it was under heavy use, but still.
As the performance was good, and I never felt endangered by the occasional lapse in surge suppression (it stalled and blew the fuse but never in all that time "kicked" or showed other untoward behaviour), I've replaced it with another of the same. But I'm wondering if there is some kind of component I can put inline or across the supply, which would safely handle whatever happens when the engine seizes, so it doesn't blow fuses and perhaps even avoids burn out in future.
Is this possible to do safely? If so, what would one use? | 2018/10/18 | [
"https://electronics.stackexchange.com/questions/401950",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/149027/"
]
| What you are looking for is called an "electronic circuit breaker". Since it sounds like you're not qualified to design such a thing from scratch, it would probably be best to look for commercial products under that designation.
The key issue for you is that you need something that will allow the normal start-up surge of the saw, but trip on anything that exceeds that, such as getting the blade stuck. There might be a standard magenetic/thermal breaker that would work for you, but an all-electronic one would be adjustable to match the exact characteristics of your tool.
Even if the rate of "nuisance" trips remains about the same, it at least eliminates the need to continually buy one-time fuses. | You can choose a 10 or 12A breaker and mount in a electric box with a socket and plug.
<https://www.amazon.co.uk/Wylex-NHXB10-Single-Circuit-Breaker/dp/B075NPNYYV/ref=zg_bs_1938267031_9?_encoding=UTF8&psc=1&refRID=EA1QB085ATFXXF57A6RN> |
401,950 | *I want to say up front, that this question involves minor modification (transient surge/current suppression) to the power supply side of a power tool. Usually I'd be the last to do anything like this (and never have). But in this case, my basic knowledge of electronics suggests that a trivial component inline with or across the mains supply, would have a very beneficial effect - no opening or changing of the tool itself is intended or would be acceptable. I think "anti surge" plugs also exist that do what I'm after, to underline that it's a safe intention. With that, on to my question.....*
I have a power tool. Actually it's [one of these](https://www.amazon.co.uk/Evolution-Electric-Concrete-2400W-230V/dp/B003OJAOPA), a 2400W 230V rotary concrete saw. I've had one of this model for years, and it's robust and reliable, with one design flaw. If the blade happens to stick, it's handled safely, from a mechanical/safety perspective. But there's clearly some kind of suppression missing or skimped in the design, because it typically also blows the 13A amp mains fuse in the plug.
Since this doesn't happen that often and replacing a fuse is trivial, I've satisfied myself with just keeping a bag of 10 fuses to hand, and replacing if it happens. It's cheaper than any alternative, which is typically an extra £200 for more rigorously built brands such as Makita, Husqvarna and the like - and 230V saws of this kind aren't easily found, so it's a limited market.
But today it clearly stuck bigger than usual because the motor itself has, after 4 years, shorted out. Swap fuse, press start button, 1/2 a second spin and fuse consistently blows. Admittedly it was under heavy use, but still.
As the performance was good, and I never felt endangered by the occasional lapse in surge suppression (it stalled and blew the fuse but never in all that time "kicked" or showed other untoward behaviour), I've replaced it with another of the same. But I'm wondering if there is some kind of component I can put inline or across the supply, which would safely handle whatever happens when the engine seizes, so it doesn't blow fuses and perhaps even avoids burn out in future.
Is this possible to do safely? If so, what would one use? | 2018/10/18 | [
"https://electronics.stackexchange.com/questions/401950",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/149027/"
]
| The term "surge suppressor" is used to describe something that protects against a surge in VOLTAGE, i.e. a problem with the line voltage coming from your utility service. What you are talking about would be something that operates on CURRENT. The technology is called is a "Current Sensing Relay" (CSR), also sometimes called an "Electronic Shear Pin" because it functions similar to a mechanical shear pin, which was a sacrificial device put into a machine that was made to break first if something jammed, but was easy and cheap to replace. CSRs are used all the time on industrial machinery for this very reason. But a CSR will turn it OFF, not limit the current. Limiting the current while also allowing it to stay running, is possible but not practical because the only way to limit the current that a motor wants to draw is to reduce the voltage getting to it. In the case of a power tool like yours that uses what's called a "Universal Motor", that then also severely reduces the speed and in doing so, may create a bad situation with regard to your blade, which could be ruined in a matter of seconds at too slow of a speed.
I looked around a little and couldn't find a CSR that would be simple to just plug your tool into, but there are plenty out there that you could mount into a box and run wires to and from it. Most likely the reason they don't exist is that it is REALLY cheap and simple to just build that into the tool! Most cutting tools that I use either have it in the electrics, or use a mechanical equivalent. Often on circular blades like that it is a specially designed washer that will "slip" if the blade jams. Perhaps your cutter came with one and you didn't realize why it was there? This isn't exactly what yours probably looks like, but it shows the concept. The "blade washers" here are designed to only grip the blade tight enough to do the desired work, but if the blade jams, they let the shaft keep turning until you can react to remove your finger from the trigger. Maybe you didn't understand the importance and discarded them or lost them? maybe you are over tightening your lock nut? It shouldn't be blowing the fuses!
[](https://i.stack.imgur.com/0Y8Zk.jpg) | You can choose a 10 or 12A breaker and mount in a electric box with a socket and plug.
<https://www.amazon.co.uk/Wylex-NHXB10-Single-Circuit-Breaker/dp/B075NPNYYV/ref=zg_bs_1938267031_9?_encoding=UTF8&psc=1&refRID=EA1QB085ATFXXF57A6RN> |
15,629,037 | This is probably a fairly obvious question, but I just can't figure it out.
I am trying to write a function that squares the even numbers in a list. When I try to run it, I am getting an error about my use of the even function. How can I fix this?
```
module SquareEvens where
squareEvens :: [Integer] -> [Integer]
squareEvens n = [ns * ns | ns <- n, even n]
``` | 2013/03/26 | [
"https://Stackoverflow.com/questions/15629037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2030543/"
]
| The code works fine if you change `even n` to `even ns`:
```
squareEvens n = [ns * ns | ns <- n, even ns]
```
But note that the convention is to use the plural to name the list and the singular to name an element from that list. So swap `n` and `ns` to follow idiomatic Haskell usage:
```
squareEvens ns = [n * n | n <- ns, even n]
``` | As you can see, it's easy to get variable names wrong. So why not do it without?
```
squareEvens = map (^2) . filter even
```
I think this is clearer than the comprehension. You can read it from right to left: Keep only the even numbers, then square them. |
5,446,644 | I have a listbox where I create a Itemtemplate with a DataTemplate. I want to be able to write events for the checkboxes and buttons in the datatemplate but they do not seem to be firing.
Here is my xaml and basically I just tried to display a messagebox.show("worked") in the event function.
```
<ListBox x:Name="ListBox_Items" Margin="0,91,0,8" Foreground="#FF4BE5DB">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="700">
<CheckBox IsChecked="{Binding needPurchase}" Click="NeedPurchase_Click" Name="CheckBox_NeedPurchase"/>
<CheckBox IsChecked="False" Name="InCart"/>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding storeLocation}"/>
</StackPanel>
<Button HorizontalAlignment="Right" Content="DELETE" Click="Button_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
``` | 2011/03/27 | [
"https://Stackoverflow.com/questions/5446644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678552/"
]
| Because the items are defined within a DataTemplate they are not hooked up to the code-behind for the parent class. If you want to handle events for templated items, then you should consider using commands instead. If you don't know what commands are (and therefore unlikely to know what MVVM is), then you should check out an explanation [like this by Jeremy Likness](http://www.wintellect.com/CS/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx). | For starters you need to remove the name from all the controls in the template. If you have 10 items in the list you will have 10 sets of controls with the same name which won't work. |
5,446,644 | I have a listbox where I create a Itemtemplate with a DataTemplate. I want to be able to write events for the checkboxes and buttons in the datatemplate but they do not seem to be firing.
Here is my xaml and basically I just tried to display a messagebox.show("worked") in the event function.
```
<ListBox x:Name="ListBox_Items" Margin="0,91,0,8" Foreground="#FF4BE5DB">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="700">
<CheckBox IsChecked="{Binding needPurchase}" Click="NeedPurchase_Click" Name="CheckBox_NeedPurchase"/>
<CheckBox IsChecked="False" Name="InCart"/>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding storeLocation}"/>
</StackPanel>
<Button HorizontalAlignment="Right" Content="DELETE" Click="Button_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
``` | 2011/03/27 | [
"https://Stackoverflow.com/questions/5446644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678552/"
]
| I agree that using commands is the best approach.
However if you still want to assess controls placed inside the ItemTemplate/DataTemplate (and subscribe to some events), then you can do this by using the VisualTreeHelper. | For starters you need to remove the name from all the controls in the template. If you have 10 items in the list you will have 10 sets of controls with the same name which won't work. |
5,446,644 | I have a listbox where I create a Itemtemplate with a DataTemplate. I want to be able to write events for the checkboxes and buttons in the datatemplate but they do not seem to be firing.
Here is my xaml and basically I just tried to display a messagebox.show("worked") in the event function.
```
<ListBox x:Name="ListBox_Items" Margin="0,91,0,8" Foreground="#FF4BE5DB">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="700">
<CheckBox IsChecked="{Binding needPurchase}" Click="NeedPurchase_Click" Name="CheckBox_NeedPurchase"/>
<CheckBox IsChecked="False" Name="InCart"/>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding name}"/>
<TextBlock Text="{Binding storeLocation}"/>
</StackPanel>
<Button HorizontalAlignment="Right" Content="DELETE" Click="Button_Click" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
``` | 2011/03/27 | [
"https://Stackoverflow.com/questions/5446644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678552/"
]
| Because the items are defined within a DataTemplate they are not hooked up to the code-behind for the parent class. If you want to handle events for templated items, then you should consider using commands instead. If you don't know what commands are (and therefore unlikely to know what MVVM is), then you should check out an explanation [like this by Jeremy Likness](http://www.wintellect.com/CS/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx). | I agree that using commands is the best approach.
However if you still want to assess controls placed inside the ItemTemplate/DataTemplate (and subscribe to some events), then you can do this by using the VisualTreeHelper. |
35,410,277 | I suddently get a 502 Bad gateway error and I don't understand why this error appear. This error appear moreover only for 1 single page!!...
The exact error in my Nginx log is :
```
Upstream prematurely closed FastCGI stdout while reading response header from upstream [..] upstream: "fastcgi://unix:/var/run/php5-fpm.sock:"
```
I tried :
* service nginx restart : NOTHING CHANGE
* service php5-fpm restart : NOTHING CHANGE
* to reboot the server : NOTHING CHANGE
* even to restart the mysql service : NOTHING CHANGE
My /var/log/upstart/php5-fpm.log (only a lot of NOTICES) :
```
Terminating...
exiting, bye-bye!
fpm is running, pid 9887
ready to handle connections
systemd monitor interval set to 10000ms
```
that makes me crazy, any idea ? | 2016/02/15 | [
"https://Stackoverflow.com/questions/35410277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899560/"
]
| Strangely enough, this is what worked for me after chasing down a mysterious 502 Bad Gateway error:
* Change `error_reporting` setting in `php-fpm` ini like this:
`error_reporting = ~E_ALL`
* Then restart `php-fpm` and `nginx`
This worked for me after trying the suggested nginx settings above to no avail. I don't have a verified explanation for this, but it would appear that excessive error reporting can overload the php-fpm process. | I did the following to server nginx config:
```
client_body_timeout 1200;
client_header_timeout 600;
```
and added zend\_extension to php fpm php.ini:
```
zend_extension = xdebug.so
``` |
35,410,277 | I suddently get a 502 Bad gateway error and I don't understand why this error appear. This error appear moreover only for 1 single page!!...
The exact error in my Nginx log is :
```
Upstream prematurely closed FastCGI stdout while reading response header from upstream [..] upstream: "fastcgi://unix:/var/run/php5-fpm.sock:"
```
I tried :
* service nginx restart : NOTHING CHANGE
* service php5-fpm restart : NOTHING CHANGE
* to reboot the server : NOTHING CHANGE
* even to restart the mysql service : NOTHING CHANGE
My /var/log/upstart/php5-fpm.log (only a lot of NOTICES) :
```
Terminating...
exiting, bye-bye!
fpm is running, pid 9887
ready to handle connections
systemd monitor interval set to 10000ms
```
that makes me crazy, any idea ? | 2016/02/15 | [
"https://Stackoverflow.com/questions/35410277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899560/"
]
| Strangely enough, this is what worked for me after chasing down a mysterious 502 Bad Gateway error:
* Change `error_reporting` setting in `php-fpm` ini like this:
`error_reporting = ~E_ALL`
* Then restart `php-fpm` and `nginx`
This worked for me after trying the suggested nginx settings above to no avail. I don't have a verified explanation for this, but it would appear that excessive error reporting can overload the php-fpm process. | Try to `include <fcgi_stdio.h>` in your source file.
This error happens to me just now,then i add `include <fcgi_stdio.h>`in my `c` file,here is my code.
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcgi_config.h>
#include <fcgi_stdio.h>
int main()
{
int count = 0;
while(FCGI_Accept() >= 0)
{
printf("content-type:text/html\r\n");
printf("\r\n");
printf("<title>Fast CGI Hello</title>");
printf("<h1>fast CGI hello</h1>");
printf("Request number %d running on host<i>%s</i>\n",++count,getenv("SERVER_NAME"));
}
return 0;
}
``` |
35,410,277 | I suddently get a 502 Bad gateway error and I don't understand why this error appear. This error appear moreover only for 1 single page!!...
The exact error in my Nginx log is :
```
Upstream prematurely closed FastCGI stdout while reading response header from upstream [..] upstream: "fastcgi://unix:/var/run/php5-fpm.sock:"
```
I tried :
* service nginx restart : NOTHING CHANGE
* service php5-fpm restart : NOTHING CHANGE
* to reboot the server : NOTHING CHANGE
* even to restart the mysql service : NOTHING CHANGE
My /var/log/upstart/php5-fpm.log (only a lot of NOTICES) :
```
Terminating...
exiting, bye-bye!
fpm is running, pid 9887
ready to handle connections
systemd monitor interval set to 10000ms
```
that makes me crazy, any idea ? | 2016/02/15 | [
"https://Stackoverflow.com/questions/35410277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899560/"
]
| Strangely enough, this is what worked for me after chasing down a mysterious 502 Bad Gateway error:
* Change `error_reporting` setting in `php-fpm` ini like this:
`error_reporting = ~E_ALL`
* Then restart `php-fpm` and `nginx`
This worked for me after trying the suggested nginx settings above to no avail. I don't have a verified explanation for this, but it would appear that excessive error reporting can overload the php-fpm process. | I had the error only for one type of requests that had 12 items in the body. May be it was related with a body size, but it worked when it was more (13 and more items) or some less (11 and less).
**upstream prematurely closed FastCGI stdout while reading response header from upstream**
```
2021/12/24 07:14:44 [error] 9#9: *49 upstream prematurely closed FastCGI stdout while reading response header from upstream, client: 172.21.0.1, server: , request: "PUT /v1/MY_PAGE/a976d2e5-afc0-4f6d-8d05-17af7dc73f46 HTTP/1.1", upstream: "fastcgi://172.21.0.3:9000", host: "localhost"
```
I used Docker containers with Nginx and PHP-FPM.
Nginx returned **502 Bad Gateway**.
[](https://i.stack.imgur.com/b3JmH.png)
PHP-FPM was used XDebug and it made the error.
When I turned on debugging the error left and when I turned off debugging the error returned.
[](https://i.stack.imgur.com/iZkxo.png)
Solution
--------
To solve the error I disabled XDebug. Also it works when I removed XDebug.
Options to solve the error (one of these):
* **Disable XDebug** (one of these):
+ Set the `XDEBUG_MODE='off'` environment variable.
+ Set `xdebug.mode=off` in `xdebug.ini` or another PHP config.
+ <https://xdebug.org/docs/all_settings#mode>
* **Remove XDebug** from your PHP server and restart PHP-FPM (one of these):
+ Remove through PECL (works with Docker): `pecl uninstall xdebug`.
+ Remove through Ubuntu APT: `sudo apt-get purge php-xdebug`.
Restart your PHP-FPM or your service/server. |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\frac{e^x+1}{e^x-1}=\frac{e^x}{e^x-1}+\frac{e^{-x}}{1-e^{-x}}.$$
Both terms are of the form $\frac{f'}f$ and you can integrate straight away, giving
$$\log|(e^x-1)(1-e^{-x})|.$$
---
Alternatively,
$$\frac{e^x+1}{e^x-1}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=2\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\to 2\log|e^{x/2}-e^{-x/2}|.$$
---
It is questionable whether this is truly "without substitution", because implicitly you are doing
$$\int\frac{f'}{f}dx=\int\frac{df}f.$$ | $$\int \frac{e^x}{e^x-1}dx = \int d(\log(e^x-1)) = \log|e^x-1|+C$$
$$\int\frac{e^x}{e^x-1}dx -\int \frac1{e^x-1}dx=\int 1dx = x + C$$
Thus $$\int \frac1{e^x-1}dx=\log|e^x-1|-x+C$$
and finally
$$ \int \frac{e^x+1}{e^x-1}dx = \int \frac{e^x}{e^x-1}dx + \int \frac1{e^x-1}dx= 2\log|e^x-1|-x+C $$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\frac{e^x+1}{e^x-1}=\frac{e^x}{e^x-1}+\frac{e^{-x}}{1-e^{-x}}.$$
Both terms are of the form $\frac{f'}f$ and you can integrate straight away, giving
$$\log|(e^x-1)(1-e^{-x})|.$$
---
Alternatively,
$$\frac{e^x+1}{e^x-1}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=2\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\to 2\log|e^{x/2}-e^{-x/2}|.$$
---
It is questionable whether this is truly "without substitution", because implicitly you are doing
$$\int\frac{f'}{f}dx=\int\frac{df}f.$$ | $$\int \frac{e^x+1}{e^x-1} dx = \int 1 + \frac 2 {e^x-1} dx = x +2\int \bigg( \frac {e^x}{e^x-1} -1 \bigg)dx$$
Now you apply your formula to evaluate last integral. You get:$$x + 2(\ln|e^x-1| - x) + c$$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\frac{e^x+1}{e^x-1}=\frac{e^x}{e^x-1}+\frac{e^{-x}}{1-e^{-x}}.$$
Both terms are of the form $\frac{f'}f$ and you can integrate straight away, giving
$$\log|(e^x-1)(1-e^{-x})|.$$
---
Alternatively,
$$\frac{e^x+1}{e^x-1}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=2\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\to 2\log|e^{x/2}-e^{-x/2}|.$$
---
It is questionable whether this is truly "without substitution", because implicitly you are doing
$$\int\frac{f'}{f}dx=\int\frac{df}f.$$ | Multiply the numerator and denominator by $e^{-x/2}$ to form
$$\frac{e^x+1}{e^x-1}\times\frac{e^{-x/2}}{e^{-x/2}}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=\frac{\cosh(\frac{x}{2})}{\sinh(\frac{x}{2})},$$
then
$$\int \frac{e^x+1}{e^x-1}\,dx=\int \frac{\cosh(\frac{x}{2})}{\sinh(\frac{x}{2})}\,dx=2\int\frac{d\left(\sinh\left(\frac{x}{2}\right)\right)}{{\sinh(\frac{x}{2})}}=2\ln\left|\sinh\left(\frac{x}{2}\right)\right|+C.$$
If $K$ is a constant, then all integrals of the form $\frac{f'}{f}$ evaluate to
$$K\int\frac{f'(x)}{f(x)}\,dx=K\ln|f(x)|+C.$$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\frac{e^x+1}{e^x-1}=\frac{e^x}{e^x-1}+\frac{e^{-x}}{1-e^{-x}}.$$
Both terms are of the form $\frac{f'}f$ and you can integrate straight away, giving
$$\log|(e^x-1)(1-e^{-x})|.$$
---
Alternatively,
$$\frac{e^x+1}{e^x-1}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=2\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\to 2\log|e^{x/2}-e^{-x/2}|.$$
---
It is questionable whether this is truly "without substitution", because implicitly you are doing
$$\int\frac{f'}{f}dx=\int\frac{df}f.$$ | Let's use your approach:
$I=\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx=2 \int\frac{\frac{e^{x/2}}{2}+\frac{e^{-x/2}}{2}}{e^{x/2}-e^{-x/2}}\mathrm dx =2 \int\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\mathrm dx =2\ln|e^{x/2}-e^{-x/2}|+c$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\int \frac{e^x+1}{e^x-1} dx = \int 1 + \frac 2 {e^x-1} dx = x +2\int \bigg( \frac {e^x}{e^x-1} -1 \bigg)dx$$
Now you apply your formula to evaluate last integral. You get:$$x + 2(\ln|e^x-1| - x) + c$$ | $$\int \frac{e^x}{e^x-1}dx = \int d(\log(e^x-1)) = \log|e^x-1|+C$$
$$\int\frac{e^x}{e^x-1}dx -\int \frac1{e^x-1}dx=\int 1dx = x + C$$
Thus $$\int \frac1{e^x-1}dx=\log|e^x-1|-x+C$$
and finally
$$ \int \frac{e^x+1}{e^x-1}dx = \int \frac{e^x}{e^x-1}dx + \int \frac1{e^x-1}dx= 2\log|e^x-1|-x+C $$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\int \frac{e^x+1}{e^x-1} dx = \int 1 + \frac 2 {e^x-1} dx = x +2\int \bigg( \frac {e^x}{e^x-1} -1 \bigg)dx$$
Now you apply your formula to evaluate last integral. You get:$$x + 2(\ln|e^x-1| - x) + c$$ | Multiply the numerator and denominator by $e^{-x/2}$ to form
$$\frac{e^x+1}{e^x-1}\times\frac{e^{-x/2}}{e^{-x/2}}=\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}=\frac{\cosh(\frac{x}{2})}{\sinh(\frac{x}{2})},$$
then
$$\int \frac{e^x+1}{e^x-1}\,dx=\int \frac{\cosh(\frac{x}{2})}{\sinh(\frac{x}{2})}\,dx=2\int\frac{d\left(\sinh\left(\frac{x}{2}\right)\right)}{{\sinh(\frac{x}{2})}}=2\ln\left|\sinh\left(\frac{x}{2}\right)\right|+C.$$
If $K$ is a constant, then all integrals of the form $\frac{f'}{f}$ evaluate to
$$K\int\frac{f'(x)}{f(x)}\,dx=K\ln|f(x)|+C.$$ |
3,812,564 | >
> $$\int\frac{e^x+1}{e^x-1}\,\mathrm dx$$
>
>
>
For this above problem, I tried adding and subtracting a $e^x$ to the numerator and proceeded. I did end up with an answer. I also tried to solve this question by taking $e^{x/2}$ common from both numerator and the denominator.
$$\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx$$
Once I've taken $e^{x/2}$ out from the denominator and the numerator, I thought of applying this property:
$$\int\frac{f'(x)}{f(x)}\, \mathrm dx = \ln |f(x)|+C$$
But I am unable to manipulate my obtained expression using this property. | 2020/09/03 | [
"https://math.stackexchange.com/questions/3812564",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/806447/"
]
| $$\int \frac{e^x+1}{e^x-1} dx = \int 1 + \frac 2 {e^x-1} dx = x +2\int \bigg( \frac {e^x}{e^x-1} -1 \bigg)dx$$
Now you apply your formula to evaluate last integral. You get:$$x + 2(\ln|e^x-1| - x) + c$$ | Let's use your approach:
$I=\int\frac{e^{x/2}+e^{-x/2}}{e^{x/2}-e^{-x/2}}\mathrm dx=2 \int\frac{\frac{e^{x/2}}{2}+\frac{e^{-x/2}}{2}}{e^{x/2}-e^{-x/2}}\mathrm dx =2 \int\frac{(e^{x/2}-e^{-x/2})'}{e^{x/2}-e^{-x/2}}\mathrm dx =2\ln|e^{x/2}-e^{-x/2}|+c$ |
1,570,989 | I'm trying to find the number of sequences of integers $0=a\_1\leq a\_2\leq\ldots\leq a\_n$ such that $a\_k<k$ for every $1\leq k\leq n$.
I know for $n=3$, the sequences are $ 000, 001, 002, 011,012$, so the number of sequences is $5$, but I don't know how to approach this further.
Any tips? | 2015/12/11 | [
"https://math.stackexchange.com/questions/1570989",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/297884/"
]
| The solution to your problem are the ultra-famous Catalan Numbers. Have a look at Wikipedia. | I don't know if there's an easy formula, but you can get the answer in terms of a recurrence which you can evaluate by hand for small $n$ or use a fast computer program for large $n$. Note that a valid sequence for $n$ gives a valid sequence for $n+1$ as long as $a\_{n+1} \geq a\_n$ and $a\_{n+1} < n+1$. So if you let $c\_{n,m}$ be the number of sequences of length $n$ that end in $m$, you get
$$c\_{n+1,m} = \sum\_{j=0}^m c\_{n,j}$$
and then your total count is $c\_n = \sum\_{m=0}^{n-1}c\_{n,m}$ |
700,209 | When i try to install the official MySQL Workbench, it shows dependency issue of the unavailabilty of libproj19. However the repos only has libproj22 when i tried to install from APT.
Can someone help me out?
```
System: Host: cosmic Kernel: 5.16.19-76051619-generic x86_64 bits: 64
Console: pty pts/1 Distro: Pop!_OS 22.04 LTS
```
```
karthik@cosmic:~/Downloads$ sudo dpkg -i mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb
Selecting previously unselected package mysql-workbench-community.
(Reading database ... 629535 files and directories currently installed.)
Preparing to unpack mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb ...
Unpacking mysql-workbench-community (8.0.28-1ubuntu21.10) ...
dpkg: dependency problems prevent configuration of mysql-workbench-community:
mysql-workbench-community depends on libproj19 (>= 7.2.0); however:
Package libproj19 is not installed.
dpkg: error processing package mysql-workbench-community (--install):
dependency problems - leaving unconfigured
Processing triggers for mailcap (3.70+nmu1ubuntu1) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu3) ...
Processing triggers for desktop-file-utils (0.26-1ubuntu3) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for shared-mime-info (2.1-2) ...
Errors were encountered while processing:
mysql-workbench-community
karthik@cosmic:~/Downloads$ sudo apt install libproj19
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Package libproj19 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'libproj19' has no installation candidate
```
```
karthik@cosmic:~/Downloads$ apt list -i | grep "libproj"
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libproj22/jammy,now 8.2.1-1 amd64 [installed]
karthik@cosmic:~/Downloads$
``` | 2022/04/24 | [
"https://unix.stackexchange.com/questions/700209",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/504271/"
]
| I solved it. Pretty dumb way but it works.
I narrowed down each conflicting dependecies and manually installed the required versions as deb files from Debian/ubuntu repos.
Whenever one of them again had dependency conflicts, I repeated the same method for them.
It took me like around 30 mins doing this but finally got the .deb version of workbench working on 22.04 | The same under ubuntu 22.04 lts.
Try to use the snap!
```
snap install mysql-workbench-community
```
Only the settings from you previous apt install of mysql workbench are gone. Don't know, if there is a way to import the settings from ~/.mysql/workbench into your new snap install. |
700,209 | When i try to install the official MySQL Workbench, it shows dependency issue of the unavailabilty of libproj19. However the repos only has libproj22 when i tried to install from APT.
Can someone help me out?
```
System: Host: cosmic Kernel: 5.16.19-76051619-generic x86_64 bits: 64
Console: pty pts/1 Distro: Pop!_OS 22.04 LTS
```
```
karthik@cosmic:~/Downloads$ sudo dpkg -i mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb
Selecting previously unselected package mysql-workbench-community.
(Reading database ... 629535 files and directories currently installed.)
Preparing to unpack mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb ...
Unpacking mysql-workbench-community (8.0.28-1ubuntu21.10) ...
dpkg: dependency problems prevent configuration of mysql-workbench-community:
mysql-workbench-community depends on libproj19 (>= 7.2.0); however:
Package libproj19 is not installed.
dpkg: error processing package mysql-workbench-community (--install):
dependency problems - leaving unconfigured
Processing triggers for mailcap (3.70+nmu1ubuntu1) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu3) ...
Processing triggers for desktop-file-utils (0.26-1ubuntu3) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for shared-mime-info (2.1-2) ...
Errors were encountered while processing:
mysql-workbench-community
karthik@cosmic:~/Downloads$ sudo apt install libproj19
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Package libproj19 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'libproj19' has no installation candidate
```
```
karthik@cosmic:~/Downloads$ apt list -i | grep "libproj"
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libproj22/jammy,now 8.2.1-1 amd64 [installed]
karthik@cosmic:~/Downloads$
``` | 2022/04/24 | [
"https://unix.stackexchange.com/questions/700209",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/504271/"
]
| The same under ubuntu 22.04 lts.
Try to use the snap!
```
snap install mysql-workbench-community
```
Only the settings from you previous apt install of mysql workbench are gone. Don't know, if there is a way to import the settings from ~/.mysql/workbench into your new snap install. | This is way easier than I thought it would be. On Ubuntu, I just allowed all permissions on the app installer, and voila! |
700,209 | When i try to install the official MySQL Workbench, it shows dependency issue of the unavailabilty of libproj19. However the repos only has libproj22 when i tried to install from APT.
Can someone help me out?
```
System: Host: cosmic Kernel: 5.16.19-76051619-generic x86_64 bits: 64
Console: pty pts/1 Distro: Pop!_OS 22.04 LTS
```
```
karthik@cosmic:~/Downloads$ sudo dpkg -i mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb
Selecting previously unselected package mysql-workbench-community.
(Reading database ... 629535 files and directories currently installed.)
Preparing to unpack mysql-workbench-community_8.0.28-1ubuntu21.10_amd64.deb ...
Unpacking mysql-workbench-community (8.0.28-1ubuntu21.10) ...
dpkg: dependency problems prevent configuration of mysql-workbench-community:
mysql-workbench-community depends on libproj19 (>= 7.2.0); however:
Package libproj19 is not installed.
dpkg: error processing package mysql-workbench-community (--install):
dependency problems - leaving unconfigured
Processing triggers for mailcap (3.70+nmu1ubuntu1) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu3) ...
Processing triggers for desktop-file-utils (0.26-1ubuntu3) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for shared-mime-info (2.1-2) ...
Errors were encountered while processing:
mysql-workbench-community
karthik@cosmic:~/Downloads$ sudo apt install libproj19
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Package libproj19 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'libproj19' has no installation candidate
```
```
karthik@cosmic:~/Downloads$ apt list -i | grep "libproj"
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
libproj22/jammy,now 8.2.1-1 amd64 [installed]
karthik@cosmic:~/Downloads$
``` | 2022/04/24 | [
"https://unix.stackexchange.com/questions/700209",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/504271/"
]
| I solved it. Pretty dumb way but it works.
I narrowed down each conflicting dependecies and manually installed the required versions as deb files from Debian/ubuntu repos.
Whenever one of them again had dependency conflicts, I repeated the same method for them.
It took me like around 30 mins doing this but finally got the .deb version of workbench working on 22.04 | This is way easier than I thought it would be. On Ubuntu, I just allowed all permissions on the app installer, and voila! |
11,176,829 | How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
The code behind is below.
```
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
``` | 2012/06/24 | [
"https://Stackoverflow.com/questions/11176829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042521/"
]
| You need to use `SelectedIndexChanged` handler to show selected value:
*Markup:*
```
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
```
*Code-behind:*
```
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
``` | You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place |
11,176,829 | How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
The code behind is below.
```
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
``` | 2012/06/24 | [
"https://Stackoverflow.com/questions/11176829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042521/"
]
| You need to use `SelectedIndexChanged` handler to show selected value:
*Markup:*
```
<asp:DropDownList ID="duty" runat="server" OnLoad="ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged"></asp:DropDownList>
```
*Code-behind:*
```
protected void duty_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(((Control)sender).NamingContainer);
DropDownList duty= (DropDownList) gvr.FindControl("duty");
TextBox1.Text = duty.SelectedItem.Value;
}
``` | this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
```
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
``` |
11,176,829 | How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
The code behind is below.
```
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
``` | 2012/06/24 | [
"https://Stackoverflow.com/questions/11176829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042521/"
]
| I had a similar problem using the `DropDownLists` in `GridView`. My solution was to adjust the `onLoad` for the dropdown so that it wouldn't re-write the `DropDownList` on every post back. This way if there's something there then it won't re-populate it.
```
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
``` | You should look into using data binding instead. You can bind the textbox.Text to the selecteditem.value, this will ensure that proper updating takes place |
11,176,829 | How can I change the value of a textbox whenever a dropdownlist within a gridview has its value changed?
On page load, the textbox shows the selected value, but when I change the selection of the dropdownlist, the textbox value doesn't change.
The code is below.
```
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false">
<Columns>
<asp:TemplateField HeaderText="Entry">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duty">
<ItemTemplate>
<asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
The code behind is below.
```
protected void ddl1_load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
Duty dy = new Duty();
dt = dy.getdutyid(Convert.ToInt32(dropcontractid.SelectedValue));
DropDownList ddl = (DropDownList)sender;
ddl.DataSource = dt;
ddl.DataTextField = "dutyid";
ddl.DataValueField = "dutyid";
ddl.DataBind();
TextBox1.Text = ddl.SelectedValue;
}
}
``` | 2012/06/24 | [
"https://Stackoverflow.com/questions/11176829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042521/"
]
| I had a similar problem using the `DropDownLists` in `GridView`. My solution was to adjust the `onLoad` for the dropdown so that it wouldn't re-write the `DropDownList` on every post back. This way if there's something there then it won't re-populate it.
```
protected void dropDownLoad(object sender, EventArgs e)
{
DropDownList dropDown = sender as DropDownList;
if (dropDown.SelectedValue == null || dropDown.SelectedValue == "")
{
// Your Code to populate table
}
}
``` | this happens to me once then i code like this... but i didnt use the onLoad attribute, tell me if this works,
```
<asp:TemplateField HeaderText="duty" SortExpression="duty">
<EditItemTemplate>
<asp:TextBox ID="duty" runat="server" Text='<%# Bind("duty_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblduty" runat="server" Text='<%# Eval("duty_Name") %>' />
<asp:DropDownList ID="ddlduty" runat="server" CssClass="dropdownlist"
OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" Visible = "false"
>
</asp:DropDownList>
</ItemTemplate>
<HeaderStyle Width="5%" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
``` |
45,208,849 | I've made an Application containing List of trainers. My Index View Displays these trainer profiles from the database. I intend to implement a sear bar to filter these results. I am not getting what i'm doing wrong. As soon as i mention the url in action of the search for, it displays reverse match error
url's.py :
```
#/trainer/
url(r'^$', views.IndexView.as_view(),name='index'),
#/trainer/<trainer_id>/
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(),name='details'),
#/trainer/trainer/add
url(r'trainer/add/$', views.TrainerCreate.as_view(), name='Trainer-add'),
#/trainer/trainer/<album_id>
url(r'trainer/(?P<pk>[0-9]+)/$', views.TrainerUpdate.as_view(), name='Trainer-update'),
#/trainer/trainer/add
url(r'trainer/(?P<pk>[0-9]+)/delete/$', views.TrainerDelete.as_view(), name='Trainer-delete'),
url(r'^search/$', views.search, name='Search'),
```
views.py
```
def search(request):
query = request.GET['q']
trainer= Trainer.objects.filter(name__icontains=query)
return render(request,'trainer/index.html', {'trainer': trainer})
```
search form in my base template
```
<form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}">
<div class="form-group">
<input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
```
index.py
```
<table style="width:100%" class="table table-hover">
<tr>
<th>#</th>
<th>Name</th>
<th>Technology</th>
<th>Location</th>
</tr>
{% for trainer in all_trainers %}
<tr>
<td><input type="checkbox" id="trainer{{ forloop.counter }}" name="trainer" value="{{ trainer.id }}"></td>
<td> <a href="{% url 'trainer:details' trainer.id %}"> {{ trainer.name }}</td>
<td>{{ trainer.technology }}</td></a>
<!-- View Details -->
<td><a href="{% url 'trainer:details' trainer.id %}" class="btn btn-primary btn-sm">View Details</a></td>
<td><a href="../media/{{ trainer.trainer_profile }}" class="btn">Download PDF</a></td>
<!-- Delete Album -->
<td>
<form action="{% url 'trainer:Trainer-delete' trainer.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="trainer_id" value="{{ trainer.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
``` | 2017/07/20 | [
"https://Stackoverflow.com/questions/45208849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331591/"
]
| change this line
```
<form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}">
```
to
```
<form class="navbar-form navbar-left" method="get" action="{% url 'Search' %}">
``` | Are you including the urls.py somewhere?
Otherwise you need to add caret ^ at the start of your regex.
```
url(r'^trainer/search/$', views.search, name='Search'),
``` |
45,208,849 | I've made an Application containing List of trainers. My Index View Displays these trainer profiles from the database. I intend to implement a sear bar to filter these results. I am not getting what i'm doing wrong. As soon as i mention the url in action of the search for, it displays reverse match error
url's.py :
```
#/trainer/
url(r'^$', views.IndexView.as_view(),name='index'),
#/trainer/<trainer_id>/
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(),name='details'),
#/trainer/trainer/add
url(r'trainer/add/$', views.TrainerCreate.as_view(), name='Trainer-add'),
#/trainer/trainer/<album_id>
url(r'trainer/(?P<pk>[0-9]+)/$', views.TrainerUpdate.as_view(), name='Trainer-update'),
#/trainer/trainer/add
url(r'trainer/(?P<pk>[0-9]+)/delete/$', views.TrainerDelete.as_view(), name='Trainer-delete'),
url(r'^search/$', views.search, name='Search'),
```
views.py
```
def search(request):
query = request.GET['q']
trainer= Trainer.objects.filter(name__icontains=query)
return render(request,'trainer/index.html', {'trainer': trainer})
```
search form in my base template
```
<form class="navbar-form navbar-left" method="get" action="{% url 'trainer:Search' %}">
<div class="form-group">
<input type="text" id="searchBox" class="input-medium search-query" name="q" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
```
index.py
```
<table style="width:100%" class="table table-hover">
<tr>
<th>#</th>
<th>Name</th>
<th>Technology</th>
<th>Location</th>
</tr>
{% for trainer in all_trainers %}
<tr>
<td><input type="checkbox" id="trainer{{ forloop.counter }}" name="trainer" value="{{ trainer.id }}"></td>
<td> <a href="{% url 'trainer:details' trainer.id %}"> {{ trainer.name }}</td>
<td>{{ trainer.technology }}</td></a>
<!-- View Details -->
<td><a href="{% url 'trainer:details' trainer.id %}" class="btn btn-primary btn-sm">View Details</a></td>
<td><a href="../media/{{ trainer.trainer_profile }}" class="btn">Download PDF</a></td>
<!-- Delete Album -->
<td>
<form action="{% url 'trainer:Trainer-delete' trainer.id %}" method="post">
{% csrf_token %}
<input type="hidden" name="trainer_id" value="{{ trainer.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
</td>
</tr>
{% endfor %}
</table>
``` | 2017/07/20 | [
"https://Stackoverflow.com/questions/45208849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331591/"
]
| You need `{% url 'Search' %}` and not `{% url 'trainer:Search' %}`; the `:` is for when you have [namespaced your urls](https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces). | Are you including the urls.py somewhere?
Otherwise you need to add caret ^ at the start of your regex.
```
url(r'^trainer/search/$', views.search, name='Search'),
``` |
30,565 | Consider this code where I read an input file with 6 columns (0-5):
1. Initialize a variable `history_ends` to 5000.
2. When the `column0` value (i.e. job[0] < 5000) I add 5000 lines of the input file in a list (`historyjobs`) else the rest of the lines until the eof in another list (`targetjobs`).
3. All the `historyjobs` list all contents in `item3`, `item4`, `item5` is equal to `targetjobs`. First list `item3`, `item4`, `item5` when this condition is satisfied. Add those `historyjobs` all `item1` to list `listsub`.
4. Find the running mean of the items in `listsub` and reverse the list, store it in list
1. Check the condition if items in `listsub > a*0.9` which satisfies the condition. Stores the result items in list `condsub`.
5. Reopen the `inputfile` and check whether `column0` is equal to items in `condsub`. If it satisfies, then add the `column1` to a list `condrun`.
6. Open the output file and write in `colum0` the second item of first list in `targetjobs` i.e. `j`, in `column1`, write the average of list `condrun`, `column2` is `(j-avg)/j`, `column3` is the maximum item in list `condrun`, `column4` is the minimum item in list `condrun`, `column5` is the length of the list `condrun`, the last four columns is based on the condition.
7. I am repeating the whole procedure using a `while` loop by assigning the variable `historyends` to the next item `int(targetjobs[1][0])`.
```
from __future__ import division
import itertools
history_begins = 1; history_ends = 5000; n = 0; total = 0
historyjobs = []; targetjobs = []
listsub = []; listrun = []; listavg = [] ; F = [] ; condsub = [] ;condrun = [] ;mlistsub = []; a = []
def check(inputfile):
f = open(inputfile,'r') #reads the inputfile
lines = f.readlines()
for line in lines:
job = line.split()
if( int(job[0]) < history_ends ): #if the column0 is less then history_ends(i,e 5000 initially)
historyjobs.append(job) #historyjobs list contains all the lines from the list whose column1 < history_ends
else:
targetjobs.append(job) #historyjobs list contains all the lines from the list whose column1 > history_ends
k = 0
for i, element in enumerate(historyjobs):
if( (int(historyjobs[i][3]) == int(targetjobs[k][3])) and (int(historyjobs[i][4]) == int(targetjobs[k][4])) and (int(historyjobs[i][5]) == int(targetjobs[k][5])) ): #historyjobs list all contents in column3,column4,column5 is equal to targetjobs first list column3,column4,column5
listsub.append(historyjobs[i][1]) #when if condition true add those historyjobs column1 to list listsub
def runningMean(iterable):
"""A generator, yielding a cumulative average of its input."""
num = 0
denom = 0
for x in iterable:
num += x
denom += 1
yield num / denom
def newfun(results):
results.reverse() # put them back in regular order
for value, average in results:
a.append(value)
return a #to return the value
def runcheck(subseq):
f = open('newfileinput','r') #again read the same inputfile
lines = f.readlines()
for line in lines:
job = line.split()
for i, element in enumerate(subseq):
if(int(job[1]) == int(subseq[i])): # if the column1 value of the inputfile becomes equal to list obtained
condrun.append(str(job[2])) #return the value of column2 which satisfies the if condition
return condrun
def listcreate(condrun,condsub):
f1 = open('outputfile','a') #outputfile to append the result
s = map(int,condrun)
j = int(targetjobs[0][2])
targetsub = int(targetjobs[0][1])
if(condsub != []):
try:
convertsub = int(condsub[-1])
a=sum(s)/len(s)
c=max(s)
d=min(s)
e1=abs(j-a)
er1=e1/j
g=len(s)
h=abs(convertsub-targetsub)
f1.write(str(j))
f1.write('\t')
f1.write('\t')
f1.write(str(round(a,2)))
f1.write('\t')
f1.write('\t')
f1.write(str(round(er1,3)))
f1.write('\t')
f1.write('\t')
f1.write(str(c))
f1.write('\t')
f1.write('\t')
f1.write(str(d))
f1.write('\t')
f1.write('\t')
f1.write(str(g))
f1.write('\t')
f1.write('\t')
f1.write(str(h))
f1.write('\t')
f1.write("\t")
if (float(er1) < 0.20):
f1.write("good")
f1.write("\t")
else :
f1.write("bad")
f1.write("\t")
if (float(er1) < 0.30):
f1.write("good")
f1.write("\t")
else :
f1.write("bad")
f1.write("\t")
if (float(er1) < 0.40):
f1.write("good")
f1.write("\t")
else :
f1.write("bad")
f1.write("\t")
if (float(er1) < 0.50):
f1.write("good")
f1.write("\n")
else :
f1.write("bad")
f1.write("\n")
except ZeroDivisionError :
print 'dem 0'
else:
print '0'
f1.close()
def new():
global history_ends
while 1: #To repeat the process untill the EOF(end of input file)
check('newfileinput') #First function call
if(len(targetjobs) != 1):
history_ends = int(targetjobs[1][0]) #initialize historyends to targetjobs second lines first item
mlistsub = map(int,listsub)
results = list(itertools.takewhile(lambda x: x[0] > 0.9 * x[1],
itertools.izip(reversed(mlistsub),
runningMean(reversed(mlistsub)))))#call runningmean function & check the condition
condsub = newfun(results) #function to reverse back the result
condrun=runcheck(condsub) #functionto match & return the value
listcreate(condrun,condsub) #function to write result to output file
del condrun[0:len(condrun)]#to delete the values in list
del condsub[0:len(condsub)]#to delete the values in list
del listsub[0:len(listsub)]#to delete the values in list
del targetjobs[0:len(targetjobs)]#to delete the values in list
del historyjobs[0:len(historyjobs)]#to delete the values in list
else:
break
def main():
new()
if __name__ == '__main__':
main()
```
The sample input file (whole file contains 200,000 lines):
>
>
> ```
> 1 0 9227 1152 34 2
> 2 111 7622 1120 34 2
> 3 68486 710 1024 14 2
> 6 265065 3389 800 22 2
> 7 393152 48438 64 132 3
> 8 412251 46744 64 132 3
> 9 430593 50866 256 95 4
> 10 430730 10770 256 95 4
> 11 433750 12701 256 14 3
> 12 437926 2794 64 34 2
> 13 440070 43 32 96 3
>
> ```
>
>
The sample output file contents:
>
>
> ```
> 930 1389.14 0.494 3625 977 7 15 bad bad bad good
> 4348 1331.75 0.694 3625 930 8 164 bad bad bad bad
> 18047 32237.0 0.786 61465 17285 3 325774 bad bad bad bad
> 1607 1509.0 0.061 1509 1509 1 6508 good good good good
> 304 40.06 0.868 80 32 35 53472 bad bad bad bad
> 7246 7247.0 0.0 7247 7247 1 9691 good good good good
> 95 1558.0 15.4 1607 1509 2 2148 bad bad bad bad
> 55 54.33 0.012 56 53 3 448142 good good good good
> 31 76.38 1.464 392 35 13 237152 bad bad bad bad
> 207 55.0 0.734 55 55 1 370 bad bad bad bad
>
> ```
>
>
If anyone could suggest some changes to help make the code run faster, that'd be helpful. | 2013/08/31 | [
"https://codereview.stackexchange.com/questions/30565",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/29122/"
]
| Comments about coding style:
* inconsistent indentation makes the code harder to read
* preferred indentation width in python is 4 spaces
Why is the question tagged python3 ? This is python2 code.
---
```
history_begins = 1; history_ends = 5000; n = 0; total = 0
historyjobs = []; targetjobs = []
listsub = []; listrun = []; listavg = [] ; F = [] ; condsub = [] ;condrun = [] ;mlistsub = []; a = []
```
There are variables defined here that aren't actually used in the script, and global variables shouldn't have one-letter names.
---
```
f = open(inputfile,'r') #reads the inputfile
```
No it doesn't, it just creates a file handle.
---
```
lines = f.readlines()
for line in lines:
```
However, this does read the file, it even loads it all in RAM at once, which is a waste because you don't actually need to, so do this instead:
```
for line in f:
```
---
```
f1.write(str(j))
f1.write('\t')
f1.write('\t')
...
if (float(er1) < 0.50):
f1.write("good")
f1.write("\n")
else:
f1.write("bad")
f1.write("\n")
```
That's redundant, factor it:
```
print(j, round(a,2), round(er1,3), c, d, g, h, sep='\t\t', end='\t\t', file=out)
w = ('bad', 'good')
print(w[er1 < .2], w[er1 < .3], w[er1 < .4], w[er1 < .5], sep='\t', file=out)
```
---
```
f = open('newfileinput','r') #again read the same inputfile
```
Why read the same file multiple times ? That's inefficient… | OK, your code is a bit of a mess. I take it you are fairly new to python. Read the [python style guide](http://www.python.org/dev/peps/pep-0008/) and stick to it. It will make it easier for people to read your code.
It is not easy to work out what you are trying to do here. As it stands the code doesn't run. However, here are some thoughts.
building on @Changaco's answer you can iterate through the file and process each row into integers like this.
```
def check(inputfile):
f = open(inputfile,'r')
for line in f:
job = [int(s) for s in line.split()]
...
```
Doing the conversion once up front you can forget all the other int() conversions that clutter up your code. This includes removing the need for your mlistsub global entirely as far as I can tell as it seems to be an integer version of the listsub variable.
I suspect the following reference to job[0] should reference job[1 ] as it is column1, not column0 that you talk about in other comments.
```
if( int(job[0]) < history_ends ): #if the column0 is less then history_ends(i,e 5000 initially)
...
```
Also, brackets are not necessary and with the above int() conversion already done the line becomes
```
if job[1] < history_ends:
...
```
I would reduce the global variables to the absolute minimum (which is usually none). I cannot work out the detail but the only reason I can see to keep globals here would be if they are continually being appended to and this is not happening as far as I can tell.
For example, I think the global variable a = [] can be removed.
Your original function.
```
def newfun(results):
results.reverse() # put them back in regular order
for value, average in results:
a.append(value)
return a #to return the value
```
is called like this
```
condsub = newfun(results) #function to reverse back the result
```
Aside from the terrible function name, this function seems to do very little. You could replace the function call with something like this
```
condsub = [value for value, average in reversed(results)] #reverse back the result
```
The following code
```
k = 0
for i, element in enumerate(historyjobs):
if( (int(historyjobs[i][3]) == int(targetjobs[k][3])) and (int(historyjobs[i][4]) == int(targetjobs[k][4])) and (int(historyjobs[i][5]) == int(targetjobs[k][5])) ): #historyjobs list all contents in column3,column4,column5 is equal to targetjobs first list column3,column4,column5
listsub.append(historyjobs[i][1]) #when if condition true add those historyjobs column1 to list listsub
```
can be significantly cleaned up. There is no need to use enumerate() just to get the i variable. The idiomatic approach is to use 'for hjob in historyjobs:'. With the int() conversion already done you can replace the complicated comparison with a simple comparison of the slice of interest.
```
tjob = targetjobs[0]
for hjob in historyjobs:
if hjob[3:6] == tjob[3:6]:
listsub.append(hjob[1])
```
If I understand your intent, you can also create a simple list and return it from the function as a way to remove the listsub global variable.
```
result = []
tjob = targetjobs[0]
for hjob in historyjobs:
if hjob[3:6] == tjob[3:6]:
result.append(hjob[1])
return result
```
A conversion and filter operation can usually be achieved with a list comprehension. Something like this should do the trick.
```
return [hjob[1] for hjob in historyjobs if hjob[3:6] == targetjobs[0][3:6]]
```
Since you are deleting all your globals at the end of each loop, I am assuming you don't need them at all.
```
del condrun[0:len(condrun)]#to delete the values in list
del condsub[0:len(condsub)]#to delete the values in list
del listsub[0:len(listsub)]#to delete the values in list
del targetjobs[0:len(targetjobs)]#to delete the values in list
del historyjobs[0:len(historyjobs)]#to delete the values in list
```
This is not necessary if you return data from your functions as above and assign the result of the function calls to variables which are created in the scope of your new() function.
As I say, I'm not sure what your doing exactly here so I can't advise on the logic. If you can tidy it up a bit then I'm sure we can help you get to the bottom of it. My feeling is that the code can become much shorter and much clearer than your current version. |
20,954,016 | I have two `ng-if`s defined in the same template that call functions of the same controller:
```
<div ng-controller="UserController">
<!-- WORKS :) -->
<p>{{ user.name }}</p>
<!--WORKS :)-->
<div ng-if="showThingOne()">
<h2>Thing One</h2>
</div>
<!--DOESN'T WORK :( ; TypeError: Cannot read property 'role' of undefined -->
<div ng-if="showThingTwo(user)">
<h2>Thing Two</h2>
</div>
</div>
```
```
angular.module('MyApp')
.controller('UserController', ['$rootScope', '$scope', 'User', function ($rootScope, $scope, User) {
var getCurrentUser = function () {
User.current(function (user) {
$scope.user = user;
$rootScope.currentUser = user;
});
};
getCurrentUser();
$scope.showThingOne = function () {
return $scope.user.role === 'Thing One Seer';
};
$scope.showThingTwo = function (user) {
return user.role === 'Thing Two Seer';
};
}]);
```
The second conforms with a bunch of things I've read about unit testing, while the first is always marked "Don't do it this way", so I'd like to write my functions the second way. Also, I'd like to understand *why* the first works and the second doesn't; I'm guessing it has something to do with how the DOM is compiled during $digest, but that's just a random guess with no real support in the Angular source or docs. | 2014/01/06 | [
"https://Stackoverflow.com/questions/20954016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1141702/"
]
| The User.current is an async function so the result get ready after the dom compiled.
showThingOne has no argument to be evaluated at compile time.
**Solution**
Add
```
$scope.user = {};
```
as the first line of user controller.
```
angular.module('MyApp')
.controller('UserController', ['$rootScope', '$scope', 'User', function ($rootScope, $scope, User) {
$scope.user = {};
var getCurrentUser = function () {
User.current(function (user) {
$scope.user = user;
$rootScope.currentUser = user;
});
};
getCurrentUser();
$scope.showThingOne = function () {
return $scope.user.role === 'Thing One Seer';
};
$scope.showThingTwo = function (user) {
return user.role === 'Thing Two Seer';
};
}]);
``` | This doesn't work because `user` is never being used:
```
$scope.showThingTwo = function (user) {
return $scope.user.role === 'Thing Two Seer';
};
```
Only `$scope.user.role` is being used (but not the `user` parameter) and it is still set to the `'Thing One Seer'` value.
If you use it like this it might work this way you are intenting:
```
$scope.showThingTwo = function (user) {
if (user) {
return user.role === 'Thing Two Seer';
}
return false;
};
``` |
52,538,546 | I'm trying to listen on keydown event on search input field in google's search box
but when I type 'enter' key I can't see any output. Is there any way to handle this?
```
window.addEventListener('keydown', (e) => {
console.log(e)
})
``` | 2018/09/27 | [
"https://Stackoverflow.com/questions/52538546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880164/"
]
| Window doesn't leason for keydown event you have to attach it to your input
```js
document.getElementById('input').addEventListener('keydown',(e) => {
console.log(e.which)
})
```
```html
<input type="text" id="input">
``` | You need check your event, if keydown (example) "Enter" and focus on input, then console.log(e.target.value); // for see your value. |
15,094,637 | I am having 8(Eight) buttons in one line(horizontal) under one linear layout. The problem is that these buttons look like rectangle whereas I want them to look like square.
```
<Button
android:id="@+id/button25"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="0.125"
android:background="#ffffffff" />
```
Can someone guide me what needs to be done so that these rectangles become squares. | 2013/02/26 | [
"https://Stackoverflow.com/questions/15094637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/328560/"
]
| Your query, as written, is trying to group by a constant expression. I think you can just change the last two lines to:
```
and i.OverrideDate between @sd and @ed
```
The `group by` statement is unnecessary. You are only returning one row, so all rows will be aggregated.
If you needed to include the `group by` for some reason (such as this being automatically generated code), then you can use a trick such as:
```
group by (case when OverrideDate = OverrideDate then @sd end),
(case when OverrideDate = OverrideDate then @ed end)
```
But I'm guessing that is unncessary in this case. | I am not sure why you using `group by` *and* `having` clauses here at all. I think you could simplify your where clause as;
```
where lbs.Name in ('Completed by Analyst',
'Delivered/Imported into Neptune Online')
and lis.Name = 'Complete'
and bt.Name = 'Live'
and i.IsRelevant = 1
and i.OverrideDate between @sd and @ed
``` |
3,974,071 | Let $\mathcal{A}$ be a σ-algebra on $\mathbb{R}$ that does not contain all Borel sets (i.e that is, it holds
that $\mathcal{B}(\mathbb{R}) \setminus \mathcal{A} \not= ∅)$. Prove that there is a continuous function f : $\mathbb{R} → \mathbb{R}$ which
is not $\mathcal{A}$-measurable
I have a really simple example but I am not sure if it correct. Take $\mathcal{A} = (\emptyset , \mathbb{R} , (0,1) , \mathbb{R}\setminus (0,1))$ This is clearly a sigma algebra.
Then take $f(x)=x$ we have that $f^{-1}((5,6))=(5,6)\notin\mathcal{A}$ so $f$ is not $\mathcal{A}$ measurable and clearly $f$ is continuous.
Is this a correct solution?
**EDIT**
Thanks to some incredibly bright chaps on this site I have seen the error in my solution, I simply misread the question. So for all those who come after here is the answer:
As $\mathcal{B}$, the Borel $\sigma$-algebra, is the smallest $\sigma$ algebra containing all open sets and $\mathcal{B} \not \subseteq \mathcal{A}$ we have at least one interval, $I \in \mathcal{B}$, that is not in $\mathcal{A}$ Hence taking the pre-image of $I$. We have: $\mathcal{B} \ni I, f^{-1}(I) = I \notin \mathcal{A}$ So $f$ is not $\mathcal{A}$ measurable | 2021/01/05 | [
"https://math.stackexchange.com/questions/3974071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
]
| The way the question is phrased, you are not allowed to choose $\mathcal A$.
But your idea works anyway. If $\mathcal A$ does not contain all Borel sets, then it fails to contain some interval. Now you can do your example using said interval. | Consider a closed set $C\notin \mathcal A$. There is a continuous (or even $C^\infty$) function $f:\Bbb R\to \Bbb R$ such that $C=f^{-1}\{0\}$. Therefore $f$ is not $\mathcal A$-measurable. |
3,974,071 | Let $\mathcal{A}$ be a σ-algebra on $\mathbb{R}$ that does not contain all Borel sets (i.e that is, it holds
that $\mathcal{B}(\mathbb{R}) \setminus \mathcal{A} \not= ∅)$. Prove that there is a continuous function f : $\mathbb{R} → \mathbb{R}$ which
is not $\mathcal{A}$-measurable
I have a really simple example but I am not sure if it correct. Take $\mathcal{A} = (\emptyset , \mathbb{R} , (0,1) , \mathbb{R}\setminus (0,1))$ This is clearly a sigma algebra.
Then take $f(x)=x$ we have that $f^{-1}((5,6))=(5,6)\notin\mathcal{A}$ so $f$ is not $\mathcal{A}$ measurable and clearly $f$ is continuous.
Is this a correct solution?
**EDIT**
Thanks to some incredibly bright chaps on this site I have seen the error in my solution, I simply misread the question. So for all those who come after here is the answer:
As $\mathcal{B}$, the Borel $\sigma$-algebra, is the smallest $\sigma$ algebra containing all open sets and $\mathcal{B} \not \subseteq \mathcal{A}$ we have at least one interval, $I \in \mathcal{B}$, that is not in $\mathcal{A}$ Hence taking the pre-image of $I$. We have: $\mathcal{B} \ni I, f^{-1}(I) = I \notin \mathcal{A}$ So $f$ is not $\mathcal{A}$ measurable | 2021/01/05 | [
"https://math.stackexchange.com/questions/3974071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
]
| I didn't want to answer (just to comment), but since some other guy answered what I commented, then let me write a simpler answer.
The identity function you propose always works. Indeed, if your $\sigma$-algebra does not contain all Borel subsets then it does not contain at least an open subset of the reals. Then just take the inverse image of that open set through the identity function. | Consider a closed set $C\notin \mathcal A$. There is a continuous (or even $C^\infty$) function $f:\Bbb R\to \Bbb R$ such that $C=f^{-1}\{0\}$. Therefore $f$ is not $\mathcal A$-measurable. |
3,974,071 | Let $\mathcal{A}$ be a σ-algebra on $\mathbb{R}$ that does not contain all Borel sets (i.e that is, it holds
that $\mathcal{B}(\mathbb{R}) \setminus \mathcal{A} \not= ∅)$. Prove that there is a continuous function f : $\mathbb{R} → \mathbb{R}$ which
is not $\mathcal{A}$-measurable
I have a really simple example but I am not sure if it correct. Take $\mathcal{A} = (\emptyset , \mathbb{R} , (0,1) , \mathbb{R}\setminus (0,1))$ This is clearly a sigma algebra.
Then take $f(x)=x$ we have that $f^{-1}((5,6))=(5,6)\notin\mathcal{A}$ so $f$ is not $\mathcal{A}$ measurable and clearly $f$ is continuous.
Is this a correct solution?
**EDIT**
Thanks to some incredibly bright chaps on this site I have seen the error in my solution, I simply misread the question. So for all those who come after here is the answer:
As $\mathcal{B}$, the Borel $\sigma$-algebra, is the smallest $\sigma$ algebra containing all open sets and $\mathcal{B} \not \subseteq \mathcal{A}$ we have at least one interval, $I \in \mathcal{B}$, that is not in $\mathcal{A}$ Hence taking the pre-image of $I$. We have: $\mathcal{B} \ni I, f^{-1}(I) = I \notin \mathcal{A}$ So $f$ is not $\mathcal{A}$ measurable | 2021/01/05 | [
"https://math.stackexchange.com/questions/3974071",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
]
| I didn't want to answer (just to comment), but since some other guy answered what I commented, then let me write a simpler answer.
The identity function you propose always works. Indeed, if your $\sigma$-algebra does not contain all Borel subsets then it does not contain at least an open subset of the reals. Then just take the inverse image of that open set through the identity function. | The way the question is phrased, you are not allowed to choose $\mathcal A$.
But your idea works anyway. If $\mathcal A$ does not contain all Borel sets, then it fails to contain some interval. Now you can do your example using said interval. |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| Here is full back end code which is working
```
const express = require('express');
var app = express();
var port = 9999;
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
// Start server
app.listen(port, function () {
console.log('server running at port: ' + port);
});
``` | Follow the [Express node server with Angular 2 CLI](https://javascriptrocks.wordpress.com/2016/06/04/express-with-angular-cli-in-5-minutes/) document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.
E.g.
Serve application with <http://localhost:5000/app>
```
app.get('/app/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'))
});
```
or
Serve data from REST calls with <http://localhost:5000/rest/contacts>
```
app.get('/rest/user', function(req, res) {
res.send({
"id": 2,
"name": "Jhon",
})
});
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
```
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
```
>
> **NO angular base-href rewrite is required! Just use `ng build` or `ng build --prod`.**
>
>
> | Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.
Here's the summary from beginning:
1. `npm install -g @angular/cli`
2. `ng new PROJECT_NAME`
3. `cd PROJECT_NAME`
4. `npm install nodemon express cookie-parser body-parser morgan method-override --save`
5.Create `app.js`:
```
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
console.log('——————————- Run on port '+ port);
/****************************** Router ***************************/
router.get('*', function(req, res){
res.sendFile('index.html', { root: __dirname + '/' });
});
/****************************** /Router ***************************/
//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder
app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*
app.listen(port);
```
6. Edit `package.json` file:
```
{
...
"scripts": {
"start": "ng build; cp app.js dist/app.js; node dist/app.js",
}
...
}
```
7. Run `npm start`
This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app. |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
```
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
```
>
> **NO angular base-href rewrite is required! Just use `ng build` or `ng build --prod`.**
>
>
> | Follow the [Express node server with Angular 2 CLI](https://javascriptrocks.wordpress.com/2016/06/04/express-with-angular-cli-in-5-minutes/) document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.
E.g.
Serve application with <http://localhost:5000/app>
```
app.get('/app/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'))
});
```
or
Serve data from REST calls with <http://localhost:5000/rest/contacts>
```
app.get('/rest/user', function(req, res) {
res.send({
"id": 2,
"name": "Jhon",
})
});
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.
Here's the summary from beginning:
1. `npm install -g @angular/cli`
2. `ng new PROJECT_NAME`
3. `cd PROJECT_NAME`
4. `npm install nodemon express cookie-parser body-parser morgan method-override --save`
5.Create `app.js`:
```
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
console.log('——————————- Run on port '+ port);
/****************************** Router ***************************/
router.get('*', function(req, res){
res.sendFile('index.html', { root: __dirname + '/' });
});
/****************************** /Router ***************************/
//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder
app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*
app.listen(port);
```
6. Edit `package.json` file:
```
{
...
"scripts": {
"start": "ng build; cp app.js dist/app.js; node dist/app.js",
}
...
}
```
7. Run `npm start`
This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app. | Step 1: In order to get static content, run this command in your angular app directory -
>
> ng build --prod
>
>
>
Step 2: The first step will create a **dist** folder in your current directory, move all files in the **dist** folder to **public** folder of your node app -
Step 3: Create a node server. App.js -
```
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieParser = require('cookie-parser');
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
var app = express();
app.use(cookieParser());
function getAngularApp(request, response) {
response.sendFile(path.resolve('./public/index.html'));
}
function defaultHandler(request, response) {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
response.sendFile(path.resolve(`public/${req.url}`));
} else {
response.sendFile(path.resolve('./public/index.html'));
}
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', getAngularApp);
app.get('/*', defaultHandler);
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
```
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
```
>
> **NO angular base-href rewrite is required! Just use `ng build` or `ng build --prod`.**
>
>
> | Step 1: In order to get static content, run this command in your angular app directory -
>
> ng build --prod
>
>
>
Step 2: The first step will create a **dist** folder in your current directory, move all files in the **dist** folder to **public** folder of your node app -
Step 3: Create a node server. App.js -
```
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieParser = require('cookie-parser');
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
var app = express();
app.use(cookieParser());
function getAngularApp(request, response) {
response.sendFile(path.resolve('./public/index.html'));
}
function defaultHandler(request, response) {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
response.sendFile(path.resolve(`public/${req.url}`));
} else {
response.sendFile(path.resolve('./public/index.html'));
}
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', getAngularApp);
app.get('/*', defaultHandler);
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| 1. Use `ng build` to build your app into build directory.
2. Create nodejs app to server the build directory as static content, then create route for api.
Following is an example of nodejs app using express that will serve the Angular2 app:
```
/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';
const port = 4000;
const apiUrl = '/api';
// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();
app
.use(compression())
.use(bodyParser.json())
// Static content
.use(express.static(html))
// Default route
.use(function(req, res) {
res.sendFile(html + 'index.html');
})
// Start server
.listen(port, function () {
console.log('Port: ' + port);
console.log('Html: ' + html);
});
// continue with api code below ...
``` | Step 1: In order to get static content, run this command in your angular app directory -
>
> ng build --prod
>
>
>
Step 2: The first step will create a **dist** folder in your current directory, move all files in the **dist** folder to **public** folder of your node app -
Step 3: Create a node server. App.js -
```
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieParser = require('cookie-parser');
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
var app = express();
app.use(cookieParser());
function getAngularApp(request, response) {
response.sendFile(path.resolve('./public/index.html'));
}
function defaultHandler(request, response) {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
response.sendFile(path.resolve(`public/${req.url}`));
} else {
response.sendFile(path.resolve('./public/index.html'));
}
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', getAngularApp);
app.get('/*', defaultHandler);
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| None of the answers worked properly for me. And if it worked, the Angular routing did not work on reload.
So this is how I solved it. Angular routing works even on full page reload.
```
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
// Note the dot at the beginning of the path
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
```
>
> **NO angular base-href rewrite is required! Just use `ng build` or `ng build --prod`.**
>
>
> | Here is full back end code which is working
```
const express = require('express');
var app = express();
var port = 9999;
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
// Start server
app.listen(port, function () {
console.log('server running at port: ' + port);
});
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| Based on @NTN-JAVA answer, here's a solution to serve an Angular app from NodeJS server.
Here's the summary from beginning:
1. `npm install -g @angular/cli`
2. `ng new PROJECT_NAME`
3. `cd PROJECT_NAME`
4. `npm install nodemon express cookie-parser body-parser morgan method-override --save`
5.Create `app.js`:
```
var express = require('express');
var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var port = process.env.PORT || 3000;
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
console.log('——————————- Run on port '+ port);
/****************************** Router ***************************/
router.get('*', function(req, res){
res.sendFile('index.html', { root: __dirname + '/' });
});
/****************************** /Router ***************************/
//app.use(morgan('dev')); // log every request to the console
app.use(express.static(__dirname + '/')); // Static (public) folder
app.use(bodyParser.urlencoded({extended:true}));// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(methodOverride());
app.use('/', router); // app.use('/parent', router); call all from localhost:port/parent/*
app.listen(port);
```
6. Edit `package.json` file:
```
{
...
"scripts": {
"start": "ng build; cp app.js dist/app.js; node dist/app.js",
}
...
}
```
7. Run `npm start`
This answer also offers a solution for calling direct URLs from browser and resolving them correctly in your app. | Follow the [Express node server with Angular 2 CLI](https://javascriptrocks.wordpress.com/2016/06/04/express-with-angular-cli-in-5-minutes/) document to serve your application through Node.js server. The application is being served Through Node.js and a REST full API. You can design this REST as your requirements.
E.g.
Serve application with <http://localhost:5000/app>
```
app.get('/app/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'))
});
```
or
Serve data from REST calls with <http://localhost:5000/rest/contacts>
```
app.get('/rest/user', function(req, res) {
res.send({
"id": 2,
"name": "Jhon",
})
});
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| 1. Use `ng build` to build your app into build directory.
2. Create nodejs app to server the build directory as static content, then create route for api.
Following is an example of nodejs app using express that will serve the Angular2 app:
```
/*
Put content of angular2 build into 'public' folder.
*/
const html = __dirname + '/public';
const port = 4000;
const apiUrl = '/api';
// Express
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
var app = express();
app
.use(compression())
.use(bodyParser.json())
// Static content
.use(express.static(html))
// Default route
.use(function(req, res) {
res.sendFile(html + 'index.html');
})
// Start server
.listen(port, function () {
console.log('Port: ' + port);
console.log('Html: ' + html);
});
// continue with api code below ...
``` | Here is full back end code which is working
```
const express = require('express');
var app = express();
var port = 9999;
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
// Start server
app.listen(port, function () {
console.log('server running at port: ' + port);
});
``` |
39,845,529 | [here is the image](http://i.stack.imgur.com/eHAoo.png) I want to add a bootstrap **caret** class in my select dropdown menu.
```css
.select_menu{
font-size: 12px;
outline: none;
border: thin #ddd solid;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #F7F7F7;
}
```
```html
<select class="form-control select_menu" style="">
<option>Click here to select purpose</option>
<option>Option 1</option>
<option>Options 2 </option>
</select>
```
I have used bootstrap form-control. How can I add caret to select dropdown menu. | 2016/10/04 | [
"https://Stackoverflow.com/questions/39845529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6907704/"
]
| Here is full back end code which is working
```
const express = require('express');
var app = express();
var port = 9999;
function getRoot(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
function getUndefined(request, response) {
response.sendFile(path.resolve('./public/angular/index.html'));
}
app.use(express.static('./public/angular'));
app.get('/', getRoot);
app.get('/*', getUndefined);
// Start server
app.listen(port, function () {
console.log('server running at port: ' + port);
});
``` | Step 1: In order to get static content, run this command in your angular app directory -
>
> ng build --prod
>
>
>
Step 2: The first step will create a **dist** folder in your current directory, move all files in the **dist** folder to **public** folder of your node app -
Step 3: Create a node server. App.js -
```
var path = require('path');
var express = require('express');
var cookieParser = require('cookie-parser');
var cookieParser = require('cookie-parser');
const allowedExt = [
'.js',
'.ico',
'.css',
'.png',
'.jpg',
'.woff2',
'.woff',
'.ttf',
'.svg',
];
var app = express();
app.use(cookieParser());
function getAngularApp(request, response) {
response.sendFile(path.resolve('./public/index.html'));
}
function defaultHandler(request, response) {
if (allowedExt.filter(ext => req.url.indexOf(ext) > 0).length > 0) {
response.sendFile(path.resolve(`public/${req.url}`));
} else {
response.sendFile(path.resolve('./public/index.html'));
}
}
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', getAngularApp);
app.get('/*', defaultHandler);
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
``` |
939,397 | I've seen a lot of examples which use
**getAccessibleContext().setAccessibleDescription(...)**
to set some "magic" description.
What is the use of this description? Where can it be seen and
how should it support accessibility?
Why **setDescription(...)** is not used?
Additionally, what is your opinion / experience with Java accessibility
stuff? | 2009/06/02 | [
"https://Stackoverflow.com/questions/939397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76393/"
]
| I haven't actually used Swing's accessibility facilities in my applications (and I probably should), but I presume that it will aid in the use of screen readers and other technologies which to improve the accessibility of an application.
From the [Accessibility and the Swing Set](http://java.sun.com/products/jfc/tsc/articles/accessibility/index.html) article:
>
> If an application fully supports the
> Java Accessibility API, it can be
> compatible with, and friendly toward,
> screen readers, screen magnifiers, and
> other kinds of assistive technologies.
>
>
>
The linked article goes in to some depth about the accessibility features of Swing and the [Accessibily API](http://java.sun.com/javase/6/docs/api/javax/accessibility/package-summary.html). | As pointed out the accessible information is used to expose information to assistive technologies such as screen readers (in short as a blind computer user I use a screen reader to gather useful information about what control has focus and other useful things happening in a application and then for it to speak it out to me. Examples of screen readers are NVDA www.nvda-project.org for windows, Orca <http://live.gnome.org/Orca> for the gnome desktop on unix platforms and voiceover included by default in MacOSX). For a number of standard controls which contain text you may be able to get away without having to explicitly set accessible information (eg. if you have a button with the text word "OK" then this probably will be spoken fine by a screen reader. The importance of setting accessible information comes in when you have no text showing (eg. a button with a graphic label) or when you are developing a custom control (from memory without going back through some of the Java swing docs, I think the accessible name is to identify the control and accessible description is to provide extra information, may be a clue as how to use it if its a custom control).
Now if you wish to see how this works, NVDA and Orca are opensource projects and voiceover is included in MacOSX 10.4 (I think) and higher, so you can try one of these at no cost (unlike some of the commercial offerings which can be very expensive). |
25,480 | Some of the boards in my hardwood floors (1949) are disintegrating.
Can anyone tell me what gives? And how I might go about stopping it?
 | 2013/02/23 | [
"https://diy.stackexchange.com/questions/25480",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/11749/"
]
| Its either rot or termites.
The discoloring suggests a water leak that persisted long enough to rot. Do you have access under that spot? Is the subfloor similarly discolored? If so, it may need to be repaired at the same time as the board.
Board replacement is possible by any flooring contractor by sawing out the center of the board and chiseling/prying out the side pieces. The replacement piece will be dropped in by cutting off the lower half of its groove (of the tounge/groove pair) and glueing it in. Small finish nails can also be used to tack it down (and set and filled with colored wood putty).
The new piece may be a bit proud if the floor has been refinished more than once, and can be presanded to blend.
Here's a [video](http://www.thisoldhouse.com/toh/video/0,,1631521,00.html) found by Shirlock Hoimes on the TOH site | Looks like water damage. Did it occur while you owned the house? If so, and you don't remember any flooding, then the water is coming from underneath the floor. This needs to be fixed or you will continue to get rot and mold. Try to get access to the subfloor from below. The rotted pieces will need to be replaced so you could remove them to take a look at the subfloor to try to find how the water is spreading. |
5,382,827 | i need to put a corporate site under a cms, which i haven't finally chosen yet, and have some tight requirements for it:
1. it should be very well organized at a code level, as i'm a developer and i need to add some very custom functionality to the site;
2. ability to create custom content types (a la drupal's cck does);
3. very good i18n abilities as the site will be multilingual to and fro;
4. caching / performance control solutions as the site experiences tens of thousands unique hosts a day;
5. publishing features like pre-moderation, authoring and versioning;
6. sending custom emails;
7. creating custom web forms with input data validation;
8. content access levels;
9. i would like to have my static content (images / css / pdf's etc) on a separate domain (possibly hosted on amazon cloud) processed by caching proxy server like nginx -- not a tight requirement, but still;
i evaluated these requirements and came up with ez publish as a solution. i'm not very experienced in cms world; i've worked with drupal and wordpress, but, being good cms'es, none of these meet my requirements (drupal isn't good at a code level and wordpress is a blog solution). also i don't want to mess with joomla or complexity of typo3. so, my question is -- does ez publish have a competitor in this field, regardless of the implemention language? | 2011/03/21 | [
"https://Stackoverflow.com/questions/5382827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/670079/"
]
| I have just refactored a bit the code and now it works (on my machine):
```
private static void CreateThumbnail(string[] b, double wid, double hght, bool Isprint)
{
string saveAt = "D:\\check";
foreach (string path in b)
{
var directory = new DirectoryInfo(path);
string outputPath = Path.Combine(saveAt, directory.Name);
foreach (FileInfo f in directory.GetFiles("*.*", SearchOption.AllDirectories))
{
if (f.DirectoryName != directory.FullName)
{
outputPath = Path.Combine(saveAt, directory.Name, f.Directory.Name);
}
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
using (Image imagesize = Image.FromFile(f.FullName))
using (Bitmap bitmapNew = new Bitmap(imagesize))
{
double maxWidth = wid;
double maxHeight = hght;
int w = imagesize.Width;
int h = imagesize.Height;
// Longest and shortest dimension
int longestDimension = (w > h) ? w : h;
int shortestDimension = (w < h) ? w : h;
// propotionality
float factor = ((float)longestDimension) / shortestDimension;
// default width is greater than height
double newWidth = maxWidth;
double newHeight = maxWidth / factor;
// if height greater than width recalculate
if (w < h)
{
newWidth = maxHeight / factor;
newHeight = maxHeight;
}
string fileName = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(f.Name) + ".jpeg");
bitmapNew.GetThumbnailImage((int)newWidth, (int)newHeight, () => false, IntPtr.Zero)
.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
```
I have to say few things about your old code:
* use `foreach` when possible;
* avoid the first three lines, they are useless;
* avoid unused variables;
* keep your code as clean as possible; | About the "GDI+ generic error" and the "Out Of Memory" exceptions, you should take a look at that link on SO: [What is the "best" way to create a thumbnail using ASP.NET?](https://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-asp-net)
You must use the C# `using` statement to make sure unmanaged GDI+ resources underneath the .NET surface are freed as quickly as possible to avoid out of memory errors.
The GDI+ generic can happen if the image cannot be converted for example. |
15,256,850 | I am using ASP.NET MVC 4 SimpleMembership "out of the box".
I set the authentication requirement as deco on the controllers with `[Authorize(Roles = "User")].`
It works fine, except when leaving the website without logging out. The next time I come back, `Request.IsAuthenticated` is still true, but when I go to a view, I get "`A network-related or instance-specific error occurred while establishing a connection to SQL.`" In fact, it looks like it is trying to connect to a local database: `"SQLExpress database file auto-creation error'` - in the App\_Data folder. But I have no connection string that points to this, it is all on Azure Sql.
Any idea what this is? And why does it pretend to stay logged in? And why the attempt to create a database?
```
------------------------------------Stack trace-------------------------------------------
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296071
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +889
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +5313314
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
``` | 2013/03/06 | [
"https://Stackoverflow.com/questions/15256850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427188/"
]
| It's most likely due to not passing a valid const char\* to [void perror(const char \*s)](http://pubs.opengroup.org/onlinepubs/009696899/functions/perror.html), which makes the file name in `<filename>: No such file or directory` output as garbage/non printable characters.
>
> The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message, which shall be written to the standard error stream as follows:
>
>
> **First (if s is not a null pointer and the character pointed to by s is not the null byte), the string pointed to by s followed by a colon and a .**
>
>
> Then an error message string followed by a .
>
>
> | I think you correct the warning driveinfo.c:17 or post your code.
And its OK ;)
Good luck ! |
15,256,850 | I am using ASP.NET MVC 4 SimpleMembership "out of the box".
I set the authentication requirement as deco on the controllers with `[Authorize(Roles = "User")].`
It works fine, except when leaving the website without logging out. The next time I come back, `Request.IsAuthenticated` is still true, but when I go to a view, I get "`A network-related or instance-specific error occurred while establishing a connection to SQL.`" In fact, it looks like it is trying to connect to a local database: `"SQLExpress database file auto-creation error'` - in the App\_Data folder. But I have no connection string that points to this, it is all on Azure Sql.
Any idea what this is? And why does it pretend to stay logged in? And why the attempt to create a database?
```
------------------------------------Stack trace-------------------------------------------
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296071
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +889
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +5313314
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +143
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +83
System.Data.SqlClient.SqlConnection.Open() +96
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386
``` | 2013/03/06 | [
"https://Stackoverflow.com/questions/15256850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427188/"
]
| It's most likely due to not passing a valid const char\* to [void perror(const char \*s)](http://pubs.opengroup.org/onlinepubs/009696899/functions/perror.html), which makes the file name in `<filename>: No such file or directory` output as garbage/non printable characters.
>
> The perror() function shall map the error number accessed through the symbol errno to a language-dependent error message, which shall be written to the standard error stream as follows:
>
>
> **First (if s is not a null pointer and the character pointed to by s is not the null byte), the string pointed to by s followed by a colon and a .**
>
>
> Then an error message string followed by a .
>
>
> | "varning att skicka heltal utan konvertering ..." sounds like it's a call to `perror` with something that isn't a string, perhaps?
If you post the code, we can probably see more clearly, but I'm pretty sure that warning and the output is related.
Edit: If you pass `filename[25]` to the function, I expect this warning. If you pass `&filename[25]`, then you are probably passing in something that isn't a string at all, so some random bytes gets printed, which could print almost anything. |
10,380,394 | I can add/commit any file/folder to repo but index.php . When I add/commit index.php to any folder under my repo it gives error as below:
```
Command Commit
Adding D:\svn\projects\myrepo\index.php
Error Commit failed (details follow):
Error Repository moved permanently to
Error 'http://mydomain.com/repos/myrepo/!svn/wrk/RANDOM-HASH/';
Error please relocate
Error Repository moved permanently to 'http://mydomain.com/repos/myrepo/'; please relocate
Finished!
```
Repo: under : /var/www/svn/myrepo
url : <http://mydomain.com/repos/myrepo>
svm mod\_dav\_svn on Red hat linux with plesk
committing/adding through windows tortoisesvn
I could not find any clue why is it. I have same configrations on my local centos test server for svn and i can commit anything there including index.php.
What can be possible reason? | 2012/04/30 | [
"https://Stackoverflow.com/questions/10380394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365293/"
]
| There are 3 reasons I can think of that a particular value could be used for the powerup IP:
1. convention - other processors in the same family/brand use the same location, and they want to give their customers a sense of familiarity
2. compatibility
3. certain areas are restricted or enhanced for certain purposes. The [6502](http://en.wikipedia.org/wiki/6502) for example has special faster instructions for accessing the first 256 bytes of memory from 0x00 to 0xff. On that CPU it makes sense to have the CPU start somewhere else. (I don't think the 8086 treats any area of memory specially however.)
compatibility and convention issues aside, the value that the instruction pointer gets when the processor powers up is largely arbitrary. For most models, the IP is intially either very close to the top of its address space (with enough room for a far JMP call to get it to where the real init code is) or at the very bottom (ie 0).
The [wikipedia](http://en.wikipedia.org/wiki/8085) [articles](http://en.wikipedia.org/wiki/Intel_8086) state that the 8086 was designed so that assembly source code from previous processors was easily *converted* to work with the 8086, but that's all. Apart from that there was no attempt to make it compatible with previous models. | I think the answer lies in the Interrupt Vector Table (IVT). The IVT was introduced in the 8086 processor. The 8085 (which's design is based on the 8080 processor) uses a different method for handling interrupts. On the 8086/8088 the IVT takes up the first 1024 bytes of memory (256 interrupt vectors consisting of 4 bytes each). For this reason there cannot be any executable code in that region. Starting with the 80286, x86/x64 processors have an Interrupt Descriptor Table register (IDTR) which can be changed so that software can relocate the interrupt vector table anywhere in the processor's address space where it's convenient.
So technically:
- The 8085 does not have a CS register and its address space is limited to 64KiB
- Execution on the 8085 starts at address 0x0000 after power-on
- Execution on the x86 and x64 family of processors starts at the last 16 bytes of addressable memory. So on 16-bit processors with 20 address lines this would be linear address 0xFFFF0. On 32-bit processors it's address 0xFFFFFFF0, and on 64-bit processors it's 0xFFFFFFFFFFFFFFF0. The system ROM must be wired to the memory bus in such a way that it will respond to these addresses.
Check out the [Intel processor manuals](http://www.intel.com/p/en_US/support/processors "Intel processor manuals") for the official explanation. |
10,380,394 | I can add/commit any file/folder to repo but index.php . When I add/commit index.php to any folder under my repo it gives error as below:
```
Command Commit
Adding D:\svn\projects\myrepo\index.php
Error Commit failed (details follow):
Error Repository moved permanently to
Error 'http://mydomain.com/repos/myrepo/!svn/wrk/RANDOM-HASH/';
Error please relocate
Error Repository moved permanently to 'http://mydomain.com/repos/myrepo/'; please relocate
Finished!
```
Repo: under : /var/www/svn/myrepo
url : <http://mydomain.com/repos/myrepo>
svm mod\_dav\_svn on Red hat linux with plesk
committing/adding through windows tortoisesvn
I could not find any clue why is it. I have same configrations on my local centos test server for svn and i can commit anything there including index.php.
What can be possible reason? | 2012/04/30 | [
"https://Stackoverflow.com/questions/10380394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365293/"
]
| There are 3 reasons I can think of that a particular value could be used for the powerup IP:
1. convention - other processors in the same family/brand use the same location, and they want to give their customers a sense of familiarity
2. compatibility
3. certain areas are restricted or enhanced for certain purposes. The [6502](http://en.wikipedia.org/wiki/6502) for example has special faster instructions for accessing the first 256 bytes of memory from 0x00 to 0xff. On that CPU it makes sense to have the CPU start somewhere else. (I don't think the 8086 treats any area of memory specially however.)
compatibility and convention issues aside, the value that the instruction pointer gets when the processor powers up is largely arbitrary. For most models, the IP is intially either very close to the top of its address space (with enough room for a far JMP call to get it to where the real init code is) or at the very bottom (ie 0).
The [wikipedia](http://en.wikipedia.org/wiki/8085) [articles](http://en.wikipedia.org/wiki/Intel_8086) state that the 8086 was designed so that assembly source code from previous processors was easily *converted* to work with the 8086, but that's all. Apart from that there was no attempt to make it compatible with previous models. | 1)In 8085 , upon reset the value of pc is 0000h. Therefore the wake up program should be written at 0000h location and can't be kept empty.
2) In 8086, reset values of CS & lP are FFFFH & 0000h resp. So 20 bit physical address will be FFFF0+0000=FFFF0H. It shouldn't be kept empty. Wake up program(code) is always in ROM and there for the ROM should be interfaced at last to cover FFFF0H. |
10,380,394 | I can add/commit any file/folder to repo but index.php . When I add/commit index.php to any folder under my repo it gives error as below:
```
Command Commit
Adding D:\svn\projects\myrepo\index.php
Error Commit failed (details follow):
Error Repository moved permanently to
Error 'http://mydomain.com/repos/myrepo/!svn/wrk/RANDOM-HASH/';
Error please relocate
Error Repository moved permanently to 'http://mydomain.com/repos/myrepo/'; please relocate
Finished!
```
Repo: under : /var/www/svn/myrepo
url : <http://mydomain.com/repos/myrepo>
svm mod\_dav\_svn on Red hat linux with plesk
committing/adding through windows tortoisesvn
I could not find any clue why is it. I have same configrations on my local centos test server for svn and i can commit anything there including index.php.
What can be possible reason? | 2012/04/30 | [
"https://Stackoverflow.com/questions/10380394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365293/"
]
| I think the answer lies in the Interrupt Vector Table (IVT). The IVT was introduced in the 8086 processor. The 8085 (which's design is based on the 8080 processor) uses a different method for handling interrupts. On the 8086/8088 the IVT takes up the first 1024 bytes of memory (256 interrupt vectors consisting of 4 bytes each). For this reason there cannot be any executable code in that region. Starting with the 80286, x86/x64 processors have an Interrupt Descriptor Table register (IDTR) which can be changed so that software can relocate the interrupt vector table anywhere in the processor's address space where it's convenient.
So technically:
- The 8085 does not have a CS register and its address space is limited to 64KiB
- Execution on the 8085 starts at address 0x0000 after power-on
- Execution on the x86 and x64 family of processors starts at the last 16 bytes of addressable memory. So on 16-bit processors with 20 address lines this would be linear address 0xFFFF0. On 32-bit processors it's address 0xFFFFFFF0, and on 64-bit processors it's 0xFFFFFFFFFFFFFFF0. The system ROM must be wired to the memory bus in such a way that it will respond to these addresses.
Check out the [Intel processor manuals](http://www.intel.com/p/en_US/support/processors "Intel processor manuals") for the official explanation. | 1)In 8085 , upon reset the value of pc is 0000h. Therefore the wake up program should be written at 0000h location and can't be kept empty.
2) In 8086, reset values of CS & lP are FFFFH & 0000h resp. So 20 bit physical address will be FFFF0+0000=FFFF0H. It shouldn't be kept empty. Wake up program(code) is always in ROM and there for the ROM should be interfaced at last to cover FFFF0H. |
2,110,193 | I was doing some exercise about Maclaurin expansion when I notice something, I used to remember the series formula of some common functions with $x$ as argument, but when I had to calculate the expansion for the same function but with $x^2$ as argument, for example, I always recalculate the series from scratch.
Then I started to realise that I could have just substituted $x$ with $x^2$. So is it wrong to say that, given a polynomial function $P(x)$ which represent the series of Maclaurin for a function $f(x)$, the series of Maclaurin for $f(g(x))$ is equal to $P(g(x))$ when $g(x)$ approach to $0$?
If it's not completely wrong can you give me some hints in order to understand when it's correct? | 2017/01/23 | [
"https://math.stackexchange.com/questions/2110193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409374/"
]
| If $P$ converges within the disc $|x|<R$, then substituting $g(x)$ into the argument of $P$ changes the disc into $|g(x)|<R$. As long as this is obeyed, $P(g(x))$ converges. | As always,
for this type of question
on generating functions,
the book "generatingfunctionology"
is a great reference.
It can be downloaded for free here:
<https://www.math.upenn.edu/~wilf/DownldGF.html> |
2,110,193 | I was doing some exercise about Maclaurin expansion when I notice something, I used to remember the series formula of some common functions with $x$ as argument, but when I had to calculate the expansion for the same function but with $x^2$ as argument, for example, I always recalculate the series from scratch.
Then I started to realise that I could have just substituted $x$ with $x^2$. So is it wrong to say that, given a polynomial function $P(x)$ which represent the series of Maclaurin for a function $f(x)$, the series of Maclaurin for $f(g(x))$ is equal to $P(g(x))$ when $g(x)$ approach to $0$?
If it's not completely wrong can you give me some hints in order to understand when it's correct? | 2017/01/23 | [
"https://math.stackexchange.com/questions/2110193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409374/"
]
| If $P$ converges within the disc $|x|<R$, then substituting $g(x)$ into the argument of $P$ changes the disc into $|g(x)|<R$. As long as this is obeyed, $P(g(x))$ converges. | Check out page 66 of Serge Lang's complex analysis textbook (4th edition).
He states and proves a theorem which tells you sufficient conditions for composing two power series formally (making no allusions to the analytic properties of the series).
In addition to the radius of convergence conditions alluded to in answers above, the odd requirement is that the inner series, $h$ in
$$
f(h(x))=g(x)
$$
has constant term zero. |
2,110,193 | I was doing some exercise about Maclaurin expansion when I notice something, I used to remember the series formula of some common functions with $x$ as argument, but when I had to calculate the expansion for the same function but with $x^2$ as argument, for example, I always recalculate the series from scratch.
Then I started to realise that I could have just substituted $x$ with $x^2$. So is it wrong to say that, given a polynomial function $P(x)$ which represent the series of Maclaurin for a function $f(x)$, the series of Maclaurin for $f(g(x))$ is equal to $P(g(x))$ when $g(x)$ approach to $0$?
If it's not completely wrong can you give me some hints in order to understand when it's correct? | 2017/01/23 | [
"https://math.stackexchange.com/questions/2110193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409374/"
]
| The most important point here is that each function has a unique Taylor Series at a each point in its domain. You might find different ways to write the same series, but in the end the forms are really the same. In your case, this means that both a substitution and a direct calculation will give the valid Taylor Series (though the series might look a bit different).
Moreover, as pointed out prior, you will have to be careful about where your new series converges when you substitute. *Always ensure you are in the disk of convergence for your new series when you substitute*. | As always,
for this type of question
on generating functions,
the book "generatingfunctionology"
is a great reference.
It can be downloaded for free here:
<https://www.math.upenn.edu/~wilf/DownldGF.html> |
2,110,193 | I was doing some exercise about Maclaurin expansion when I notice something, I used to remember the series formula of some common functions with $x$ as argument, but when I had to calculate the expansion for the same function but with $x^2$ as argument, for example, I always recalculate the series from scratch.
Then I started to realise that I could have just substituted $x$ with $x^2$. So is it wrong to say that, given a polynomial function $P(x)$ which represent the series of Maclaurin for a function $f(x)$, the series of Maclaurin for $f(g(x))$ is equal to $P(g(x))$ when $g(x)$ approach to $0$?
If it's not completely wrong can you give me some hints in order to understand when it's correct? | 2017/01/23 | [
"https://math.stackexchange.com/questions/2110193",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/409374/"
]
| The most important point here is that each function has a unique Taylor Series at a each point in its domain. You might find different ways to write the same series, but in the end the forms are really the same. In your case, this means that both a substitution and a direct calculation will give the valid Taylor Series (though the series might look a bit different).
Moreover, as pointed out prior, you will have to be careful about where your new series converges when you substitute. *Always ensure you are in the disk of convergence for your new series when you substitute*. | Check out page 66 of Serge Lang's complex analysis textbook (4th edition).
He states and proves a theorem which tells you sufficient conditions for composing two power series formally (making no allusions to the analytic properties of the series).
In addition to the radius of convergence conditions alluded to in answers above, the odd requirement is that the inner series, $h$ in
$$
f(h(x))=g(x)
$$
has constant term zero. |
55,633,162 | I have a dataset in following format.
>
> row\_num;locale;day\_of\_week;hour\_of\_day;agent\_id;entry\_page;path\_id\_set;traffic\_type;session\_durantion;hits
>
> "988681;L6;Monday;17;1;2111;""31672;0"";6;7037;\N"
> "988680;L2;Thursday;22;10;2113;""31965;0"";2;49;14"
> "988679;L4;Saturday;21;2;2100;""0;78464"";1;1892;14"
> "988678;L3;Saturday;19;8;2113;51462;6;0;1;\N"
>
>
>
I want it to be in following format :
>
> row\_num locale day\_of\_week hour\_of\_day agent\_id entry\_page path\_id\_set traffic\_type session\_durantion hits
>
> 988681 L6 Monday 17 1 2111 31672 0 6 7037 N
>
> 988680 L2 Thursday 22 10 2113 31965 0 2 49 14
>
> 988679 L4 Saturday 21 2 2100 0 78464 1 1892 14
>
> 988678 L3 Saturday 19 8 2113 51462 6 0 1 N
>
>
>
I tried with the following code :
```
import pandas as pd
df = pd.read_csv("C:\Users\Rahhy\Desktop\trivago.csv", delimiter = ";")
```
But I am getting a error as :
```
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
``` | 2019/04/11 | [
"https://Stackoverflow.com/questions/55633162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11345901/"
]
| The simplest way is to create a file in the directory structure and use mkelem -mkpath...
I created a "temp1" directory, and a "temp2" directory, and a "temp.txt" file in one of my sandbox vobs, then added the file to source control with -mkpath from the parent of the "temp1" view private directory.
```
PS M:\tempview\foobarf\Documents> cleartool mkelem -mkpath .\temp1\temp2\temp.txt
Creating parent directory element ".\temp1\temp2".
Creating parent directory element ".\temp1".
Created directory element ".\temp1".
Checking out parent directory ".\temp1".
Created directory element ".\temp1\temp2".
Checking out parent directory ".\temp1\temp2".
Creation comments for ".\temp1\temp2\temp.txt":
Test1.
.
Created element ".\temp1\temp2\temp.txt" (type "utf16le_file").
Checked out ".\temp1\temp2\temp.txt" from version "\main\0".
```
It's UTF-16LE because Powershell's Locale is wide character and the "temp.txt" was created using "dir > temp1\temp2\temp.txt". | `cleartool mkelem -mkpath` is a good option when adding *one* file.
But if you have *multiple* files to add, in a tree structure which does not exist yet, don't forget about [`clearfsimport`](https://www.ibm.com/support/knowledgecenter/en/SSSH27_9.0.1/com.ibm.rational.clearcase.cc_ref.doc/topics/clearfsimport.htm): it can [import flat files to a branch](https://www-01.ibm.com/support/docview.wss?uid=swg21228449) in one command, and will create any missing folder for you.
As [seen here](https://stackoverflow.com/q/36478572/6309): `clearfsimport -rec -nset <Source> <target>` |
6,873,184 | ```
static final ArrayList<HashMap<String,String>> arraylistobject = new ArrayList<HashMap<String,String>>();
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen","MONT Blanc");
temp.put("price", "200 rs");
arraylistobject.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("pen","Gucci");
temp1.put("price", "300 rs");
arraylistobject.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("pen","Parker");
temp2.put("price", "400 rs");
arraylistobject.add(temp2);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("pen","Sailor");
temp3.put("price", "500 rs");
arraylistobject.add(temp3);
HashMap<String,String> temp4 = new HashMap<String,String>();
temp4.put("pen","Porsche Design");
temp4.put("price", "600 rs");
arraylistobject.add(temp4);
``` | 2011/07/29 | [
"https://Stackoverflow.com/questions/6873184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/869373/"
]
| You can use a loop to create the HashMaps and add them to your List, but you still have to do something about those hard-coded String literals.
```
for(int i = 0; i < 150; i++) {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen", "MONT Blanc");
temp.put("price", "200 rs");
arraylistobject.add(temp);
}
```
You could read the values that you put in the `temp` map from a configuration file or a database to initialize the List, but that's a whole other issue.
You should also check out the [Java Tutorials: Collections](http://download.oracle.com/javase/tutorial/collections/index.html) articles. | A `List` is meant to grow, not have a pre-initialised size. So if you want 150 as the length, you should add 150 elements to the list. Otherwise, stick to arrays. |
6,873,184 | ```
static final ArrayList<HashMap<String,String>> arraylistobject = new ArrayList<HashMap<String,String>>();
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen","MONT Blanc");
temp.put("price", "200 rs");
arraylistobject.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("pen","Gucci");
temp1.put("price", "300 rs");
arraylistobject.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("pen","Parker");
temp2.put("price", "400 rs");
arraylistobject.add(temp2);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("pen","Sailor");
temp3.put("price", "500 rs");
arraylistobject.add(temp3);
HashMap<String,String> temp4 = new HashMap<String,String>();
temp4.put("pen","Porsche Design");
temp4.put("price", "600 rs");
arraylistobject.add(temp4);
``` | 2011/07/29 | [
"https://Stackoverflow.com/questions/6873184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/869373/"
]
| You can use a loop to create the HashMaps and add them to your List, but you still have to do something about those hard-coded String literals.
```
for(int i = 0; i < 150; i++) {
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("pen", "MONT Blanc");
temp.put("price", "200 rs");
arraylistobject.add(temp);
}
```
You could read the values that you put in the `temp` map from a configuration file or a database to initialize the List, but that's a whole other issue.
You should also check out the [Java Tutorials: Collections](http://download.oracle.com/javase/tutorial/collections/index.html) articles. | Pretty sure this is what you're looking for:
```
HashMap temp5 = new HashMap();
arraylistobject.add(temp5);
HashMap temp6 = new HashMap();
arraylistobject.add(temp6);
HashMap temp7 = new HashMap();
arraylistobject.add(temp7);
HashMap temp8 = new HashMap();
arraylistobject.add(temp8);
HashMap temp9 = new HashMap();
arraylistobject.add(temp9);
HashMap temp10 = new HashMap();
arraylistobject.add(temp10);
HashMap temp11 = new HashMap();
arraylistobject.add(temp11);
HashMap temp12 = new HashMap();
arraylistobject.add(temp12);
HashMap temp13 = new HashMap();
arraylistobject.add(temp13);
HashMap temp14 = new HashMap();
arraylistobject.add(temp14);
HashMap temp15 = new HashMap();
arraylistobject.add(temp15);
HashMap temp16 = new HashMap();
arraylistobject.add(temp16);
HashMap temp17 = new HashMap();
arraylistobject.add(temp17);
HashMap temp18 = new HashMap();
arraylistobject.add(temp18);
HashMap temp19 = new HashMap();
arraylistobject.add(temp19);
HashMap temp20 = new HashMap();
arraylistobject.add(temp20);
HashMap temp21 = new HashMap();
arraylistobject.add(temp21);
HashMap temp22 = new HashMap();
arraylistobject.add(temp22);
HashMap temp23 = new HashMap();
arraylistobject.add(temp23);
HashMap temp24 = new HashMap();
arraylistobject.add(temp24);
HashMap temp25 = new HashMap();
arraylistobject.add(temp25);
HashMap temp26 = new HashMap();
arraylistobject.add(temp26);
HashMap temp27 = new HashMap();
arraylistobject.add(temp27);
HashMap temp28 = new HashMap();
arraylistobject.add(temp28);
HashMap temp29 = new HashMap();
arraylistobject.add(temp29);
HashMap temp30 = new HashMap();
arraylistobject.add(temp30);
HashMap temp31 = new HashMap();
arraylistobject.add(temp31);
HashMap temp32 = new HashMap();
arraylistobject.add(temp32);
HashMap temp33 = new HashMap();
arraylistobject.add(temp33);
HashMap temp34 = new HashMap();
arraylistobject.add(temp34);
HashMap temp35 = new HashMap();
arraylistobject.add(temp35);
HashMap temp36 = new HashMap();
arraylistobject.add(temp36);
HashMap temp37 = new HashMap();
arraylistobject.add(temp37);
HashMap temp38 = new HashMap();
arraylistobject.add(temp38);
HashMap temp39 = new HashMap();
arraylistobject.add(temp39);
HashMap temp40 = new HashMap();
arraylistobject.add(temp40);
HashMap temp41 = new HashMap();
arraylistobject.add(temp41);
HashMap temp42 = new HashMap();
arraylistobject.add(temp42);
HashMap temp43 = new HashMap();
arraylistobject.add(temp43);
HashMap temp44 = new HashMap();
arraylistobject.add(temp44);
HashMap temp45 = new HashMap();
arraylistobject.add(temp45);
HashMap temp46 = new HashMap();
arraylistobject.add(temp46);
HashMap temp47 = new HashMap();
arraylistobject.add(temp47);
HashMap temp48 = new HashMap();
arraylistobject.add(temp48);
HashMap temp49 = new HashMap();
arraylistobject.add(temp49);
HashMap temp50 = new HashMap();
arraylistobject.add(temp50);
HashMap temp51 = new HashMap();
arraylistobject.add(temp51);
HashMap temp52 = new HashMap();
arraylistobject.add(temp52);
HashMap temp53 = new HashMap();
arraylistobject.add(temp53);
HashMap temp54 = new HashMap();
arraylistobject.add(temp54);
HashMap temp55 = new HashMap();
arraylistobject.add(temp55);
HashMap temp56 = new HashMap();
arraylistobject.add(temp56);
HashMap temp57 = new HashMap();
arraylistobject.add(temp57);
HashMap temp58 = new HashMap();
arraylistobject.add(temp58);
HashMap temp59 = new HashMap();
arraylistobject.add(temp59);
HashMap temp60 = new HashMap();
arraylistobject.add(temp60);
HashMap temp61 = new HashMap();
arraylistobject.add(temp61);
HashMap temp62 = new HashMap();
arraylistobject.add(temp62);
HashMap temp63 = new HashMap();
arraylistobject.add(temp63);
HashMap temp64 = new HashMap();
arraylistobject.add(temp64);
HashMap temp65 = new HashMap();
arraylistobject.add(temp65);
HashMap temp66 = new HashMap();
arraylistobject.add(temp66);
HashMap temp67 = new HashMap();
arraylistobject.add(temp67);
HashMap temp68 = new HashMap();
arraylistobject.add(temp68);
HashMap temp69 = new HashMap();
arraylistobject.add(temp69);
HashMap temp70 = new HashMap();
arraylistobject.add(temp70);
HashMap temp71 = new HashMap();
arraylistobject.add(temp71);
HashMap temp72 = new HashMap();
arraylistobject.add(temp72);
HashMap temp73 = new HashMap();
arraylistobject.add(temp73);
HashMap temp74 = new HashMap();
arraylistobject.add(temp74);
HashMap temp75 = new HashMap();
arraylistobject.add(temp75);
HashMap temp76 = new HashMap();
arraylistobject.add(temp76);
HashMap temp77 = new HashMap();
arraylistobject.add(temp77);
HashMap temp78 = new HashMap();
arraylistobject.add(temp78);
HashMap temp79 = new HashMap();
arraylistobject.add(temp79);
HashMap temp80 = new HashMap();
arraylistobject.add(temp80);
HashMap temp81 = new HashMap();
arraylistobject.add(temp81);
HashMap temp82 = new HashMap();
arraylistobject.add(temp82);
HashMap temp83 = new HashMap();
arraylistobject.add(temp83);
HashMap temp84 = new HashMap();
arraylistobject.add(temp84);
HashMap temp85 = new HashMap();
arraylistobject.add(temp85);
HashMap temp86 = new HashMap();
arraylistobject.add(temp86);
HashMap temp87 = new HashMap();
arraylistobject.add(temp87);
HashMap temp88 = new HashMap();
arraylistobject.add(temp88);
HashMap temp89 = new HashMap();
arraylistobject.add(temp89);
HashMap temp90 = new HashMap();
arraylistobject.add(temp90);
HashMap temp91 = new HashMap();
arraylistobject.add(temp91);
HashMap temp92 = new HashMap();
arraylistobject.add(temp92);
HashMap temp93 = new HashMap();
arraylistobject.add(temp93);
HashMap temp94 = new HashMap();
arraylistobject.add(temp94);
HashMap temp95 = new HashMap();
arraylistobject.add(temp95);
HashMap temp96 = new HashMap();
arraylistobject.add(temp96);
HashMap temp97 = new HashMap();
arraylistobject.add(temp97);
HashMap temp98 = new HashMap();
arraylistobject.add(temp98);
HashMap temp99 = new HashMap();
arraylistobject.add(temp99);
HashMap temp100 = new HashMap();
arraylistobject.add(temp100);
HashMap temp101 = new HashMap();
arraylistobject.add(temp101);
HashMap temp102 = new HashMap();
arraylistobject.add(temp102);
HashMap temp103 = new HashMap();
arraylistobject.add(temp103);
HashMap temp104 = new HashMap();
arraylistobject.add(temp104);
HashMap temp105 = new HashMap();
arraylistobject.add(temp105);
HashMap temp106 = new HashMap();
arraylistobject.add(temp106);
HashMap temp107 = new HashMap();
arraylistobject.add(temp107);
HashMap temp108 = new HashMap();
arraylistobject.add(temp108);
HashMap temp109 = new HashMap();
arraylistobject.add(temp109);
HashMap temp110 = new HashMap();
arraylistobject.add(temp110);
HashMap temp111 = new HashMap();
arraylistobject.add(temp111);
HashMap temp112 = new HashMap();
arraylistobject.add(temp112);
HashMap temp113 = new HashMap();
arraylistobject.add(temp113);
HashMap temp114 = new HashMap();
arraylistobject.add(temp114);
HashMap temp115 = new HashMap();
arraylistobject.add(temp115);
HashMap temp116 = new HashMap();
arraylistobject.add(temp116);
HashMap temp117 = new HashMap();
arraylistobject.add(temp117);
HashMap temp118 = new HashMap();
arraylistobject.add(temp118);
HashMap temp119 = new HashMap();
arraylistobject.add(temp119);
HashMap temp120 = new HashMap();
arraylistobject.add(temp120);
HashMap temp121 = new HashMap();
arraylistobject.add(temp121);
HashMap temp122 = new HashMap();
arraylistobject.add(temp122);
HashMap temp123 = new HashMap();
arraylistobject.add(temp123);
HashMap temp124 = new HashMap();
arraylistobject.add(temp124);
HashMap temp125 = new HashMap();
arraylistobject.add(temp125);
HashMap temp126 = new HashMap();
arraylistobject.add(temp126);
HashMap temp127 = new HashMap();
arraylistobject.add(temp127);
HashMap temp128 = new HashMap();
arraylistobject.add(temp128);
HashMap temp129 = new HashMap();
arraylistobject.add(temp129);
HashMap temp130 = new HashMap();
arraylistobject.add(temp130);
HashMap temp131 = new HashMap();
arraylistobject.add(temp131);
HashMap temp132 = new HashMap();
arraylistobject.add(temp132);
HashMap temp133 = new HashMap();
arraylistobject.add(temp133);
HashMap temp134 = new HashMap();
arraylistobject.add(temp134);
HashMap temp135 = new HashMap();
arraylistobject.add(temp135);
HashMap temp136 = new HashMap();
arraylistobject.add(temp136);
HashMap temp137 = new HashMap();
arraylistobject.add(temp137);
HashMap temp138 = new HashMap();
arraylistobject.add(temp138);
HashMap temp139 = new HashMap();
arraylistobject.add(temp139);
HashMap temp140 = new HashMap();
arraylistobject.add(temp140);
HashMap temp141 = new HashMap();
arraylistobject.add(temp141);
HashMap temp142 = new HashMap();
arraylistobject.add(temp142);
HashMap temp143 = new HashMap();
arraylistobject.add(temp143);
HashMap temp144 = new HashMap();
arraylistobject.add(temp144);
HashMap temp145 = new HashMap();
arraylistobject.add(temp145);
HashMap temp146 = new HashMap();
arraylistobject.add(temp146);
HashMap temp147 = new HashMap();
arraylistobject.add(temp147);
HashMap temp148 = new HashMap();
arraylistobject.add(temp148);
HashMap temp149 = new HashMap();
arraylistobject.add(temp149);
HashMap temp150 = new HashMap();
arraylistobject.add(temp150);
``` |
17,282,507 | How can I change name of uploaded file in Laravel 4.
So far I have been doing it like this:
```
$file = Input::file('file');
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();
```
But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like `(2)` added at the end of the second file name or to change the file name completely | 2013/06/24 | [
"https://Stackoverflow.com/questions/17282507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291189/"
]
| The first step is to check if the file exists. If it doesn't, extract the filename and extension with [`pathinfo()`](http://php.net/pathinfo) and then rename it with the following code:
```
$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
$filecounter = 1;
while (file_exists($destinationPath)) {
$img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
$destinationPath = $destinationPath . $img_duplicate;
}
```
The loop will continue renaming files as `file_1`, `file_2` etc. as long as the condition `file_exists($destinationPath)` returns true. | I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:
(... in the controller: ... )
```
$path = public_path().'\\uploads\\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);
```
this function get an "unused" filename:
```
public function getNewFileName($filename, $extension, $path){
$i = 1;
$new_filename = $filename.'.'.$extension;
while( File::exists($path.$new_filename) )
$new_filename = $filename.' ('.$i++.').'.$extension;
return $new_filename;
}
``` |
61,329,435 | I need to reverse taking element from array. I have to start from the last one. I can't find any different solution to use in Cypress than jQuery 'reverse' but I have problem to use it.
Don't work in both way:
```
cy.get('.btn-remove.action.delete').reverse().each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - TypeError: cy.get(...).reverse is not a function
And
```
cy.get('.btn-remove.action.delete').invoke('reverse').each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - CypressError: Timed out retrying: cy.invoke() errored because the property: 'reverse' does not exist on your subject.
Or maybe there is different way than reverse()? | 2020/04/20 | [
"https://Stackoverflow.com/questions/61329435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13364935/"
]
| What about trying with for loop and iterating from the end, using [eq()](https://docs.cypress.io/api/commands/eq.html):
```
cy.get('.btn-remove.action.delete').its('length').then((numberOfItems) => {
for (var i = numberOfItems-1; i>=0; i--) {
cy.get('.btn-remove.action.delete').eq(i).click({force:true})
}
})
```
Maybe it is not the cleanest way, but should work.
Not sure what was the cy.wait(1000) for in your code, but it shouldn't be necessary here. [(Actually, you should avoid using cy.wait() as much as possible)](https://docs.cypress.io/guides/references/best-practices.html#Unnecessary-Waiting)
Let me know if you have any questions. | the eq solution implemented with .each()
```
cy.get('[data-cy="sections"] > optgroup > option').each(
(_$option, index, $list) => {
const firstIndex = 0;
const lastIndex = $list.length - 1;
const descendingIndex = lastIndex - index;
cy.wrap($list).eq(descendingIndex).click({force:true})
}
);
```
Cons:
* $list: HTMLElement[] instead of JQuery<HTMLElement[]>
+ We have to use javascript to get access the $list
+ We cannot use $list[descendingIndex].text() or $list[descendingIndex].val()
+ Instead we can use $list.innerHTML, $list.[descendingIndex].click() or ($list).value
I recommend to use cy.wrap($list).(cypress command) for actions
and if we need access to some string, number, or value, use javascript to get it from the $list. |
61,329,435 | I need to reverse taking element from array. I have to start from the last one. I can't find any different solution to use in Cypress than jQuery 'reverse' but I have problem to use it.
Don't work in both way:
```
cy.get('.btn-remove.action.delete').reverse().each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - TypeError: cy.get(...).reverse is not a function
And
```
cy.get('.btn-remove.action.delete').invoke('reverse').each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - CypressError: Timed out retrying: cy.invoke() errored because the property: 'reverse' does not exist on your subject.
Or maybe there is different way than reverse()? | 2020/04/20 | [
"https://Stackoverflow.com/questions/61329435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13364935/"
]
| What about trying with for loop and iterating from the end, using [eq()](https://docs.cypress.io/api/commands/eq.html):
```
cy.get('.btn-remove.action.delete').its('length').then((numberOfItems) => {
for (var i = numberOfItems-1; i>=0; i--) {
cy.get('.btn-remove.action.delete').eq(i).click({force:true})
}
})
```
Maybe it is not the cleanest way, but should work.
Not sure what was the cy.wait(1000) for in your code, but it shouldn't be necessary here. [(Actually, you should avoid using cy.wait() as much as possible)](https://docs.cypress.io/guides/references/best-practices.html#Unnecessary-Waiting)
Let me know if you have any questions. | You can apply `reverse()` like this
```js
cy.get('[data-cy="sections"] > optgroup > option')
.then($options => $options.get().reverse())
.each($option => { // reverse order
...
})
```
Note the reverse method is `Array.reverse()` so you need to precede it with jQuery `.get()`. |
61,329,435 | I need to reverse taking element from array. I have to start from the last one. I can't find any different solution to use in Cypress than jQuery 'reverse' but I have problem to use it.
Don't work in both way:
```
cy.get('.btn-remove.action.delete').reverse().each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - TypeError: cy.get(...).reverse is not a function
And
```
cy.get('.btn-remove.action.delete').invoke('reverse').each(($el, index, $list) => {
cy.get($el).click({force:true})
cy.wait(1000)
})
```
answer from Cypress - CypressError: Timed out retrying: cy.invoke() errored because the property: 'reverse' does not exist on your subject.
Or maybe there is different way than reverse()? | 2020/04/20 | [
"https://Stackoverflow.com/questions/61329435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13364935/"
]
| You can apply `reverse()` like this
```js
cy.get('[data-cy="sections"] > optgroup > option')
.then($options => $options.get().reverse())
.each($option => { // reverse order
...
})
```
Note the reverse method is `Array.reverse()` so you need to precede it with jQuery `.get()`. | the eq solution implemented with .each()
```
cy.get('[data-cy="sections"] > optgroup > option').each(
(_$option, index, $list) => {
const firstIndex = 0;
const lastIndex = $list.length - 1;
const descendingIndex = lastIndex - index;
cy.wrap($list).eq(descendingIndex).click({force:true})
}
);
```
Cons:
* $list: HTMLElement[] instead of JQuery<HTMLElement[]>
+ We have to use javascript to get access the $list
+ We cannot use $list[descendingIndex].text() or $list[descendingIndex].val()
+ Instead we can use $list.innerHTML, $list.[descendingIndex].click() or ($list).value
I recommend to use cy.wrap($list).(cypress command) for actions
and if we need access to some string, number, or value, use javascript to get it from the $list. |
68,839,163 | I have a base class and a class template, and I want to be able to instantiate it as follows:
```
class Base
{
};
template<int i>
class Foo
{
};
namespace SomeEnum
{
enum
{
First,
Second,
Third,
...
Last
};
}
void bar()
{
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum::Last;
ptr = std::make_unique<Foo<fooType>> // Causes error because I'm passing a run-time value to something that expects a compile-time value
}
```
The enum used to be a class enum but I changed it to a regular enum so that I could use the design presented above, since the enum in question is quite large. I thought I was being clever at the time but I now realize I had kind of forgotten that templates are handled at compile-time.
Is there any way to circumvent this, without completely changing my design? I could obviously do something like this:
```
switch(fooType)
{
case 0:
ptr = std::make_unique<Foo<0>>();
break;
case 1:
ptr = std::make_unique<Foo<1>>();
break;
...
}
```
But it doesn't look very elegant and pretty much removes the motivation for not just using a class enum since I will have to make a switch case for every value in the enum. Is there any other solution, or have I painted myself into a corner with this design? | 2021/08/18 | [
"https://Stackoverflow.com/questions/68839163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13699024/"
]
| Some metaprogramming utility stuff:
```
template<class T>
struct tag_t {using type=T;};
template<class T>
constexpr tag_t<T> tag{};
template<auto I>
using constant_t = std::integral_constant<std::decay_t<decltype(I)>, I>;
template<auto I>
constexpr constant_t<I> constant{};
template<class T, T...ts>
struct sequence{};
```
We need `sequence` because `std::integer_sequence` is overspecified.
Now we have our enum:
```
enum class SomeEnum {
A,B,C,
ValueCount,
};
```
Some enum helpers:
```
template<class E, std::size_t...Is>
constexpr auto EnumsSequence( std::index_sequence<Is...> ) {
return sequence<E, static_cast<E>(Is)...>{};
}
template<class E> // requires E::ValueCount
constexpr std::size_t EnumsSize(tag_t<E> =tag<E>) {
return static_cast<std::size_t>(E::ValueCount);
}
template<class E> // requires E::ValueCount
constexpr auto EnumsSequence(tag_t<E> =tag<E>) {
return EnumsSequence<E>(std::make_index_sequence< EnumsSize(tag<E>) >{} );
}
template<class E>
using make_enums_sequence = decltype( EnumsSequence(tag<E>) );
```
we can now do `make_enums_sequence<SomeEnum>` and get `std::integral_sequence<SomeEnum, SomeEnum::A, SomeEnum::B, SomeEnum::C>`. Woo, really basic compile-time reflection. It works on any type with a `ValueCount` enumerator, or you can override `EnumsSize(tag_t<E>)` and/or `EnumsSequence(tag_t<E>)` for a specific type if you have a different convention.
Next we want to make a variant from an `integral_sequence`:
```
template<class S>
struct variant_over_helper;
template<class E, E...es>
struct variant_over_helper< sequence<E, es...> > {
using type=std::variant< constant_t<es>... >;
};
template<class E>
using variant_over_t = typename variant_over_helper<make_enums_sequence<E>>::type;
```
let us think about the variant `variant_over_t<SomeEnum>`.
It contains an index of what alternative it holds. Alternative number 0 corresponds to `SomeEnum::A`, whose value is 0. Alternative number 1 corresponds to `SomeEnum::B`.
Basically, `variant_over_t<SomeEnum>` a struct containing an integer that lines up with `SomeEnum`'s value. Except we can `std::visit` this variant. Bwahahah.
Next we need to be able to convert a runtime `SomeEnum` to a `variant_over_t<SomeEnum>`.
```
template<class E, E... es>
variant_over_t<E> get_variant_enum( sequence<E, es...>, E e ) {
using generator = variant_over_t<E>(*)();
const generator gen[] = {
[]()->variant_over_t<E> {
return constant<es>;
}...
};
return gen[ static_cast<std::size_t>(e) ]();
}
template<class E>
variant_over_t<E> get_variant_enum( E e ) {
return get_variant_enum( EnumsSequence(tag<E>), e );
}
```
and we are done.
```
struct Base{
virtual ~Base() {}
};
enum class SomeEnum
{
First,
Second,
Third,
ValueCount
};
template<SomeEnum i>
struct Foo:Base{};
void bar()
{
std::unique_ptr<Base> ptr;
SomeEnum fooType = static_cast<SomeEnum>( rand() % (int)SomeEnum::ValueCount );
auto vFooType = get_variant_enum(fooType);
ptr = std::visit( [](auto efoo)->std::unique_ptr<Base>{
return std::make_unique<Foo<efoo>>();
}, vFooType );
}
```
[Live example](https://godbolt.org/z/b4dbxez37).
Note that this *requires* that your enum be contiguous and start at 0 (for the `gen[]` array lookup). Some work could be done to handle non-contiguous cases, but that gets complex, so no don't do it. (use `EnumsSequence` to either build a if-tree to find what index to use with `std::in_place_index_t<I>` or `constant<E>`, and/or build an enum-to-index mapping.)
This code runs in O(1) time, not counting data that can be initialized once.
I used `ValueCount` as the number of elements in the enum. If you really need it to be called `Last`, simply add:
```
constexpr std::size_t EnumsSize( tag_t<decltype(SomeEnum::Last)> ) {
return static_cast<std::size_t>(SomeEnum::Last);
}
```
to the namespace of `tag_t` **or** the namespace of `SomeEnum`, and all of the code automatically adapts via argument dependent lookup.
Best part? All of that metaprogramming to create `get_variant_enum` complies down to:
```
movzx edx, ah
mov WORD PTR [rsp+14], ax
```
ie, copy some bytes over.
The visit call is a bit more complex. | There is possibility to make it feasible. That is to use `tuple` which stores `std::make_unique` functions corresponding to enum size.
A helper method to generate the `tuple` using `index_sequence`
```
template<std::size_t... I>
auto generate(std::index_sequence<I...>)
{
return std::make_tuple(std::make_unique<Foo<I>>...);
}
```
Next, to be able to iterate over it and find the index matching with the wanted value the recursive call is applied to increase it by 1.
```
template<std::size_t I = 0, typename... Tp, typename std::enable_if<I == sizeof...(Tp)>::type* = nullptr>
void make(const std::tuple<Tp...> &, std::unique_ptr<Base>&, int) // Unused arguments are given no names.
{ return;}
template<std::size_t I = 0, typename... Tp, typename std::enable_if<I < sizeof...(Tp)>::type* = nullptr>
void make(const std::tuple<Tp...>& t, std::unique_ptr<Base>& p, int value)
{
if (value == I) {
p = std::get<I>(t)();
}
make<I + 1, Tp...>(t, p, value);
}
```
Combine two above methods, you can simply do
```
auto t = generate(std::make_index_sequence<4>{});
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum::Last;
make(t, ptr, fooType);
``` |
68,839,163 | I have a base class and a class template, and I want to be able to instantiate it as follows:
```
class Base
{
};
template<int i>
class Foo
{
};
namespace SomeEnum
{
enum
{
First,
Second,
Third,
...
Last
};
}
void bar()
{
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum::Last;
ptr = std::make_unique<Foo<fooType>> // Causes error because I'm passing a run-time value to something that expects a compile-time value
}
```
The enum used to be a class enum but I changed it to a regular enum so that I could use the design presented above, since the enum in question is quite large. I thought I was being clever at the time but I now realize I had kind of forgotten that templates are handled at compile-time.
Is there any way to circumvent this, without completely changing my design? I could obviously do something like this:
```
switch(fooType)
{
case 0:
ptr = std::make_unique<Foo<0>>();
break;
case 1:
ptr = std::make_unique<Foo<1>>();
break;
...
}
```
But it doesn't look very elegant and pretty much removes the motivation for not just using a class enum since I will have to make a switch case for every value in the enum. Is there any other solution, or have I painted myself into a corner with this design? | 2021/08/18 | [
"https://Stackoverflow.com/questions/68839163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13699024/"
]
| A simple solution would be this:
```
namespace detail {
template<size_t I>
std::unique_ptr<Base> makeForIndex() {
return std::make_unique<Foo<I>>();
}
template<size_t... Is>
auto makeFoo(size_t nIdx, std::index_sequence<Is...>) {
using FuncType = std::unique_ptr<Base>(*)();
constexpr FuncType arFuncs[] = {
detail::makeForIndex<Is>...
};
return arFuncs[nIdx]();
}
}
auto makeFoo(size_t nIdx) {
return detail::makeFoo(nIdx, std::make_index_sequence<SomeEnum::Last>());
}
```
This would not require template recursion either and is rather easy to understand. We create an array of function pointers and index into that using the runtime value provided by the caller.
Now you can create your `Foo<n>` like
```
size_t n;
...
auto ptr = makeFoo(n);
``` | There is possibility to make it feasible. That is to use `tuple` which stores `std::make_unique` functions corresponding to enum size.
A helper method to generate the `tuple` using `index_sequence`
```
template<std::size_t... I>
auto generate(std::index_sequence<I...>)
{
return std::make_tuple(std::make_unique<Foo<I>>...);
}
```
Next, to be able to iterate over it and find the index matching with the wanted value the recursive call is applied to increase it by 1.
```
template<std::size_t I = 0, typename... Tp, typename std::enable_if<I == sizeof...(Tp)>::type* = nullptr>
void make(const std::tuple<Tp...> &, std::unique_ptr<Base>&, int) // Unused arguments are given no names.
{ return;}
template<std::size_t I = 0, typename... Tp, typename std::enable_if<I < sizeof...(Tp)>::type* = nullptr>
void make(const std::tuple<Tp...>& t, std::unique_ptr<Base>& p, int value)
{
if (value == I) {
p = std::get<I>(t)();
}
make<I + 1, Tp...>(t, p, value);
}
```
Combine two above methods, you can simply do
```
auto t = generate(std::make_index_sequence<4>{});
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum::Last;
make(t, ptr, fooType);
``` |
68,839,163 | I have a base class and a class template, and I want to be able to instantiate it as follows:
```
class Base
{
};
template<int i>
class Foo
{
};
namespace SomeEnum
{
enum
{
First,
Second,
Third,
...
Last
};
}
void bar()
{
std::unique_ptr<Base> ptr{ nullptr };
int fooType = rand() % SomeEnum::Last;
ptr = std::make_unique<Foo<fooType>> // Causes error because I'm passing a run-time value to something that expects a compile-time value
}
```
The enum used to be a class enum but I changed it to a regular enum so that I could use the design presented above, since the enum in question is quite large. I thought I was being clever at the time but I now realize I had kind of forgotten that templates are handled at compile-time.
Is there any way to circumvent this, without completely changing my design? I could obviously do something like this:
```
switch(fooType)
{
case 0:
ptr = std::make_unique<Foo<0>>();
break;
case 1:
ptr = std::make_unique<Foo<1>>();
break;
...
}
```
But it doesn't look very elegant and pretty much removes the motivation for not just using a class enum since I will have to make a switch case for every value in the enum. Is there any other solution, or have I painted myself into a corner with this design? | 2021/08/18 | [
"https://Stackoverflow.com/questions/68839163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13699024/"
]
| A simple solution would be this:
```
namespace detail {
template<size_t I>
std::unique_ptr<Base> makeForIndex() {
return std::make_unique<Foo<I>>();
}
template<size_t... Is>
auto makeFoo(size_t nIdx, std::index_sequence<Is...>) {
using FuncType = std::unique_ptr<Base>(*)();
constexpr FuncType arFuncs[] = {
detail::makeForIndex<Is>...
};
return arFuncs[nIdx]();
}
}
auto makeFoo(size_t nIdx) {
return detail::makeFoo(nIdx, std::make_index_sequence<SomeEnum::Last>());
}
```
This would not require template recursion either and is rather easy to understand. We create an array of function pointers and index into that using the runtime value provided by the caller.
Now you can create your `Foo<n>` like
```
size_t n;
...
auto ptr = makeFoo(n);
``` | Some metaprogramming utility stuff:
```
template<class T>
struct tag_t {using type=T;};
template<class T>
constexpr tag_t<T> tag{};
template<auto I>
using constant_t = std::integral_constant<std::decay_t<decltype(I)>, I>;
template<auto I>
constexpr constant_t<I> constant{};
template<class T, T...ts>
struct sequence{};
```
We need `sequence` because `std::integer_sequence` is overspecified.
Now we have our enum:
```
enum class SomeEnum {
A,B,C,
ValueCount,
};
```
Some enum helpers:
```
template<class E, std::size_t...Is>
constexpr auto EnumsSequence( std::index_sequence<Is...> ) {
return sequence<E, static_cast<E>(Is)...>{};
}
template<class E> // requires E::ValueCount
constexpr std::size_t EnumsSize(tag_t<E> =tag<E>) {
return static_cast<std::size_t>(E::ValueCount);
}
template<class E> // requires E::ValueCount
constexpr auto EnumsSequence(tag_t<E> =tag<E>) {
return EnumsSequence<E>(std::make_index_sequence< EnumsSize(tag<E>) >{} );
}
template<class E>
using make_enums_sequence = decltype( EnumsSequence(tag<E>) );
```
we can now do `make_enums_sequence<SomeEnum>` and get `std::integral_sequence<SomeEnum, SomeEnum::A, SomeEnum::B, SomeEnum::C>`. Woo, really basic compile-time reflection. It works on any type with a `ValueCount` enumerator, or you can override `EnumsSize(tag_t<E>)` and/or `EnumsSequence(tag_t<E>)` for a specific type if you have a different convention.
Next we want to make a variant from an `integral_sequence`:
```
template<class S>
struct variant_over_helper;
template<class E, E...es>
struct variant_over_helper< sequence<E, es...> > {
using type=std::variant< constant_t<es>... >;
};
template<class E>
using variant_over_t = typename variant_over_helper<make_enums_sequence<E>>::type;
```
let us think about the variant `variant_over_t<SomeEnum>`.
It contains an index of what alternative it holds. Alternative number 0 corresponds to `SomeEnum::A`, whose value is 0. Alternative number 1 corresponds to `SomeEnum::B`.
Basically, `variant_over_t<SomeEnum>` a struct containing an integer that lines up with `SomeEnum`'s value. Except we can `std::visit` this variant. Bwahahah.
Next we need to be able to convert a runtime `SomeEnum` to a `variant_over_t<SomeEnum>`.
```
template<class E, E... es>
variant_over_t<E> get_variant_enum( sequence<E, es...>, E e ) {
using generator = variant_over_t<E>(*)();
const generator gen[] = {
[]()->variant_over_t<E> {
return constant<es>;
}...
};
return gen[ static_cast<std::size_t>(e) ]();
}
template<class E>
variant_over_t<E> get_variant_enum( E e ) {
return get_variant_enum( EnumsSequence(tag<E>), e );
}
```
and we are done.
```
struct Base{
virtual ~Base() {}
};
enum class SomeEnum
{
First,
Second,
Third,
ValueCount
};
template<SomeEnum i>
struct Foo:Base{};
void bar()
{
std::unique_ptr<Base> ptr;
SomeEnum fooType = static_cast<SomeEnum>( rand() % (int)SomeEnum::ValueCount );
auto vFooType = get_variant_enum(fooType);
ptr = std::visit( [](auto efoo)->std::unique_ptr<Base>{
return std::make_unique<Foo<efoo>>();
}, vFooType );
}
```
[Live example](https://godbolt.org/z/b4dbxez37).
Note that this *requires* that your enum be contiguous and start at 0 (for the `gen[]` array lookup). Some work could be done to handle non-contiguous cases, but that gets complex, so no don't do it. (use `EnumsSequence` to either build a if-tree to find what index to use with `std::in_place_index_t<I>` or `constant<E>`, and/or build an enum-to-index mapping.)
This code runs in O(1) time, not counting data that can be initialized once.
I used `ValueCount` as the number of elements in the enum. If you really need it to be called `Last`, simply add:
```
constexpr std::size_t EnumsSize( tag_t<decltype(SomeEnum::Last)> ) {
return static_cast<std::size_t>(SomeEnum::Last);
}
```
to the namespace of `tag_t` **or** the namespace of `SomeEnum`, and all of the code automatically adapts via argument dependent lookup.
Best part? All of that metaprogramming to create `get_variant_enum` complies down to:
```
movzx edx, ah
mov WORD PTR [rsp+14], ax
```
ie, copy some bytes over.
The visit call is a bit more complex. |
131,299 | If I were to publicly display the 6 digit code from my google authenticator, would my account security be diminished beyond it's valid life time?
What if it were the code and the time it was generated?
What if it were N sequential codes?
I'd like to know why or why not for each case. | 2016/07/28 | [
"https://security.stackexchange.com/questions/131299",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/118844/"
]
| No. Thats the whole point of TOTP/HOTP. That it should be infeasible, given any sequence of valid codes, to generate future codes or recreate the seed.
The reason is that the TOTP/HOTP algoritm, use HMAC-SHA1 as hash, given the "challenge" (either current UNIX time or a counter of usages) and the secret "seed" as key. The resulting hash output is then truncated according to a very specific rule.
This would mean, in your first case, it would be impossible to do, as multiple valid keys will come up with the "correct" 6-digit code but will turn out to be incorrect as future codes from these "valid keys" will be invalid.
To successfully mount a bruteforce attack against a seed, you would atleast need 2 valid auth codes, possible more, and even in that case, its infeasible (eg, practically impossible) to do it. | The first OTP definition in RFC 2289 based on S/Key had even this design requirement.
It was not ment to implement two factor authentication but to merely protect the password or passphrase. It was simply used to avoid the password crossing the network - obviously it was assumed that the transmission could be evesdropped or unencrypted.
So as already stated, it is a fundamental design in all OTP systems (S/Key, mOTP, OATH) to not allow the guessing of future passwords based on used passwords.
**But:** With an event based algorithm like HOTP you can of course create OTP lists. If you generate an OTP value *now* and post it on the internet but don't use it for login, everyone else can use it. It only gets invalidated, when this very value gets used or a later value gets used. |
131,299 | If I were to publicly display the 6 digit code from my google authenticator, would my account security be diminished beyond it's valid life time?
What if it were the code and the time it was generated?
What if it were N sequential codes?
I'd like to know why or why not for each case. | 2016/07/28 | [
"https://security.stackexchange.com/questions/131299",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/118844/"
]
| [Google Authenticator](https://en.wikipedia.org/wiki/Google_Authenticator) uses the [Time-based One-time Password Algorithm](https://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm) ("TOTP"), which works by computing [HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code) with a secret key over a timestamp.
HMAC is a [message authentication code](https://en.wikipedia.org/wiki/Message_authentication_code) ("MAC"). The standard security requirement for a MAC is that it be able to resist **existential forgery** (an attacker *who doesn't know the key* should not be able to forge any `(message, tag)` pairs) under **adaptive chosen text attack** (we allow the attacker the ability to cause the defender to compute tags for any messages of the attacker's choice, and to learn from earlier results when choosing new queries).
The TOTP 6-digit result however is not a straight MAC output, but rather a truncation of a MAC tag, so the question could be raised whether truncating the MAC is also a secure MAC. However HMAC, when used with a good hash function, is also believed to be a [pseudo-random function](https://en.wikipedia.org/wiki/Pseudorandom_function_family). PRFs are automatically good MACs, and the truncation of a PRF is also a PRF, so the truncation of HMAC is also a good MAC.
**TL;DR:** Not unless the attacker could break HMAC-SHA1 under unfavorable conditions, which would be a really big setback for the crypto world as a whole, not just TOTP. | The first OTP definition in RFC 2289 based on S/Key had even this design requirement.
It was not ment to implement two factor authentication but to merely protect the password or passphrase. It was simply used to avoid the password crossing the network - obviously it was assumed that the transmission could be evesdropped or unencrypted.
So as already stated, it is a fundamental design in all OTP systems (S/Key, mOTP, OATH) to not allow the guessing of future passwords based on used passwords.
**But:** With an event based algorithm like HOTP you can of course create OTP lists. If you generate an OTP value *now* and post it on the internet but don't use it for login, everyone else can use it. It only gets invalidated, when this very value gets used or a later value gets used. |
144,926 | I have upgraded my ubuntu with 11.10 i368,after completion of installation i have connected my EVDO card and configured all mobile broadband setting. At first it got connected and was able to surf properly....but after completion of installation and updating all packages (its was like 414 packages to download) i was no more able setup my broadband connection with EVDO.
I always Enable the mobile broadband before conneting,but still i was unable to connect my EVDO.
Any solution???? | 2012/06/01 | [
"https://askubuntu.com/questions/144926",
"https://askubuntu.com",
"https://askubuntu.com/users/67627/"
]
| Has the resolvconf got updated? Go through the following link and give it a shot. Worked for me for my BSNL EVDO (Prithvi dongle)
>
> You might have issues with resolvconf stomping on your DNS
> configuration in /etc/resolv.conf - but if you're getting an IP
> address from the remote peer then the modem is working, even if you
> can't access any websites etc. If you don't use resolvconf, consider
> just uninstalling it.
>
>
>
Source: <https://wiki.ubuntu.com/NetworkManager/Hardware/3G/Probing> | Look for comparable reports in Launchpad: <https://bugs.launchpad.net/ubuntu/+source/network-manager/?field.searchtext=evdo&search=Search&field.status%3Alist=NEW&field.status%3Alist=OPINION&field.status%3Alist=INVALID&field.status%3Alist=WONTFIX&field.status%3Alist=EXPIRED&field.status%3Alist=CONFIRMED&field.status%3Alist=TRIAGED&field.status%3Alist=INPROGRESS&field.status%3Alist=FIXCOMMITTED&field.status%3Alist=FIXRELEASED&field.status%3Alist=INCOMPLETE_WITH_RESPONSE&field.status%3Alist=INCOMPLETE_WITHOUT_RESPONSE&assignee_option=any&field.assignee=&field.bug_reporter=&field.bug_commenter=&field.subscriber=&field.tag=&field.tags_combinator=ANY&field.status_upstream-empty-marker=1&field.upstream_target=&field.has_cve.used=&field.omit_dupes.used=&field.omit_dupes=on&field.affects_me.used=&field.has_patch.used=&field.has_branches.used=&field.has_branches=on&field.has_no_branches.used=&field.has_no_branches=on&field.has_blueprints.used=&field.has_blueprints=on&field.has_no_blueprints.used=&field.has_no_blueprints=on> |
22,563,682 | I'm trying to enable/disable my network ethernet interface using C++ and WIN32\_NetworkAdapter class of WMI. But unfortunately i did not found how the methods of the class may be invoked.
thanks in advance... | 2014/03/21 | [
"https://Stackoverflow.com/questions/22563682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3445539/"
]
| To execute the WMI methods you must use the [`ExecMethod`](http://msdn.microsoft.com/en-us/library/aa392103%28v=vs.85%29.aspx) method of the [`IWbemServices`](http://msdn.microsoft.com/en-us/library/aa392093%28v=vs.85%29.aspx) class. On this case you must pass the Index of the Network adapter to Enable/Disble methods.
Btw if you are new using the WMI and C++ you can use the [WDCC](http://code.google.com/p/wmi-delphi-code-creator/) Tool , which can help you generate code to access the WMI from C++.
Try this sample code.
```
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
# pragma comment(lib, "wbemuuid.lib")
//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx
#define CRED_MAX_USERNAME_LENGTH 513
#define CRED_MAX_CREDENTIAL_BLOB_SIZE 512
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE / 2)
#pragma argsused
int main(int argc, char* argv[])
{
wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user";
wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password";
BSTR strNetworkResource;
//To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
bool localconn = true;
strNetworkResource = localconn ? L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2";
COAUTHIDENTITY *userAcct = NULL ;
COAUTHIDENTITY authIdent;
HRESULT hres;
// Initialize COM. ------------------------------------------
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Set general COM security levels --------------------------
if (localconn)
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
else
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IDENTIFY, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Obtain the initial locator to WMI -------------------------
IWbemLocator *pLoc = NULL;
hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object. " << "Err code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
// Connect to the root\\CIMV2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
if (localconn)
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
else
hres = pLoc->ConnectServer(
_bstr_t(strNetworkResource), // Object path of WMI namespace
_bstr_t(pszName), // User name
_bstr_t(pszPwd), // User password
NULL, // Locale
NULL, // Security flags
NULL, // Authority
NULL, // Context object
&pSvc // IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
cout << "Connected to root\\CIMV2 WMI namespace" << endl;
// Set security levels on the proxy -------------------------
if (localconn)
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
else
{
// Create COAUTHIDENTITY that can be used for setting security on proxy
memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
authIdent.PasswordLength = wcslen (pszPwd);
authIdent.Password = (USHORT*)pszPwd;
authIdent.User = (USHORT*)pszName;
authIdent.UserLength = wcslen(pszName);
authIdent.Domain = 0;
authIdent.DomainLength = 0;
authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;
userAcct = &authIdent;
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_DEFAULT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_DEFAULT, // RPC_C_AUTHZ_xxx
COLE_DEFAULT_PRINCIPAL, // Server principal name
RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
userAcct, // client identity
EOAC_NONE // proxy capabilities
);
}
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
// Use the IWbemServices pointer to make requests of WMI ----
BSTR MethodName = SysAllocString(L"Disable");
BSTR ClassName = SysAllocString(L"Win32_NetworkAdapter");
IWbemClassObject* pClass = NULL;
hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
IWbemClassObject* pInParamsDefinition = NULL;
hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);
IWbemClassObject* pClassInstance = NULL;
hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);
// Execute Method
IWbemClassObject* pOutParams = NULL;
hres = pSvc->ExecMethod(L"Win32_NetworkAdapter.DeviceID=\"0\"", MethodName, 0,
NULL, pClassInstance, &pOutParams, NULL);
if (FAILED(hres))
{
cout << "Could not execute method. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pSvc) pSvc->Release();
if (pLoc) pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
VARIANT varReturnValue;
hres = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, 0);
if (!FAILED(hres))
wcout << "ReturnValue " << varReturnValue.intVal << endl;
VariantClear(&varReturnValue);
// Clean up
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pLoc) pLoc->Release();
if (pSvc) pSvc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0;
}
``` | The code RRUZ posted won't work as is because `WIN32_NetworkAdapter`'s `Disable()` (and `Enable()`) methods for have no input parameters. In the call to `ExecMethod()`, you need to pass in a null in place of `pClassInstance` (obviously, don't call `SpawnInstance()` on the null `pInParamsDefinition`). Note, however, that this doesn't necessarily apply to all cases where there seem to be no input parameters; see the discussion at <http://microsoft.public.win32.programmer.wmi.narkive.com/Pxy4mfTi/calling-method-with-no-input-params-in-c> |
54,955,165 | I'm trying to create an SVG with base and height 100px. But not sure if it is correct. I'm not getting the exact output as I need. Below is the code sample
```html
<svg id="triangle" viewBox="0 0 100 100">
<polygon points="50 15, 100 100, 0 100"/>
</svg>
```
Please correct me where I'm doing wrong. I really appreciate your help.
Thank you! | 2019/03/02 | [
"https://Stackoverflow.com/questions/54955165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7691736/"
]
| Wrap in a container and set the size as a percentage. Then it will be possible to adjust the size and the shape will be adaptive.
```css
.container {
width:30%;
height:30%;
}
```
```html
<div class="container">
<svg id="triangle" viewBox="0 0 100 100">
<polygon points="50 15, 100 100, 0 100"/>
</svg>
</div>
```
second option without using the container:
```html
<svg id="triangle" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="30%" height="30%" viewBox="0 0 100 100">
<polygon points="50 15, 100 100, 0 100"/>
</svg>
```
third option
Write syntax as per specification [polygon](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polygon)
The comma must separate the coordinate "X" and "Y"
```html
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100" style="border:1px solid gray;" >
<polygon points="50, 13.397 100, 100 0, 100"/>
</svg>
```
**Update**
Reply to comments
>
> The compiler still giving me an error that it is not a valid triangle.
>
>
>
To validate the file I added the required parameters
```html
<!DOCTYPE html>
<head>
<title>Triangle</title>
</head>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100" >
<polygon points="50, 13.397 100, 100 0, 100/>
</svg>
```
Download this file to the validator <https://validator.nu/>
[](https://i.stack.imgur.com/o3obl.png) | ```html
<svg id="triangle" viewBox="0 0 100 100">
<polygon points="0 0, 100 0 50 100" fill="blue" stroke="red"/>
</svg>
``` |
18,882,874 | I was using Google Analytics API v2 and it was working great. When a user open my app, it will show up on the real time analysis and if the user quits the app, that user was not showing up anymore on that report. That took it around 20 or 30 seconds.
But using the new session management suggested by Google on the Analytics API v3, it took almost 3 minutes for a user to disappear from the real time report after quitting my app.
This is the code that I'm using when launching my app:
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
....
[GAI sharedInstance].trackUncaughtExceptions = NO;
// Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
[GAI sharedInstance].dispatchInterval = 20;
// Initialize tracker.
id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:@"XX-YYYYYYYY-Z"];
[tracker set:kGAISessionControl value:@"start"];
}
```
And this is the code to end analytics session:
```
- (void)applicationWillResignActive:(UIApplication *)application
{
id<GAITracker> tracker = [[GAI sharedInstance] trackerWithTrackingId:@"XX-YYYYYYYY-Z"];
[tracker set:kGAISessionControl value:@"end"];
}
```
Is this code correct? Am I missing something? | 2013/09/18 | [
"https://Stackoverflow.com/questions/18882874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1136433/"
]
| Not sure if it is the best solution or even if you can control this, but it may work if you do double-encoding: for example, instead of "%23", make it use "%2523".
The unwanted decoding should then convert "%2523" to "%23", leaving the desired result in the redirect URL that the browser shows. | You need to URI-escape the "#" character. |
27,972 | This is in part a UX and a legal (UK) question.
Is there a best practice in terms of opt in statements for data protection for registration. I have had our CRM team suggest that we should include an automatic opt in as part of the T's & C's so a user has to receive communications (email / phone / post / text) from us and has no option but to proceed with this.
I am opposed to this on a user level and also on an ethical level as we are a good cause.
Any feedback on this greatly appreciated. | 2012/10/18 | [
"https://ux.stackexchange.com/questions/27972",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/17299/"
]
| This is a really interesting question.
My understanding of the legal situation is a user doesn't have to specifically opt-in to your marketing, providing you give them a way to opt-out in every email you send them. This seems to be referred to as 'soft opt-in', or 'implied consent' - they give you their details as part of getting a quote (or signing up to something else on your site, or similar) and that's enough to think they might want to be on your mailing list.
However... Just because you can doesn't mean you should. I'm definitely with you on the ethical level.
The other problem with not asking your users to specifically sign up to a mailing list is the spam button in their email client. Apparently, [30% of recipients click the spam button](http://kb.mailchimp.com/article/ask-before-you-blast) on marketing emails even if they have signed up. This becomes a whole lot more likely if they didn't actually ask to get the emails. Not sure how many times that button would need to be clicked before the ISP put you on the spam list, but I'm willing to bet it's not too many.
There's also a good UK-based write up [here](http://www.lawdonut.co.uk/law/sales-and-marketing/marketing-and-advertising/your-email-marketing-and-anti-spam-law) that articulates the issues a whole lot better than me. | This is the official line ( 'The Information Commissioner’s Office is *the UK’s independent authority set up to uphold information rights in the public interest, promoting openness by public bodies and data privacy for individuals*'
<http://www.ico.gov.uk/global/faqs/privacy_and_electronic_communications_regulations_for_the_public.aspx>
Q: I am receiving unsolicited marketing emails. What can I do about these?
The Privacy and Electronic Communications Regulations lay down rules for organisations sending unsolicited marketing by electronic means. The rules are different depending whether the recipient is an 'individual subscriber' (eg Jonsmith@yahoo) or a 'corporate subscriber' (eg Jonsmith@ico).
The regulations say that organisations must have prior consent to send unsolicited marketing material by electronic mail to individual subscribers, unless they have obtained the details during the course of a sale, or negotiations towards one, and they give you the opportunity to object in every message. If you are an individual subscriber receiving unsolicited marketing by electronic mail, and the organisation hasn't stopped even though you've tried to opt out, you can complain to the ICO.
If you are a corporate subscriber the prior consent rule does not apply. Marketing communications should still identify the sender and provide a valid address. Depending on the information the company holds about you, a corporate subscriber may also have rights under the Data Protection Act.
[Read our topic guide about spam email](http://www.ico.gov.uk/for_the_public/topic_specific_guides/online/spam_emails.aspx) |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| Ultimately, I believe the Objective-C philosophy, as embodied by the Cocoa frameworks (and the NextStep frameworks before it) is that being explicit, and easy to maintain takes precedence over terseness of code. The main evidence for this philosophy is that Objective-C selectors have named arguments (e.g. `-[NSObject performSelector:withObject:]`).
In the case of factory methods such as `+[NSString stringWithString:]`, you must remember that subclasses may override these class methods to return subclasses (for example class clusters such as `NSNumber`).
So, you may end up with a call like `[MyPoorlyNamedSubclass stringWithString:]` in which case `-[MyPoorlyNamedSubclass withString:]` would not be obviously informative as to the type of object returned (recall that many factory methods return type `id`). `stringWithString:`, on the other hand makes it clear that the method will return a string (or subclass thereof). | If you don't like it, why not write up a bunch of #define statements that you include in all your projects? |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| Because it's consistent.
There are methods like:
```
[NSDictionary dictionary]
[NSArray array]
```
Getting rid of everything up to `with` is obviously not an option here. Keeping these, but shortening others would introduce inconsistency in naming of convenience methods.
And convenience methods are consistent with `init` and `initWith…` methods. | They also use that one extra word to tell if the object is autoreleased or not. initWithFormat is for non-autoreleased, and when its stringWithFormat it is autoreleased... I guess they just went with that way of telling the reader what kind of memory management the object uses... |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| There is actually a technical reason for it to be that way. If every `shoelaceWithString:`-type method were changed to just `withString:`, we would end up with a fearsomely huge number of classes with identically named methods and different signatures. This plays mean tricks on the compiler's static type checking and can cause it to throw up all sorts of annoying and unnecessary warnings.
There's also an aspect of Cocoa culture where developers like their code to be self-documenting. This means that method names indicate both what their arguments are and what they return. Apple's coding guidelines actually warn about methods with vague names, suggesting that adding words to the name to make it clear what a method does is preferable. | I think it's just part of the general "say exactly what you mean" wordiness philosophy of the cocoa framework. A few choice selections:
```
[UIView setAnimationBeginsFromCurrentState]
[UITableView scrollToNearestSelectedRowAtScrollPosition]
[UIApplication didRegisterForRemoteNotificationsWithDeviceToken]
```
etc.
ETA:
To answer the questions specifically about constructors, one thing I like about the way they are done is that it's easy within x-code to identify which methods are constructor type methods. For example, you start typing:
```
[NSString string
```
And the "intellisense" whittles down the list of methods to those that start with "string" which of course are all the constructor methods (and all conveniently grouped together as well). Same thing applies for the "init" convention. |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| They also use that one extra word to tell if the object is autoreleased or not. initWithFormat is for non-autoreleased, and when its stringWithFormat it is autoreleased... I guess they just went with that way of telling the reader what kind of memory management the object uses... | If you don't like it, why not write up a bunch of #define statements that you include in all your projects? |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| Because it's consistent.
There are methods like:
```
[NSDictionary dictionary]
[NSArray array]
```
Getting rid of everything up to `with` is obviously not an option here. Keeping these, but shortening others would introduce inconsistency in naming of convenience methods.
And convenience methods are consistent with `init` and `initWith…` methods. | I think it's just part of the general "say exactly what you mean" wordiness philosophy of the cocoa framework. A few choice selections:
```
[UIView setAnimationBeginsFromCurrentState]
[UITableView scrollToNearestSelectedRowAtScrollPosition]
[UIApplication didRegisterForRemoteNotificationsWithDeviceToken]
```
etc.
ETA:
To answer the questions specifically about constructors, one thing I like about the way they are done is that it's easy within x-code to identify which methods are constructor type methods. For example, you start typing:
```
[NSString string
```
And the "intellisense" whittles down the list of methods to those that start with "string" which of course are all the constructor methods (and all conveniently grouped together as well). Same thing applies for the "init" convention. |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| There is actually a technical reason for it to be that way. If every `shoelaceWithString:`-type method were changed to just `withString:`, we would end up with a fearsomely huge number of classes with identically named methods and different signatures. This plays mean tricks on the compiler's static type checking and can cause it to throw up all sorts of annoying and unnecessary warnings.
There's also an aspect of Cocoa culture where developers like their code to be self-documenting. This means that method names indicate both what their arguments are and what they return. Apple's coding guidelines actually warn about methods with vague names, suggesting that adding words to the name to make it clear what a method does is preferable. | Ultimately, I believe the Objective-C philosophy, as embodied by the Cocoa frameworks (and the NextStep frameworks before it) is that being explicit, and easy to maintain takes precedence over terseness of code. The main evidence for this philosophy is that Objective-C selectors have named arguments (e.g. `-[NSObject performSelector:withObject:]`).
In the case of factory methods such as `+[NSString stringWithString:]`, you must remember that subclasses may override these class methods to return subclasses (for example class clusters such as `NSNumber`).
So, you may end up with a call like `[MyPoorlyNamedSubclass stringWithString:]` in which case `-[MyPoorlyNamedSubclass withString:]` would not be obviously informative as to the type of object returned (recall that many factory methods return type `id`). `stringWithString:`, on the other hand makes it clear that the method will return a string (or subclass thereof). |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| There is actually a technical reason for it to be that way. If every `shoelaceWithString:`-type method were changed to just `withString:`, we would end up with a fearsomely huge number of classes with identically named methods and different signatures. This plays mean tricks on the compiler's static type checking and can cause it to throw up all sorts of annoying and unnecessary warnings.
There's also an aspect of Cocoa culture where developers like their code to be self-documenting. This means that method names indicate both what their arguments are and what they return. Apple's coding guidelines actually warn about methods with vague names, suggesting that adding words to the name to make it clear what a method does is preferable. | Because it's consistent.
There are methods like:
```
[NSDictionary dictionary]
[NSArray array]
```
Getting rid of everything up to `with` is obviously not an option here. Keeping these, but shortening others would introduce inconsistency in naming of convenience methods.
And convenience methods are consistent with `init` and `initWith…` methods. |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| There is actually a technical reason for it to be that way. If every `shoelaceWithString:`-type method were changed to just `withString:`, we would end up with a fearsomely huge number of classes with identically named methods and different signatures. This plays mean tricks on the compiler's static type checking and can cause it to throw up all sorts of annoying and unnecessary warnings.
There's also an aspect of Cocoa culture where developers like their code to be self-documenting. This means that method names indicate both what their arguments are and what they return. Apple's coding guidelines actually warn about methods with vague names, suggesting that adding words to the name to make it clear what a method does is preferable. | They also use that one extra word to tell if the object is autoreleased or not. initWithFormat is for non-autoreleased, and when its stringWithFormat it is autoreleased... I guess they just went with that way of telling the reader what kind of memory management the object uses... |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| I think it's just part of the general "say exactly what you mean" wordiness philosophy of the cocoa framework. A few choice selections:
```
[UIView setAnimationBeginsFromCurrentState]
[UITableView scrollToNearestSelectedRowAtScrollPosition]
[UIApplication didRegisterForRemoteNotificationsWithDeviceToken]
```
etc.
ETA:
To answer the questions specifically about constructors, one thing I like about the way they are done is that it's easy within x-code to identify which methods are constructor type methods. For example, you start typing:
```
[NSString string
```
And the "intellisense" whittles down the list of methods to those that start with "string" which of course are all the constructor methods (and all conveniently grouped together as well). Same thing applies for the "init" convention. | If you don't like it, why not write up a bunch of #define statements that you include in all your projects? |
1,017,652 | One of the things I like most about Cocoa is the readability factor.
One of the things that annoys me the most is the convention of convenience constructors to force repetition.
Here's an example:
```
[NSString stringWithString:s]
[NSNumber numberWithDouble:d]
[NSValue valueWithInt:i]
[NSDictionary dictionaryWithObjectsAndKeys:<blah>]
```
etc.
Why doesn't the convention simply start convenience constructors with the word "with"? so then we would have:
```
[NSString withString:s]
[NSNumber withDouble:d]
[NSValue withInt:i]
[NSDictionary withObjectsAndKeys:<blah>]
```
etc.
It's a minor discussion point, but one I thought I would just throw out there and see if anyone with more clout than me can explain all the echos in my head.
Obviously, I'm not going to petition AAPL to re-write the appKit in favour of my suggestion, but are there any arguments against naming my own convenience constructors as such?
Of course I can use whatever conventions I want in my own code but I hate to swim upstream blindly. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1017652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78568/"
]
| There is actually a technical reason for it to be that way. If every `shoelaceWithString:`-type method were changed to just `withString:`, we would end up with a fearsomely huge number of classes with identically named methods and different signatures. This plays mean tricks on the compiler's static type checking and can cause it to throw up all sorts of annoying and unnecessary warnings.
There's also an aspect of Cocoa culture where developers like their code to be self-documenting. This means that method names indicate both what their arguments are and what they return. Apple's coding guidelines actually warn about methods with vague names, suggesting that adding words to the name to make it clear what a method does is preferable. | If you don't like it, why not write up a bunch of #define statements that you include in all your projects? |
58,878,486 | I have a div that has a background-image with the background-attachment as fixed. I change from fixed to scroll when the div with the background images is halfway using jQuery. I seem to have got it working however when I scroll down, there seems to be jump when the property is changed. How can I avoid this jump?
```js
$(window).scroll(function() {
var halfHeight = $(window).height() / 2
if ($(this).scrollTop() >= $('.service-logo').offset().top + halfHeight) {
$('.service-logo').addClass('bg-scroll');
} else {
$('.service-logo').removeClass('bg-scroll');
}
});
```
```css
.content {
background: red;
height: 1000px;
}
.content2 {
background: black;
height: 1000px;
}
.service-logo {
background-image: url(https://www.w3schools.com/css/img_5terre.jpg);
background-attachment: fixed;
background-repeat: no-repeat;
background-size: 200px;
background-position: center;
}
.bg-scroll {
background-attachment: scroll !important;
}
.content3 {
background: green;
height: 1000px;
}
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<div class="content">
</div>
<div class="content2 service-logo">
</div>
<div class="content3">
</div>
``` | 2019/11/15 | [
"https://Stackoverflow.com/questions/58878486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4060521/"
]
| Use `SPLIT()` with corresponding delimiters in an array and apply a `TRANSPOSE()` so instead of consequent cells horizontally, it will return emails in rows.
```
=TRANSPOSE(SPLIT(A1, {"|" ; char(10) ; ";" ; ","}))
```
Add any email-separating character you want inside the curly braces above. `char(10)` is the *line break* character.
If you want to apply the formula to a whole column or an array of cells, put the formula inside an `ARRAYFORMULA()` and change the cell address to an array:
```
=ARRAYFORMULA(TRANSPOSE(SPLIT(A1:A, {"|" ; char(10) ; ";" ; ","})))
```
Toggle with `TRANSPOSE()` and see which one returns your desired results. | In the code you provided you are doing this `var cell = e.toString().split("\n");` if you want to split by "\n" and ";" you can chain split and joins.
This is some code that illustrates what I mean:
```
var x = "a\nb\nc";
var y = "a;b;c";
var z = x+";"+y;
console.log(x,x.split('\n').join(';').split(';'));
console.log(y,y.split('\n').join(';').split(';'));
console.log(z,z.split('\n').join(';').split(';'));
``` |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| The cube graph is an example of a [bipartite graph](https://en.wikipedia.org/wiki/Bipartite_graph), where the vertices can be divided into two group such that the edges always connect a vertex from one group to a vertex in the other group, never to another vertex in the same group.
The group can be seen in your diagram by moving vertex $1$ in amongst the other odd-numbered vertices and vertex $8$ likewise into the even-numbered group. Then you will always traverse an odd number of edges to reach a vertex in the other group from the starting vertex, plus all cycles are even length, etc. | The 8 vertices of the graph can be divided into 2 disjoint sets $V\_1=\{1,3,5,7\}$ and $V\_2=\{2,4,6,8\}$. Each edge of the graph connects a vertex of $V\_1$ to a vertex of $V\_2$, therefore, moving from a point of one of the sets to another point of the same set requires an even number of steps, and moving from one set to another requires an odd number of steps. $1\in V\_1$ and $8\in V\_2$, so the trip from one to another cannot be made in an even number of steps. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| The 8 vertices of the graph can be divided into 2 disjoint sets $V\_1=\{1,3,5,7\}$ and $V\_2=\{2,4,6,8\}$. Each edge of the graph connects a vertex of $V\_1$ to a vertex of $V\_2$, therefore, moving from a point of one of the sets to another point of the same set requires an even number of steps, and moving from one set to another requires an odd number of steps. $1\in V\_1$ and $8\in V\_2$, so the trip from one to another cannot be made in an even number of steps. | As you can see you have bipartite graph here and one of the things of bipartite graph is that for any u,v vertices all the paths from u to v has to odd or even (can't be 1 path odd while there is other even) so if we have bipartite graph and we show 1 odd path then all the paths are odd. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| Indeed the graph is *bipartite* and 1 and 8 are on opposite *sides* (all edges go from one side to the other). Going from one to the other can only be done in an odd number of steps.
[](https://i.stack.imgur.com/GTbTQ.png)
The graph can also be shown to be *layered*, so that the shortest path from 1 to 8 has length 3.
[](https://i.stack.imgur.com/XWIrN.png) | The 8 vertices of the graph can be divided into 2 disjoint sets $V\_1=\{1,3,5,7\}$ and $V\_2=\{2,4,6,8\}$. Each edge of the graph connects a vertex of $V\_1$ to a vertex of $V\_2$, therefore, moving from a point of one of the sets to another point of the same set requires an even number of steps, and moving from one set to another requires an odd number of steps. $1\in V\_1$ and $8\in V\_2$, so the trip from one to another cannot be made in an even number of steps. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| The cube graph is an example of a [bipartite graph](https://en.wikipedia.org/wiki/Bipartite_graph), where the vertices can be divided into two group such that the edges always connect a vertex from one group to a vertex in the other group, never to another vertex in the same group.
The group can be seen in your diagram by moving vertex $1$ in amongst the other odd-numbered vertices and vertex $8$ likewise into the even-numbered group. Then you will always traverse an odd number of edges to reach a vertex in the other group from the starting vertex, plus all cycles are even length, etc. | Notice that every dot is connected to 3 other dots and these three dots are of different parity ( if first dot is even then other three will be odd and if first dot is odd then the other three will be even). So if you start with even you will go to odd in next step and similarly when you start from odd you will go to even in next step.
Now just start from 1 and notice that:
step 1 -reached even,
step 2-reached odd,
step 3-reached even
.
.
.
.
Step odd-reached even.
Since you want to reach 8 which is even so you will have to take odd steps. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| Notice that every dot is connected to 3 other dots and these three dots are of different parity ( if first dot is even then other three will be odd and if first dot is odd then the other three will be even). So if you start with even you will go to odd in next step and similarly when you start from odd you will go to even in next step.
Now just start from 1 and notice that:
step 1 -reached even,
step 2-reached odd,
step 3-reached even
.
.
.
.
Step odd-reached even.
Since you want to reach 8 which is even so you will have to take odd steps. | As you can see you have bipartite graph here and one of the things of bipartite graph is that for any u,v vertices all the paths from u to v has to odd or even (can't be 1 path odd while there is other even) so if we have bipartite graph and we show 1 odd path then all the paths are odd. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| Indeed the graph is *bipartite* and 1 and 8 are on opposite *sides* (all edges go from one side to the other). Going from one to the other can only be done in an odd number of steps.
[](https://i.stack.imgur.com/GTbTQ.png)
The graph can also be shown to be *layered*, so that the shortest path from 1 to 8 has length 3.
[](https://i.stack.imgur.com/XWIrN.png) | Notice that every dot is connected to 3 other dots and these three dots are of different parity ( if first dot is even then other three will be odd and if first dot is odd then the other three will be even). So if you start with even you will go to odd in next step and similarly when you start from odd you will go to even in next step.
Now just start from 1 and notice that:
step 1 -reached even,
step 2-reached odd,
step 3-reached even
.
.
.
.
Step odd-reached even.
Since you want to reach 8 which is even so you will have to take odd steps. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| The cube graph is an example of a [bipartite graph](https://en.wikipedia.org/wiki/Bipartite_graph), where the vertices can be divided into two group such that the edges always connect a vertex from one group to a vertex in the other group, never to another vertex in the same group.
The group can be seen in your diagram by moving vertex $1$ in amongst the other odd-numbered vertices and vertex $8$ likewise into the even-numbered group. Then you will always traverse an odd number of edges to reach a vertex in the other group from the starting vertex, plus all cycles are even length, etc. | As you can see you have bipartite graph here and one of the things of bipartite graph is that for any u,v vertices all the paths from u to v has to odd or even (can't be 1 path odd while there is other even) so if we have bipartite graph and we show 1 odd path then all the paths are odd. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| Indeed the graph is *bipartite* and 1 and 8 are on opposite *sides* (all edges go from one side to the other). Going from one to the other can only be done in an odd number of steps.
[](https://i.stack.imgur.com/GTbTQ.png)
The graph can also be shown to be *layered*, so that the shortest path from 1 to 8 has length 3.
[](https://i.stack.imgur.com/XWIrN.png) | The cube graph is an example of a [bipartite graph](https://en.wikipedia.org/wiki/Bipartite_graph), where the vertices can be divided into two group such that the edges always connect a vertex from one group to a vertex in the other group, never to another vertex in the same group.
The group can be seen in your diagram by moving vertex $1$ in amongst the other odd-numbered vertices and vertex $8$ likewise into the even-numbered group. Then you will always traverse an odd number of edges to reach a vertex in the other group from the starting vertex, plus all cycles are even length, etc. |
2,050,093 | Let's suppose that $a\_n$ satisfy $|a\_{n+1}-a\_n|<2^{-n}$ for all $n$ . How can I prove that $a\_n$ is a cauchy sequence? | 2016/12/08 | [
"https://math.stackexchange.com/questions/2050093",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/384885/"
]
| Indeed the graph is *bipartite* and 1 and 8 are on opposite *sides* (all edges go from one side to the other). Going from one to the other can only be done in an odd number of steps.
[](https://i.stack.imgur.com/GTbTQ.png)
The graph can also be shown to be *layered*, so that the shortest path from 1 to 8 has length 3.
[](https://i.stack.imgur.com/XWIrN.png) | As you can see you have bipartite graph here and one of the things of bipartite graph is that for any u,v vertices all the paths from u to v has to odd or even (can't be 1 path odd while there is other even) so if we have bipartite graph and we show 1 odd path then all the paths are odd. |
893 | I'm hosting a Minecraft server with 14 friends of mine playing on it. We peacefully build houses and structures, hold events, go kill the enderdragon, stuff like that. All is peaceful. Until one day, another friend of mine (let's call him "A") joined the server. Then our houses got griefed and burned. Our stuff is all gone. We (me, another owner, and 2 mods) took a month to investigate and finally found that "A" was griefing. We talked to him and told him not to grief again or else we'll kick him. And eventually we kicked him.
And now the problem begins. A moderator wrote to me saying that I should give "A" another chance, and that he apologized. So I thought, why not? Then, after I added him back -- on the very same day -- my best friend's house got filled with water. Checking the records, I found out that it was "A" again. I wanted to kick him, but it would hurt our friendship. I mean, we meet each other at school every day. He would be so mad at me. But if I don't kick him, 3 other players will leave the server.
What should I do to solve this mess? | 2014/11/25 | [
"https://moderators.stackexchange.com/questions/893",
"https://moderators.stackexchange.com",
"https://moderators.stackexchange.com/users/708/"
]
| It's always a bit tricky when you have a situation where real life and online life cross. Fundamentally, you have to decide which matters more, the real life situation or preventing the problems online.
If it is a friendship that you both value, then it may be worth having a chat with him offline about the behavior. Make sure he understands why it is a problem, that people, including you, don't like it and explain what the consequences will be. Get him to agree that he understands.
If he continues to do the behavior, follow through. You talked to him in real life and explained what would happen. He agreed to it and did it anyway. He doesn't have any right to be mad at that point. If he's willing to lie to your face, grief people, and then get upset about being removed, then he isn't really that good of a friend to begin with and probably isn't a big loss.
You could also consider allowing him back in eventually, but I'd suggest using increasing amounts of time that you don't let him back for, so he knows it will get more and more serious until hopefully his desire to spend time with you will offset his desire to cause trouble. | Create a second server where you can play and have fun and leave him a copy where he can destroy if that is his prefered way of playing. |
893 | I'm hosting a Minecraft server with 14 friends of mine playing on it. We peacefully build houses and structures, hold events, go kill the enderdragon, stuff like that. All is peaceful. Until one day, another friend of mine (let's call him "A") joined the server. Then our houses got griefed and burned. Our stuff is all gone. We (me, another owner, and 2 mods) took a month to investigate and finally found that "A" was griefing. We talked to him and told him not to grief again or else we'll kick him. And eventually we kicked him.
And now the problem begins. A moderator wrote to me saying that I should give "A" another chance, and that he apologized. So I thought, why not? Then, after I added him back -- on the very same day -- my best friend's house got filled with water. Checking the records, I found out that it was "A" again. I wanted to kick him, but it would hurt our friendship. I mean, we meet each other at school every day. He would be so mad at me. But if I don't kick him, 3 other players will leave the server.
What should I do to solve this mess? | 2014/11/25 | [
"https://moderators.stackexchange.com/questions/893",
"https://moderators.stackexchange.com",
"https://moderators.stackexchange.com/users/708/"
]
| It's always a bit tricky when you have a situation where real life and online life cross. Fundamentally, you have to decide which matters more, the real life situation or preventing the problems online.
If it is a friendship that you both value, then it may be worth having a chat with him offline about the behavior. Make sure he understands why it is a problem, that people, including you, don't like it and explain what the consequences will be. Get him to agree that he understands.
If he continues to do the behavior, follow through. You talked to him in real life and explained what would happen. He agreed to it and did it anyway. He doesn't have any right to be mad at that point. If he's willing to lie to your face, grief people, and then get upset about being removed, then he isn't really that good of a friend to begin with and probably isn't a big loss.
You could also consider allowing him back in eventually, but I'd suggest using increasing amounts of time that you don't let him back for, so he knows it will get more and more serious until hopefully his desire to spend time with you will offset his desire to cause trouble. | I think it is rather simple. You like this game, you enjoy playing it with other people.
Tell him that, if he values you as a friend, he will stop his behavior, if not just kick him.
People sometimes misses the real meaning of what is going on because they think is only an "online" event. But what if you were building real stuff, and he came and destroy it, would you accept that? What if you were writing a story on your computer, that is "virtual", would you like if he came and deleted it all?
You invest time in that game, is something you enjoy, the game is online, it may not be important, but your time and feelings are, if he can not accept/understand/respect that, do you think he will be able to understand in other contexts?
Value your time and feelings, and have friends that value them also. |
893 | I'm hosting a Minecraft server with 14 friends of mine playing on it. We peacefully build houses and structures, hold events, go kill the enderdragon, stuff like that. All is peaceful. Until one day, another friend of mine (let's call him "A") joined the server. Then our houses got griefed and burned. Our stuff is all gone. We (me, another owner, and 2 mods) took a month to investigate and finally found that "A" was griefing. We talked to him and told him not to grief again or else we'll kick him. And eventually we kicked him.
And now the problem begins. A moderator wrote to me saying that I should give "A" another chance, and that he apologized. So I thought, why not? Then, after I added him back -- on the very same day -- my best friend's house got filled with water. Checking the records, I found out that it was "A" again. I wanted to kick him, but it would hurt our friendship. I mean, we meet each other at school every day. He would be so mad at me. But if I don't kick him, 3 other players will leave the server.
What should I do to solve this mess? | 2014/11/25 | [
"https://moderators.stackexchange.com/questions/893",
"https://moderators.stackexchange.com",
"https://moderators.stackexchange.com/users/708/"
]
| It's always a bit tricky when you have a situation where real life and online life cross. Fundamentally, you have to decide which matters more, the real life situation or preventing the problems online.
If it is a friendship that you both value, then it may be worth having a chat with him offline about the behavior. Make sure he understands why it is a problem, that people, including you, don't like it and explain what the consequences will be. Get him to agree that he understands.
If he continues to do the behavior, follow through. You talked to him in real life and explained what would happen. He agreed to it and did it anyway. He doesn't have any right to be mad at that point. If he's willing to lie to your face, grief people, and then get upset about being removed, then he isn't really that good of a friend to begin with and probably isn't a big loss.
You could also consider allowing him back in eventually, but I'd suggest using increasing amounts of time that you don't let him back for, so he knows it will get more and more serious until hopefully his desire to spend time with you will offset his desire to cause trouble. | In an ideal case, he should have to be obey all the same rules as any other member of the server, even if you did not know him in real life.
There are two ways to achieve this, the first is by excluding people who break the rules, the second is by making the rules impossible to break.
As an aside, you say, *"He would be mad at me"*, but I'm not sure how that is more important than you being mad at him, let alone whether he is even actually justified in being angry. Consider that you are putting his wants above your own *and* your other friends.
---
1. Explain to him that he *will* be kicked if he does it again, that these are the rules on the server and *any* case of griefing is dealt with in the same way. Then follow through.
---
2. If you would rather enforce your rules by modifying the game itself, then there are some protective things you can do for you and your friends.
* Mods which restrict certain people to a "starter area" are common in most public minecraft servers
* Possibly other mods (*I'm not aware of what all is out there*), which restrict harmful behavior in some way
* Frequent and automatic backups of the server, just reload a backup when he goes on a destruction spree.
* A second server occasionally duplicated from the first one that he can run around in. |
893 | I'm hosting a Minecraft server with 14 friends of mine playing on it. We peacefully build houses and structures, hold events, go kill the enderdragon, stuff like that. All is peaceful. Until one day, another friend of mine (let's call him "A") joined the server. Then our houses got griefed and burned. Our stuff is all gone. We (me, another owner, and 2 mods) took a month to investigate and finally found that "A" was griefing. We talked to him and told him not to grief again or else we'll kick him. And eventually we kicked him.
And now the problem begins. A moderator wrote to me saying that I should give "A" another chance, and that he apologized. So I thought, why not? Then, after I added him back -- on the very same day -- my best friend's house got filled with water. Checking the records, I found out that it was "A" again. I wanted to kick him, but it would hurt our friendship. I mean, we meet each other at school every day. He would be so mad at me. But if I don't kick him, 3 other players will leave the server.
What should I do to solve this mess? | 2014/11/25 | [
"https://moderators.stackexchange.com/questions/893",
"https://moderators.stackexchange.com",
"https://moderators.stackexchange.com/users/708/"
]
| I think it is rather simple. You like this game, you enjoy playing it with other people.
Tell him that, if he values you as a friend, he will stop his behavior, if not just kick him.
People sometimes misses the real meaning of what is going on because they think is only an "online" event. But what if you were building real stuff, and he came and destroy it, would you accept that? What if you were writing a story on your computer, that is "virtual", would you like if he came and deleted it all?
You invest time in that game, is something you enjoy, the game is online, it may not be important, but your time and feelings are, if he can not accept/understand/respect that, do you think he will be able to understand in other contexts?
Value your time and feelings, and have friends that value them also. | Create a second server where you can play and have fun and leave him a copy where he can destroy if that is his prefered way of playing. |
893 | I'm hosting a Minecraft server with 14 friends of mine playing on it. We peacefully build houses and structures, hold events, go kill the enderdragon, stuff like that. All is peaceful. Until one day, another friend of mine (let's call him "A") joined the server. Then our houses got griefed and burned. Our stuff is all gone. We (me, another owner, and 2 mods) took a month to investigate and finally found that "A" was griefing. We talked to him and told him not to grief again or else we'll kick him. And eventually we kicked him.
And now the problem begins. A moderator wrote to me saying that I should give "A" another chance, and that he apologized. So I thought, why not? Then, after I added him back -- on the very same day -- my best friend's house got filled with water. Checking the records, I found out that it was "A" again. I wanted to kick him, but it would hurt our friendship. I mean, we meet each other at school every day. He would be so mad at me. But if I don't kick him, 3 other players will leave the server.
What should I do to solve this mess? | 2014/11/25 | [
"https://moderators.stackexchange.com/questions/893",
"https://moderators.stackexchange.com",
"https://moderators.stackexchange.com/users/708/"
]
| In an ideal case, he should have to be obey all the same rules as any other member of the server, even if you did not know him in real life.
There are two ways to achieve this, the first is by excluding people who break the rules, the second is by making the rules impossible to break.
As an aside, you say, *"He would be mad at me"*, but I'm not sure how that is more important than you being mad at him, let alone whether he is even actually justified in being angry. Consider that you are putting his wants above your own *and* your other friends.
---
1. Explain to him that he *will* be kicked if he does it again, that these are the rules on the server and *any* case of griefing is dealt with in the same way. Then follow through.
---
2. If you would rather enforce your rules by modifying the game itself, then there are some protective things you can do for you and your friends.
* Mods which restrict certain people to a "starter area" are common in most public minecraft servers
* Possibly other mods (*I'm not aware of what all is out there*), which restrict harmful behavior in some way
* Frequent and automatic backups of the server, just reload a backup when he goes on a destruction spree.
* A second server occasionally duplicated from the first one that he can run around in. | Create a second server where you can play and have fun and leave him a copy where he can destroy if that is his prefered way of playing. |
68,967,488 | Check if there are any orders before a given date (`Date` column). The procedure has a passing parameter "date" as date and another passing parameter "count". This parameter returns the number of orders before this date.
The simple way of doing it would be:
```
SELECT COUNT([Sales].[dbo].[Order].[Date])
FROM [Sales].[dbo].[Order]
WHERE [Sales].[dbo].[Order].[Date] >= '2019-03-11'
```
But unfortunately I have to use the procedure and the cursor. My attempt is this:
```
CREATE OR ALTER PROCEDURE OrderBeforeDate
(@date date,
@count int OUT)
AS
BEGIN
SET @count = 0;
DECLARE cursor1 SCROLL CURSOR FOR
SELECT [Sales].[dbo].[Order].[Date]
FROM [Sales].[dbo].[Order]
FOR READ ONLY
OPEN cursor1;
FETCH NEXT FROM cursor1 INTO @date
WHILE @@FETCH_STATUS = 0
BEGIN
IF @date <= '2019-03-11'
SET @count = @count + 1;
END
CLOSE cursor1;
DEALLOCATE cursor1;
END
DECLARE @count int
EXEC OrderBeforeDate @count OUT
PRINT 'Number of Orders after 2019-03-11'': ' + CAST(@count AS VARCHAR(10))
```
But I get the following error message:
>
> Operand type collision: int is incompatible with date
>
>
>
I don't know what to do. Please give me a helping hand. | 2021/08/28 | [
"https://Stackoverflow.com/questions/68967488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16769977/"
]
| You are not passing the expected parameters. In your mock-up I would expect to see
```
DECLARE @count int=0, @Date date='20190311'
EXEC OrderBeforeDate @Date, @count OUT
PRINT 'Number of Orders after 2019-03-11: ' + CAST(@count AS VARCHAR(10))
```
I would also point out (as you presumably already know) this cursor serves no purpose other than to put the brakes on SQL Server performance.
Also your procedure is counting rows *before* your date value, your `print` statement states the opposite. | Probably you miss giving the value for date parameter when call OrderBeforeDate procedure. You only pass in 1 argument and SQL server may regard @count value as the value for date paramter.
```
EXEC OrderBeforeDate @count OUT
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.