qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
6,073,935 | I have installed the Java 3D API on PC via the exe installer, which simply created a new directory with `j3dcore.jar`, `vecmath.jar`, `j3dutils.jar` in a lib sub-directory and `j3dcore-ogl.dll` in a bin sub-directory.
Netbeans had no issues and my code compiled and executed smoothly, however once I built my project and tried to run it from the command prompt I got an `UnsatisfiedLinkError` saying that `no j3dcore-ogl in java.library.path`.
Google came to the rescue and gave me 3 viable solutions:
* by copying the dll file into my JRE's bin directory
* by adding the path of the dll file to the library path (`java -Djava.library.path=dllpath`)
* load the dll in the program with `System.load()` (I couldn't get this one to work, actually)
My question is: Is there an elegant solution to this problem, that I missed?
It seems tedious that for each different PC someone would like to use this program on, he'd have to either copy the dll or add it to the library path before it can run. (Side question: How come Netbeans didn't have a problem with the dll?) | 2011/05/20 | [
"https://Stackoverflow.com/questions/6073935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/639422/"
] | >
> Making my Java program easily distributable
>
>
>
If you mean 'easy for the end user' look to [Java Web Start](https://stackoverflow.com/tags/java-web-start/info).
---
A passer-by asks:
>
> Can you package the dll dependencies with Web Start?
>
>
>
Yes, but much, much better. You can package the natives for each platform in separate Jars, and supply them only to the platform that uses that native, even so far as partitioning the download between 32 & 64 bit versions of the natives.
JWS puts the natives on the run-time class-path of the application, ready for loading in code.
This all happens automatically for the end user, they click a link, approve the trust dialog(s) when asked, and the application installs - possibly with desktop integration, and appears on screen like magic.
JWS apps. that use natives need to be distributed as `all-permissions` security level, because the JVM cannot guarantee the actions of anything that 'goes native'. |
44,608,964 | ```
pt=new Date(2019,11,12,8,2,3)
console.log(pt.getFullYear()," ",pt.getMonth());
```
gives result `2019 " " 11`
```
console.log(pt.getFullYear()+" "+pt.getMonth());
```
gives the result as `2019 11`
What is the difference between using, and + in this example? | 2017/06/17 | [
"https://Stackoverflow.com/questions/44608964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3967709/"
] | The first of these gives three separate arguments to console.log, while the second appends the three together, then passes that as a single argument to console.log. |
343,937 | I need to take some online tests for school.
This website tells me I need Flash Player 11.3.0 or higher. As far as I can see that is not yet avaible for Linux.
I use Ubuntu 12.04 LTS and Chromium. Is there a way I can work around it?
Greetz. Rob. | 2013/09/10 | [
"https://askubuntu.com/questions/343937",
"https://askubuntu.com",
"https://askubuntu.com/users/191781/"
] | The best way to get Flash Player 11.2+ is to use Google Chrome in Ubuntu. There is no other way to get it, because a higher version has not been released for Ubuntu.
[Download Google Chrome From Here](https://www.google.com/intl/en/chrome/browser/)
Select your OS version x86 or x64 and download it to any path.
Then you can open it with the Ubuntu Software Center to install.
You can also install by executing command:
```
sudo dpkg -i <googlechromefile.deb>
```
Hope it helps you somewhat!! |
40,155,466 | we got homework to make convertor of weights where the fields are updated while typing the number (no need to click "calculate" or anything). one of the students offered the code below.
the code works: when putting a number in field 1, field 2 changes while typing.
what i dont understand is how does that work?
in the `onKey` method, no value is given to `View` `int` and `keyEvent`
so how does the listener "knows" on which view to and what keys to listen to or what event to activate ?
```
public class Screen extends Activity {
double weight = 2.20462;
EditText kgEdit, lbsEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
kgEdit = (EditText) findViewById(R.id.kgEdit);
lbsEdit = (EditText) findViewById(R.id.lbsEdit);
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
}
});
lbsEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
String lbs = lbsEdit.getText().toString();
if (lbs.isEmpty()) {
kgEdit.setText("");
} else {
double num = Double.valueOf(lbsEdit.getText().toString()) / weight;
kgEdit.setText(num + "");
}
return false;
}
});
}
```
} | 2016/10/20 | [
"https://Stackoverflow.com/questions/40155466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932394/"
] | I'm going to focus on just 1 of the text fields to answer this. Look at this first line:
`kgEdit = (EditText) findViewById(R.id.kgEdit);`
All this does is get a reference to the `EditText` for entering kg. Now that there is a reference, we can call methods on that object.
Next, we have this:
```
kgEdit.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// ...
}
}
```
What the above does is the following. Take our reference to the `EditText` for kilograms that we retrieved in our first line. The method `setOnKeyListener` does the following (from [here](https://developer.android.com/reference/android/view/View.html#setOnKeyListener(android.view.View.OnKeyListener))): "Register a callback to be invoked when a hardware key is pressed in this view."
What this means is that you've now told the view that you want to be informed every time the user presses a key while this EditText has the focus. You make this call to the Android API and in the background Android handles everything you're asking. It will call the method with the `View view`, `int keyCode` and `KeyEvent event`. You give it a method that then handles those inputs. So nowhere in your code do you need to call the method, Android calls it in the background where you'll never have to see or worry about it.
Now, because you called the method on `kgEdit`, that means the following code will ONLY be called when `kgEdit` is focused and keys are typed, so there's no confusion with the other `EditText`. It gets its own method call later, just below. Here's the rest of the code inside the `setOnKeyListener`:
```
String kg = kgEdit.getText().toString();
if (kg.isEmpty()) {
lbsEdit.setText("");
} else {
double num = Double.valueOf(kgEdit.getText().toString()) * weight;
lbsEdit.setText(num + "");
}
return false;
```
What this does is get the current text in `kgEdit`, which has already been updated with the key the user pressed. And it just checks if the text is empty, and if so remove the text in `lbsEdit`. If it's not empty, then get the text, convert it to a number, convert the number from kg to lbs and update `lbsEdit` |
19,074,447 | I have to go into a table to retrieve a parameter, then go back into the same table to retrieve data based on the parameter.
```
<cfquery name = "selnm" datasource = "Moxart">
select SelName from AuxXref
where Fieldname = <cfqueryparam value = "#orig#">
</cfquery>
<cfset selname = selnm.SelName>
<cfquery name = "fld" datasource = "Moxart">
select Fieldname, DBname from AuxXref
where SelName = <cfqueryparam value = "#selname#">
</cfquery>
```
Can this be done in a single query? | 2013/09/29 | [
"https://Stackoverflow.com/questions/19074447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1497281/"
] | You can do this in one query like so:
```
<cfquery name = "fld" datasource = "Moxart">
select Fieldname, DBname, SelName from AuxXref
where SelName = <cfqueryparam value = "#orig#">
AND FieldName = <cfqueryparam value = "#orig#">
</cfquery>
``` |
115,794 | **Rules**
1. Place some pentominoes into an 8 x 8 grid. They do not touch each other. They can touch only diagonally (with corner).
2. Pentominoes cannot repeat in the grid. Rotations and reflections of a pentomino are considered the same shape.
3. Grid is 8 x 8. | 2022/04/17 | [
"https://puzzling.stackexchange.com/questions/115794",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/79520/"
] | With integer programming, I managed to place
>
> 8 pieces, proved to be optimal
>
>
>
like this.
>
> $$\begin{array}{cccccccc} 3&3&3&3& &5&5&5\\ 3& & & & &5& &5\\ &4&4&4&4& &A&\\ 6& & &4& &A&A&A\\ 6&6&6& &8& &A&\\ & &6& &8&8& &B\\ 2&2& &8&8& &B&B\\2&2&2& & &B&B&\\ \end{array}$$
>
>
>
Here is my formulation. I happened to solve a similar model to solve a puzzle called One puzzle a day. Let $B$ be the set of cells in the 8x8 board, and $P$ be the set of all kinds of pieces (rotating and flipping count difference here), so I have $|P|=63$, then we need to choose a subset of $P$ and place them only by translation. Let binary variable $x\_{pb}$ indicate whether the piece $p$ is placed on the cell $b$ (some predefined reference point on the piece being on $b$). Let the set $P\_i\subset P$ represent all flipped and rotated version of a same pentomino, and binary variable $y\_i$ indicates whether the pentomino $i$ is placed on the board, so we have
$$
y\_i = \sum\_{p\in P\_i} \sum\_{b\in B} x\_{pb}
$$
and the objective is to maximize $\sum\_i y\_i$.
Putting the reference point on some cells make the tile out of the board, let that set be $F\_p$, we have
$$
x\_{pb} = 0 \quad\forall b \in F\_p.
$$
Now the main part. Actually in every cell $b$, we could find all possible $(p,b')$ that will cover the cell $b$, say the set is $Covered(b)$. By constraining $\sum\_{Covered(b)} x\_{pb'} \leq 1$, we could prevent overlap. To prevent neighboring, I build sets $Edge(b) = \{(p, b')\}$ similarly, which means if putting $p$ in $b'$, the cell $b$ will be on the edge of that piece. Then we need some constraints like
$$
\alpha \sum\_{(p,b')\in Covered(b)} x\_{pb'} + \beta \sum\_{(p,b') \in Edge(b)} x\_{pb'} \leq \delta
$$
The parameters $\alpha, \beta, \delta >0$should satisfy that $\alpha \leq \delta$, $4\beta \leq \delta$, $\alpha + \beta > \delta$, $2\alpha > \delta$, meaning that "one cover is allowed", "four edges on the same cell is allowed", "one cover and one edge is not allowed" (that is when two pieces are next to each other) and "no overlap".
I chose $\alpha=\delta=1, \beta=0.25$ (actually any $\beta > 0$ works...).
That is all constraints we need. |
44,410,809 | I'm looking for changing the **TextView** Sizes automatically. And I found the solution as well. Here is the official [Doc](https://developer.android.com/preview/features/autosizing-textview.html) for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.
Here is the my xml code and gradle code snippets
myactivity.xml
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<include layout="@layout/toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:autoSizeTextType="uniform"/>
</LinearLayout>
```
Gradle snippet
```
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:support-v4:25.2.0'//Added support library
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
testCompile 'junit:junit:4.12'
}
``` | 2017/06/07 | [
"https://Stackoverflow.com/questions/44410809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3824298/"
] | As stated in the [docs](https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview.html#setting-textview-autosize):
>
> The Support Library 26.0 provides full support to the autosizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The library provides support to Android 4.0 (API level 14) and higher. **The android.support.v4.widget package contains the TextViewCompat** class to access features in a backward-compatible fashion.
>
>
>
You need to replace `TextView` with `AppCompatTextView` and upgrade your support lib to v26.0.0 in order to use that feature.
```
compile 'com.android.support:support-v4:26.0.0'
```
Don't forget to upgrade your `buildToolsVersion` to `26.0.0` and `compileSdkVersion` to `26` as well. |
52,007,637 | I have the following string that corresponds to a JSON object.
```
$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}'
```
And I would like to cast it to a `stdClass`. My current solution:
```
$object = (object)(array)json_decode($string);
```
While this is functioning, is there a better way? This seems messy and inefficient. | 2018/08/24 | [
"https://Stackoverflow.com/questions/52007637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8115861/"
] | A much cleaner way would be:
```
$string = '{"status": "success", "count": 3, "data": [{"id": 112233}]}';
$object = json_decode($string);
```
check out what the output for print\_r($object); looks like:
```
stdClass Object
(
[status] => success
[count] => 3
[data] => Array
(
[0] => stdClass Object
(
[id] => 112233
)
)
``` |
2,829,287 | For example,
User adds this "iamsmelly.com".
And if I add an href to this, the link would be
www.mywebsite.com/iamsmelly.com
Is there a way to make it absolute if its not prepended by an http:// ?
Or should I revert to jQuery for this? | 2010/05/13 | [
"https://Stackoverflow.com/questions/2829287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93311/"
] | Probably a good place to handle this is in a `before_save` on your model. I'm not aware of a predefined helper (though `auto_link` comes somewhat close) but a relatively simple regexp should do the job:
```
class User < ActiveRecord::Base
before_save :check_links
def check_links
self.link = "http://" + self.link unless self.link.match /^(https?|ftp):\/\//
end
end
``` |
16,114,993 | I have a `<div id="content">`. I want to load the content from <http://vietduc24h.com> into my `div`:
```
<html>
<head>
<script type="text/javascript">
$(document).ready(function()
{
$("#content").attr("src","http://vietduc24h.com");
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html
```
I don't want to use an iframe. How can I do this? | 2013/04/19 | [
"https://Stackoverflow.com/questions/16114993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2300976/"
] | You need to think about CORS in this aspect. The code you need to have is:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("http://vietduc24h.com");
})
</script>
```
When your domain is not inside `vietduc24h.com`, you might get some security exception. In order to avoid that, you can host a local proxy here. In PHP, we do this way (`url.php`):
```
<?php
$url = file_get_contents(urlencode($_GET["url"]));
echo $url;
?>
```
And in the script, you need to modify this way:
```
<script type="text/javascript">
$(document).ready(function()
{
$("#content").load("proxy.php?url=http://vietduc24h.com");
})
</script>
``` |
7,262,136 | ![http://farm4.static.flickr.com/3338/4564960137_0d3c09192d_o.png](https://i.stack.imgur.com/Y2gpf.png)
can we change text in this lightbox
want to change "This site requires that you Connect with Facebook." and "Connect with Facebook to Continue" | 2011/08/31 | [
"https://Stackoverflow.com/questions/7262136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922283/"
] | For most (if not all) arithmetic operations, Java will assume you want the maximum defined precision. Imagine if you did this:
```
long a = ...;
int b = ...;
long c = a % b + Integer.MAX_VALUE;
```
If Java automatically down-casted `a % b` to an `int`, then the above code would cause an `int` overflow rather than setting `c` to a perfectly reasonable `long` value.
This is the same reason that performing operations with a `double` and an `int` will produce a `double`. It's much safer to up-cast the least-accurate value to a more accurate one. Then if the programmer knows more than the compiler and wants to down-cast, he can do it explicitly.
Update
------
Also, after thinking more about this, I'm guessing most CPU architectures don't have operations that combine 32-bit and 64-bit values. So the 32-bit value would need to be promoted to a 64-bit value just to use it as an argument to the CPU's mod operation, and the result of that operation would be a 64-bit value natively. A down-cast to an `int` would add an operation, which has performance implications. Combining that fact with the idea that you might actually want to keep a `long` value for other operations (as I mention above), it really wouldn't make sense to force the result into an `int` unless the developer explicitly wants it to be one. |
45,507,197 | This is about converting the enumeration values to a string array. I have an enumeration:
```
enum Weather {
RAINY, SUNNY, STORMY
}
```
And I want to convert this to a string array with minimal effort and no loops with Java 8+. This is the best I came up with:
```
Arrays.stream(Weather.values()).map(Enum::toString).toArray(String[]::new)
```
Any other and similarly or more convenient ways to do the same thing? | 2017/08/04 | [
"https://Stackoverflow.com/questions/45507197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2735286/"
] | Original post
=============
Yes, that's a good Java 8 way, but...
The `toString` can be overridden, so you'd better go with `Weather::name` which returns the name of an enum constant (exactly as declared in the enum declaration) and can't be changed:
```
Stream.of(Weather.values()).map(Weather::name).toArray(String[]::new);
```
---
A bit of generics
=================
I wrote a helper class to deal with any enum in a generic way:
```
class EnumUtils {
public static <T extends Enum<T>> String[] getStringValues(Class<T> enumClass) {
return getStringValuesWithStringExtractor(enumClass, Enum::name);
}
public static <T extends Enum<T>> String[] getStringValuesWithStringExtractor(
Class<T> enumClass,
Function<? super T, String> extractor
) {
return of(enumClass.getEnumConstants()).map(extractor).toArray(String[]::new);
}
}
```
Here is a demonstration:
```
enum Weather {
RAINY, SUNNY, STORMY;
@Override
public String toString() {
return String.valueOf(hashCode());
}
public static void main(String[] args) {
System.out.println(Arrays.toString(EnumUtils.getStringValues(Weather.class)));
System.out.println(Arrays.toString(EnumUtils.getStringValuesWithStringExtractor(Weather.class, Weather::toString)));
}
}
```
And the output:
```
[RAINY, SUNNY, STORMY]
[359023572, 305808283, 2111991224]
``` |
26,351 | I was studying for icing and a tailplane stall. I have looked up some internet pages and instrument flying handbook, and found the procedure below.
1. raise flaps to the previous setting. (To reduce down wash from the main wing so that reducing negative angle of attack of the tail and break the stall)
2. apply nose up elevator pressure (I don't get it. The nose up pressure will make the elevator to go up and wouldn't this increase the negative angle of attack and worsen the stall?)
3. do not increase airspeed unless it is necessary to avoid a wing stall. (Why shouldn't we increase airspeed?)
So now I'm trying to understand the reason why should a pilot do such actions. Can you help me out? | 2016/03/23 | [
"https://aviation.stackexchange.com/questions/26351",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/6831/"
] | Lets start with the very basic concepts....
In most aircraft, the Centre of Gravity (cg) is somewhat forward of the wing or mainplane Centre of Pressure. The exact distance between the cg and the Centre of pressure will depend on aircraft loading, configuration, thrust setting and drag. However, cg forward of the Centre of Pressure produces a nose-down pitching moment. The horizontal stabilizer, or tailplane, then provides a downward force to overcome this normal, nose-down, pitching moment.
The tailplane behaves as an ‘upside down’ wing and operates with negative Angle of Attack (AOA) as shown in Figure 1
***Positive and Negative Angle of Attack***
![enter image description here](https://i.stack.imgur.com/60asc.jpg)
Figure 1 - Positive and Negative Angle of Attack
If the horizontal stabiliser becomes contaminated with ice, airflow separation from the surface can prevent it from providing sufficient downward force or negative lift to balance the aircraft and a nose-down pitch upset can occur.
When compared to an aircraft's mainplane, the horizontal stabiliser normally has a thinner aerofoil with a sharper leading edge. Differences in the ice collection efficiency or catch rate between the two surfaces means ice accumulates faster on the horizontal stabiliser and may form before any ice is present on the aircraft's mainplane.
Tailplane stall can occur at relatively high speeds, well above the normal 1G stall speed of the mainplane. Typically, tailplane stall induced by icing is most likely to occur near the flap limit speed when the flaps are extended to the landing position, especially when extension is combined with a nose down pitching manoeuvre, airspeed change, power change or flight through turbulence. Aircraft stall warning systems provide warnings based on an uncontaminated mainplane stall so during a tailplane stall induced upset there will be NO artificial stall warning indications, such as a stick shaker, warning horn or the mainplane or flap buffeting normally associated with a mainplane stall.
**Tailplane Stall Aerodynamics**
1. The horizontal stabiliser, or tailplane, of an aircraft is an aerofoil that provides a downward force to overcome the aircraft's normal nose-down pitching moment. The further forward the Centre of Gravity is from the Center of Pressure, the greater the nose down moment and, thus, the greater the amount of down-force that must be generated by the tailplane. This, in turn, requires a greater negative tailplane angle of attack (AOA). angle of attack (AOA).
[As shown in Figure 1, The tailplane is effectively an upside down aerofoil so an increase in negative tailplane AOA occurs with UP elevator movement or when the aircraft is pitching nose down.]
2. Accumulation of ice on the tailplane will result in disruption of the normal airflow around that surface and will reduce the critical (or stalling) negative AOA of the horizontal stabiliser.
3. Ice can accumulate on the tailplane before it begins to accumulate on the mainplane or other parts of the aircraft.
4. Flaps extension usually moves the mainplane Centre of Pressure aft, lengthening the arm between the Centre of Pressure and the cg and increasing the mainplane nose down moment. More down force is required from the tailplane to counter this moment, necessitating a higher negative tailplane AOA.
5. Flap extension, especially near the maximum extension speed, increases the negative tailplane AOA due to the increase in downwash, as shown in Figure 2
6. Increasing the power setting on a propeller driven aircraft may, depending on aircraft configuration and flap settings, increase the downwash and negative tailplane AOA.
7. When the critical negative AOA of the horizontal stabiliser is exceeded causing it to stall.
8. Tailplane stall drastically reduces the downward force it produces, creating a rapid aircraft nose-down pitching moment.
**Effect of mainplane flap on downwash**
![enter image description here](https://i.stack.imgur.com/xHo2B.jpg)
Figure 2 - Effect of mainplane flap on downwash
On aircraft with reversible (unpowered) elevator, tailplane airflow changes caused by ice accretion may lead to an aerodynamic overbalance driving the elevator trailing edge down and pitching the aircraft nose down. This can occur separately from or in combination with the nose down pitching moment caused by tailplane stall. The yoke may be snatched forward out of the pilot’s hands and the control force required for the pilot to return the elevator to neutral or to a nose-up deflection can be significant and potentially greater than the pilot can exert.
**now match with your recovery actions**
1. You have no doubt with your 1st point.
2. The second point: You have to resist the nose down elevator movement. Once the tailplane is already stalled then you have to assume the elevator has already gone in down position to make your ac nose down. So you have to apply nose up elevator pressure.
3. You should not increase the airspeed cause it might make the situation worse. Cause in dive with increased airspeed is always difficult to maintain the aircraft control. And you might end up with overstressing the elevator which is not good at all in such condition. |
2,093,466 | I understand that division by zero isn't allowed, but we merely just multiplied $f(x) = 1$ by $\frac{x-1}{x-1}$ to get $f(x) = \frac{x-1}{x-1}$ and $a\cdot 1 = 1\cdot a = a$ so they're the **same function** but with **different domain** how is this possible?
*Or in other words* why don't we simplify $f(x) = \frac{x-1}{x-1}$ to $f(x) = 1$ before plotting the points.
Is it just defined this way or is there a particular reason ?
**Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
$f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$. | 2017/01/11 | [
"https://math.stackexchange.com/questions/2093466",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/406041/"
] | They are the same *almost everywhere*. But clearly one of them does not exist for $x=1$ (since "$\tfrac{0}{0}$" is undefined), while the other one is simply $1$ at $x=1$.
>
> I understand that division by zero isn't allowed, but we merely just multiplied f(x) = 1 by (x-1)/(x-1)
>
>
>
You can multiply by any fraction $\tfrac{a}{a}$; but not when $a=0$ because the fraction you want to multiply with, isn't even defined then. So multiplying by $\tfrac{x-1}{x-1}$ is fine, but only valid for $x \ne 1$.
>
> why don't we simplify f(x) = (x-1)/(x-1) to f(x) = 1 before plotting the points.
> Is it just defined this way or is there a particular reason ?
>
>
>
You can simplify, but recall that simplifying is actually dividing numerator and denominator by the same number: you can simplify $\tfrac{ka}{kb}$ to $\tfrac{a}{b}$ by dividing by $k$. But also then: this only works for $k \ne 0$ since you can't divide by $0$. So "simplifying" $\tfrac{x-1}{x-1}$ to $1$ is fine, for $x-1 \ne 0$ so for $x \ne 1$.
---
>
> **Note:** my book says the domain of $f(x) = 1$ is $\mathbb{R}$ and the domain of
> $f(x) = \frac{x-1}{x-1}$ is $\mathbb{R}$ except $1$.
>
>
>
Technically, the domain is a part of the function: it should be given (as well as the codomain). It is very common though that when unspecified, in the context of real-valued functions of a real variable, we assume the 'maximal domain' is intended (and $\mathbb{R}$ is taken as codomain). Then look at:
$$f : \mathbb{R} \to \mathbb{R} : x \mapsto f(x) = 1$$
and
$$g : \mathbb{R} \setminus \left\{ 1 \right\} \to \mathbb{R} : x \mapsto g(x) = \frac{x-1}{x-1}$$
The functions $f$ and $g$ are different, but $f(x) = g(x)=1$ for all $x$ except when $x=1$, where $g$ is undefined. |
59,133,760 | I have following HTML code
```
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-valid ng-star-inserted ng-dirty ng-touched" ng-reflect-model="false">
<label class="checkbox__label" for= "adapt-checkbox-453-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-453-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - ABC</span>
</div>
<div class="compatible-product ng-star-inserted">
<adapt-checkbox2 class="checkbox ng-untouched ng-pristine ng-valid ng-star-inserted">
<label class="checkbox__label" for="adapt-checkbox-454-input">
<input class="checkbox__input" type="checkbox" id="adapt-checkbox-454-input" tabindex="0" aria-label="" aria-checked="false">
<span class="checkbox__item">
<span class="sr-only" ng-reflect-ng-class="[object Object]"></span>
</span>
</label>
</adapt-checkbox2>
<span class="compatible-product-name" style="">Product - XYZ</span>
</div>
```
[Please check screenshot here](https://i.stack.imgur.com/0iOkd.png)
From which
1) First I need to select/click on "adapt-checkbox2" who is left to Span "Product - ABC"
So I have written code as follows
```
WebElement selectCompatibleProduct1 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - ABC']")));
selectCompatibleProduct1.click();
```
**Which is working fine. Its selecting the correct check-box.**
2) But Whenever I tried to select 2nd check-box its not working. Its again clicking/selecting 1st checkbox.
Code for 2nd checkbox is:-
```
WebElement selectCompatibleProduct2 = driver.findElement(RelativeLocator.withTagName("adapt-checkbox2").toLeftOf(By.xpath("//*[text()='Product - XYZ']")));
selectCompatibleProduct2.click();
```
Selenium Version is:- 4.0.0-alpha-3
Please can someone help me on this?
Thanks in advance. | 2019/12/02 | [
"https://Stackoverflow.com/questions/59133760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189243/"
] | Basically, you are getting an **Array of Object** and you want to access the last element of the array, you can **get last array position by** `array.length - 1`, and access the gfs value. if you want to **check whether gfs value is array** not then you can **check by** `typeof gfs`
```js
var data= [
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'base',
pos: 0,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 1,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'node',
pos: 2,
gfs: null
},
{
url: 'https://playy-test.s3.ap-south-1.amazonaws.com/hidden.mp4',
typ: 'boomerang',
pos: 3,
gfs: ['a','b','c']
}
]
// You can access like this
console.log(data[data.length-1].gfs)
``` |
299,700 | I was following [this tutorial](https://www.youtube.com/watch?v=lrvLnhm6Rqw&list=PLpVC00PAQQxHi-llE9Z8-Q747NYWpsq6t&index=32) on Drupal module development. It talks about database query joins in module development. The tutorial is made for Drupal 8 and I'm using Drupal 9.
Then I made this (look at the join part):
```
protected function load () {
$select = Database::getConnection()->select('rsvplist', 'r');
$select.join('users_field_data', 'u', 'r.uid = u.uid');
$select->join('node_field_data', 'n', 'r.nid = n.nid');
$select->addField('u', 'name');
$select->addField('n', 'title');
$select->addField('r', 'mail');
$entries = $select->execute()->fetchAll(\PDO::FETCH_ASSOC);
return $entries;
}
```
But get this error:
```
warning: join() expects at most 2 parameters, 3 given in Drupal\rsvplist\Controller\ReportController->load() (line 24 of /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php)
#0 /var/www/htdocs/drupal-modules/core/includes/bootstrap.inc(305): _drupal_error_handler_real(2, 'join() expects ...', '/var/www/htdocs...', 24)
#1 [internal function]: _drupal_error_handler(2, 'join() expects ...', '/var/www/htdocs...', 24, Array)
#2 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(24): join('users_field_dat...', 'u', 'r.uid = u.uid')
#3 /var/www/htdocs/drupal-modules/modules/custom/rsvplist/src/Controller/ReportController.php(52): Drupal\rsvplist\Controller\ReportController->load()
#4 [internal function]: Drupal\rsvplist\Controller\ReportController->report()
#5 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#6 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/Render/Renderer.php(573): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#7 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#8 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#9 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#10 /var/www/htdocs/drupal-modules/vendor/symfony/http-kernel/HttpKernel.php(80): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#11 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/Session.php(57): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#12 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(47): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#13 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#14 /var/www/htdocs/drupal-modules/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#15 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(47): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#16 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(52): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /var/www/htdocs/drupal-modules/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /var/www/htdocs/drupal-modules/core/lib/Drupal/Core/DrupalKernel.php(706): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /var/www/htdocs/drupal-modules/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#20 {main}
```
Drupal 9's join don't accepts the third argument:
```
'r.uid = u.uid'
```
A made some research but I was not able to find an equivalent example about how to use join this way in Drupap 9 documentation and other sources.
How can I add joins to a query in Drupal 9? | 2021/01/25 | [
"https://drupal.stackexchange.com/questions/299700",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/102226/"
] | In PHP:
* `.` is the string concatenation operator, not the one to call an object method
* [`join()`](https://www.php.net/manual/en/function.join.php) is an alias for the [`implode()`](https://www.php.net/manual/en/function.implode.php) function, which effectively requires 2 arguments, not 3
This means that `$select.join('users_field_data', 'u', 'r.uid = u.uid')` (which PHP reads as `$select . join('users_field_data', 'u', 'r.uid = u.uid')`) is:
* Converting the value contained in `$select` to a string
* Concatenating that string with the string returned by `implode()`
The arguments accepted by [`implode()`](https://www.php.net/manual/en/function.implode.php) has been changed in the latest PHP versions, but the function has never accepted three arguments, and the first two arguments has never been two strings.
This explains the error you are getting.
In Drupal 9, if `$select` is an object implementing [`SelectInterface`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21SelectInterface.php/interface/SelectInterface/9.0.x), [`$select->join()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21Select.php/function/Select%3A%3Ajoin/9.0.x) is an available method.
```php
public function join($table, $alias = NULL, $condition = NULL, $arguments = []) {
return $this->addJoin('INNER', $table, $alias, $condition, $arguments);
}
```
Instead of `$select->join()`, you could call `$select->addJoin()`.
The first method doesn't require to specify the first or the last argument of `$select->addJoin()`, and it's the normally called method.
As side note, instead of using `$select` on database tables used for entity data, it's generally preferable to use the class returned from [`Drupal::entityQuery()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AentityQuery/9.0.x). |
74,243,879 | I want to use UTC dates in my Node.js backend app, however, I need to be able to set time (hours and minutes) in a local/user-specified timezone.
I am looking for a solution in either pure JS or using `dayjs`. I am not looking for a solution in `moment`.
It seemed like using `dayjs` I could solve this problem quite easily, however, I could not find a way to accomplish this.
I can use UTC timezone by using [`dayjs.utc()`](https://day.js.org/docs/en/plugin/utc) or using [`dayjs.tz(someDate, 'Etc/UTC')`](https://day.js.org/docs/en/timezone/timezone).
When using `dayjs.utc()`, I cannot use/specify other timezones for *anything*, therefore I could not find a way to tell `dayjs` I want to set hours/minutes in a particular (non-UTC) timezone.
When using `dayjs.tz()`, I still cannot define a timezone of time I want to set to a particular date.
### Example in plain JS
My locale timezone is `Europe/Slovakia` (CEST = UTC+02 with DST, CET = UTC+1 without DST), however, I want this to work with any timezone.
```js
// Expected outcome
// old: 2022-10-29T10:00:00.000Z
// new time: 10h 15m CEST
// new: 2022-10-29T08:15:00.000Z
// Plain JS
const now = new Date('2022-10-29T10:00:00.000Z')
const hours = 10
const minutes = 15
now.setHours(10)
now.setMinutes(15)
// As my default timezone is `Europe/Bratislava`, it seems to work as expected
console.log(now)
// Output: 2022-10-29T08:15:00.000Z
// However, it won't work with timezones other than my local timezone
```
### (Nearly) a solution
***Update: I posted a working function in [this answer](https://stackoverflow.com/a/74245936/3408342).***
The following functions seems to work for most test cases, however, it fails for 6 4 cases known to me (any help is greatly appreciated):
* [DST to ST] `now` in DST before double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in DST during double hour, `newDate` in ST during double hour;
* [DST to ST] `now` in ST during double hour, `newDate` in DST during double hour;
* [DST to ST] `now` in ST after double hour, `newDate` in DST during double hour;
* [ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour;
* [ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour.
I think the only missing piece is to find a way to check if a particular date in a non-UTC timezone falls into double hour. By *double hour* I mean a situation caused by changint DST to ST, i.e. setting our clock back an hour (e.g. at 3am to 2am → double hour is between `02:00:00.000` and `02:59:59.999`, which occur both in DST and ST).
```js
/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
// TODO: Rename the property to `{h, m, s, ms}`.
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.indexOf(v) !== -1)
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour',
time: {h: 1, m: 55}
},
// FIXME
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour',
time: {h: 3, m: 55}
}
// TODO: Add a test of a date in DST and ST on a day on which there is no timezone change (two tests in total, one for DST and another for ST).
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)
``` | 2022/10/29 | [
"https://Stackoverflow.com/questions/74243879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408342/"
] | I created the following function that sets the time in a local timezone, for example, if you have `Date` object and you want to change its time (but not date in a particular timezone, regardless of the UTC date of that time), you provide this function with that `Date` object, the required time, timezone and optionally whether you prefer using the new timezone (see below).
I had to add `preferNewTimezone` parameter because off so-called *double hours* (hours in a non-UTC timezone that occur twice because of setting the clock back by an hour), as those failed to output the date (including timezone offset) I expected.
I don’t say it is fast nor perfect, however, it works. :)
I have created 52 tests of this function in `Europe/Bratislava` timezone. They all pass. I presume it’ll work for any timezone. If not and you find an issue or have an improvement/optimisation, I want to hear about it.
```js
/**
* Set time provided in a timezone
*
* @param {Date} [dto.date = new Date()] Date object to work with
* @param {boolean} [dto.preferNewTimezone = false] Whether to prefer new timezone for double hours
* @param {number} [dto.time.h = 0] Hour to set
* @param {number} [dto.time.m = 0] Minute to set
* @param {number} [dto.time.s = 0] Second to set
* @param {number} [dto.time.ms = 0] Millisecond to set
* @param {string} [dto.timezone = 'Europe/Bratislava'] Timezone of `dto.time`
*
* @return {Date} Date object
*/
function setLocalTime(dto = {
date: new Date(),
preferNewTimezone: false,
time: {h: 0, m: 0, ms: 0, s: 0},
timezone: 'Europe/Bratislava'
}) {
const defaultTime = {h: 0, m: 0, ms: 0, s: 0}
const defaultTimeKeys = Object.keys(defaultTime)
// src: https://stackoverflow.com/a/44118363/3408342
if (!Intl || !Intl.DateTimeFormat().resolvedOptions().timeZone) {
throw new Error('`Intl` API is not available or it does not contain a list of timezone identifiers in this environment')
}
if (!(dto.date instanceof Date)) {
throw Error('`date` must be a `Date` object.')
}
try {
Intl.DateTimeFormat(undefined, {timeZone: dto.timezone})
} catch (e) {
throw Error('`timezone` must be a valid IANA timezone.')
}
if (
typeof dto.time !== 'undefined'
&& typeof dto.time !== 'object'
&& dto.time instanceof Object
&& Object.keys(dto.time).every(v => defaultTimeKeys.includes(v))
) {
throw Error('`time` must be an object of `{h: number, m: number, s: number, ms: number}` format, where numbers should be valid time values.')
}
dto.time = Object.assign({}, defaultTime, dto.time)
/**
* Whether a date falls in double hour in a particular timezone
*
* @param {Date} dto.date Date
* @param {string} dto.timezone IANA timezone
* @return {boolean} `true` if the specified Date falls in double hour in a particular timezone, `false` otherwise
*/
const isInDoubleHour = (dto = {date: new Date(), timezone: 'Europe/Bratislava'}) => {
// Get hour in `dto.timezone` of timezones an hour before and after `dto.date`
const hourBeforeHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() - 1)))?.[0].value
const hourDateHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(dto.date)?.[0].value
const hourAfterHour = +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(new Date(new Date(dto.date).setUTCHours(dto.date.getUTCHours() + 1)))?.[0].value
return hourBeforeHour === hourDateHour || hourAfterHour === hourDateHour
}
const getTimezoneOffsetHours = ({date, localisedDate, returnNumber, timezone}) => {
let offsetString
if (localisedDate) {
offsetString = localisedDate.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
} else {
offsetString = new Intl
.DateTimeFormat('en-GB', {timeZone: timezone, timeZoneName: 'longOffset'})
.formatToParts(date)
.find(i => i.type === 'timeZoneName').value.match(/[\d+:-]+$/)?.[0]
}
return returnNumber ? offsetString.split(':').reduce((a, c) => /^[+-]/.test(c) ? +c * 60 : a + +c, 0) : offsetString
}
/**
* Pad a number with zeros from left to a required length
*
* @param {number} n Number
* @param {number} len Length
* @return {string} Padded number
*/
const pad = (n, len) => `00${n}`.slice(-len)
let [datePart, offset] = dto.date.toLocaleDateString('sv', {
timeZone: dto.timezone,
timeZoneName: 'longOffset'
}).split(/ GMT|\//)
offset = offset.replace(String.fromCharCode(8722), '-')
const newDateWithoutOffset = `${datePart}T${pad(dto.time.h || 0, 2)}:${pad(dto.time.m || 0, 2)}:${pad(dto.time.s || 0, 2)}.${pad(dto.time.ms || 0, 3)}`
let newDate = new Date(`${newDateWithoutOffset}${offset}`)
const newDateTimezoneOffsetHours = getTimezoneOffsetHours({date: newDate, timezone: dto.timezone})
// Check if timezones of `dto.date` and `newDate` match; if not, use the new timezone to re-create `newDate`
newDate = newDateTimezoneOffsetHours === offset
? newDate
: new Date(`${newDateWithoutOffset}${newDateTimezoneOffsetHours}`)
// Invalidate the date in `newDate` when the hour defined by user is not the same as the hour of `newDate` formatted in the user-defined timezone
if (dto.time.h !== +new Intl.DateTimeFormat('en-GB', {hour: 'numeric', timeZone: dto.timezone}).formatToParts(newDate)?.[0].value) {
newDate = new Date('')
}
// Check if the user prefers using the new timezone when `newDate` is in double hour
newDate = dto.preferNewTimezone && !isNaN(newDate) && isInDoubleHour({date: newDate, timezone: dto.timezone})
? new Date(`${newDateWithoutOffset}${getTimezoneOffsetHours({date: new Date(new Date(newDate).setUTCHours(dto.date.getUTCHours() + 1)), timezone: dto.timezone})}`)
: newDate
return newDate
}
const timezoneIana = 'Europe/Bratislava'
const tests = [
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: false,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [don\'t prefer new timezone]',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [don\'t prefer new timezone]',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: false,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-29T23:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST before double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in DST during double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST during double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '30/10/2022, 01:55:00 GMT+02:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in DST before double hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 02:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST during double hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '30/10/2022, 03:55:00 GMT+01:00',
now: new Date('2022-10-30T02:56:12.006Z'),
preferNewTimezone: true,
testName: '[DST to ST] `now` in ST after double hour, `newDate` in ST after double hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T00:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in ST before skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '26/03/2023, 01:55:00 GMT+01:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST before skipped hour [prefer new timezone] ',
time: {h: 1, m: 55}
},
{
expString: 'Invalid Date',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in ST in skipped hour [prefer new timezone] ',
time: {h: 2, m: 55}
},
{
expString: '26/03/2023, 03:55:00 GMT+02:00',
now: new Date('2023-03-26T01:56:12.006Z'),
preferNewTimezone: true,
testName: '[ST to DST] `now` in DST after skipped hour, `newDate` in DST after skipped hour [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 03:55:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in ST, `newDate` in ST before `now` [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 12:00:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in ST, `newDate` in ST after `now` [prefer new timezone] ',
time: {h: 12}
},
{
expString: '01/07/2023, 03:55:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in DST, `newDate` in DST before `now` [prefer new timezone] ',
time: {h: 3, m: 55}
},
{
expString: '01/07/2023, 12:00:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: true,
testName: '[ST] `now` in DST, `newDate` in DST after `now` [prefer new timezone] ',
time: {h: 12}
},
{
expString: '01/01/2023, 03:55:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in ST, `newDate` in ST before `now` [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '01/01/2023, 12:00:00 GMT+01:00',
now: new Date('2023-01-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in ST, `newDate` in ST after `now` [don\'t prefer new timezone]',
time: {h: 12}
},
{
expString: '01/07/2023, 03:55:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in DST, `newDate` in DST before `now` [don\'t prefer new timezone]',
time: {h: 3, m: 55}
},
{
expString: '01/07/2023, 12:00:00 GMT+02:00',
now: new Date('2023-07-01T10:00:00.000Z'),
preferNewTimezone: false,
testName: '[ST] `now` in DST, `newDate` in DST after `now` [don\'t prefer new timezone]',
time: {h: 12}
}
]
const results = tests.map(t => {
const newDate = setLocalTime({date: t.now, preferNewTimezone: t.preferNewTimezone, time: t.time, timezone: timezoneIana})
const newDateString = newDate.toLocaleString('en-GB', {timeZone: timezoneIana, timeZoneName: 'longOffset'})
const testResult = newDateString === t.expString
if (testResult) {
console.log(testResult, `: ${t.testName} : ${newDateString}`)
} else {
console.log(testResult, `: ${t.testName} : ${newDateString} :`, {newDate, newDateString, test: t})
}
return testResult
}).reduce((a, c, i) => {
if (c) {
a.passed++
} else {
a.failed++
a.failedTestIds.push(i)
}
return a
}, {failed: 0, failedTestIds: [], passed: 0})
console.log(results)
``` |
199,880 | Is there any way to show a calculated field when I'm filling out a new item for a list?
For example:
If I select "Blue" in field1, and "Bird" in field2,
then, on the same page where I am filling in information, I can see field3(Calculated field) show a value of "Blue Jay"
Currently, the calculated field doesn't show until I add a new item.
It would be even better if the update was in real time, though I don't expect that. | 2016/11/17 | [
"https://sharepoint.stackexchange.com/questions/199880",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61825/"
] | **As a short answer** : unfortunately , No, the calculated field is calculated after the item added or updated
If you are using Enterprise Edition of SharePoint then try editing list form with InfoPath and insert field which will do the calculation for you. Make that field read-only and then publish the form.
In InfoPath , You can
* Add a Textbox as `field3` in your form
* At `field2` add new a `Action rule` and at **run these action select** `set a fields value`
* At **Field** Value select Field3
* At **Value** concatenate your `field1` and `field2`
[![enter image description here](https://i.stack.imgur.com/SN6jP.gif)](https://i.stack.imgur.com/SN6jP.gif) |
77,133 | There seems to be a lot of software to control (or emulate) mouse input through the keyboard, but what about the opposite?
Basically I'm looking for a way to emulate up/down/left/right clicks with mouse movement, at a fast rate (i.e. lots of very short and quick right clicks while I move the mouse to the right)
If I have to learn some scripting language to do it, ok, but I don't know if it would even be possible.
Note: This is meant to work on fullscreen, and having a way to turn it on/off with an F# key would be awesome!
Thanks for your time :) | 2009/11/30 | [
"https://superuser.com/questions/77133",
"https://superuser.com",
"https://superuser.com/users/19668/"
] | OK, hopefully supplying a *useful* answer this time, instead of the inverse of the actual answer you wanted...
How about an AutoHotkey script for [mouse gestures](http://www.autohotkey.com/docs/scripts/MouseGestures.htm)? You haven't indicated what sort of control you require, so perhaps a set of gestures is adequate. If, however, you're looking to essentially replace the whole keyboard with one mouse, well, this may not be the answer you need. Or, good luck memorizing all those gestures. :-D
---
As is so often the case, [AutoHotkey](http://www.autohotkey.com) is your tool. I won't bore you with extensive review or details, as Google (and even SuperUser) are loaded with info about it.
EDIT: In fact, here's a [ready-made script](http://www.autohotkey.com/docs/scripts/NumpadMouse.htm) that'll enable you to use your numeric keypad as a mouse, with several customizations. |
95,407 | I was playing some math games intended for children, in Japanese, and the subject was 引き算.
The isolated question came up "14は10といくつ?" In the context of 引き算 it makes sense that the answer turned out to be 4, but I don't understand the question structurally. How does it imply "If you take 10 away from 14, what's left?" Is this to be understood only in the context? Assuming the と is conditional, my rough translation is "As for 14... if (you take away) 10... how much(left)?" with everything in parenthesis being only implied. Is this correct? Are the は and と particles doing what I think? | 2022/07/15 | [
"https://japanese.stackexchange.com/questions/95407",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/41549/"
] | >
> Is this to be understood only in the context? Assuming the と is conditional
>
>
>
The と is not conditional, and you can tell that from the word followed by the と.
**The conditional と should follow 活用語の終止形/the terminal form of a conjugatable word**, such as verb, i/na-adjective, auxiliary, eg 「話す」「寒い」「静かだ」「〇〇だ」「~ない」. It *cannot* follow a 体言(unconjugatable word).
>
> Eg.
>
> **食べると**太ってしまう
>
> **明るいと**眠れない
>
> **静かだと**勉強がはかどる
>
> 佐藤さんが**いないと**困る
>
>
>
When と is attached to a 体言 (unconjugatable word) as in your example where と is attached to 「10」, it should be the case particle (格助詞).
The case particle と can attach to words of various part-of-speech (because of its quotative usage). It can be used for saying "~ and ~" (enumeration), "with (someone)", (same/different) as/from..." (comparison), "(saying) that..."(quotation), etc., as you probably know.
>
> Eg.
>
> **13と**14 -- "~ and ~" ← と follows 体言
>
> **リンゴとバナナと**ヨーグルト -- "~ and ~" ← と follows 体言
>
> **妹と**一緒に勉強する -- "with (someone)" ← と follows 体言
>
> **山田さんと**同じクラス -- "(same) as ~" ← と follows 体言
>
> いや**だと**言う -- "(say) that..." ← と can follow various words
>
>
>
And as you can see, と in the sense "~ and ~" would make the most sense in your example.
---
>
> "14**は**10**と**いくつ?"
>
>
>
I'd say the は is the topic marker, or the thematic は (主題の「は」).
>
> *lit.* **As for** 14, 10 **and** how many (is it)?
>
>
> |
57,779,158 | I am using material-ui for my project and I have a need to get the selected text (not the value) and do some parsing. I can't seem to find a way to do this.
Here is what my component looks like:
```
<TextField
select
margin="dense"
label="Name"
variant="outlined"
className={classes.textField}
value={values.nameId}
onChange={handleChange('nameId')}
>
{names.map(row => (
<MenuItem key={row.Id} value={row.Id}>{row.Name}</MenuItem>
))}
</TextField>
```
handler looks like this:
```
const handleChange = name => event => {
setValues({ ...values, [name]: event.target.value });
};
```
Obviously event.target.value gets my selected value, but I want to also get the selected innerText of the selected index. Any ideas? | 2019/09/03 | [
"https://Stackoverflow.com/questions/57779158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8484824/"
] | This regex match should get you what you're looking for
```js
let regex = /1-[0-9]{3}-[0-9]{3}-[0-9]{4}/
``` |
2,554,836 | I have $\ln (D(x)+1) $. What is the way to prove , that this is a Lebesgue measurable function ? | 2017/12/07 | [
"https://math.stackexchange.com/questions/2554836",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/503239/"
] | You're on the right path.
You need to argue that $\sum a^{-1} = \sum a$ because the map $a \mapsto a^{-1}$ is a bijection.
Then you can finish as you have done:
$$
\sum a^{-1} = \sum a = \frac{(p-1)p}{2} = \frac{(p-1)}{2}p \equiv 0 \bmod p
$$
Note where you need $p$ to be odd. |
55,620 | I want to cite an IEEE norm in a document. They provide several way to cite it on their website and in particular `bibTeX`. This is perfect because I use LaTeX.
However, the citation does not contain any author field. This raise a warning.
Should I keep this warning or modify the entry to avoid it? And in this case, what should I enter as author?
[Link to the norm page](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=4610935&filter%3DAND%28p_Publication_Number%3A4610933%29). In abstract, go to download citation.
For example bibTeX citation only:
```
@ARTICLE{4610935,
journal={IEEE Std 754-2008},
title={IEEE Standard for Floating-Point Arithmetic},
year={2008},
pages={1-70},
keywords={IEEE standards;floating point arithmetic;programming;IEEE standard;arithmetic formats;computer programming;decimal floating-point arithmetic;754-2008;NaN;arithmetic;binary;computer;decimal;exponent;floating-point;format;interchange;number;rounding;significand;subnormal},
doi={10.1109/IEEESTD.2008.4610935},
month={Aug},}
``` | 2015/10/07 | [
"https://academia.stackexchange.com/questions/55620",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/14659/"
] | I assume that the venue you want to publish in follows the [IEEE editorial style guide](http://www.ieee.org/documents/style_manual.pdf). On page 38, the guide shows how to reference standards:
>
> Basic Format:
>
>
> [1] *Title of Standard*, Standard number, date.
>
>
> Examples:
>
>
> [1] *IEEE Criteria for Class IE Electric Systems*, IEEE
> Standard 308, 1969.
>
>
> [2] *Letter Symbols for Quantities*, ANSI Standard
> Y10.5-1968.
>
>
>
So this is what the end result should look like. If this *is* your end result, you can disregard warnings.
However, I'd assume that BibTeX issues warnings about missing authors because it *expects* authors in the particular entry type you are using. You may need to recode your BibTeX file entry from, say, `@Article` to `@Techreport`. If you run into problems with (Bib)TeX, [tex.SE](https://tex.stackexchange.com/) may be helpful. |
195,501 | Is it coherent to suggest that it is possible to iterate, one-by-one, through every single item in an infinite set? Some have suggested that it is possible to iterate (or count) completely through an infinite set with no start (or lower bound), making infinite regress a genuinely possible reality.
Mathematically, is this possible?
I don't know much about math proofs, so the more basic (with the least symbols) you can keep your answer, the more likely I will understand and appreciate it.
Thank you very much!
ADDENDUM
When I write an infinite loop into my computer code, the code begins to execute and will never complete it's looping (unless it crashes or I stop it). I am wondering if it is mathematically possible, adding one to another, to ever arrive at the completion of an infinite set, like the set of negative integers, or will it continue permanently? | 2012/09/14 | [
"https://math.stackexchange.com/questions/195501",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/40191/"
] | We may count through the integers by listing them $0,1,-1,2,-2,\dots$. This is an infinite set without a lower bound. In general, if you have a bijection $f:\mathbb{N} \to X$ where $X$ is an infinite set, then you can "iterate" through them by listing $f(1),f(2),f(3), \dots$. |
69,581,492 | I have string column in my `df` table, like this below:
```
d = {'col1': ['1.2', '3.4', '1.99', '0.14', '2.9', '', '2.3']}
df = pd.DataFrame(data=d)
df
```
[![enter image description here](https://i.stack.imgur.com/X2WXJ.png)](https://i.stack.imgur.com/X2WXJ.png)
I would like to convert this column, so that all values contain two decimal places, but **without changing the type of this column to numeric type**.
Expected output - a string column with values:
[![enter image description here](https://i.stack.imgur.com/3Aefa.png)](https://i.stack.imgur.com/3Aefa.png)
I am a little new to Python, I tried padding 0 [How to pad a numeric string with zeros to the right in Python?](https://stackoverflow.com/questions/40999973/how-to-pad-a-numeric-string-with-zeros-to-the-right-in-python/46021306) depending on the length of the value in the column, but it actually didn't work.
Do you have idea how to handle it? | 2021/10/15 | [
"https://Stackoverflow.com/questions/69581492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16734748/"
] | Use [`str.ljust`](https://pandas.pydata.org/docs/reference/api/pandas.Series.str.ljust.html):
```
df['col1'] = df['col1'].str.ljust(4, '0')
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5 2.30
```
To leave empty rows intact:
```
df['col1'] = df['col1'].mask(df['col1'].astype(bool), df['col1'].str.ljust(4, '0'))
```
output:
```
col1
0 1.20
1 3.40
2 1.99
3 0.14
4 2.90
5
6 2.30
```
NB. to get the max string length: `df['col1'].str.len().max()` -> `4` |
2,435,039 | Sorry the title's so convoluted... I must've tried for ten minutes to get a good, descriptive title! Basically, here's the scenario.
Let's say a user can pick fifty different hat colors and styles to put on an avatar. The avatar can move his head around, so we'd need the same types of movements in the symbol for when that happens.
Additionally, it gets which hat should be on the 'avatar' from a database. The problem is that we can't just make 50 different frames with a different hat on each. And each hat symbol will have the same movements, it'll just be different styles, colors and sizes.
So how can I make one variable that is the HAT, that way we can just put the appropriate hat symbol into the variable and always be able to call Hat.gotoAndplay('tip\_hat') or any other generic functions.... Does that make sense?
Hope that's not too confusing. Sorry, I'm not great at the visual Flash stuff, but it's gotta be done! Thanks! | 2010/03/12 | [
"https://Stackoverflow.com/questions/2435039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48957/"
] | [debu's suggestion](https://stackoverflow.com/questions/2435039/best-way-to-be-able-to-pick-multiple-colors-designs-of-symbols-dynamically-from-f/2435101#2435101) about a hat container makes sense in order to separate out control of the hat movement.
You could take this further by separating out different aspects of the appearance of each hat (not just the colours, but also style, pattern, size, orientation etc) - this would allow you produce a wide variety of different hats from just a few parameters.
So for example 6 styles x 4 patterns x 8 colours = 192 different hats (without having to draw each one!)
[![parametric hats diagram](https://i.stack.imgur.com/dHyh6.jpg)](https://i.stack.imgur.com/dHyh6.jpg)
(source: [webfactional.com](http://roi.webfactional.com/img/so/hats.jpg)) |
26,678,924 | I'm writing a Linux device driver using kernel 3.13.0 and I'm confused as to why I'm getting this warning.
```
warning: initialization from incompatible pointer type [enabled by default]
.read = read_proc,
^
warning: (near initialization for ‘proc_fops.read’) [enabled by default]
```
As far as I can tell my file\_operations setup for the proc functions are identical to the device functions. I can read/write to /dev/MyDevice with no issue and there are no warnings. The proc write function does not throw a warning, only the read. What did I do wrong?
```
/*****************************************************************************/
//DEVICE OPERATIONS
/*****************************************************************************/
static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t
len, loff_t *p_off)
{
//Not relevant to this question
}
static ssize_t dev_write(struct file *pfil, const char __user *pBuf,
size_t len, loff_t *p_off)
{
//Not relevant to this question
}
static struct file_operations dev_fops =
{ //None of these cause a warning but the code is identical the proc code below
.owner = THIS_MODULE,
.read = dev_read,
.write = dev_write
};
/*****************************************************************************/
//PROCESS OPERATIONS
/*****************************************************************************/
static int read_proc(struct file *pfil, char __user *pBuf, size_t
len, loff_t *p_off)
{
//Not relevant to this question
}
static ssize_t write_proc(struct file *pfil, const char __user *pBuf,
size_t len, loff_t *p_off)
{
//Not relevant to this question
}
struct file_operations proc_fops =
{
.owner = THIS_MODULE,
.write = write_proc,
.read = read_proc, //This line causes the warning.
};
```
EDIT: So the answer is that I'm an idiot for not seeing the "int" versus "ssize\_t". Thank you everyone! Both Codenheim and Andrew Medico had the correct answer at roughly the same time but I chose Medico's because it's more pedantic and obvious for future visitors. | 2014/10/31 | [
"https://Stackoverflow.com/questions/26678924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/289746/"
] | The return type of your `read_proc` function (which throws the warning) does not match the the function that compiles cleanly.
```
static ssize_t dev_read(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off)
```
vs.
```
static int read_proc(struct file *pfil, char __user *pBuf, size_t len, loff_t *p_off)
```
`ssize_t` and `int` may be different sizes. Your function's return type should be `ssize_t`. |
8,499 | I am writing an application, running on a server, where multiple users access data from a database which is AES encrypted with a master secret. The master secret itself is initially randomly generated, and then AES encrypted with a user-secret to yield a 'user-hash'. The master secret is never stored, but the user-hash is stored in a database.
When a user enters his user-secret, the user-hash is decrypted to temporarily (on the fly) yield the master-secret which is used to decrypt the data. The data is then send to the user.
If a user is deleted, the user-hash is deleted. He may have saved decrypted data, but cannot decrypt further data.
The question is: How safe is the master-secret in this constellation? If the database is compromised, an attacker has access to the user-hash and the encrypted data. If the attacker was a user, he may also have decrypted data. Will he then be able to break the master-secret? | 2013/05/30 | [
"https://crypto.stackexchange.com/questions/8499",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/7065/"
] | If a user has a copy of both the encrypted and decrypted data, he is in a position to perform at least a [known-plaintext attack](http://en.wikipedia.org/wiki/Known-plaintext_attack). If users can submit arbitrary plaintexts for encryption, they can conduct a [chosen-plaintext attack](http://en.wikipedia.org/wiki/Chosen-plaintext_attack), which is stronger. In a chosen-plaintext attack, the attacker can submit any number of plaintexts and can retrieve the corresponding ciphertext.
All reasonable encryption algorithms are resistant to chosen-plaintext attacks, and AES is considered a reasonable encryption algorithm. Someone in possession of some (plaintext, ciphertext) pairs cannot encrypt or decrypt other messages (except sometimes messages derived from the known messages if a bad mode is used). In particular, no matter how many known plaintexts and ciphertexts the attacker is, he has no method to obtain the key that is better than brute force (trying all possible $2^{128}$ keys).
Do note that deleting the private secret does not delete the master secret. The master secret can still be recovered from backup copies of the private secret that weren't deleted, from other users' private secret, or from extant copies of the master secret. |
2,055,713 | In his book "Men of Mathematics", Eric Temple Bell repeatedly makes the point that a student of mathematics must read the classics.
My question is what are some classic books in mathematics ( Dictionary definition : judged over a period of time to be of the highest quality and outstanding of its kind.) that can be used by a high school/undergraduate student to start the study of higher mathematics?
Some subjects I would like reference in particular, otherwise state any book you consider a classic, are:
1) Analysis
2) Abstract algebra
3) Linear Algebra
4) Number theory
5) Combinatorics and Graph theory, etc. | 2016/12/12 | [
"https://math.stackexchange.com/questions/2055713",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | I don’t agree with Bell on this point: one may well learn better and more easily from a book that is *not* generally considered a classic. For example, most people have never even heard of John Greever’s modified Moore method textbook *Theory and Examples of Point-Set Topology*, but for me it was the ideal introduction to the field. That said, I can nevertheless name a few examples.
For someone of my generation I.N. Herstein’s *Topics in Algebra* is a classic introduction to abstract algebra. The first volume of William J. LeVeque’s two-volume *Topics in Number Theory* is a classic at the higher end of the undergraduate level; Underwood Dudley’s *Elementary Number Theory* is a classic at the lower end. |
36,447,958 | I'm using the [jQuery Validate Plugin](http://jqueryvalidation.org/validate) and I want to be able to hide the error messages next to my inputs and have a main error message at the bottom, I have this working kind of but the error messages are showing next to my input fields. (Obviously I would clean up the styling if i was using it).
As you can see at the bottom it is telling me there are 4 errors see details below.. I want this to stay but not the error messages and styling above?
[![enter image description here](https://i.stack.imgur.com/taT8w.png)](https://i.stack.imgur.com/taT8w.png)
```
$( ".form-group-rules" ).validate({
rules: {
rule_name: {
required: true
},
rule_desc: {
required: false
},
rule_type: {
required: true
},
vali_type: {
required: true
},
tran_type: {
required: true
},
vali_fields: {
required: true
},
acct_sel: {
required: true
}
},
messages: {
rule_name: "Please enter a rule name",
rule_type: "Please select a rule type",
vali_fields: "Please select a validation field",
tran_type: "Please select at least 1 transaction type",
vali_type: "Please select a valiation type",
acct_sel: "Please select at least 1 account"
},
showErrors: function(errorMap, errorList) {
$(".error-container").html("Your form contains "
+ this.numberOfInvalids()
+ " errors, see details below.");
this.defaultShowErrors();
}
});
``` | 2016/04/06 | [
"https://Stackoverflow.com/questions/36447958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4532646/"
] | May be use the Validator method
```
errorPlacement: function(error,element) {
return true;
}
```
It will not append the error to the inputs. |
9,994,676 | I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
```
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
``` | 2012/04/03 | [
"https://Stackoverflow.com/questions/9994676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310575/"
] | If you want to use Gson, then first you declare classes for holding each element and sub elements:
```
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
```
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
```
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
```
Then you simply access the elements of `data`.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item\_name" etc. |
10,839 | I am reading Novuum Lumen Chemicum with the help of Waite’s English translation. (<https://www.sacred-texts.com/alc/hm2/hm204.htm>) The following passage I cannot understand clearly. It seems that Waite had skipped this.(org.: Musaeum Hermeticum, Frankfurt, 1677, p.545 – page number misprinted as 454)
>
> Nos dum illam quaerimus alia invenimus: & nisi ita usitata esset procreatio humana, & natura in eo suum jus teneret, jam vix non deviaremus.
>
>
>
The sentences before and after this one:
>
> Si hoc revivisceret ipse Philosophorum pater Hermes, & subtilis ingenii Geber, cum profundissimo RAYMUNDO LULLIO, non pro Philosophis, sed potius pro discipulis a nostris Chemistis haberentur: Nescirent tot hodie usitatas destilationes, tot circulationes, tot calcinationes, & tot alia innumerabilia alia Artistarum opera, quae ex illorum scriptis hujus saeculi homines invenerunt & excogitarunt. Unicum tantum nobis deest, ut id sciamus quod ipsi fecerunt, lapidem videlicet Philosophorum seu Tincturam Physicam. Nos dum illam quaerimus alia invenimus: & nisi ita usitata esset procreatio humana, & natura in eo suum jus teneret, jam vix non deviaremus. Sed, ut revertar ad propositum, promisi in hoc primo tractatu Naturam explicare; ne nos a simplici via vera, vana deflectat imaginatio.
>
>
>
I would appreciate any help. | 2019/05/24 | [
"https://latin.stackexchange.com/questions/10839",
"https://latin.stackexchange.com",
"https://latin.stackexchange.com/users/2954/"
] | To supplement, I've located [a different published (i.e. professional) English translation](https://archive.org/details/alchymytakenouto00sedz): that of a Dr John French, published in 1674. Here's what he has to say [for this section](https://archive.org/details/alchymytakenouto00sedz/page/2):
>
> If *Hermes* himfelf, the Father of Philosophers, should now be alive, and subtil-witted *Geber*, together with most profound *Raimundus Lullius*, they would not be accounted by our Chymists for Philosophers, but rather for Scholars: They would be ignorant of those so many Distillations, so many Circulations, so many Calcinations, and so many other innumerable Operations of Artists now adays used, which men of this age devised, and found out of their Writings. There is one only thing wanting to us, that is, to know that which they effected, *viz.* the Philosophers Stone, or Physical Tincture **we whilst we seek that, find out other things: and unless the Procreation of Man were so usual as it is, and Nature did in that thing still observe her own Law, and Rules we should scarce not but err.** But to return to what I intended; I promised in this first Treatise to explain Nature, lest every idle fancy should turn us aside from the true and plain way.
>
>
>
(Errors as in the original.)
I'm afraid I'm not sure what "unless the Procreation of Man were so usual as it is" is supposed to mean: it's a very literal translation of the Latin, but doesn't really seem to make a lot of sense. |
72,026,622 | I have an array of objects:
```
this.array = [{name: null}, {name: null}, {name: null}]
```
and array of reservend names:
```
this.reserved = ["name2", "name3"]
```
I loop through array and try to set uniques name (not included inside `reserved` array)
```
for (let i = 0; i < array.length; i++) {
this.setDefaultName(array[i], 1);
}
private setDefaultName(obj, index){
if (!this.reserved.includes(`name${index}`)) {
obj.name = `name${index}`;
this.reserved.push(`name${index}`);
} else {
return this.setDefaultName(obj, index + 1);
}
}
```
After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5".
Could anyone help me? | 2022/04/27 | [
"https://Stackoverflow.com/questions/72026622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16078729/"
] | **Update:**
In the meantime, GitLab have released a new version of their Docker Machine fork which upgrades the default AMI to Ubuntu 20.04. That means that upgrading Docker Machine to the latest version released by GitLab will fix the issue without changing your runner configuration. The latest release can be found [here](https://gitlab-docker-machine-downloads.s3.amazonaws.com/main/index.html).
**Original Workaround/fix:**
Explicitly specify the AMI in your runner configuration and do not rely on the default one anymore, i.e. add something like `"amazonec2-ami=ami-02584c1c9d05efa69"` to your `MachineOptions`:
```
MachineOptions = [
"amazonec2-access-key=xxx",
"amazonec2-secret-key=xxx",
"amazonec2-region=eu-central-1",
"amazonec2-vpc-id=vpc-xxx",
"amazonec2-subnet-id=subnet-xxx",
"amazonec2-use-private-address=true",
"amazonec2-tags=runner-manager-name,gitlab-aws-autoscaler,gitlab,true,gitlab-runner-autoscale,true",
"amazonec2-security-group=ci-runners",
"amazonec2-instance-type=m5.large",
"amazonec2-ami=ami-02584c1c9d05efa69", # Ubuntu 20.04 for amd64 in eu-central-1
"amazonec2-request-spot-instance=true",
"amazonec2-spot-price=0.045"
]
```
You can get a list of Ubuntu AMI IDs [here](https://cloud-images.ubuntu.com/locator/ec2/). Be sure to select one that fits your AWS region and instance architecture and [is supported by Docker](https://docs.docker.com/engine/install/ubuntu/#os-requirements).
**Explanation:**
The default AMI that GitLab Runner / the Docker Machine EC2 driver use is Ubuntu 16.04. The install script for Docker, which is available on <https://get.docker.com/> and which Docker Machine relies on, seems to have stopped supporting Ubuntu 16.04 recently. Thus, the installation of Docker fails on the EC2 instance spawned by Docker Machine and the job cannot run.
See also [this](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/69) GitLab issue.
[Azure](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/71) and [GCP](https://gitlab.com/gitlab-org/ci-cd/docker-machine/-/issues/70) suffer from similar problems. |
32,251,446 | I am developing an Android application and I have trouvble making javascript work.
Here is my main activity code :
```
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "create LocalDialogActivity");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_dialog);
webView = (WebView)findViewById(R.id.local_dialog_webview);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
}
}
private class WebAppInterface {
@JavascriptInterface
public void validate() {
//do some action...
}
@JavascriptInterface
public void cancel() {
//do some actions...
}
}
```
here is my html code :
```
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<script src="../js/myjavascript.js"></script>
</head>
<body>
<section id="header">
</section>
<section id="buttons">
<button class="button" id="no" onclick="cancel()">cancel</button>
<button class="button" id="yes" onclick="validate()">validate</button>
</section>
<footer id="footer">
</footer>
</body>
</html>
```
When I click on my buttons, the functions validate() and cancel() doesn't work.
here is my javascript code :
```
function validate() {
Interface.validate();
}
function cancel() {
Interface.cancel();
}
```
Interface is my javascriptInterface in my Android code.
Any ideas would be welcome. | 2015/08/27 | [
"https://Stackoverflow.com/questions/32251446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3664585/"
] | Just add
```
webView.getSettings().setDomStorageEnabled(true);
``` |
49,336,275 | Prestashop 1.6 has some strange functions. One of them is:
```
\themes\my_theme\js\autoload\15-jquery.uniform-modified.js
```
Which add span to radio, input button. For example:
```
<div class="checker" id="uniform-cgv">
<span class="checked">
<input name="cgv" id="cgv" value="1" type="checkbox">
</span>
</div>
```
If this span has class checked then checkbox is checked. the problem is when quest user want buy products without create a account. The user need to provide some information about his self. In the end click on "save" button
```
<button type="submit" name="submitGuestAccount" id="submitGuestAccount" class="btn btn-default button button-medium"><span>Zapisz<i class="icon-chevron-right right"></i></span></button>
```
When I click this button the html is change to:
```
<p class="checkbox">
<input name="cgv" id="cgv" value="1" checked="checked" type="checkbox">
</p>
```
the question is. How can I call function which add span to input field after click on this button. For now I have something like this:
```
$('#submitGuestAccount').click(function () {
});
```
Below I past all content from:
[view-source:https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js](https://dev.suszek.info/themes/default-bootstrap/js/autoload/15-jquery.uniform-modified.js)
Thanks for any help. | 2018/03/17 | [
"https://Stackoverflow.com/questions/49336275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9368657/"
] | If you want to get the same checkbox like with uniform you just need to invoke method bindUniform() after your button was handled. I assume that you get an answer after form handling with an ajax response, so you need to add
`if (typeof bindUniform !=='undefined') {
bindUniform();
}`
after you get response and DOM was done. |
12,023,986 | Today I noticed that new MVC projects in VS 2012 are using [WebMatrix.WebData.WebSecurity](http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v=vs.99%29.aspx) to handle membership related tasks.
I went to msdn to a quick look at the documentation and was surprised. Lot's of good stuff in there and it will definitely save me a lot of time in future projects.
But one thing got my attention:
It doesn't have a function to "Remove Accounts". Is there a particular reason for that? Should I use the underlying membership provider to remove accounts (and other things such as unlock accounts)? | 2012/08/19 | [
"https://Stackoverflow.com/questions/12023986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061342/"
] | Found the answer at MSDN:
<http://msdn.microsoft.com/en-us/library/webmatrix.webdata.simplemembershipprovider%28v=vs.111%29>
>
> In ASP.NET Web Pages sites, you can access the functionality of the SimpleMembershipProvider class by using the Membership property of a web page. You do not (in fact, cannot) initialize a new instance of the SimpleMembershipProvider class...
>
>
> |
60,655,194 | everyone!
I am trying to render the exchange rates from a server to my page.
Here is my React code:
```
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor() {
super();
this.state = {
exRates: []
};
}
getCurrencyRatesFromDB = () => {
fetch('https://api.exchangeratesapi.io/latest')
.then((response) => {
console.log('then 1', response);
return response.json();
}).then((data) => {
console.log('then 2', data);
this.setState({
exRates: data.rates
});
});
}
render() {
console.log('render started');
return (
<div>
console.log('return started'),
<button
type="button"
className="btn"
onClick={() => {
this.getCurrencyRatesFromDB();
}}
>
Load rates
</button>
<p>{this.state}</p>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
```
How do I modify the 'render' part to see the rates in a column like it is on the server?
Thank very much to you in advance! | 2020/03/12 | [
"https://Stackoverflow.com/questions/60655194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11894807/"
] | 1. You must not had an empty line beetween
`@app.route("/profile/<name>")` and `def profile(name):`
2. You have to set the html file in a folder called templates.
3. You have to set the templates folder and run.py in the same folder |
35,285,191 | I am executing a stored procedure but it is failing at some point,
Current error code is not helping me to find where and exactly what the error is
I wanted to know where it is exactly failing so wanted to print line by line output while executing.
for eg :
```
create or replace
-- decaring required variable
PROCEDURE "PROC_DATA_TABLE_DETAILS" IS
FOR TABLEDETAILS IN (SELECT * FROM user_tables )
LOOP
dbms_output.put_line (TABLENAME);
select NUM_ROWS INTO COUNTRECORDS from all_tables where owner not like 'SYS%'and TABLE_NAME = TABLEDETAILS.TABLE_NAME;
FOR FIELDSDETAILS IN (SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME = TABLENAME)
LOOP
FIELDNAME :=FIELDSDETAILS.COLUMN_NAME;
dbms_output.put_line (FIELDNAME );
execute immediate 'SELECT NVL(count(*),0) FROM ' ||TABLENAME || ' WHERE '|| FIELDNAME || ' is not null ' into TEMPNONBLANK;
END LOOP;
INSERT INTO DATA_TABLE_DETAILS VALUES (TABLEDETAILS.TABLE_NAME,COUNTFIELDS)
END LOOP;
END PROC_DATA_TABLE_DETAILS;
``` | 2016/02/09 | [
"https://Stackoverflow.com/questions/35285191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767969/"
] | Your code will look like this; additionally you can write a procedure with autonomous transactions to log all error or logs. you will also get online code for this functionality.
[http://log4plsql.sourceforge.net/](http://logs)
```
create or replace procedure proc_data_table_details is
tablename varchar2(30);
countrecords number;
fieldname varchar2(30);
tempnonblank number;
begin
for tabledetails in (select * from user_tables where rownum < 3) loop
tablename := tabledetails.table_name;
dbms_output.put_line(tabledetails.table_name);
select num_rows
into countrecords
from all_tables
where owner not like 'SYS%'
and table_name = tablename;
for fieldsdetails in (select * from user_tab_columns where table_name = tablename) loop
fieldname := fieldsdetails.column_name;
dbms_output.put_line(fieldname);
execute immediate 'SELECT NVL(count(*),0) FROM ' || tablename || ' WHERE ' || fieldname || ' is not null '
into tempnonblank;
dbms_output.put_line('TABLENAME :' || tablename || ' column name :' || fieldname || ' count :' || tempnonblank);
end loop;
end loop;
end proc_data_table_details;
``` |
9,094,681 | I am having string like this
```
abcdedfd?xyz
adcdefghdfd?red
```
so i wanted to remove the characters after the `? | 2012/02/01 | [
"https://Stackoverflow.com/questions/9094681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551179/"
] | ```
NSString *newString = [[yourString componentsBySeparatedByString: @"?"] objectAtIndex: 0];
```
This assuming the string you want to trim is in `NSString *yourString`. |
29,908,287 | I need help with my program. I declared a one-dimensional array of 6 and I want to show random values between 1-6 in a text box
My question is how do I show values in my array in textbox1.text?
Here is my code:
```
Public Sub ClickMyFirstClassButton()
If FirstClass.Checked = True Then
'This piece of code declares an array
Dim Seats As Integer()
'This is a One Dimensional Array
ReDim Seats(6)
TextBox1.Text = (String.Format("First Class is checked. The number of seats are : ", (Seats)))
'ElseIf FirstClass.AutoCheck = True Then
'MessageBox.Show("FirstClass is Auto checked")
End If
End Sub
```
I messed around with my program and this is what I did.
Public Sub ClickMyFirstClassButton()
```
If FirstClass.Checked = True Then
'Dim Seats As Integer() = {1, 2, 3, 4, 5, 6}
Dim Seats(0 To 6) As Integer
Seats(0) = 1
Seats(1) = 2
Seats(2) = 3
Seats(3) = 4
Seats(4) = 5
Seats(5) = 6
TextBox1.Text = (String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats))))
MessageBox.Show(String.Format("First Class is checked. Your seat is : {0}", Seats(RandomNumber(Seats))))
'ElseIf FirstClass.AutoCheck Then
'MessageBox.Show("FirstClass is Auto checked")
End If
End Sub
``` | 2015/04/28 | [
"https://Stackoverflow.com/questions/29908287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4601982/"
] | As suggested by @eryksun, this solves the issue:
```
p = subprocess.Popen('clip.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.communicate('hello \n world')
p.wait()
``` |
11,881,490 | In a C# enumeration, are there any negative side effects of using a negative number?
I am modelling response codes and one of the codes in negative. This compiles but I want to know if there are any negative side effects to this.
```
public enum ResponseCodes
{
InvalidServerUserPasswordCombo = -1,
// etc.
}
``` | 2012/08/09 | [
"https://Stackoverflow.com/questions/11881490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64226/"
] | >
> negative side effects of using a negative number
>
>
>
Clearly, with any underlying signed type, any bitwise operations are going to get "interesting" very quickly.
But using an enum as a collection of related constants can quite happily use negative values. |
261,384 | I am trying to install additional drivers on Ubuntu 12.04. The application is returning an error. In the log file I can see various NVIDIA module failed to load. However, my PC do not have NVIDIA graphics card. Its Intel card, then why is Ubuntu searching for NVIDIA card?
I have installed Ubuntu 12.04 and additional drivers before without any error.
Though this is the first time I am using Windows installer version. I don't know if its related to that. | 2013/02/26 | [
"https://askubuntu.com/questions/261384",
"https://askubuntu.com",
"https://askubuntu.com/users/135680/"
] | **Yes**, but you will need Ubuntu 12.10.
1. Download Steam from Ubuntu Software Center
2. Start it up, you will be asked to log in with your Steam account. If you don't have one you can choose the create account option.
3. Go to the Store tab
4. Enter Don't Starve in the search bar in the top-right and click Don't Starve
5. Scroll a bit down and click the green button to buy the game
6. Pay with credit card or PayPal. It costs €14
7. The game will be downloaded and installed
8. **Play :-D** |
3,195,720 | I know the question has been asked thousands of times, but I'll ask it again: is there a way (even patchy) to write/read a dumb text file with Javascript or Protoype ?
This is only for debug purposes, and is not designed for production. The thing is I need it to work with (at least) both Firefox and IE (preferably under Windows).
Thanks in advance ! | 2010/07/07 | [
"https://Stackoverflow.com/questions/3195720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277128/"
] | Writing to a file is not possible, you'd have to write a server-side script and make a request to that script. Reading is possible if you use an iframe with the text file's location as source, and reading the iframe contents. |
945,527 | Isn't that nicely recursive?
I've got a portable command prompt on my external drive, and it has a nice .bat file to configure some initial settings, but I'd like more!
Here's what I know how to set from .bat:
* Colors = (color XY) where x and y are hex digits for the predefined colors
* Prompt = (prompt $p$g) sets the prompt to "C:\etc\etc >" the default prompt
* Title = (title "text") sets the window title to "text"
* Screen Size = (mode con: cols=XX lines=YY) sets the columns and lines size of the window
* Path = (SET PATH=%~d0\bin;%PATH%) sets up local path to my tools and appends the computer's path
So that's all great. But there are a few settings I can't seem to set from the bat. Like, how would I set these up wihtout using the Properties dialogue:
* Buffer = not screen size, but the buffer
* Options like quick edit mode and autocomplete
* Popup colors
* Font. And can you use a font on the portable drive, or must it be installed to work?
* Command history options | 2009/06/03 | [
"https://Stackoverflow.com/questions/945527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93221/"
] | Regarding setting the buffer size:
Using `mode con: cols=XX lines=YY` sets not only the window (screen) size, but the buffer size too.
If you specify a size allowed by your system, based on available screen size, you'll see that both window and buffer dimension are set to the same value; .e.g:
```
mode con: cols=100 lines=30
```
results in the following (values are the same):
* window size: Width=**160**, Height=**78**
* buffer size: Width=**160**, Height=**78**
By contrast, if you specify values that are too large based on the available screen size, you'll see that the window size changes to its maximum, but the buffer size is changed to the values as specified.
```
mode con: cols=1600 lines=900
```
With a screen resolution of 1280x1024, you'll get:
* window size: Width=**160**, Height=**78**
* buffer size: Width=**1600**, Height=**900** |
53,386,051 | I would like to append a 256 digits to thousands of number in notepad plus to appear as below:
```
776333533
774361221
772333707
771615215
784713890
786164089
777664662
```
I would want all these numbers to appear as below:
```
256776333533
256774361221
256772333707
256771615215
256784713890
256786164089
256777664662
```
i need a command that can enable me achieve this | 2018/11/20 | [
"https://Stackoverflow.com/questions/53386051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10626686/"
] | Here below is I think a good example of your requirement. Modules will be loaded with page properties. As page property is depended on iron-page, `selected='{{page}}'` when page value has been changed with iron-page's name properties, its observer loads the that page's modules. :
```
static get properties() { return {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged'
},
.......
_pageChanged(page, oldPage) {
if (page != null) {
let cb = this._pageLoaded.bind(this, Boolean(oldPage));
// HERE BELOW YOUR PAGE NAMES
switch (page) {
case 'list':
import('./shop-list.js').then(cb);
break;
case 'detail':
import('./shop-detail.js').then(cb);
break;
case 'cart':
import('./shop-cart.js').then(cb);
break;
case 'checkout':
import('./shop-checkout.js').then(cb);
break;
default:
this._pageLoaded(Boolean(oldPage));
}
```
here above `cb` is a function which is loading lazy modules but needs to load immediately after the first render. Which is minimum required files.
```
_pageLoaded(shouldResetLayout) {
this._ensureLazyLoaded();
}
```
Here the full code's link of the above. Hope this helps In case of any question I will try to reply. <https://github.com/Polymer/shop/blob/master/src/shop-app.js> |
223,590 | Where does this meme come from (as in a *trip down memory lane*) ?
Is it from a book ? | 2015/01/25 | [
"https://english.stackexchange.com/questions/223590",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/64820/"
] | Christine Ammer, *The Facts on File Dictionary of Clichés*, second edition (2006) has this entry for the phrase "down memory lane":
>
> **down memory lane** Looking back on the past. Often put in a nostalgic way, this term may have originated as the title of a popular song of 1924, "Memory Lane," words by Bud de Sylva, and music by Larry Spier and Con Conrad. It was revived in the film *In Society* (1944), starring [Bud] Abbott and [Lou] Costello. That is where former movie actor President Ronald Reagan may have picked it up; he then used it in his 1984 speech accepting the Republican nomination, "Well, let's take them [his opponents] on a little stroll down memory lane."
>
>
>
Ammer's chronology notwithstanding, "memory lane" was a familiar turn of phrase back in 1972, when Loudon Wainright III turned it on itself in his 1972 song "Old Friend," from his third album:
>
> It's been so long, things are so different.
>
>
> Memory lane's a one-way street.
>
>
>
Although Ammer may be correct that "memory lane" owes its first surge of popularity to a song from 1924, the phrase was certainly used before that time. A Google Books search finds this instance from B. M. Balch, "[Memory Lane](https://books.google.com/books?id=syATAAAAIAAJ&pg=RA1-PA101&dq=%22memory+lane%22&hl=en&sa=X&ei=7cvEVOf9KsT6oQS0xIHgCw&ved=0CCIQ6AEwAQ#v=onepage&q=%22memory%20lane%22&f=false)," in *Hamilton Literary Magazine* (December 1894):
>
> On the shore of vast gray sea lies an old town; so old that no records of its founding have ever been discovered, though its archives cover centuries of existence. Every wall is crumbling away. Every gable is lichen-grown and covered with moss. In the whole great city there is nothing new. Thro the centre of the town a quaint old street, paved with square blocks of various hues from a somber gray to a bright crimson, runs down to the sea. This is Memory Lane—lonely and drear to some, pleasant and gay to others.
>
>
>
Older still is this instance of "memory's lane," from William Bowen, "[That Frozen Pipe](https://books.google.com/books?id=WpcVAAAAYAAJ&pg=PA79&dq=%22down+memory+lane%22&hl=en&sa=X&ei=BtDEVNiZKYj7yASty4GgBA&ved=0CBwQ6AEwADge#v=onepage&q=%22down%20memory%20lane%22&f=false)," in *Chained Lightning, a Book of Fun* (1883):
>
> When you have come as near as may be to the frozen spot, hold the flat-iron on the pipe and settle down for ten minutes of meditation. You won't have traveled down memory's lane over half a mile before something will happen. The pipe will burst exactly on a line with your eyes, and you will have cause to wonder all the rest of your life how a gallon of water could have collected at that one point for your benefit.
>
>
>
A search of the Library of Congress's Chronicling America database of U.S. newspapers finds the same "That Frozen Pipe" story in the [*[Rayville, Louisiana] Richland Beacon*](http://chroniclingamerica.loc.gov/lccn/sn86079088/1881-04-23/ed-1/seq-4/#date1=1836&index=0&rows=20&words=down+lane+memory+traveled&searchType=basic&sequence=0&state=&date2=1882&proxtext=%22traveled+down+memory%27s+lane%22&y=12&x=16&dateFilterType=yearRange&page=1) (April 23, 1881), which gives its source as the *Detroit Free Press* (undated). I couldn't find the *Detroit Free Press* version of the story in the Library of Congress database.
Also of possible interest, another song called "[Memory Lane](https://books.google.com/books?id=ff43AQAAMAAJ&pg=PA585&dq=%22memory+lane%22&hl=en&sa=X&ei=kc7EVJTuJomqogSbpIHgDw&ved=0CDkQ6AEwBjhk#v=onepage&q=%22memory%20lane%22&f=false)"—this one by R.H. Elkin and A. L. Liebmann—was catalogued in London on January 19, 1903.
---
Almost certainly unrelated, but an amusing coincidence, is this item from the [*[Washington, D.C.] Evening Star*](http://chroniclingamerica.loc.gov/lccn/sn83045462/1879-01-06/ed-1/seq-3/#date1=1836&index=5&rows=20&words=Lane+memory+recitation&searchType=basic&sequence=0&state=&date2=1922&proxtext=memory.+Lane%27s+recitation&y=10&x=15&dateFilterType=yearRange&page=1) (January 6, 1879):
>
> A story of a wonderful memory comes from Sydney, Australia. A prisoner set up in his defense an alibi, claiming that, at the time of the robbery, he was at home listening to the recital of a novel, "The Old Baron," by a man named Lane, who had committed it, with other works, to memory. Lane's recitation, he said, took two hours and a half. The Attorney General holding this to be incredible, Lane began: ... After the witness had recited several pages, the Attorney General told him to stop, as he was satisfied. But the defense insisted that, as the veracity of the witness had been questioned, he should be allowed to go on. Finally a compromise was effected, Lane gave a chapter from the middle of the story and its conclusion, and the accused was found not guilty.
>
>
>
The story reappeared in newspapers from Louisiana, Michigan, Minnesota, North Carolina, Ohio, Pennsylvania, Tennessee, and Washington Territory over the next five months. It also appeared, in a slightly more detailed form, in [*Frank Leslie's Illustrated Newspaper*](https://books.google.com/books?id=ZUJaAAAAYAAJ&pg=PA365&dq=%22Lane%27s+recitation%22&hl=en&sa=X&ei=AKPGVNvbIMm6ogSxyICQCw&ved=0CCQQ6AEwAQ#v=onepage&q=%22Lane%27s%20recitation%22&f=false) (January 18, 1879), with such additional details as the name of the author of *The Old Baron* (Horace Walpole) and the fact that the episode occurred in January 1847.
Was "memory lane" influenced by the stir made in 1879 by the account of the remarkable memory of Mr. Lane of Sydney, Australia? I don't think so, but it makes a good apocryphal story. |
41,983,979 | Configuring multiple sources for an agent throwing me lock error using FILE channel. Below is my config file.
```
a1.sources = r1 r2
a1.sinks = k1 k2
a1.channels = c1 c3
#sources
a1.sources.r1.type=netcat
a1.sources.r1.bind=localhost
a1.sources.r1.port=4444
a1.sources.r2.type=exec
a1.sources.r2.command=tail -f /opt/gen_logs/logs/access.log
#sinks
a1.sinks.k1.type=hdfs
a1.sinks.k1.hdfs.path=/flume201
a1.sinks.k1.hdfs.filePrefix=netcat-
a1.sinks.k1.rollInterval=100
a1.sinks.k1.hdfs.fileType=DataStream
a1.sinks.k1.hdfs.callTimeout=100000
a1.sinks.k2.type=hdfs
a1.sinks.k2.hdfs.path=/flume202
a1.sinks.k2.hdfs.filePefix=execCommand-
a1.sinks.k2.rollInterval=100
a1.sinks.k2.hdfs.fileType=DataStream
a1.sinks.k2.hdfs.callTimeOut=100000
#channels
a1.channels.c1.type=file
a1.channels.c1.checkpointDir=/home/cloudera/alpha/001
a1.channels.c3.type=file
a1.channels.c3.checkpointDir=/home/cloudera/beta/001
#bind r1 c1 k1
a1.sources.r1.channels=c1
a1.sinks.k1.channel=c1
a1.sources.r2.channels=c3
a1.sinks.k2.channel=c3
```
I am getting below error
```
Channel closed [channel=c3]. Due to java.io.IOException: Cannot lock /home/cloudera/.flume/file-channel/data. The directory is already locked. [channel=c3]
```
But when i am using memory channel. Its working fine. | 2017/02/01 | [
"https://Stackoverflow.com/questions/41983979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4029265/"
] | Check your php.ini for:
**session.gc\_maxlifetime** - Default 1440 secs - 24 mins
>
> **session.gc\_maxlifetime** specifies the number of seconds after which data will be seen as 'garbage' and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc\_probability and session.gc\_divisor).
>
>
>
**session.cookie\_lifetime** - Default 0
>**session.cookie\_lifetime** specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0. See also session\_get\_cookie\_params() and session\_set\_cookie\_params().
In case it is less time than the Laravel configuration, the cookie will be removed because the local php.ini have **preference** over Laravel configuration.
You can just increase it or comment/delete.
In case is not solved something on your App is destroying the session.
**UPDATE**
After release [v5.5.22](https://github.com/laravel/laravel/releases/tag/v5.5.22) session lifetime is loaded from `.env` and is not hardcoded anymore at `config/session.php`, changes [there](https://github.com/laravel/laravel/commit/084f10004582299ef3897f6ec14315209d5c1df1#diff-cbfd64a28982a1818f2b5f16e7f9d634).
Now you can modify the session lifetime using:
```
SESSION_LIFETIME=90 //minutes
```
In your `.env` file. |
22,153,836 | I am curious as to why Start-Job increments in twos. My worry is that I am doing something wrong that makes the ID of a new job jump by 2.
```
Start-Job -ScriptBlock {Get-WinEvent -LogName system -MaxEvents 1000}
```
Results as shown by Get-Job
```
Id Name State HasMoreData Command
-- ---- ----- ----------- -------
2 Job2 Completed False Get-WinEvent -LogName system -MaxEvents 1000
4 Job4 Completed False Get-WinEvent -LogName system -MaxEvents 1000
6 Job6 Completed True Get-WinEvent -LogName system -MaxEvents 1000
```
Question: Can you control the Start-Job Id increments, or force them to be just 1? | 2014/03/03 | [
"https://Stackoverflow.com/questions/22153836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200586/"
] | Each time you start a job, it consists of a parent job and one or more child jobs. If you run `get-job | fl` you'll see the child jobs, and you'll see that their names are the "missing" odd numbered names. |
4,554,498 | I am creating a Chart (DataVisualization.Charting.Chart) programmatically, which is a Stacked Bar chart.
I am also adding Legend entries programmatically to it. I want to show the Legend at the bottom of the chart.
But, while doing so, the Legend overlapps with the X-axis of the chart.
Here is the code I am using:
```
Private Function GetLegend(ByVal legendName As String, ByVal s As Single) As System.Windows.Forms.DataVisualization.Charting.Legend
Dim objLegend As System.Windows.Forms.DataVisualization.Charting.Legend = New System.Windows.Forms.DataVisualization.Charting.Legend()
objLegend.Name = legendName
objLegend.Font = New System.Drawing.Font("Verdana", s)
objLegend.IsDockedInsideChartArea = False
objLegend.Docking = Docking.Bottom
Return objLegend
End Function
```
Below statement adds that Legend to the chart
```
_msChart.Legends.Add(GetLegend("SomeValue1", 10.0F))
```
Any idea, what is missing? I want to show the legend at the bottom only, but it should not overlapp with the X-axis. | 2010/12/29 | [
"https://Stackoverflow.com/questions/4554498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/557172/"
] | I had the same problem today. Try adding:
```
objLegend.Position.Auto = true
objLegend.DockedToChartArea = "yourChartAreaName"
```
That did not help me but I found on the net that this might be helpful (and clean solution).
What actually worked for me was moving chart area to make space for legend so it no longer overlaps. My legend was on top so this code worked for me:
```
chart.ChartAreas[0].Position.Y = 15
```
You can try resizing it instead, forcing it to be for example 20 pixels shorter than `chart.Size`.
Hope this helps. |
68,722,703 | I understand this is usually a pointer error. However, I can't seem to solve it here is what I have tried:
* Repair visual studio
* Repair .NET core
* Reinstall visual studio
* Reinstall .NET core
* Clean and rebuild the solution
After doing all of these I am still getting the same error. Does anyone have any more ideas on how I could solve this issue? In case it is needed it is being triggered on line 79 of Microsoft.AspNetCore.Razor.Design.CodeGeneration.targets which is the following code block
```
<RazorTagHelper
Debug="$(_RazorDebugTagHelperTask)"
DebugTool="$(_RazorDebugTagHelperTool)"
ToolAssembly="$(_RazorToolAssembly)"
UseServer="$(UseRazorBuildServer)"
ForceServer="$(_RazorForceBuildServer)"
PipeName="$(_RazorBuildServerPipeName)"
Version="$(RazorLangVersion)"
Configuration="@(ResolvedRazorConfiguration)"
Extensions="@(ResolvedRazorExtension)"
Assemblies="@(RazorReferencePath)"
ProjectRoot="$(MSBuildProjectDirectory)"
TagHelperManifest="$(_RazorTagHelperOutputCache)">
<Output
TaskParameter="TagHelperManifest"
ItemName="FileWrites"/>
</RazorTagHelper>
``` | 2021/08/10 | [
"https://Stackoverflow.com/questions/68722703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4990927/"
] | I managed to solve this by having to install an older depreciated version of .NET alongside the version of .NET being used for the project with the older version that was required to be installed being version [2.0.9](https://dotnet.microsoft.com/download/dotnet/2.0/runtime?utm_source=getdotnetcore&utm_medium=referral) |
15,759,186 | Ok this is my JavaScript
```
<script type="text/javascript" language="JavaScript">
function manageCart(task,item) {
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
}
function reportError(request) {
$F('cartResult') = "An error occurred";
}
```
And this is HTML
```
<p>
<a href="javascript:void(0)" onclick="manageCart('add',83)">Add to cart</a>
</p>
```
This script doesn't work in Firefox, I've ran a few Firefox JS debuggers but they displayed no errors. I'm not so good in JavaScript so please help me if you can :)
This script actually uses Prototype library if it will make things clearer. | 2013/04/02 | [
"https://Stackoverflow.com/questions/15759186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2181279/"
] | For this type of Ajax call do not use `Ajax.Updater` as that is designed to update a specific element with the contents of the ajax response. I believe that you want to just make a simple single ajax call so using `Ajax.Request` would be what you want to use.
Original Code using Ajax.Updater
```
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
```
Code using Ajax.Request
```
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Request(url,
{
method: 'get',
parameters: params,
onFailure: reportError,
onSuccess: function(){
console.log('It Worked');
}
});
```
I put a success handler in this call just to confirm that it worked for you - and it should output to your console. You can remove it or comment the `console.log()` when you are satisfied it works |
35,854,555 | We will be developing a new web site for a client who already has a Kentico 8.2 license. I am trying to make a case for developing the site using Kentico 9. Some key features I have found so far include:
* faster performance (how much in real-world terms?)
* better integration with .Net MVC
* content staging tasks can be synchronized per user account
* better rollback functionality: previously we had to make full database backups, content staging in Kentico 8.2 causes issues for restoring previous versions of a page.
* built in source control support for GIT
It looks like Kentico integration with the client's existing database may be possible. Has anyone done this? What are the limitations or caveats?
Is there a discount for upgrading the license from 8.2 to 9?
Thanks in advance for your feedback! | 2016/03/07 | [
"https://Stackoverflow.com/questions/35854555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5971415/"
] | There are many tools available to you to persist data from an app. Choosing an appropriate one requires some understanding of your needs, or at least making a guess. Here's where I would start but keep an eye out in case my assumptions don't match your needs.
*What type of data do you want to persist?*
Presumably you want to store the array of Strings seen in `var name = Array<String>()` but maybe you have some other data type in mind.
*When do you need to read/write it (do you need to worry about multiple systems trying to write at the same time, is loading the data going to be very expensive because it is very large, do you only need to load a small piece at a time, ...)?*
Sounds like you're fine reading/writing all the data at once and only on app launch/termination. There could be a reasonable maximum size to this calculation history to total storage size is probably fairly small.
*How long does it need to be persisted?*
Calculation histories are usually nice to have but not a catastrophic loss if they go missing. It would be nice to keep this data around but the app will work without it. Depending on use it may or may not cost the user time and frustration if the data is deleted unexpectedly.
*Who needs access to it (is it also show on a web site, should it sync to all of a user's devices, ...)?*
It's probably enough to keep this history just on the local device.
**So what should we do?**
For a small amount of data loaded all at once and only used locally I would write this data to a file.
Since you're just working with an array of strings we can use a plist (<https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html>)
NSArray (note: not a Swift array) has `arrayWithContentsOfURL:` and `writeToURL:atomically:` which can be a convenient way to read and write plist compatible data.
Using a file means we need to decide where to store this file. Take a look at [Where You Should Put Your App’s Files](https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW28). In this case it seems reasonable to write this data to either `Documents` or `Library/Caches` depending on how you plan to use it.
With all that covered we could save this stack something like:
`let array = names as NSArray
guard let cachesURL = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first else {
print("Unable to find Caches directory, cannot save file.")
return
}
let fileURL = cachesURL.URLByAppendingPathComponent("history.plist")
array.writeToURL(fileURL, atomically: false)`
Reading the file is similar. You'll need the same URL so decide which component is responsible for deciding where to save/load this data and let it supply the URL to use. You'll also need to check if any saved history exists or not (note that `arrayWithContentsOfURL:` can return nil).
At some point you might find it useful to model this data as a more specific data type, perhaps defining your own struct to capture these operations. A custom type can't be automatically written to or read from a file so you'll need to do a little more work. Apple has a nice example of how you might use NSCoding to do that in their tutorials: <https://developer.apple.com/library/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html> |
9,415 | What does テラス means in the context of declining an invitation, like below?
>
> うううううう!!いきたい!けどその時間帯もろに仕事だ:::またやって!!テラスーーーーー
>
>
>
I guess it is slang?
I am familiar with テラワロス but it seems different in both spelling and context.
More context: Public comment sent on a night-time birthday event page on a social network. テラス is not her nickname. | 2012/11/13 | [
"https://japanese.stackexchange.com/questions/9415",
"https://japanese.stackexchange.com",
"https://japanese.stackexchange.com/users/107/"
] | So far the only viable explanation I can think of is that テラス is a contracted form of テラワロス.
* [ニコニコ[百科]{ひゃっか} entry for テラス](http://dic.nicovideo.jp/a/%E3%83%86%E3%83%A9%E3%82%B9) defines it as: `3. テラワロスの略`
+ 3rd sense: Contraction of "terawarosu"
* [a 2ch.net post](http://2chnull.info/r/train/1273323743/901-1000) says:`「法テラス」(テラワロスじゃないぞw)`
+ "Law-terrace" (and no, it's not "terawarosu" lol)
* [a blog post](http://blog.kanjosen.com/?eid=1006137) writes: `「針テラス(テラワロスではない。2ちゃんの見過ぎ)」`
+ "[Hari Tea-time Resort Station](http://hari-trs.com/haritrs.html) (to 2ch addicts: it's not "terawarosu")"
As to why you'd want to "roll on the floor laughing" in the context of declining an invitation, I don't have a definitive answer, but maybe one of these:
* She's laughing at the unexpected coincidence of the event and her work.
* She's laughing at herself for having to work when everyone else is able to attend the event. Perhaps the time of the event is normally considered overtime?
* She's softening the request to hold another event for her by adding a laugh. |
471,151 | $(l^2,\|\cdot\|\_2)$ is a Hilbert space with scalar product $\langle x,y\rangle=\sum^{\infty}\_{k=1}x\_ky\_k$.
How can I show that every vector $x\in l^2$ can be written in a form $\sum^{\infty}\_{k=1}x\_ke^k$ where $e^k,k\in N$ are unit vectors? | 2013/08/19 | [
"https://math.stackexchange.com/questions/471151",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/20885/"
] | By definition equality
$$
x=\sum\limits\_{k=1}^\infty x\_k e^k
$$
means that
$$
x=\lim\limits\_{n\to\infty}\sum\limits\_{k=1}^n x\_k e^k
$$
which by definition means that
$$
\lim\limits\_{n\to\infty}\left\Vert x-\sum\limits\_{k=1}^n x\_k e^k\right\Vert\_2=0\tag{1}
$$
Now use the fact that $\Vert z\Vert\_2^2=\langle z,z\rangle$ to reduce $(1)$ to
$$
\lim\limits\_{n\to\infty}\sum\limits\_{k=n+1}^\infty |x\_k|^2=0\tag{2}
$$
Note that I used here the fact that $\Vert e^k\Vert\_2=1$. I suggest you to recall that $x\in \ell\_2$, to understand why $(2)$ holds. |
177,933 | Harry Potter chose to come back from the dead because he was the master of death. But how could he be the master of death as he never had the Elder Wand?
If Harry could come back does that mean that Dumbledore could come back from the dead too? Why/why not?
After all, Dumbledore did have the three Deathly Hallows. He owned the Elder Wand and the Resurrection Stone and the Cloak of Invisibility. He passes the Cloak to Harry, but he still owned it: you can give something to someone but you are still the owner of it.
So when you die as the master of death you have a choice to come back. Dumbledore died as master of death but he never came back.
Does that means that Dumbledore did not choose to come back or that he cannot and the Deathly Hallows don't work like this? | 2018/01/02 | [
"https://scifi.stackexchange.com/questions/177933",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/93971/"
] | There are many fundamental errors in your question itself. I really suggest you go back and read the books because your understanding of both the Hallows and Harry's resurrection is wrong.
Firstly, Harry was the owner of Elder Wand having won it from Draco Malfoy when he escaped from Malfoy Manor. Draco became the owner of Elder wand when he disarmed Dumbledore at the end of Half-blood Prince. Both these points are explained in the book.
Next, Dumbledore never owned the invisibility cloak, it belonged to James Potter. Dumbledore merely borrowed it to examine suspecting that it was one of the Hallows. After the death of the Potters he simply kept it till the time Harry came to Hogwarts and then passed it to Harry during his first year telling him that the cloak had once belonged to his father.
And most important, Harry did not come back from the dead because he was able to unite the Hallows. He came back from the dead because when Voldemort cast the killing curse on Harry, he killed a part of his own soul which was living inside Harry (as Harry was the Horcrux which he never intended to make).
Even if a person can unite all the Hallows I don't think they gain the ability to come back from the dead. As it is explained in the books, Hallows were just very powerful magical objects created by Wizards and the whole lore about possessor of Hallows being "Master of Death" was just a fairytale which was based on these powerful magical objects.
>
> “So it’s true?” asked Harry. “All of it? The Peverell brothers—”
>
>
> “—were the three brothers of the tale,” said Dumbledore, nodding. “Oh
> yes, I think so. Whether they met Death on a lonely road . . . I think
> it more likely that the Peverell brothers were simply gifted,
> dangerous wizards who succeeded in creating those powerful objects.
> The story of them being Death’s own Hallows seems to me the sort of
> legend that might have sprung up around such creations.
>
>
> “You. You have guessed, I know, why the Cloak was in my possession on
> the night your parents died. James had showed it to me just a few days
> previously. It explained so much of his undetected wrong-doing at
> school! I could hardly believe what I was seeing. I asked to borrow
> it, to examine it.”
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
>
>
>
The reason why Harry didn't die was also explained by Dumbledore. The reason for it wasn't the Hallows, even though Harry was the owner of all three Hallows by the time he went to the forest to face Voldemort.
>
> “But you’re dead.” said Harry.
>
>
> “Oh yes,” said Dumbledore matter-of-factly.
>
>
> “Then . . . I’m dead too?”
>
>
> “Ah,” said Dumbledore, smiling still more broadly. “That is the question,
> isn’t it? On the whole, dear boy, I think not.”
>
>
> “But . . . ” Harry raised his hand
> instinctively towards the lightning scar. It did not seem to be there.
> “But I should have died—I didn’t defend myself! I meant to let him
> kill me!”
>
>
> “And that,” said Dumbledore, “will, I think, have made all
> the difference.”
>
>
> “I let him kill me,” said Harry. “Didn’t I?”
>
>
> “You did,” said Dumbledore, nodding. “Go on!”
>
>
> “So the part of his soul that
> was in me . . . ”
>
>
> Dumbledore nodded still more enthusiastically,
> urging Harry onward, a broad smile of encouragement on his face.
>
>
> “. . . has it gone?”
>
>
> “Oh yes!” said Dumbledore. “Yes, he destroyed it. Your
> soul is whole, and completely your own, Harry.”
>
>
> “But if Voldemort used
> the Killing Curse,” Harry started again “and nobody died for me this
> time—how can I be alive?”
>
>
> “I think you know,” said Dumbledore. “Think
> back. Remember what he did, in his ignorance, in his greed and his
> cruelty.”
>
>
> “He took my blood.” said Harry.
>
>
> “Precisely!” said
> Dumbledore. “He took your blood and rebuilt his living body with it!
> Your blood in his veins, Harry, Lily’s protection inside both of you!
> He tethered you to life while he lives!”
>
>
> “I live . . . while he lives!
> But I thought . . . I thought it was the other way round! I thought we
> both had to die? Or is it the same thing?”
>
>
> “You were the seventh
> Horcrux, Harry, the Horcrux he never meant to make. He had rendered
> his soul so unstable that it broke apart when he committed those acts of unspeakable evil, the murder of your parents, the at- tempted killing of a child. But what escaped from that room was even less than he knew. He left more than his body behind.
> He left part of himself latched to you, the would-be victim who had survived.
>
>
> “He took your blood believing it would strengthen him. He took into
> his body a tiny part of the enchantment your mother laid upon you when
> she died for you. His body keeps her sacrifice alive, and while that
> enchantment survives, so do you and so does Voldemort’s one last hope
> for himself.”
>
>
> “Without meaning to, as you now know, Lord Voldemort
> doubled the bond between you when he returned to a human form. A part
> of his soul was still attached to yours, and, thinking to strengthen
> himself, he took a part of your mother’s sacrifice into himself.”
>
>
> Harry sat in thought for a long time, or perhaps seconds. It was very hard
> to be sure of things like time, here.
>
>
> “He killed me with your wand.”
>
>
> “He *failed* to kill you with my wand,” Dumbledore corrected Harry. “I
> think we can agree you are not dead.
>
>
> *Harry Potter and the Deathly Hallows: Ch 35: King's Cross*
>
>
> |
95,207 | How does a Stack Overflow moderator know about sock puppet accounts?
How do they trap the user? | 2011/06/15 | [
"https://meta.stackexchange.com/questions/95207",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/161645/"
] | I am not going to answer this directly, for reasons that should be obvious.
However; this isn't a "trap" - it is our attempt at *enforcing reasonable behaviour*; using a sock-puppet for *any purpose* (most commonly, but not exclusively: upvoting yourself) is unacceptable.
If you want the vote of the masses; write good questions and answers. |
71,288,129 | I am trying to extend the symbols available to me for plotting in 3D. In 2D, I use:
```
x1 <- sort(rnorm(10))
y1 <- rnorm(10)
z1 <- rnorm(10) + atan2(x1, y1)
x2 <- sort(rnorm(10))
y2 <- rnorm(10)
z2 <- rnorm(10) + atan2(x2, y2)
x3 <- sort(rnorm(10))
y3 <- rnorm(10)
z3 <- rnorm(10) + atan2(x3, y3)
new.styles <- -1*c(9818:9824, 9829, 9830, 9831)
```
In 2D, my plot works and gives the appropriate symbol:
```
plot(x1, y1, col="red", bg="red", pch=new.styles, cex = 2)
```
and the plot is here:[![example 2D plot with appropriate symbols](https://i.stack.imgur.com/S9mlN.png)](https://i.stack.imgur.com/S9mlN.png)
In 3D, however, the symbols do not get translated correctly.
```
rgl::plot3d(x1, y1, z1, col="red", bg="red", pch=new.styles, size = 10)
```
this yields: [![enter image description here](https://i.stack.imgur.com/THPIm.png)](https://i.stack.imgur.com/THPIm.png)
The symbols are getting replaced with (one) circle.
I also tried with pch3d and got blank plots. However, pch3d does work with the "standard" plotting symbols.
```
rgl::pch3d(x1, y1, z1, col="red", bg="red", pch=10:19, size = 10)
```
I get the plot: [![3D plot with standard symbols](https://i.stack.imgur.com/ReAGn.png)](https://i.stack.imgur.com/ReAGn.png)
So, it appears to be that at least the symbols are not displaying in 3D. How can I display the preferred symbols? | 2022/02/27 | [
"https://Stackoverflow.com/questions/71288129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3236841/"
] | I was able to only get a solution using `text3d()` -- hopefully there exists a better solution.
```
x1 <- sort(rnorm(12))
y1 <- rnorm(12)
z1 <- rnorm(12) + atan2(x1, y1)
x2 <- sort(rnorm(12))
y2 <- rnorm(12)
z2 <- rnorm(12) + atan2(x2, y2)
x3 <- sort(rnorm(12))
y3 <- rnorm(12)
z3 <- rnorm(12) + atan2(x3, y3)
new.styles <- c(9818:9824, 9829, 9830, 9831, 9832, 9827)
rgl::open3d()
pal.col <- RColorBrewer::brewer.pal(name = "Paired", n = 12)
for (i in 1:12)
rgl::text3d(x1[i], y1[i], z1[i], col=pal.col[i], text = intToUtf8(new.styles[i]), cex = 2, usePlotmath = TRUE)
rgl::box3d()
```
This yields the figure:
[![Using text3d](https://i.stack.imgur.com/uBgCd.png)](https://i.stack.imgur.com/uBgCd.png)
This may well be too complicated, hopefully there are better solutions out there. |
1,336,337 | I've got my first RoR app deployed to Dreamhost and it's using Passenger. The one note on Dreamhost's wiki about slow response mentioned changing a RewriteRules line in the public/.htaccess file to use FastCGI. But I assume this will have no effect if I'm using Passenger, is that right?
I've looked at the logs and compared them to my local logs, and it looks like there is a wider range on Dreamhost. Some responses are comparable to the quick local ones, others can take a few seconds.
I'm using a Flex front end with HTTPServices to the rails backend, and I think I also need to add logging around my services to see what kind of network delay I'm getting and try to isolate where the delays are.
I should also add that there is probably plenty of room for improvement in the area of eager loading associations. I think I did that a little early on, but haven't done it thoroughly through all the associations. I have the local logs set to the default where I can see all the queries, and there are a lot of them. | 2009/08/26 | [
"https://Stackoverflow.com/questions/1336337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26270/"
] | You must be running in Development mode. Try running in Production mode to see if it is still slow.
Post below may help:
[Ruby On Rails is slow...?](https://stackoverflow.com/questions/566401/ruby-on-rails-is-slow) |
205,706 | I can't find a way to toggle mc internal editor in hex mode. [Here](http://www.tldp.org/LDP/LG/issue23/wkndmech_dec97/mc_article.html) it says to use F4 however it suggest to replace. How to do it? | 2015/05/26 | [
"https://unix.stackexchange.com/questions/205706",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/50426/"
] | You can open file with `F3`.
Hex view - `F4`.
Start edit - `F2`. |
6,061,310 | I'm getting crazy, cause I cannot find what are the "default" keys you would have in a PDF Document.
For example, if I want to retrieve an hyperlink from a CGPDFDocument, I do this:
```
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
break;
}
```
In this case, the key is "URI". Is there a document explaining what are the keys of a CGPDFDictionary? | 2011/05/19 | [
"https://Stackoverflow.com/questions/6061310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287454/"
] | It's absurd that you would have to go read 1300 page long specs just to find what keys a dictionary contains, a dictionary that could contain anything depending on what kind of annotation it is.
To get a list of keys in a `CGPDFDictionaryRef` you do:
```
// temporary C function to print out keys
void printPDFKeys(const char *key, CGPDFObjectRef ob, void *info) {
NSLog(@"key = %s", key);
}
```
In the place where you're trying to see the contents:
```
CGPDFDictionaryRef mysteriousDictionary; // this is your dictionary with keys
CGPDFDictionaryApplyFunction(mysteriousDictionary, printPDFKeys, NULL);
// break on or right after above, and you will have the list of keys NSLogged
``` |
36,711,776 | This is the HTML I want to extract from.
```
<input type="hidden" id="continueTo" name="continueTo" value="/oauth2/authz/?response_type=code&client_id=localoauth20&redirect_uri=http%3A%2F%2Fbg-sip-activemq%3A8080%2Fjbpm-console%2Foauth20Callback&state=72a37ba7-2033-47f4-8e7e-69a207406dfb" />
```
I need a Xpath to extract only state value i.e `72a37ba7-2033-47f4-8e7e-69a207406dfb` | 2016/04/19 | [
"https://Stackoverflow.com/questions/36711776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5850305/"
] | The XPATH:
```
//input[@id="continueTo"]/@value
```
It will get the value of the node `input` with id `continueTo`. Then it will need to be processed with a Regex first to get a final result.
The Regex:
```
`[^=]+$`
```
`$` means the end of the string. It will get everything on the end of the string which is not `=`. |
25,242,580 | I am working on node.js where forever is installed. I am not sure where is intalled . when i go to project directory then type command `forever list` then it will display no forever
Can any body tell me how to check and how to resart processes.
My website is running. it means forever may be running | 2014/08/11 | [
"https://Stackoverflow.com/questions/25242580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3883164/"
] | If `forever list` is empty, your nodeJS app is not running.
You have to start it first by doing `forever start yourApp.js` |
60,784 | I'm starting a VPN connection using Network Manager.
Once the connection is established I have to change [MTU](http://en.wikipedia.org/wiki/Maximum_transmission_unit) in order it to work properly.
For example:
```
sudo ifconfig ppp0 mtu 777
```
It is very annoying to execute this command every time I open a VPN connection. Is there any idea to create a script that would execute this command automatically once the connection is established (ppp0 interface is up)? | 2011/09/10 | [
"https://askubuntu.com/questions/60784",
"https://askubuntu.com",
"https://askubuntu.com/users/24741/"
] | Create a script in `/etc/network/if-up.d`, containing
```
#!/bin/sh
if [ "$IFACE" = "ppp0" ]; then
ifconfig ppp0 mtu 777
fi
```
and [make it executable](https://askubuntu.com/questions/122428/how-to-run-sh-file). |
9,479,819 | Sorry for the very noob question.
Let's suppose I have an enum like so
```
public enum MyElementType {
TYPE_ONE,
TYPE_TWO,
TYPE_THREE;
}
```
When I want to loop over this enum, I always see this solution:
```
for(MyElementType type: MyElementType.values())
{
//do things
}
```
I wonder if there exist a viable solution with the while loop.
Seraching around I see that Enumeration interface exposes the method
hasMoreElements()
but I don't know how to link the things together.
Any advice? | 2012/02/28 | [
"https://Stackoverflow.com/questions/9479819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/740480/"
] | Why do you want to use a while loop rather than the for-each you more typically see?
In any case, it's pretty simple
```
Set<MyElementType> elements = EnumSet.allOf(MyElementType.class);
Iterator<MyElementType> it = elements.iterator();
while (it.hasNext()) {
MyElementType el = it.next();
// etc
}
// or
Iterator<MyElementType> it = Arrays.asList(MyElementType.values()).iterator();
``` |
2,855 | Consider an application that currently uses a combination of license file and/or subscription to verify which features to activate. I can use a smart contract instead of the license file, and potentially the subscription. But today, the subscription check requires an online validation and associated credential check.
With the Ethereum blockchain, is it possible to check state while offline? I'd like to implement a system where people are not required to be online to use the software. I can imagine having contracts that return themselves as valid while offline, but will nodes provide access to data if they are not sync'd up? I'd be ok using out of date data for up to a month or more, but I'd need the local client to respond.
Alternatively, I could create local license files from the node when the node is online, but I could almost as easily email license files. But by using the blockchain, the licenses and other assets could be traded and available should the company fold. | 2016/04/10 | [
"https://ethereum.stackexchange.com/questions/2855",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/1161/"
] | When your app is able to sync with the blockchain (network connection available), the check the blockchain and update your app settings file to allow use for up to e.g. 1 week after the blockchain subscription check. Just tell the user that they have to sync before the period is up.
One extra feature you can add:
* Your app has a unique public and private Ethereum key embedded in it and has to send a small amount of ethers back to your account on a periodic basis.
* If you get sent more ether transactions from your app than expected, your customer is running more than one copy of your app. |
4,347,995 | I ask this as someone who loves maths but has no ability. So 2 axioms & a question.
Axiom 1 - a digital processor exists that can find the n'th prime number of any size instantly.
Axiom 2 - all natural numbers can be expressed as the sum of 2 primes.
Would it take more/less/same amount of bits to define a natural number exactly as the sum of primes or as traditional POW2 digital format and will that fact apply to all natural numbers whatever their size? I presume a +/- wouldn't be needed because if it's a - then the larger prime is given first. I'm also interested to know if it's ALWAYS more/less efficient or is their a numerical point at which the optimal solution alters.
Maybe it's a very badly written question. If so, I can only apologise. I have wondered this for 20 years but never had anywhere to ask. Thanks. | 2022/01/03 | [
"https://math.stackexchange.com/questions/4347995",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/603487/"
] | The ordinary way of storing natural numbers by means of bits is already optimal. This can easily be seen: Each of the $2^n$ combinations of assignments of $n$ bits represents exactly one distinct natural number between $0$ and $2^n-1$. If there was a way of storing more numbers with the same amount of bits, and we would try to create the mapping between the combination of bits and the actual numbers, we would necessarily end up with a combination of bits that maps to more than one natural number, see [pigeonhole principle](https://en.wikipedia.org/wiki/Pigeonhole_principle). This obviously does not make sense, because we want each number to be unambiguously represented as a certain "bit pattern" in the memory.
But it is even worse: We know for sure, that there are infinitely many numbers that can be represented as sum of two primes in more than one way (see [Infinitely many even numbers that can be expressed as the sum of $m$ primes in $n$ different ways](https://math.stackexchange.com/q/1443667/407833)). This means, that there will be definitely fewer natural numbers than unique combinations of two primes. Even if your axioms were true, you would have to represent the pairs of primes in such way that each sum appears only once, i.e. you need some magic that skips the combinations that map to natural numbers that are already covered by other prime pairs. |
4,568,514 | I'm working through Example 2.22 in Steward and Tall's Algebraic Number Theory book. The goal is to determine the ring of integers of $\mathbb Q(\sqrt[3]5)$. Let $\theta\in\mathbb R$ such that $\theta^3=5$. Let $\omega=e^{2\pi i/3}$. I'm at the point where I need to check whether
$$
\alpha=\frac 13(1+\theta+\theta^2)
$$
or
$$
\beta=\frac 13(2+2\theta+2\theta^2)
$$
are algebraic integers (I've checked the other cases). Let's start with $\alpha$. I can think of two ways to do this. The first would be to consider the norm
$$
N(\alpha)=\frac 1{27}(1+\theta+\theta^2)(1+\omega\theta+\omega^2\theta^2)(1+\omega^2\theta+\omega\theta^2).
$$
If $\alpha$ is an algebaric integer, then $N(\alpha)\in\mathbb Z$. However, the expression of $N(\alpha)$ is a bit complicated (unless I'm overlooking something). The second would be to determine the minimum polynomial $\mu$ of $\alpha$ over $\mathbb Q$, and then invoke that $\alpha$ is an algebraic integer iff $\mu\in\mathbb Z[X]$.
In both cases I'm not too hopeful. Should I still proceed in this way, or is there something obvious I'm missing? | 2022/11/03 | [
"https://math.stackexchange.com/questions/4568514",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/405827/"
] | [![enter image description here](https://i.stack.imgur.com/7hWo2.png)](https://i.stack.imgur.com/7hWo2.png)
As pointed out by dezdichado, the problem can be done by two applications of Cosine Formula.
Refer to the figure,
One such formula is:
$$\cos \alpha=\frac{(c-x)^2+y^2-a^2}{2(c-x)y}$$
Applying Cosine Formula to the other triangle and combining the $2$ equations would yield the required answer. |
4,605,482 | I want my marker to appear not in the center of the screen, but 25% of the way up to give extra room for the popup box. Although sticking an offset in is easy, the offset depends on the zoom level as if you're zoomed far out, you'll want to center the map quite far up (such as 50km). If you're really zoomed in, then you'll want to center it just a tiny amount like 10 meters.
I'm not sure how to accomplish this. Any ideas? | 2011/01/05 | [
"https://Stackoverflow.com/questions/4605482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/174375/"
] | Try this:
Take the height of the plugin and get 25% of that.
Then you need to multiply that by the degrees or kilometres per pixel scale at that height (if you can't get it straight from the plugin then I guess do the math), then centre the screen at that point on the globe. |
44,487,654 | I know this is a very classical question which might be answered many times in this forum, however I could not find any clear answer which explains this clearly from scratch.
Firstly, imgine that my dataset called my\_data has 4 variables such as
my\_data = variable1, variable2, variable3, target\_variable
So, let's come to my problem. I'll explain all my steps and ask your help for where I've been stuck:
```
# STEP1 : split my_data into [predictors] and [targets]
predictors = my_data[[
'variable1',
'variable2',
'variable3'
]]
targets = my_data.target_variable
# STEP2 : import the required libraries
from sklearn import cross_validation
from sklearn.ensemble import RandomForestRegressor
#STEP3 : define a simple Random Forest model attirbutes
model = RandomForestClassifier(n_estimators=100)
#STEP4 : Simple K-Fold cross validation. 3 folds.
cv = cross_validation.KFold(len(my_data), n_folds=3, random_state=30)
# STEP 5
```
At this step, I want to fit my model based on the training dataset, and then
use that model on test dataset and predict test targets. I also want to calculate the required statistics such as MSE, r2 etc. for understanding the performance of my model.
I'd appreciate if someone helps me woth some basic codelines for Step5. | 2017/06/11 | [
"https://Stackoverflow.com/questions/44487654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8010314/"
] | First off, you are using the deprecated package `cross-validation` of scikit library. New package is named `model_selection`. So I am using that in this answer.
Second, you are importing `RandomForestRegressor`, but defining `RandomForestClassifier` in the code. I am taking `RandomForestRegressor` here, because the metrics you want (MSE, R2 etc) are only defined for regression problems, not classification.
There are multiple ways to do what you want. I assume that since you are trying to use the KFold cross-validation here, you want to use the left-out data of each fold as test fold. To accomplish this, we can do:
```
predictors = my_data[[
'variable1',
'variable2',
'variable3'
]]
targets = my_data.target_variable
from sklearn import model_selection
from sklearn.ensemble import RandomForestRegressor
from sklearn import metrics
model = RandomForestRegressor(n_estimators=100)
cv = model_selection.KFold(n_splits=3)
for train_index, test_index in kf.split(predictors):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = predictors[train_index], predictors[test_index]
y_train, y_test = targets[train_index], targets[test_index]
# For training, fit() is used
model.fit(X_train, y_train)
# Default metric is R2 for regression, which can be accessed by score()
model.score(X_test, y_test)
# For other metrics, we need the predictions of the model
y_pred = model.predict(X_test)
metrics.mean_squared_error(y_test, y_pred)
metrics.r2_score(y_test, y_pred)
```
For all this, documentation is your best friend. And scikit-learn documentation are one of the best I have ever seen. Following links may help you know more about them:
* <http://scikit-learn.org/stable/modules/cross_validation.html#cross-validation-evaluating-estimator-performance>
* <http://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics>
* <http://scikit-learn.org/stable/user_guide.html> |
10,248,776 | Requirements for a TextBox control were to accept the following as valid inputs:
1. A sequence of numbers.
2. Literal string 'Number of rooms'.
3. No value at all (left blank). Not specifying a value at all should allow for the RegularExpressionValidator to pass.
Following RegEx yielded the desired results (successfully validated the 3 types of inputs):
```
"Number of rooms|[0-9]*"
```
However, I couldn't come up with an explanation when a colleague asked why the following fails to validate when the string 'Number of rooms' is specified (requirement #2):
```
"[0-9]*|Number of rooms"
```
An explanation as to why the ordering of alternation matters in this case would be very insightful indeed.
UPDATE:
The second regex successfully matches the target string "Number of rooms" in console app as shown [here](http://pastebin.com/yzr6Bqcd). However, using the identical expression in aspx markup doesn't match when the input is "Number of rooms". Here's the relevant aspx markup:
```
<asp:TextBox runat="server" ID="textbox1" >
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
EnableClientScript="false" runat="server" ControlToValidate="textbox1"
ValidationExpression="[0-9]*|Number of rooms"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
``` | 2012/04/20 | [
"https://Stackoverflow.com/questions/10248776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988951/"
] | The order matters since that is the order which the Regex engine will try to match.
Case 1: `Number of rooms|[0-9]*`
In this case the regex engine will first try to match the text "Number of room". If this fails will then try to match numbers or nothing.
Case 2: `[0-9]*|Number of rooms`:
In this case the engine will first try to match number or nothing. But nothing will *always* match. In this case it never needs to try "Number of rooms"
This is kind of like the || operator in C#. Once the left side matches the right side is ignored.
**Update:**
To answer your second question. It behaves differently with the RegularExpressionValidator because that is doing more than just checking for a match.
```
// .....
Match m = Regex.Match(controlValue, ValidationExpression);
return(m.Success && m.Index == 0 && m.Length == controlValue.Length);
// .....
```
It is checking for a match as well as making sure the length of the match is the whole string. This rules out partial or empty matches. |
83,623 | I am trying to round the corners of a custom shape, but it is just straightening the original curves out.
*Note: This is in Illustrator CS5*
**Here is the shape before the effect:**
[![enter image description here](https://i.stack.imgur.com/luohd.png)](https://i.stack.imgur.com/luohd.png)
The 3 "corners should be rounded".
**Here is what happens when I use the effect:**
[![enter image description here](https://i.stack.imgur.com/3jyfQ.png)](https://i.stack.imgur.com/3jyfQ.png)
**How can I preserve the curves, and just round the actual corners?** | 2017/01/20 | [
"https://graphicdesign.stackexchange.com/questions/83623",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/84489/"
] | I don't have CS5, but this should work:
Select your path. With the pen tool selected, create points on each side of the anchor points, something like the following:
[![Path with new anchor points added near the original cusp points.](https://i.stack.imgur.com/U3Mk7.png)](https://i.stack.imgur.com/U3Mk7.png)
With the white arrow tool selected, click one of the original cusp points (i.e., corner points) and then `Shift`-click the other two to select all three. Then, click the `Convert selected anchor points to smooth` icon in the toolbar at the top of the screen (alternatively, with the pen tool selected you can `Alt` or `Option`-drag on a corner point to convert it to a smooth point):
[![Convert selected anchor points to smooth icon](https://i.stack.imgur.com/mchHs.png)](https://i.stack.imgur.com/mchHs.png)
You should end up with something similar to this:
[![Path with bulging corners.](https://i.stack.imgur.com/zOo3s.png)](https://i.stack.imgur.com/zOo3s.png)
With the white arrow tool, drag each of the bulging corner points inward until they look appropriate:
[![Bulging corner points fixed.](https://i.stack.imgur.com/glD9N.png)](https://i.stack.imgur.com/glD9N.png)
Here's the new path overlaying your original shape.
[![Path with rounded corners.](https://i.stack.imgur.com/Mz93L.png)](https://i.stack.imgur.com/Mz93L.png)
If you want the corners to be more rounded, make sure the anchor points you added in the first step are farther away from the corner points. |
66,920,844 | I use a custom hook to support dark mode with tailwindcss in my new react-native app, created with Expo CLI. The TailwindProvider with the dark mode logic looks like this:
```js
const TailwindProvider: React.FC = ({ children }) => {
const [currentColorScheme, setcurrentColorScheme] = useState(Appearance.getColorScheme());
console.log("CurrentColorScheme:", currentColorScheme);
const isDarkMode = currentColorScheme == "dark";
const tw = (classes: string) => tailwind(handleThemeClasses(classes, isDarkMode))
return <TailwindContext.Provider value={{ currentColorScheme, setcurrentColorScheme, tw, isDarkMode }}>{children}</TailwindContext.Provider>;
}
```
as you can see, i use the `Appearance.getColorScheme()` method from `react-native` to get the current ColorScheme. But both on iOS and Android, i always get `light` instead of `dark`, in debug as well as in production mode.
How can I fix this? | 2021/04/02 | [
"https://Stackoverflow.com/questions/66920844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10183816/"
] | Use `systimestamp` since that includes a time zone.
```
select systimestamp at time zone 'US/Eastern'
from dual;
```
should return a timestamp in the Eastern time zone (assuming your database time zone files are up to date).
Note that if you ask for a timestamp in EST, that should be an hour earlier than the current time in the Eastern time zone of the United States because the US is in Daylight Savings Time. So the Eastern time zone is in EDT currently not EST. |
65,536,088 | I have a dataframe which is called "df". It looks like this:
```
a
0 2
1 3
2 0
3 5
4 1
5 3
6 1
7 2
8 2
9 1
```
I would like to produce a cummulative sum column which:
* Sums the contents of column "a" cumulatively;
* Until it gets a sum of "5";
* Resets the cumsum total, to 0, when it reaches a sum of "5", and continues with the summing process;
I would like the dataframe to look like this:
```
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
In the dataframe, the column "a\_cumm\_summ" contains the results of the cumulative sum.
Does anyone know how I can achieve this? I have hunted through the forums. And saw similar questions, for example, [this one](https://stackoverflow.com/questions/41488676/python-data-frame-cumulative-sum-of-column-until-condition-is-reached-and-retur), but they did not meet my exact requirements. | 2021/01/02 | [
"https://Stackoverflow.com/questions/65536088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11622176/"
] | You can get the cumsum, and floor divide by 5. Then subtract the result of the floor division, multiplied by 5, from the below row's cumulative sum:
```
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
df
Out[1]:
a a_cumm_sum
0 2 2
1 3 5
2 0 0
3 5 5
4 1 1
5 3 4
6 1 5
7 2 2
8 2 4
9 1 5
```
---
Solution #2 (more robust):
Per Trenton's comment, A good, diverse sample dataset goes a long way to figure out unbreakable logic for these types of problems. I probably would have come up with a better solution first time around with a good sample dataset. Here is a solution that overcomes the sample dataset that Trenton mentioned in the comments. As shown, there are more conditions to handle as you have to deal with carry-over. On a large dataset, this would still be much more performant than a for-loop, but it is much more difficult logic to vectorize:
```
df = pd.DataFrame({'a': {0: 2, 1: 4, 2: 1, 3: 5, 4: 1, 5: 3, 6: 1, 7: 2, 8: 2, 9: 1}})
c = df['a'].cumsum()
g = 5 * (c // 5)
df['a_cumm_sum'] = (c.shift(-1) - g).shift().fillna(df['a']).astype(int)
over = (df['a_cumm_sum'].shift(1) - 5)
df['a_cumm_sum'] = df['a_cumm_sum'] - np.where(over > 0, df['a_cumm_sum'] - over, 0).cumsum()
s = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum']*-1, 0).cumsum()
df['a_cumm_sum'] = np.where((df['a_cumm_sum'] > 0) & (s > 0), s + df['a_cumm_sum'],
df['a_cumm_sum'])
df['a_cumm_sum'] = np.where(df['a_cumm_sum'] < 0, df['a_cumm_sum'].shift() + df['a'], df['a_cumm_sum'])
df
Out[2]:
a a_cumm_sum
0 2 2.0
1 4 6.0
2 1 1.0
3 5 6.0
4 1 1.0
5 3 4.0
6 1 5.0
7 2 2.0
8 2 4.0
9 1 5.0
``` |
325,415 | (<https://webapps.stackexchange.com/review/suggested-edits/111499> shows action by both.) [Edit: At first glance they both looked like special users. Not so.] | 2019/03/18 | [
"https://meta.stackexchange.com/questions/325415",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/218120/"
] | Community♦ is [a special user](https://meta.stackexchange.com/questions/19738/who-is-the-community-user). Community is credited for reviews when they are:
* Done by deleted users
* Improved, in which case Community is shown as having approved the edit
* Rejected and edited, in which case Community is shown as having rejected the edit
[user0](https://webapps.stackexchange.com/users/186471/user0) is a normal user who just happens to have "0" in the username. user0 approved the edit before it was improved by a different user. |
48,751,289 | My project can switch between languages. The items are stored in a database, and using $\_GET['lang'] in the database gives back the correct items. For now, only English and French are in use, so it works with this code :
```
if ($_GET['lang'] == 'fr' OR ($_GET['lang'] == 'en')) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
} else {
header('Location: error.php');
}
```
What I'm looking for is some way to be prepared in case a language is added in the db. The code below approaches what I need (and obviously didn't work).
```
while ($translations = $languagesList->fetch()) {
if ($_GET['lang'] == $translations['code']) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
} else {
header('Location: language.php');
}
}
```
Is there any way to create a code that would generate multiple if conditions based on the number of languages in the db ? | 2018/02/12 | [
"https://Stackoverflow.com/questions/48751289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9244707/"
] | You should move the else part outside of the loop, as otherwise you will always execute it at some point in the loop iterations. Only when you have iterated through *all* possibilities, and you still have no match, then you can be sure there to have to navigate to the language page:
```
$header = null;
while ($translations = $languagesList->fetch()) {
if ($_GET['lang'] == $translations['code']) {
$header = getTranslation('header', $_GET['lang']);
$footer = getTranslation('footer', $_GET['lang']);
break; // No need to waste time to look further.
}
}
if ($header === null) {
header('Location: language.php');
}
```
But it would be smarter to [prepare an SQL statement](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) that gets you the result for the *particular* language only (with `where code = ?` and bind `$_GET['lang']` to it). Then you don't have to iterate in PHP, which will in general be slower than what the database can provide. Instead you can just see whether you had 0 or 1 records back (Or use `select count(*)` and check whether that is 0 or not). |
36,937,302 | I have a list of strings (see below) how do I concatenate these strings into one list containing one string.
```
["hello","stack","overflow"]
```
to
```
["hellostackoverflow"]
```
I am just allowed to import Data.Char and Data.List | 2016/04/29 | [
"https://Stackoverflow.com/questions/36937302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6219741/"
] | Consider each string in a list as a list of characters
```
["hello","stack","overflow"] :: [[Char]]
```
Concatenation is a process of connecting several lists into one. It must have a following type:
```
concat :: [[a]] -> [a]
```
If you will have such a function, you'll get a half of job done. You are looking for a way to get
```
["hellostackoverflow"]
```
as a result of concatenation. Once again, look at it's type:
```
["hellostackoverflow"] :: [[Char]]
```
It is the same type as you had at the beginning except that there is only one element in a list. So now you need a function which puts something into a list. It must have a type
```
putToList :: a -> [a]
```
Once you'll have both `concat` and `putToList` functions, your solution will be almost ready. Last thing you need to do is to compose it like that:
```
myConcatenation = putToList . concat
```
---
I suggest you to use [Hoogle](https://www.haskell.org/hoogle/) to search existing function by it's type. |
5,809,104 | Here T could be an array or a single object. How can add the array to an arraylist or add a single object to the same arraylist. This gives me a build-time error that the overloaded match for `AddRange` has invalid arguments.
```
T loadedContent;
if (typeof(T).IsArray)
{
contentArrayList.AddRange(loadedContent);
}
else
{
contentArrayList.Add(loadedContent);
}
``` | 2011/04/27 | [
"https://Stackoverflow.com/questions/5809104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727904/"
] | Make sure you have set the correct editor associations and content types
Go to settings (`Window -> preferences`)
**Content Types**
1. Type in `Content Types` in the search box (should show under `General -> Types`
2. Click on the arrow next to `Text`, select `PHP Content Type`
3. Add `*.ctp` by clicking on the Add button on the right side
**File Association**
1. Type in `File Associations` in the search box on the left
2. Add \*.ctp (click the Add button on the top right side)
3. Associate the proper editor for it by clicking Add (on the bottom right side) and selecting PHP Editor |
55,102,475 | I read that 'It is not recommended you use insertAdjacentHTML() when inserting plain text' [here](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) .
I do see those tags which differentiate a plain text from tags+text+tags combination.
Is it safe to use `insertAdjacentHTML()` method to add a `sibling with text` to an element. This is what I am trying to do:
```
<div id="one"></div>
#adding a sibling to above div with text
<div id="one"></div>
<div id="two">text here</div>
```
Any advice would be helpful. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55102475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10197341/"
] | Well really the answer to your question is in the link you provided. Is it derived from user input? Then it's unsafe without proper anti-XSS procedures. Is it something you typed from the server and will only ever be something that you intend it to be? Then feel free to use `insertAdjacentHTML()`. See Vinz243's link about XSS. |
133,508 | I've tried connecting a camera to my Raspberry Pi and I've enabled it on `raspi-config` but `vcgencmd get_camera` still shows `supported=0` `detected=0`. Also, in my `boot/config.txt`, `start_x=1` is not even commented nor enabled upon enabling camera interface. Another thing to note is my Raspberry Pi constantly shows a low voltage warning but I am unsure whether this is related in any way. What might be the issue? | 2021/11/25 | [
"https://raspberrypi.stackexchange.com/questions/133508",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/141166/"
] | Thanks to the comments, I have rectified the issue. The issue was with the bullseye version of the os. I used a buster version and it worked just fine |
21,876,004 | I am having problems while doing some test for a new app.
I have an activity in which I execute an asynctask to communicate with my server and ask for a json file.
I want that this file is downloaded periodically (don't know, 3-4 seconds) so I created a handler in my activity to execute it each time.
It works fine with Logs but whenever I try to execute asynctask, it makes an exception saying:
```
02-19 10:16:41.510: WARN/System.err(9051): java.lang.IllegalStateException: Cannot execute task: the task is already running.
02-19 10:16:41.510: WARN/System.err(9051): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:576)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.AsyncTask.execute(AsyncTask.java:535)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity.askForData(mySecondActivity.java:68)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity.access$000(mySecondActivity.java:22)
02-19 10:16:41.510: WARN/System.err(9051): at com.mobile.myPacket.mySecondActivity$1.run(mySecondActivity.java:56)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Handler.handleCallback(Handler.java:733)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Handler.dispatchMessage(Handler.java:95)
02-19 10:16:41.510: WARN/System.err(9051): at android.os.Looper.loop(Looper.java:136)
02-19 10:16:41.510: WARN/System.err(9051): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-19 10:16:41.510: WARN/System.err(9051): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 10:16:41.510: WARN/System.err(9051): at java.lang.reflect.Method.invoke(Method.java:515)
02-19 10:16:41.510: WARN/System.err(9051): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-19 10:16:41.510: WARN/System.err(9051): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-19 10:16:41.510: WARN/System.err(9051): at dalvik.system.NativeStart.main(Native Method)
```
I think it is because it is another thread and second call is making a problem with the first one. But I don't know how to solve it.
This is my activity:
```
package com.mobile.myPacket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.mobile.clases.AsyncResponse;
import com.mobile.clases.MyTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends Activity implements AsyncResponse {
private String urlServer = "url";
MyTask asyncTask =new MyTask();
Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
setContentView(R.layout.secondActivity);
asyncTask.delegate = this;
//We ask for data the first time
askForData();
}
@Override
public void processFinish(JSONArray output) { //Executed from asyncTask
//Data received
Log.i("TEST", output.toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
askForData();
//Log.i("TEST","aa");
handler.postDelayed(this, 3000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
private void askForData(){
Log.i("TEST","askForData");
asyncTask.execute(urlServer+"test.php");
}
}
```
Without handler, asyncTask works fine just one time. So I guess that class is ok. | 2014/02/19 | [
"https://Stackoverflow.com/questions/21876004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463191/"
] | You cannot execute the same `AsyncTask` multiple times.
Before executing the `AsyncTask`, instantiate a new instance first:
```
private void askForData(){
asyncTask = new MyTask();
asyncTask.delegate = this;
asyncTask.execute(urlServer+"test.php");
}
```
Also remove the instantiation of the `AsyncTask` at the beginning of your class. |
17,206,523 | I was processing my `resultset` to get the details. I need to return an `ArrayList`, so how can I put the key,values from the `resultset` to any of the collection objects and then put the same to an `ArrayList`?
Here is the code:
```
public List<Bike> addBikes() throws ClassNotFoundException, SQLException{
List<Bike> bikeList = new ArrayList<Bike>();
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
Statement stm = null;
ResultSet rs = null;
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/spring_hibernate","root","root"); ;
stm=con.createStatement();
String qry="Select * from bike";
rs=stm.executeQuery(qry);
while(rs.next())
{
/* I need to put
* rs.getString("name"),rs.getString("model")
* etc into any of the suitable collection objects
* and then need to add those to the ArrayList - bikeList
*
*/
}
return bikeList;
}
``` | 2013/06/20 | [
"https://Stackoverflow.com/questions/17206523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/930544/"
] | For each result in the result set, create a `new Bike()` and copy the values from that result to the new bikes fields. At the end, add the bike to the list.
```
Bike bike = new Bike()
bike.setName(rs.getString("name"));
//...
bikeList.add(bike);
``` |
72,632,348 | In Visual Studio there is a possibility to mute an exception when it happens in particular place, e.g. We are aware that there is some `NullRefereneceException` in `Calculator.cs` and we still want to catch those types of exceptions when thrown from all other places in code, but `Calculator.cs`.
How it looks like in VS:
[![enter image description here](https://i.stack.imgur.com/gb5hN.png)](https://i.stack.imgur.com/gb5hN.png)
Is such a feature available in Rider? | 2022/06/15 | [
"https://Stackoverflow.com/questions/72632348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10049966/"
] | I wasn't able to find a solution to your question.
The only thing I found is to not break on a specific exception type - but that's unrelated to the line.
For example, let's take the following code:
```cs
public class OtherClass
{
public void ThrowNullReferenceException()
{
try
{
throw new NullReferenceException();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
```
With the following *Exception Settings*, the handled `NullReferenceException` gets swallowed:
[![enter image description here](https://i.stack.imgur.com/KiB6K.png)](https://i.stack.imgur.com/KiB6K.png)
Maybe you can get in contact with [Rider support](https://rider-support.jetbrains.com/hc/en-us/requests/new?ticket_form_id=97145). |
4,268,625 | What is the best and/or fastest to learn Java API for consuming XML feeds like this:
```
<body copyright="Company">
<student id="1" fname="Anthony" lname="Hopkins"/>
<student id="2" fname="John" lname="Anderson"/>
<student id="3" fname="Will" lname="Smitherman"/>
</body>
```
As you can see it provides all the data with attributes. Also, XML Feed data will be accessed using URLs with parameters specified in the query string.
Thanks in advance guys. | 2010/11/24 | [
"https://Stackoverflow.com/questions/4268625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311263/"
] | Easiest way is to use JaxB to generate the Java classes for you. If you have a schema you use xjb tool that will create the classes and can let java do all the parsing without you needing to do anything.
Look at <http://www.javaworld.com/javaworld/jw-06-2006/jw-0626-jaxb.html> |
25,656,841 | I'm trying to make a Greasemonkey script to hide a really annoying div, on a website, that pops up after a few seconds. Neither of these works:
```
$("#flyin").hide();
$(document).ready(function(){
$("#flyin").hide();
});
```
I assume it's because the `#flyin` div is not created, yet. How do I tell jQuery to keep on looking for this div, maybe every n seconds, so I can hide it?
When I try to hide a non js, regular old div that is always present on the page, it works. | 2014/09/04 | [
"https://Stackoverflow.com/questions/25656841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1347640/"
] | There's [a utility for that (waitForKeyElements)](https://gist.github.com/2625891).
Your **whole script** would simply be:
```
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
waitForKeyElements ("#flyin", hideFlyin);
function hideFlyin (jNode) {
jNode.hide ();
}
```
Or, if the node only appears once per page load and the pages are not wholly changed via AJAX, use:
```
//-- Unload after one run.
waitForKeyElements ("#flyin", hideFlyin, true);
``` |
180,502 | I wrote a selector for several countries. This selector allows the user to choose a country, then a region and then a city. After the user chooses a city, it displays the selected object's country code, region code and area code (in terms of the [VK API](https://vk.com/dev/database.getCities) social network).
The selectors use the [jquery ui](https://api.jqueryui.com/autocomplete/) autocomplete plugin.
### HTML:
```
<div class="outer" id="countryOuter">
<input id="country" placeholder="Страна">
</div>
<div class="outer" id="regionOuter">
<input id="region" placeholder="Регион">
</div>
<div class="outer" id="cityOuter">
<input id="city" placeholder="Город">
</div>
```
### JS:
```
$( document ).ready(function() {
getCountries();
var countriesArr = [],
countriesObj = {};
var regionsArr = [],
regionsObj = {};
var citiesArr = [],
citiesObj = {};
$('#region').attr('disabled', 'disabled');
$('#city').attr('disabled', 'disabled');
function getCountries() {
$.ajax({
url: "http://api.vk.com/method/database.getCountries?v=5.69",
dataType: "jsonp",
success: function( data ) {
var countriesRaw = data['response']['items'];
console.log( countriesRaw );
countriesArr = countriesRaw.map(function(country) {
return country.title;
});
console.log(countriesArr);
countriesRaw.forEach(function(country) {
countriesObj[country.title] = country.id;
});
console.log(countriesObj);
document.getElementById('countryOuter').style.display = 'block';
$( "#country" ).autocomplete({
delay: 0.5,
source: countriesArr,
select: function(event, ui) {
$('#country').attr('disabled', 'disabled');
$('#region').removeAttr('disabled');
console.log(event, countriesObj[ui.item.label]);
getRegions(countriesObj[ui.item.label]);
}
});
}
});
};
function getRegions(countryId) {
$.ajax({
url: "http://api.vk.com/method/database.getRegions?v=5.69&country_id=" + countryId,
dataType: "jsonp",
success: function( data ) {
var regionsRaw = data['response']['items'];
console.log( regionsRaw );
regionsArr = regionsRaw.map(function(region) {
return region.title;
});
console.log(regionsArr);
regionsRaw.forEach(function(region) {
regionsObj[region.title] = region.id;
});
console.log(regionsObj);
console.log('____countryId', countryId);
$( "#region" ).autocomplete({
delay: 0.5,
source: regionsArr,
select: function(event, ui) {
$('#region').attr('disabled', 'disabled');
$('#city').removeAttr('disabled');
console.log(event, ui);
getCitiesOut(countryId, regionsObj[ui.item.label]);
}
});
}
})
};
function getCitiesOut(countryId, regionId) {
console.log('countryId, regionId', countryId, regionId);
getCities();
function getCities( offset, limit ) {
if( ! limit || limit > 1000 ) limit = 1000; //число запрашиваемых городов, максимально 1000, по умолчанию 1000
if( ! offset ) offset = 0; //по умолчанию 0
$.ajax({
url: "http://api.vk.com/method/database.getCities?v=5.69&need_all=0&count="+limit+"&country_id=" + countryId +"®ion_id=" + regionId +"&offset="+(offset*limit),
dataType: "jsonp",
success: function( data ) {
console.log('data', data);
var allCities = data.response.count;
console.log('allCities', allCities);
var citiesRaw = data['response']['items'];
//с помощью concat можно объеденить 2 массива.
citiesArr = citiesArr.concat(citiesRaw.map(function(city) {
return city.title;
}));
//если в текущем ответе не все города то делаем ещё запрос с новым offset
if( allCities > offset*limit + limit)
getCities(offset+1, limit);
console.log('citiesArr', citiesArr);
citiesRaw.forEach(function(cities) {
citiesObj[cities.title] = cities.id;
});
$( "#city" ).autocomplete({
delay: 0.5,
source: citiesArr,
select: function(event, ui) {
$('#city').attr('disabled', 'disabled');
console.log(event, ui);
alert('Код страны' + countryId + ', Код региона' + regionId + ', Код города' + citiesObj[ui.item.label]);
}
});
}
});
};
}
});
```
Unfortunately jsfiddle and similar services do not support JSONP-requests which are used in my code, but [this Plunker example demonstrates the code](http://embed.plnkr.co/fnTVnN0mcYdi5o4xO6XR/). | 2017/11/15 | [
"https://codereview.stackexchange.com/questions/180502",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/91959/"
] | 1. There is too much nesting, which, for me, makes the logic hard to read. A good rule of thumb is to aim for two levels of nesting, by using the Extract Method refactoring.
2. When the user clicks on the input, nothing happens. When the user starts typing a name that isn't in the list, sometimes the list pops up (if the initial matches) and sometimes they just type (if there is no matching string). I expect many users will be confused, and they might feel more comfortable if you re-used an existing paradigm.
3. Your three functions contain a lot of identical code. This means that whenever you want to change the user experience in all three fields, you will need to change it in three places. Yet if you want the experience to be consistent, you probably want to change it in only one place. I suggest extracting the common functionality into a shared function. |
83,635 | I'm a complete cooking newb. I saw on youtube the other day that you should cook steak in an oven before frying it. I think it makes it softer (not sure, please let me know).
But anyway, I never used an oven in my entire life. And I looked inside the oven and there are no trays in there. So I went to the store and the only trays I saw in the cooking section were meant for "cookies" that you cook in the oven, and other things like that, muffins etc. But they never mentioned steak.
So can I cook my steak on trays meant for deserts, or do I need to look for a tray meant for steaks? and should I even cook my steak in the oven in the first place? | 2017/08/10 | [
"https://cooking.stackexchange.com/questions/83635",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/60749/"
] | To answer your question directly, if the method of cooking is what I think it is, the pan you use should be fine, even if it has a nonstick coating on it. You can read the second section to see if my assumption about your cooking method is correct.
It's important that you don't use nonstick cookware for extremely high heat cooking. If the nonstick coating gets to the smoking point, it releases gases that are toxic enough (as a friend tragically learned) to kill pets. This includes pans that go in the oven, and on the stovetop.
Since the temperature at which you're cooking the steak isn't that much hotter than you'd use baking cookies, it should be fine. If it does have a nonstick coating, you should not use it under a broiler, which is much hotter than just sitting in the oven while it bakes.
---
Even though it's not exactly what you asked, since you don't seem to be super confident in what you're doing, I'll give you a little more info on what I believe is the technique you're trying to pull off.
I think what you're referring to is the method of cooking where you cook a steak slowly in the oven until the internal doneness (rare, medium rare, etc.) is just how you like it, and then you give it a good hot sear in a pan so you form a flavorful crust on the outside. It's pretty intuitive when you consider the following:
* Making sure steak (or chicken, or pork chops, or other quick-cooking cuts of meat) is cooked through simply involves getting it to the desired internal temperature. The more consistent the internal temperature throughout the meat, the more consistent the texture and juiciness.
+ The best way to control the overall internal temperature of the meat is to use gentler lower temperature methods of cooking so the inside has time to warm up before the outside gets overcooked.
* Getting optimum flavor in a steak requires a nice sear/crust on the meat.
+ The best way to get a nice crust on your steak is to add a decent amount of salt, and use a high-heat cooking method to trigger the Maillard reaction (what's happening chemically when browning occurs) and perhaps some charring.
You can see where the conflict lies between these two needs.
Using the method you read about, you can use the oven to gently bring it up to temperature so it's consistently cooked inside, and then you can use a pan (which does not have a nonstick coating) to give it a nice hot sear after it comes out of the oven.
It is easy to overcook steak if you're not particularly experienced, especially using more complicated dual-cook methods. Nobody wants to eat a tough, dry mess. Though it's tempting to rely on cooking times you find on the internet, **time is usually the least precise method to determine how cooked something is.** I highly recommend using an instant-read thermometer to check the actual temperature inside. |
31,714,522 | I have two strings.
```
str_a = "the_quick_brown_fox"
str_b = "the_quick_red_fox"
```
I want to find the first index at which the two strings differ (i.e. `str_a[i] != str_b[i]`).
I know I could solve this with something like the following:
```
def diff_char_index(str_a, str_b)
arr_a, arr_b = str_a.split(""), str_b.split("")
return -1 unless valid_string?(str_a) && valid_string?(str_b)
arr_a.each_index do |i|
return i unless arr_a[i] == arr_b[i]
end
end
def valid_string?(str)
return false unless str.is_a?(String)
return false unless str.size > 0
true
end
diff_char_index(str_a, str_b) # => 10
```
Is there a better way to do this? | 2015/07/30 | [
"https://Stackoverflow.com/questions/31714522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295407/"
] | Something like this ought to work:
```
str_a.each_char.with_index
.find_index {|char, idx| char != str_b[idx] } || str_a.size
```
**Edit:** It works: <http://ideone.com/Ttwu1x>
**Edit 2:** My original code returned `nil` if `str_a` was shorter than `str_b`. I've updated it to work correctly (it will return `str_a.size`, so if e.g. the last index in `str_a` is 3, it will return 4).
Here's another method that may strike some as slightly simpler:
```
(0...str_a.size).find {|i| str_a[i] != str_b[i] } || str_a.size
```
<http://ideone.com/275cEU> |
2,015 | So this question... <https://serverfault.com/questions/45734/the-coolest-server-names>
It's horribly off topic. It's got a few votes to delete it right now because the community does not want it here (it's already been deleted once by the community).
I understand that it's being kept around for its historical significance, but it's not this site's history.
It's a question which came from SO, had many answers given by SO, and was migrated here. So can we send it back to SO? It's off topic there, yes, but it's also off topic here. At least at SO it would be back to its historical roots.
Or we could just delete it. That's happened once already, but Jeff brought it back. I don't want to start a "community vs. the mods (or SO leadership)" battle. At what point does "We don’t run Server Fault. The community does." begin or end?
The other option is we could just leave it. But it's not on topic. I don't fully understand why we would leave this off topic question here when we delete others that are similarly off topic. | 2011/09/04 | [
"https://meta.serverfault.com/questions/2015",
"https://meta.serverfault.com",
"https://meta.serverfault.com/users/33118/"
] | Throw this question into the sun. |
115,769 | I have a 40 gallon (bladdered) pressure tank in the basement which keeps pressure to my office building, and a 2-inch 2 horsepower submersible pump in a dug well 450 feet away.
The pump is cycling waaay too fast, and the tank will hold pressure at 41 pounds to 43 pounds but not at 60 pounds at shut-off pressure. (The pump comes on at 40 and shuts off at 60). It only takes 6 seconds for the pump to come on and shut off and I fear I will cook the pump if this keeps up.
I have recently tested the pressure in the tank and it is 50 pounds. Does this mean the bladder leaked and caused pressure to increase in the tank? I know the tank pressure should be set at around 39, or a little below the 'turn-on' pressure. Could this be the cause of the short cycle? | 2017/06/02 | [
"https://diy.stackexchange.com/questions/115769",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/70373/"
] | The bladder is there to flatten the pressure/volume curve so pressure doesn't change rapidly as water is pumped.
This allows for a longer duty cycle.
The expected symptom of a burst bladder is just as you describe. |
9,482,602 | I'm working on a Google Chrome extension with a popup, in which I load a page from a node.js + express.js server. The page I load changes depending on the status of the `req.session.user` in this way:
```
app.get('/', function(req, res){
if(req.session.user){
res.render(__dirname + '/pages/base.jade', {});
}
else{
res.render(__dirname + '/pages/login_register.jade', {});
}
});
```
If `req.session.user` is null I send a page in which the user can do the login or register. If he/she does a login, this is what happens in the server:
```
app.post('/login', function(req, res){
var user = {};
user.username = req.body.username;
user.password = req.body.password;
checkLogin(user, function(foundUser){
//login correct
console.log("login!");
req.session.user = foundUser;
res.render(__dirname + '/pages/base.jade', {
});
});
});
```
So if the user logs in correctly `req.session.user` should be set with the credentials of the current user. The problem is that once I log in and then close the popup of the Chrome extension, whenever I reopen it I still receive the login page.
My question is: does the popup supports session storage in the express.js server? If yes, then there is something wrong with my code, can anyone point out what am I doing wrong? Thanks.
EDIT:
This is how I setup the server:
```
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
```
I might be doing something redundant here, since I still don't have a deep understanding of how that works. | 2012/02/28 | [
"https://Stackoverflow.com/questions/9482602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/617461/"
] | The problem is how you have set up your server - you're using the `cookieParser` and `session` middlewares twice:
```
var app = express.createServer(
express.logger(),
express.cookieParser(),
express.session({ secret: 'keyboard cat' })
);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
```
You should only use *either* middlewares as parameters to `createServer`, *or* `use`, so:
```
var app = express.createServer();
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
``` |
19,270,638 | I am creating a BitSet with a fixed number of bits.
In this case the length of my String holding the binary representation is 508 characters long.
So I create BitSet the following way:
```
BitSet bs = new BitSet(binary.length());
// binary.length() = 508
```
But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.
Maybe there is some misunderstanding of the following documentation:
>
> **BitSet(int nbits)**
>
>
> Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.
>
>
>
Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19270638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/664010/"
] | The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The `size()` of a Bitset is effectively its current *capacity*, though the specification is rather more rubbery than that.
>
> So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ?
>
>
>
Correct, and yes.
If you want the logical size (i.e. the highest bit index that is set) use the `length()` method, not the `size()` method.
>
> If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0.
>
>
>
In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the `length()` will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value.
A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.) |
41,004,429 | hi guys this is my "login.php":
```
<?php
session_start();
// connect to database
if (isset($_POST['login_btn'])) {
$username =$_POST['username'];
$password =$_POST['password'];
$_SESSION['username'] = $_POST['username'];
$conn = oci_connect('insidedba', 'progetto16', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$password = md5($password); // remember we hashed password before storing last time
$sql = oci_parse($conn,"SELECT * FROM UTENTI WHERE USERNAME='$username' AND PASSWORD='$password'");
$result =oci_execute($sql);
if ($result) {
$stid = oci_parse($conn, "SELECT * FROM UTENTI WHERE username='$username' AND password='$password'");
oci_execute($stid);
oci_fetch($stid);
if (oci_num_rows($stid) == 1) {
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header("location: panel/index.php"); //redirect to home page
} else{
$_SESSION['message'] = "Username/password combination incorrect";
}
} else {
$_SESSION['message'] = "Query error";
}
}
?>
```
and it works,and i'm asking if i can use the $username variable in another php.
"myorder.php":
```
<?php
session_start()
$conn = oci_connect('insidedba', 'progetto16', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$columns = array(
'Nome cinema ' => 'NOME_CINEMA',
'Ora' => 'ORARIO',
'Data' => 'DATA',
'Titolo' => 'TITOLO',
'Numero prenotazione' =>'Codice_della_prenotazione',
'Numero sala' =>'Numero_sala',
'Fila' =>'fila',
'Numero sala' =>'numero',
);
// Run the query
$sql = oci_parse($conn,"SELECT DISTINCT CIN.NOME AS NOME_CINEMA,PAL.DATA as DATA,PAL.ORA ORARIO,F.Titolo as TITOLO,
PRE.ID as Codice_della_prenotazione,S.CODS AS Numero_sala,P.FILA as fila,P.NUMERO as numero
FROM (((((UTENTI U JOIN PRENOTAZIONI PRE ON PRE.UTENTE=U.ID AND U.USERNAME='$username')
JOIN PALINSESTI PAL ON PAL.ID=PRE.PALINSESTO)
JOIN FILM F ON F.ID=PAL.FILM)
JOIN CINEMA CIN ON CIN.ID=PAL.CINEMA )
JOIN POSTI P ON P.PRENOTAZIONE=PRE.ID AND P.CINEMA=CIN.ID)
JOIN SALE S ON S.CINEMA=CIN.ID and p.SALA=S.CODS WHERE BOOL_PAGATO=1
ORDER BY PRE.ID");
oci_execute($sql);
// Output table header
echo "<table border=\"1px solid black\" width=\"95%\"><tr>";
foreach ($columns as $name => $col_name) {
echo "<th>$name</th>";
}
echo "</tr>";
// Output rows
while($row = oci_fetch_array($sql)) {
echo "<tr>";
foreach ($columns as $name => $col_name) {
echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>";
}
echo "</tr>";
}
// Close table
echo "</table>"
?>
```
it says undefined variable,
How can i solve this?
i tried " but it still doesnt work. | 2016/12/06 | [
"https://Stackoverflow.com/questions/41004429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7160791/"
] | If it's stored in session you can.
```
session_start();
if(!empty($_SESSION['username'])) $username = $_SESSION['username'];
else $username = "guest";
``` |
65,915,932 | I tried to look in other solutions. But it didn't help me out. Kindly look into this.
my html code.
```
<tbody>
{% for st in stu %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.role}}</td>
<td>
<a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %}
<form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %}
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
```
my views.py and urls.py code
```
def delete_data(request,id):
if request.method == 'POST':
pi = User.objects.get(pk=id)
pi.delete()
return HttpResponseRedirect('/')
urlpatterns=[
re_path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
``` | 2021/01/27 | [
"https://Stackoverflow.com/questions/65915932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13533843/"
] | You are using `re_path` like it is `path`. `re_path` expects regex, it does not have path converters like `path`. You can either write a regex or switch to `path`.
Regex solution:
```
urlpatterns=[
re_path(r'delete/(?P<pk>\d+)/',views.delete_data,name="deletedata")
]
```
path solution:
```
from django.urls import path
urlpatterns=[
path('delete/<int:pk>/',views.delete_data,name="deletedata")
]
```
**Edit:** Also in your view you have named your parameter as **id**, all captured arguments from the url pattern are passed as keyword arguments, ensure that your naming is **consistent** in your pattern, view, template.
Change your view definition (and all usages of the variable in the view function to **pk**) to:
```
def delete_data(request, pk):
``` |
12,165,002 | You know how PHP's `isset()` can accept multiple (no limit either) arguments?
Like I can do:
```
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
```
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it? | 2012/08/28 | [
"https://Stackoverflow.com/questions/12165002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [`func_get_args`](http://php.net/manual/en/function.func-get-args.php) will do what you want:
```
function infinite_parameters() {
foreach (func_get_args() as $param) {
echo "Param is $param" . PHP_EOL;
}
}
```
You can also use `func_get_arg` to get a specific parameter (it's zero-indexed):
```
function infinite_parameters() {
echo func_get_arg(2);
}
```
But be careful to check that you have that parameter:
```
function infinite_parameters() {
if (func_num_args() < 3) {
throw new BadFunctionCallException("Not enough parameters!");
}
}
```
You can even mix together `func_*_arg` and regular parameters:
```
function foo($param1, $param2) {
echo $param1; // Works as normal
echo func_get_arg(0); // Gets $param1
if (func_num_args() >= 3) {
echo func_get_arg(2);
}
}
```
But before using it, think about whether you *really* want to have indefinite parameters. Would an array not suffice? |
75,277 | I've seen quite a few security camera examples and many have options for a duty schedule that activates the camera during certain specified days/hours to set up a routine. However I have fairly dynamic schedule and would like for my security cameras to turn on when our phones are not on the WiFi network. This would be an easy shortcut to "on when we're not home" and prevents it from taking intrusive pictures when we are.
Is there a way to configure OpenCV or Motion, or to run a python script to activate a camera when our phones are off the WiFi network? I would like to take advantage of some features of the above software to email or stream footage, so I would like to avoid redesigning a system from the ground up to do this.
Any advice? Thanks! | 2017/11/16 | [
"https://raspberrypi.stackexchange.com/questions/75277",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/54665/"
] | You'd need to know either the MAC or IP address of the phones you want to monitor but you could just `ping` or `arping` each one in turn and if none reply start your recording otherwise stop recording. Calling something like this from `cron` might do the trick:
```
#!/bin/bash
#
# Determine if we should be recording or not by pinging each phone in the list
# and setting the variable to "NO" if any reply. If the variable is still "YES"
# at the end we check if the recording process is running and start it if not.
#
LIST="192.168.123.25 192.168.123.56 192.168.123.13 MyPhone.local 192.168.123.78"
RECORD_CMD="RecordingCommand"
RECORD="YES"
for HOST in $LIST; do
ping -c1 "$HOST" &> /dev/null && RECORD="NO"
done
if [ "$RECORD" == "YES" ]; then
# Start or continue recording?
if [ $(pgrep -c "$RECORD_CMD") -eq 0 ]; then
# Not currently recording so we need to start...
"$RECORD_CMD"
fi
else
# Stop recording...
killall "$RECORD_CMD"
fi
exit 0
``` |
58,655,207 | I'm currently trying to extend [a model](https://github.com/microsoft/MASS) that is based on FairSeq/PyTorch. During training I need to train two encoders: one with the target sample, and the original one with the source sample.
So the current forward function looks like this:
```
def forward(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
return decoder_out
```
And based on this [this idea](https://github.com/golsun/SpaceFusion) i want something like this:
```
def forward_test(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
decoder_out = self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
return decoder_out
def forward_train(self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs)
concat = some_concatination_func(encoder_out, autoencoder_out)
decoder_out = self.decoder(prev_output_tokens, encoder_out=concat, **kwargs)
return decoder_out
```
Is there any way to do this?
Edit:
These are the constraints that I have, since I need to extend *FairseqEncoderDecoderModel*:
```
@register_model('transformer_mass')
class TransformerMASSModel(FairseqEncoderDecoderModel):
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
```
Edit 2:
The parameters passed to the forward function in Fairseq can be altered by implementing your own Criterion, see for example [CrossEntropyCriterion](https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/cross_entropy.py#L28), where `sample['net_input']` is passed to the `__call__` function of the model, which invokes the `forward` method. | 2019/11/01 | [
"https://Stackoverflow.com/questions/58655207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3128562/"
] | First of all you should **always use and define `forward`** not some other methods that you call on the `torch.nn.Module` instance.
**Definitely do not overload `eval()` as shown by [trsvchn](https://stackoverflow.com/a/58659193/10886420) as it's evaluation method defined by PyTorch ([see here](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.eval)).** This method allows layers inside your model to be put into evaluation mode (e.g. specific changes to layers like inference mode for `Dropout` or `BatchNorm`).
Furthermore you should call it with `__call__` magic method. Why? Because hooks and other PyTorch specific stuff is registered that way properly.
**Secondly, do not use some external `mode` string variable as suggested by [@Anant Mittal](https://stackoverflow.com/questions/58655207/pytorch-different-forward-methods-for-train-and-test-validation/58655415#58655415)**. That's what `train` variable in PyTorch is for, it's standard to differentiate by it whether model is in `eval` mode or `train` mode.
That being said you are the best off doing it like this:
```
import torch
class Network(torch.nn.Module):
def __init__(self):
super().__init__()
...
# You could split it into two functions but both should be called by forward
def forward(
self, src_tokens=None, src_lengths=None, prev_output_tokens=None, **kwargs
):
encoder_out = self.encoder(src_tokens, src_lengths=src_lengths, **kwargs)
if self.train:
return self.decoder(prev_output_tokens, encoder_out=encoder_out, **kwargs)
autoencoder_out = self.encoder(tgt_tokens, src_lengths=src_lengths, **kwargs)
concat = some_concatination_func(encoder_out, autoencoder_out)
return self.decoder(prev_output_tokens, encoder_out=concat, **kwargs)
```
You could (and arguably should) split the above into two separate methods, but that's not too bad as the function is rather short and readable that way. Just stick to PyTorch's way of handling things if easily possible and not some ad-hoc solutions. And no, there will be no problem with backpropagation, why would there be one? |
3,829,211 | I did some changes at my CoreData Model. So far, I added a attribute called 'language'. When my application is launched and I click on "Create new Customer" a instance variable Customer is created. This variable is created by:
```
Customer *newCustomer = [NSEntityDescription insertNewObjectForEntityForName:@"Customer" inManagedObjectContext:appDelegate.managedObjectContext];
```
Before I did these changes everything worked fine and as planned. But now i get a dump with this error message:`reason = "The model used to open the store is incompatible with the one used to create the store";`
What do I have to do to solve this? reseting the persistence store didn't help so far. | 2010/09/30 | [
"https://Stackoverflow.com/questions/3829211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/455928/"
] | What I did to get around this problem was to add this
>
> [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
>
>
>
to my appDelegate in the persistentStoreCoordinator before adding the persistent store. This deletes the existing store that no longer is compatible with your data model. Remember to comment this line before you run the application the next time if you want to keep what is stored.
My implementation of the persistentStoreCoordinator looks like this when I have to remove an old store.
```
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSError *error = nil;
NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyPinballScore.sqlite"]];
//The following line removes your current store so that you can create a new one that is compatible with your new model
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil];
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator_;
```
} |
11,678,794 | I have problem with dll file and have project which need this file System.Windows.Controls.dll for
```
listBox1.ItemsSource
```
error fix , and add reference with this dll to fix error.
Where i can find this dll file?
Is there any download link ? Share please !
Thanks !
In "Add Reference" it doesn't exist !
Solution: <http://download.microsoft.com/download/7/7/6/776875B7-AD81-44D4-AA47-648D1BCB097E/silverlight_sdk.exe> | 2012/07/26 | [
"https://Stackoverflow.com/questions/11678794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539124/"
] | Here are the steps:
1. Right click on `References` in the `Solutions Explorer` (Solutions explorer is on the right of your IDE)
2. Select `Add Reference`
3. In the window that opens, Select `Assemblies > Framework`
4. Check the `PresentationFramework` component box and click ok |
9,525,464 | So I am figuring out how to set up some options for a class. 'options' is a hash. I want to
1) filter out options I don't want or need
2) set some instance variables to use elsewhere
3) and set up another hash with the processed options as @current\_options.
```
def initialize_options(options)
@whitelisted_options, @current_options = [:timestamps_offset, :destructive, :minimal_author], {}
n_options = options.select { |k,v| @whitelisted_options.include?(k) }
@current_options[:timestamps_offset] = @timestamp_offset = n_options.fetch(:timestamps_offset, 0)*(60*60*24)
@current_options[:destructive] = @destructive = n_options.fetch(:destructive, false)
@current_options[:minimal_author] = @minimal_author = n_options.fetch(:minimal_author, false)
end
```
I'm guessing this is a bit much, no matter what I pass in I get:
```
{:timestamps_offset=>0, :destructive=>false, :minimal_author=>false}
```
When I do this line by line from the command line, it works as I want it to but not in my class. So what is going on and how do I clean this up?
EDIT: this actually works disembodied from the class I'm using it in, but inside it doesn't so the reality is something is going on I'm not aware of right now.
attr\_reader :current\_options is how this is set on the class, perhaps that needs some revision.
EDIT2: line 2 of the method is supposed to select from @whitelisted\_options
EDIT3: Actually turned out to be something I wasn't thinking of..."options" comes in parsed from a yaml file as strings....and I was fetching symbols, changing that around makes a difference where before the method was looking for symbols and finding none, e.g. "destructive" vs :destructive, so always defaulting to the defaults. In short, I just needed to symbolize the hash keys when options are imported. | 2012/03/01 | [
"https://Stackoverflow.com/questions/9525464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/697364/"
] | Your `@current_options` is initialized as an empty hash. When you filter the `options` passed as params, none of the keys will be present in `@current_options` so `n_options` will end up empty.
Then when you set up `@current_options` in the following lines, it will always grab the default values `(0, false, false)`, and that's why your output's always the same.
You solve this problem by conditionally initializing @current\_options so that it's only set to `{}` once:
@current\_options ||= {}
**Post-OP edit:**
Your issue's with `options.select` -- in Ruby 1.8, it doesn't return a Hash, but rather an Array. Your calls to `fetch` are then always failing (as symbols can't be array indexes), so always returning defaults.
Instead, try:
```
n_options = options.inject({}) {|h, p| h[p[0]] = p[1] if @whitelisted_options.include? p[0]; h }
```
where `p` is an array containing each key/value pair.
In Ruby 1.9.2, `Hash.select` behaves the way you expected it to.
**Edit 2: Here's how I'd approach it:**
```
class Foo
@@whitelisted_options= {:timestamps_offset => 0, :destructive => false, :minimal_author =>false}
@@whitelisted_options.keys.each do |option|
define_method(option) { return @current_options[option] rescue nil}
end
def initialize_options(options)
@current_options = {}
@@whitelisted_options.each {|k, v| @current_options[k] = options[k] || v}
@current_options
end
end
```
In use:
```
f = Foo.new
f.destructive #=> nil
f.initialize_options(:minimal_author => true, :ignore => :lol)
f.destructive #=> false
f.minimal_author #=> true
f.timestamps_offset #=> 0
``` |
47,539,905 | I am very new to CSS and javascript, so take it easy on me.
I am trying to remove the class `disable-stream` from each of the div elements under the div class="stream-notifications". (See image, below)
I have tried the following in Tampermonkey, but it doesn't seem to work:
```
(function() {
'use strict';
disable-stream.classList.remove("disable-stream");})();
```
[![screen shot of page structure](https://i.stack.imgur.com/FNFGz.jpg)](https://i.stack.imgur.com/FNFGz.jpg) | 2017/11/28 | [
"https://Stackoverflow.com/questions/47539905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6632302/"
] | That looks to be an AJAX-driven web page, so you need to use AJAX-aware techniques to deal with it. EG [waitForKeyElements](https://gist.github.com/2625891), or `MutationObserver`, or similar.
Here's **a complete script** that should work:
```
// ==UserScript==
// @name _Remove a select class from nodes
// @match *://app.hubspot.com/reports-dashboard/*
// @match *://app.hubspot.com/sales-notifications-embedded/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.
console.log ("Do you see this?");
waitForKeyElements (".disable-stream", removeDSclass);
function removeDSclass (jNode) {
console.log ("Cleaned node: ", jNode);
jNode.removeClass ("disable-stream");
}
```
---
Note that there are two `@match` statements because the nodes, that the OP cared about, turned out to be in an iframe. |