qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
65,948,015
I have a variable where the user inputs one number. That variable is of type `int` because that's the return value of `fgetc(stdin)` and `getchar()`. In this case, I'm using `fgetc(stdin)`. After the user inputs the number, I would like to convert it to an integer with `strtol()`, however, I get a warning about an incompatible integer to pointer conversion because of `strtol()`'s first argument being a `const char *`. Here is the code: ``` int option; char *endptr; int8_t choice; printf("=========================================Login or Create Account=========================================\n\n"); while(1) { printf("Welcome to the Bank management program! Would you like to 1. Create Account or 2. Login?\n>>> "); fflush(stdout); option = fgetc(stdin); choice = strtol(option, &endptr, 10); ``` Does anyone know how to get around this?
2021/01/29
[ "https://Stackoverflow.com/questions/65948015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13716610/" ]
`strtol` is used to convert a "string" into `long`, not a single char. You just need `choice = option - '0'` to get the value. But you don't actually need to convert because you can directly switch on the char value ``` switch (option) { case '1': // ... break; case '2': // ... break; } ``` If you really want to call `strtol` then you must make a string ``` char[2] str; str[0] = option; str[1] = 0; // null terminator choice = strtol(str, &endptr, 10); ```
since the variable 'option' is already an integer, there is no reason to call 'strtol' anymore. or you can used gets to get a buffer from stdin, then transform the buffer into integer by strtol.
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
1. Disable auto-suggestions(`android:inputType="textFilter"` or `textNoSuggestions`): 2. Set maxLength ``` <EditText android:id="@+id/editText" android:inputType="textFilter" android:maxLength="8" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` I hope, it helps
**Unfortunately the following answer does not work. However, it helped us to find out that the bug mentioned by Poly Bug is not reproducible if the input begins with a number.** --- You can use a `TextWatcher` to listen for `EditText` changes and prevent the user from typing too many characters into the field. The following code works for me: ```java final int maxLength = 10; EditText editText = (EditText) findViewById(R.id.my_edittext_id); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= maxLength) s.delete(maxLength, s.length()); } }); ``` In `afterTextChanged`, the code compares the length of the inserted text with the maximal length `maxLength` and deletes all superfluous characters. --- You might replace all standard `EditText` classes with the following class to use the listener in conjunction with the `maxLength` XML attribute: ```java public class MyMaxLengthEditText extends EditText { public static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"; private final int mMaxLength; public MyMaxLengthEditText(Context context) { super(context, null); mMaxLength = -1; } public MyMaxLengthEditText(Context context, AttributeSet attrs) { super(context, attrs); mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1); addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= mMaxLength) s.delete(mMaxLength, s.length()); } }); } } ```
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
**Unfortunately the following answer does not work. However, it helped us to find out that the bug mentioned by Poly Bug is not reproducible if the input begins with a number.** --- You can use a `TextWatcher` to listen for `EditText` changes and prevent the user from typing too many characters into the field. The following code works for me: ```java final int maxLength = 10; EditText editText = (EditText) findViewById(R.id.my_edittext_id); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= maxLength) s.delete(maxLength, s.length()); } }); ``` In `afterTextChanged`, the code compares the length of the inserted text with the maximal length `maxLength` and deletes all superfluous characters. --- You might replace all standard `EditText` classes with the following class to use the listener in conjunction with the `maxLength` XML attribute: ```java public class MyMaxLengthEditText extends EditText { public static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"; private final int mMaxLength; public MyMaxLengthEditText(Context context) { super(context, null); mMaxLength = -1; } public MyMaxLengthEditText(Context context, AttributeSet attrs) { super(context, attrs); mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1); addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= mMaxLength) s.delete(mMaxLength, s.length()); } }); } } ```
You can use **[InputFilter](http://developer.android.com/intl/es/reference/android/text/InputFilter.html)** > > InputFilters can be attached to Editables to constrain the changes > that can be made to them. > > > **Xml** ``` <EditText android:id="@+id/edit_Text" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Java Class** ``` int maxLengthofYourEditText = 5; // Set Your Limit edit_TextObj.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofYourEditText)}); ```
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
**Unfortunately the following answer does not work. However, it helped us to find out that the bug mentioned by Poly Bug is not reproducible if the input begins with a number.** --- You can use a `TextWatcher` to listen for `EditText` changes and prevent the user from typing too many characters into the field. The following code works for me: ```java final int maxLength = 10; EditText editText = (EditText) findViewById(R.id.my_edittext_id); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= maxLength) s.delete(maxLength, s.length()); } }); ``` In `afterTextChanged`, the code compares the length of the inserted text with the maximal length `maxLength` and deletes all superfluous characters. --- You might replace all standard `EditText` classes with the following class to use the listener in conjunction with the `maxLength` XML attribute: ```java public class MyMaxLengthEditText extends EditText { public static final String XML_NAMESPACE_ANDROID = "http://schemas.android.com/apk/res/android"; private final int mMaxLength; public MyMaxLengthEditText(Context context) { super(context, null); mMaxLength = -1; } public MyMaxLengthEditText(Context context, AttributeSet attrs) { super(context, attrs); mMaxLength = attrs.getAttributeIntValue(XML_NAMESPACE_ANDROID, "maxLength", -1); addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s.length() >= mMaxLength) s.delete(mMaxLength, s.length()); } }); } } ```
I also bumped into this situation when had a series of fields containing 1 symbol (a usual pin-code). My solution is based on @jmeinke answer. Create a layout containing several `EditText`s with `android:maxLength="2"` (we will enter 1 symbol in any of them and jump to another `EditText`. Strange, but on some phones the code below works even for maxLength=1). ``` class YourTextWatcher( private val prevEdit: EditText?, private val currEdit: EditText, private val nextEdit: EditText?, private val method: () -> Unit ) : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s.isNullOrEmpty()) { prevEdit?.requestFocus() } else { if (s.length > 1) { if (currEdit.selectionEnd > 1) { // If stand on second position of EditText and enter new symbol, // will move to next EditText copying second symbol. val secondSymbol = s.substring(1, 2) nextEdit?.setText(secondSymbol) } // Remove second symbol. s.delete(1, s.length) } nextEdit?.requestFocus() nextEdit?.setSelection(nextEdit.length(), nextEdit.length()) method() } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } } ``` Then for all `EditText`s do following: ``` currEdit.addTextChangedListener( YourTextWatcher(prevEdit, currEdit, nextEdit) { yourMethodToValidateText() }) ``` Instead of prevEdit, currEdit, nextEdit set your `EditText` controls. For instance, for the first: ``` edit1.addTextChangedListener( YourTextWatcher(null, edit1, edit2) { yourMethodToValidateText() }) ``` yourMethodToValidateText() is a method that will check entered symbols. For instance, you can check if all `EditText`s are filled. This solution has a bug when you try to press BackSpace in empty `EditText`. Nothing happens, you won't go to a previous `EditText`. You can catch BackSpace in View.OnKeyListener, but it can intersect with TextWatcher. Also I didn't check a situation when copy & paste a text to `EditText`, forgot to check, what happens, when select a text in `EditText` and press Delete.
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
1. Disable auto-suggestions(`android:inputType="textFilter"` or `textNoSuggestions`): 2. Set maxLength ``` <EditText android:id="@+id/editText" android:inputType="textFilter" android:maxLength="8" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` I hope, it helps
You can use **[InputFilter](http://developer.android.com/intl/es/reference/android/text/InputFilter.html)** > > InputFilters can be attached to Editables to constrain the changes > that can be made to them. > > > **Xml** ``` <EditText android:id="@+id/edit_Text" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Java Class** ``` int maxLengthofYourEditText = 5; // Set Your Limit edit_TextObj.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofYourEditText)}); ```
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
1. Disable auto-suggestions(`android:inputType="textFilter"` or `textNoSuggestions`): 2. Set maxLength ``` <EditText android:id="@+id/editText" android:inputType="textFilter" android:maxLength="8" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` I hope, it helps
I also bumped into this situation when had a series of fields containing 1 symbol (a usual pin-code). My solution is based on @jmeinke answer. Create a layout containing several `EditText`s with `android:maxLength="2"` (we will enter 1 symbol in any of them and jump to another `EditText`. Strange, but on some phones the code below works even for maxLength=1). ``` class YourTextWatcher( private val prevEdit: EditText?, private val currEdit: EditText, private val nextEdit: EditText?, private val method: () -> Unit ) : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s.isNullOrEmpty()) { prevEdit?.requestFocus() } else { if (s.length > 1) { if (currEdit.selectionEnd > 1) { // If stand on second position of EditText and enter new symbol, // will move to next EditText copying second symbol. val secondSymbol = s.substring(1, 2) nextEdit?.setText(secondSymbol) } // Remove second symbol. s.delete(1, s.length) } nextEdit?.requestFocus() nextEdit?.setSelection(nextEdit.length(), nextEdit.length()) method() } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } } ``` Then for all `EditText`s do following: ``` currEdit.addTextChangedListener( YourTextWatcher(prevEdit, currEdit, nextEdit) { yourMethodToValidateText() }) ``` Instead of prevEdit, currEdit, nextEdit set your `EditText` controls. For instance, for the first: ``` edit1.addTextChangedListener( YourTextWatcher(null, edit1, edit2) { yourMethodToValidateText() }) ``` yourMethodToValidateText() is a method that will check entered symbols. For instance, you can check if all `EditText`s are filled. This solution has a bug when you try to press BackSpace in empty `EditText`. Nothing happens, you won't go to a previous `EditText`. You can catch BackSpace in View.OnKeyListener, but it can intersect with TextWatcher. Also I didn't check a situation when copy & paste a text to `EditText`, forgot to check, what happens, when select a text in `EditText` and press Delete.
25,900,333
I've already set the maxLength attribute for an EditText widget in the xml layout file, and it does limit the display of characters. But it still allows the user to press more letters on the keyboard, and backspacing deletes these extra presses rather than the last letter on the display. I believe this is not how it's supposed to be. Pressing keys after the limit has been reached should stop accepting more input even if it is not displayed. Any fix on this? **Update** Based on the answer below, for multiline EditText, add the textMultiLine attribute too. ``` android:inputType="textFilter|textMultiLine" ```
2014/09/17
[ "https://Stackoverflow.com/questions/25900333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3893122/" ]
You can use **[InputFilter](http://developer.android.com/intl/es/reference/android/text/InputFilter.html)** > > InputFilters can be attached to Editables to constrain the changes > that can be made to them. > > > **Xml** ``` <EditText android:id="@+id/edit_Text" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` **Java Class** ``` int maxLengthofYourEditText = 5; // Set Your Limit edit_TextObj.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofYourEditText)}); ```
I also bumped into this situation when had a series of fields containing 1 symbol (a usual pin-code). My solution is based on @jmeinke answer. Create a layout containing several `EditText`s with `android:maxLength="2"` (we will enter 1 symbol in any of them and jump to another `EditText`. Strange, but on some phones the code below works even for maxLength=1). ``` class YourTextWatcher( private val prevEdit: EditText?, private val currEdit: EditText, private val nextEdit: EditText?, private val method: () -> Unit ) : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s.isNullOrEmpty()) { prevEdit?.requestFocus() } else { if (s.length > 1) { if (currEdit.selectionEnd > 1) { // If stand on second position of EditText and enter new symbol, // will move to next EditText copying second symbol. val secondSymbol = s.substring(1, 2) nextEdit?.setText(secondSymbol) } // Remove second symbol. s.delete(1, s.length) } nextEdit?.requestFocus() nextEdit?.setSelection(nextEdit.length(), nextEdit.length()) method() } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } } ``` Then for all `EditText`s do following: ``` currEdit.addTextChangedListener( YourTextWatcher(prevEdit, currEdit, nextEdit) { yourMethodToValidateText() }) ``` Instead of prevEdit, currEdit, nextEdit set your `EditText` controls. For instance, for the first: ``` edit1.addTextChangedListener( YourTextWatcher(null, edit1, edit2) { yourMethodToValidateText() }) ``` yourMethodToValidateText() is a method that will check entered symbols. For instance, you can check if all `EditText`s are filled. This solution has a bug when you try to press BackSpace in empty `EditText`. Nothing happens, you won't go to a previous `EditText`. You can catch BackSpace in View.OnKeyListener, but it can intersect with TextWatcher. Also I didn't check a situation when copy & paste a text to `EditText`, forgot to check, what happens, when select a text in `EditText` and press Delete.
93,442
Is there any way to index the following query? ``` SELECT run_id, MAX ( frame ) , MAX ( time ) FROM run.frames_stat GROUP BY run_id; ``` I've tried creating sorted (non-composite) indexes on `frame` and `time`, and an index on `run_id`, but the query planner doesn't use them. Misc info: * Unfortunately (and for reasons I won't get into) I cannot change the query * The `frames_stat` table has 42 million rows * The table is unchanging (no further inserts/deletes will ever take place) * The query was always slow, it's just gotten slower because this dataset is larger than in the past. * There are no indexes on the table * We are using Postgres 9.4 * The db's "work\_mem" size is 128MB (if that's relevant). * Hardware: 130GB Ram, 10 core Xeon Schema: ``` CREATE TABLE run.frame_stat ( id bigint NOT NULL, run_id bigint NOT NULL, frame bigint NOT NULL, heap_size bigint NOT NULL, "time" timestamp without time zone NOT NULL, CONSTRAINT frame_stat_pkey PRIMARY KEY (id) ) ``` Explain analyze: ``` HashAggregate (cost=1086240.000..1086242.800 rows=280 width=24) (actual time=14182.426..14182.545 rows=280 loops=1) Group Key: run_id -> Seq Scan on zulu (cost=0.000..770880.000 rows=42048000 width=24) (actual time=0.037..4077.182 rows=42048000 loops=1) ```
2015/02/20
[ "https://dba.stackexchange.com/questions/93442", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/59983/" ]
### Too bad If you cannot change the query at all, that's **too bad**. You won't get a good solution. If you had not table-qualified the table (**`run.`**`frames_stat`), you could create a materialized view (see below) with the same name in another schema (or just a temporary one) and adapt the [`search_path`](https://stackoverflow.com/a/9067777/939860) (optionally just in sessions where this is desirable) - for hugely superior performance. Here's a recipe for such a technique: * [How can I fake inet\_client\_addr() for unit tests in PostgreSQL?](https://dba.stackexchange.com/questions/69988/how-can-i-fake-inet-client-addr-for-unit-tests-in-postgresql/70009#70009) [@Joishi's idea](https://dba.stackexchange.com/a/93443/3684) with a `RULE` would be a measure of (desperate) last resort. But I would rather not go there. Too many pitfalls with unexpected behavior. Better query / indexes ---------------------- If you could change the query, you should try to emulate a loose index scan: * [Optimize GROUP BY query to retrieve latest record per user](https://stackoverflow.com/a/25536748/939860) This is even more efficient when based on a separate **table with one row per relevant `run_id`** - let's call it `run_tbl`. Create it if you don't have it, yet! Implemented with correlated subqueries: ``` SELECT run_id , (SELECT frame FROM run.frames_stat WHERE run_id = r.run_id ORDER BY frame DESC NULLS LAST LIMIT 1) AS max_frame , (SELECT "time" FROM run.frames_stat WHERE run_id = r.run_id ORDER BY "time" DESC NULLS LAST LIMIT 1) AS max_time FROM run_tbl r; ``` Create two [multicolumn indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html) with matching sort order for *lightening* performance: ``` CREATE index fun_frame_idx ON run.frames_stat (run_id, frame DESC NULLS LAST); CREATE index fun_frame_idx ON run.frames_stat (run_id, "time" DESC NULLS LAST); ``` `NULLS LAST` is only necessary if there *can* be null values. But it won't hurt either way. * [Unused index in range of dates query](https://dba.stackexchange.com/questions/90128/unused-index-in-range-of-dates-query/90183#90183) With only 280 distinct `run_id`, this will be *very* fast. MATERIALIZED VIEW ----------------- Or, based on these key pieces of information: > > The "frames\_stat" table has 42 million rows > > > > > rows=280 -- number of returned rows = disctinct run\_id > > > > > The table is unchanging (no inserts/deletes) > > > Use a [**`MATERIALIZED VIEW`**](https://www.postgresql.org/docs/current/sql-creatematerializedview.html), it will be tiny (only 280 rows) and super fast. You still need to change the query to base it on the MV instead of the table. Aside: never use [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) like `time` (in standard SQL) as identifier.
You could try creating an `INSTEAD OF SELECT` rule on the table .. although this might break the application (depending on what all actually uses the table in question) ``` CREATE RULE "RETURN_MODIFIED_SELECT" AS ON SELECT TO run.frames_stat DO INSTEAD <MY QUERY FROM BELOW>; ``` I have not used `RULE`s that much, personally - so I may have this COMPLETELY wrong .. someone please correct me in a comment if that's the case. Quote from the documentation: > > Presently, ON SELECT rules must be unconditional INSTEAD rules and must have actions that consist of a single SELECT command. Thus, an ON SELECT rule effectively turns the table into a view, whose visible contents are the rows returned by the rule's SELECT command rather than whatever had been stored in the table (if anything). It is considered better style to write a CREATE VIEW command than to create a real table and define an ON SELECT rule for it. > > > If my query from below isn't considered a "single select command" (which it may not, considering it uses CTEs), then you could try writing a function that encapsulates my query and having the rule return the select of the function. [CREATE RULE documentation](http://www.postgresql.org/docs/current/static/sql-createrule.html) **ORIGINAL POST BELOW** - It was added in OP that query is not able to be changed .. so below will not work for OP (but leaving in case others will benefit from it) Try splitting it up into two separate queries.. ``` WITH max_frame AS ( SELECT run_id, MAX(frame) AS max_frame FROM run.frames_stat GROUP BY run_id ), max_time AS ( SELECT run_id, MAX(time) AS max_time FROM run.frames_stat GROUP BY run_id ) SELECT a.run_id, a.max_frame, b.max_time FROM max_frame a JOIN max_time b ON a.run_id = b.run_id ``` In terms of indexes .. an index on run\_id MAY be enough for both queries .. but if it's not, try having two indexes ... one on (run\_id, frame) and one on (run\_id, time) I BELIEVE this will help improve your query - postgres optimizer is probably assuming it will need to scan most of the rows of the table (even though it knows an index is available) because it will need to find the `MAX (frame)` AND the `MAX (time)` in one pass.. By splitting it up as I have, it will know that it only needs to find one `MAX` value (instead of two), so should use the index to find it. If that doesn't, then you really need to provide the data requested in the link that @a\_horse\_with\_no\_name supplied..
5,069,239
``` setcookie("cookie1", "", 0, "/",".domain.com"); setcookie("cookie2", "", 0, "/",".domain.com"); header('Location: /index.php'); ``` It doesn't delete cookie1 and cookie2. Why is that?
2011/02/21
[ "https://Stackoverflow.com/questions/5069239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/237681/" ]
An expiration time of 0 is a special value which means the cookie will be deleted when the browser is closed. To delete it immediately, you need to give a valid expiration time in the past. An example from the [PHP docs](http://php.net/manual/en/function.setcookie.php): ``` // set the expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); ```
My best guess would be that the browser simply hasn't done it yet. Cookie management is the responsibility of the browser, and depending on the browser settings it may not delete your cookie immediately.
40,881,166
I am working in child theme and put following code for admin ajax js ``` function wpb_adding_scripts() { /* echo "string". get_stylesheet_directory_uri().'/css/jquery.bxslider.css'; exit();*/ wp_register_script('flexslider', get_stylesheet_directory_uri() . '/js/jquery.flexisel.js', array('jquery'),'1.1', true); wp_enqueue_script('flexslider'); wp_enqueue_script('bxslider', get_stylesheet_directory_uri() . '/js/jquery.bxslider.min.js', array(),true, true); wp_enqueue_script('bxslider'); wp_enqueue_script('custom', get_stylesheet_directory_uri() . '/js/custom.js', array(),true, true); wp_enqueue_script('custom'); //wp_localize_script('admin_script', 'ajaxurl', admin_url( 'admin-ajax.php' ) ); wp_localize_script('admin_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script( 'jquery' ); wp_enqueue_script('admin_script'); } add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts', 999 ); ``` but it given me error like ``` ReferenceError: myAjax is not defined url : myAjax.ajaxurl, ``` I used myAjax declaration in my custom js.. ``` jQuery('#load_more_posts').on('click',function(){ var lng =jQuery(".post_item").length; jQuery.ajax({ type : "post", url : myAjax.ajaxurl, data : {action: "load_more_posts_home",count : lng}, }).done(function(response){ var posts = JSON.parse(response); for( var i = 0; i < posts.length; i++ ) { if( posts[i] == "0" ) jQuery("#load_more_posts").fadeOut(); else jQuery("#load_more_posts").before(posts[i]); } }); }); ``` so how could i resolve this issue in my wordpress child theme.
2016/11/30
[ "https://Stackoverflow.com/questions/40881166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7034664/" ]
Try this: ``` wp_enqueue_script('custom'); //Name of the script. Should be unique.here is 'custom' wp_localize_script('custom', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); // remove admin_script and add unique javascript file. ``` Here above code localized the object:'myAjax' in script "custom". and you can access property "ajax\_url" by adding below code in custom script file. in **custom.js** ``` alert(myAjax.ajaxurl); ```
Instead of `admin_script` use `ajax-script` like this ``` wp_localize_script( 'ajax-script', 'myAjax',array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); ``` Otherwise you can add `wp_enqueue_script('ajax-script');` before you have define your ajax script localize function.
144,036
I have an [IKEA desk](https://www.ikea.com/us/en/catalog/products/S49932175/#/S59133593) with a subtle fake wood grain paint layer (black) on the surface. The paint in the area that my mouse moves has worn away leaving a shiny textureless surface that the laser mouse doesn't detect. What's the simplest, cheapest, most effective way to re-surface that region (or the whole desk)? I don't like mouse mats. I'm thinking wallpaper or paint, but I don't know what types of paint will provide the surface required for the laser mouse to accurately detect movement.
2018/07/27
[ "https://diy.stackexchange.com/questions/144036", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/89230/" ]
Shelf liner (contact paper). Cut it into an oversize mouse pad shape with rounded corners and stick it down. You want it large enough that you aren't snagging the edge with your arm, keyboard, etc. It'll feel like nothing but give your mouse a better view. You could use black so it's not so conspicuous, but a bold color pattern might be spiffy. Change it out when it gets polished or worn.
You need a surface with a pattern or texture on it. In my experience any 1/4" span of distance needs to have at least 2-3 transitions on it. If all the sensor sees is a solid color, it can't realize you have moved it. The wood grain was doing that for you. As you have discovered, routine use of a computer mouse will polish the surface to a mirror finish, and **optical mice don't work on mirror finishes**. The reflectivity blinds the mouse regardless of underlying pattern. You could remove the gloss by light sanding (we painters call it 'scuff sanding'), but there still needs to be an underlying pattern. Obviously, a weak or fragile finish will quickly fail. So we can cross a few things off the list * any latex paint (fragile) * any solid-color paint (no pattern) * gloss paint (too reflective) * any LPU coating without some flattening additive (too reflective) That leaves us little choice. It's a tough problem. Only paint I can really think is epoxy garage floor paint, with plenty of chips to add a pattern. This surface may not end up smooth, so I would sand it smooth. So I would look at other coatings, e.g. A vinyl stick-down coating, I print out a sheet of hashmarks and change it regularly, but now we're just talking a mouse pad, which is what you don't want.
144,036
I have an [IKEA desk](https://www.ikea.com/us/en/catalog/products/S49932175/#/S59133593) with a subtle fake wood grain paint layer (black) on the surface. The paint in the area that my mouse moves has worn away leaving a shiny textureless surface that the laser mouse doesn't detect. What's the simplest, cheapest, most effective way to re-surface that region (or the whole desk)? I don't like mouse mats. I'm thinking wallpaper or paint, but I don't know what types of paint will provide the surface required for the laser mouse to accurately detect movement.
2018/07/27
[ "https://diy.stackexchange.com/questions/144036", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/89230/" ]
Shelf liner (contact paper). Cut it into an oversize mouse pad shape with rounded corners and stick it down. You want it large enough that you aren't snagging the edge with your arm, keyboard, etc. It'll feel like nothing but give your mouse a better view. You could use black so it's not so conspicuous, but a bold color pattern might be spiffy. Change it out when it gets polished or worn.
Rub the area with 000 or 0000 steel wool to bring back some subtle texture. It won't be possibly lumpy or uneven like paint, and you can easily texture the affected area only. This is a far cheaper solution in terms of money and time than paint.
144,036
I have an [IKEA desk](https://www.ikea.com/us/en/catalog/products/S49932175/#/S59133593) with a subtle fake wood grain paint layer (black) on the surface. The paint in the area that my mouse moves has worn away leaving a shiny textureless surface that the laser mouse doesn't detect. What's the simplest, cheapest, most effective way to re-surface that region (or the whole desk)? I don't like mouse mats. I'm thinking wallpaper or paint, but I don't know what types of paint will provide the surface required for the laser mouse to accurately detect movement.
2018/07/27
[ "https://diy.stackexchange.com/questions/144036", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/89230/" ]
Shelf liner (contact paper). Cut it into an oversize mouse pad shape with rounded corners and stick it down. You want it large enough that you aren't snagging the edge with your arm, keyboard, etc. It'll feel like nothing but give your mouse a better view. You could use black so it's not so conspicuous, but a bold color pattern might be spiffy. Change it out when it gets polished or worn.
Use fabric. The threads are detectable by the mouse. You can cover the whole top with something like a table cloth, or use a smaller piece in the work area. You say you don't like mouse pads but you're considering something like wallpaper, so I assume the mouse pad thickness is it's main problem, and maybe the issue of keeping it positioned. Soft fabric, like cotton, will have more friction; something like nylon will have less. If you want almost no friction, laminate a piece of cloth. That will also keep the surface from wearing and make it easily cleanable. It will be cardstock thickness. Something the size of a mouse pad or place mat can be laminated in readily available heat laminators, or you can use adhesive laminating pockets that don't require heat. A matte lamination film will probably work better than a glossy film for mouse purposes. You could also print out a custom pattern on paper, as Harper suggested, and laminate it to give it a longer life. An area-sized piece can be stuck to the desktop with a temporary adhesive so that it doesn't move around. Note that if you're going to laminate cloth (or a paper pattern) and stick it to the desktop, you're essentially making your own shelf liner, so isherwood's idea is a lot simpler. I'd use my idea instead only if you were going with a table cloth or wanted a material or pattern that wasn't available in a ready-made shelf liner.
24,992,036
I have a simple factory that returns a promise after a async.-request. ``` getUpdates: function(){ var q = $q.defer(); $http.get(...) .success(function(data, status, headers, config) { q.resolve(data); }) .error(function(data, status, headers, config) { q.reject(status); }); return q.promise; } ``` In my controller I just call the getUpdates-method and receive the promise. ``` var updates = factory.getUpdates(); ``` How can I provide a success/error functionality of the getUpdates method? ``` factory.getUpdates().success(function(promise){...}).error(function(err)... ``` What do I have to add to my getUpdates function?
2014/07/28
[ "https://Stackoverflow.com/questions/24992036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2329592/" ]
The `$http` service already return a promise, there is no need to use `$q.defer()` to create an another promise in this case. You could just write it like this: ``` getUpdates: function () { return $http.get(...); } ``` This way the `success()` and `error()` methods will still be available. Or if you really have a reason why you are using `$q.defer()`, please include it in the question.
You `then` function to handle the success and failure of the promise: ``` factory.getUpdates() .then(function(value) { // handle success }, function(reason) { // handle failure }); ```
24,992,036
I have a simple factory that returns a promise after a async.-request. ``` getUpdates: function(){ var q = $q.defer(); $http.get(...) .success(function(data, status, headers, config) { q.resolve(data); }) .error(function(data, status, headers, config) { q.reject(status); }); return q.promise; } ``` In my controller I just call the getUpdates-method and receive the promise. ``` var updates = factory.getUpdates(); ``` How can I provide a success/error functionality of the getUpdates method? ``` factory.getUpdates().success(function(promise){...}).error(function(err)... ``` What do I have to add to my getUpdates function?
2014/07/28
[ "https://Stackoverflow.com/questions/24992036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2329592/" ]
The `$http` service already return a promise, there is no need to use `$q.defer()` to create an another promise in this case. You could just write it like this: ``` getUpdates: function () { return $http.get(...); } ``` This way the `success()` and `error()` methods will still be available. Or if you really have a reason why you are using `$q.defer()`, please include it in the question.
``` factory.getUpdates().then( //onSucess function(response) { // ... }, //onError function() { // ... } ); ```
24,992,036
I have a simple factory that returns a promise after a async.-request. ``` getUpdates: function(){ var q = $q.defer(); $http.get(...) .success(function(data, status, headers, config) { q.resolve(data); }) .error(function(data, status, headers, config) { q.reject(status); }); return q.promise; } ``` In my controller I just call the getUpdates-method and receive the promise. ``` var updates = factory.getUpdates(); ``` How can I provide a success/error functionality of the getUpdates method? ``` factory.getUpdates().success(function(promise){...}).error(function(err)... ``` What do I have to add to my getUpdates function?
2014/07/28
[ "https://Stackoverflow.com/questions/24992036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2329592/" ]
You `then` function to handle the success and failure of the promise: ``` factory.getUpdates() .then(function(value) { // handle success }, function(reason) { // handle failure }); ```
``` factory.getUpdates().then( //onSucess function(response) { // ... }, //onError function() { // ... } ); ```
50,897,066
I'm developing an Electron application and I aim to 'split up' `index.js` (main process) file. Currently I have put my menu bar-related and Touch Bar-related code into two separate files, `menu.js` and `touchBar.js`. Both of these files rely on a function named `redir`, which is in `index.js`. Whenever I attempt to activate the `click` event in my Menu Bar - which relies on `redir` - I get an error: `TypeError: redir is not a function`. This also applies to my Touch Bar code. Here are my (truncated) files: `index.js` ``` const { app, BrowserWindow } = require('electron'); // eslint-disable-line const initTB = require('./touchBar.js'); const initMenu = require('./menu.js'); ... let mainWindow; // eslint-disable-line // Routing + IPC const redir = (route) => { if (mainWindow.webContents) { mainWindow.webContents.send('redir', route); } }; module.exports.redir = redir; function createWindow() { mainWindow = new BrowserWindow({ height: 600, width: 800, title: 'Braindead', titleBarStyle: 'hiddenInset', show: false, resizable: false, maximizable: false, }); mainWindow.loadURL(winURL); initMenu(); mainWindow.setTouchBar(initTB); ... } app.on('ready', createWindow); ... ``` `menu.js` ``` const redir = require('./index'); const { app, Menu, shell } = require('electron'); // eslint-disable-line // Generate template function getMenuTemplate() { const template = [ ... { label: 'Help', role: 'help', submenu: [ { label: 'Learn more about x', click: () => { shell.openExternal('x'); // these DO work. }, }, ... ], }, ]; if (process.platform === 'darwin') { template.unshift({ label: 'Braindead', submenu: [ ... { label: 'Preferences...', accelerator: 'Cmd+,', click: () => { redir('/preferences'); // this does NOT work }, } ... ], }); ... }; return template; } // Set the menu module.exports = function initMenu() { const menu = Menu.buildFromTemplate(getMenuTemplate()); Menu.setApplicationMenu(menu); }; ``` My file structure is simple - all three files are in the same directory. Any code criticisms are also welcome; I've spent hours banging my head trying to figure all this out.
2018/06/17
[ "https://Stackoverflow.com/questions/50897066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3991859/" ]
`redir` it is not a function, because you're exporting an object, containing a `redir` property, which is a function. So you should either use: ``` const { redir } = require('./index.js'); ``` Or export it this way ``` module.exports = redir ``` When you do: `module.exports.redir = redir;` You're exporting: `{ redir: [Function] }`
You are exporting ``` module.exports.redir = redir; ``` That means that your import ``` const redir = require('./index'); ``` is the exported object. `redir` happens to be one of its keys. To use the function, use ``` const redir = require('./index').redir; ``` or destructure directly into redir ``` const { redir } = require('./index'); ```
11,860,855
To create buttons in the SDL Tridion ribbon toolbar, where can we find the extension related information (like the config file, js files) of already existing controls like Check-in, Check-out, Undo Check-out so we can use them as a reference?
2012/08/08
[ "https://Stackoverflow.com/questions/11860855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1544948/" ]
Parts of the configuration are in the `..\Tridion\web\WebUI\Editors\CME\Configuration\CME.config`, the rest is in the `..\Tridion\web\WebUI\WebRoot\Configuration\System.config` I believe. The ASPX, CSS and JS files are all located in `..\Tridion\web\WebUI\Editors\CME`, interesting paths to follow there are the `Views` and the `Views\Popups` but also the `Controls` might contain useful items for you to investigate.
I don't have a running system to check with right now, but I believe you can find this information by "following the trail" from System.Config. Just like with our own extensions, the Tridion CME must register its commands in there, and will have links to js, css, config, etc.
133,701
There is kind of a risk gaining an access to personal data or some way getting debts with a passport. Is there a chance someone can read biometric RFID data from an international passport, like fingerprints or a photograph?
2019/03/12
[ "https://travel.stackexchange.com/questions/133701", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/68847/" ]
The RFID chip in a biometric passport can be convinced to communicate all the data stored therein if the right keys are provided to it. Note it’s not a matter of downloading encrypted data from the chip and then having a go at it with decryption tools of some kind; the communication with the chip is bi-directional and authentication has to be provided first. The core data such as name and the photograph are secured by Basic Access Control, where the key can be derived from machine readable data visible on the passport itself. In essence, after viewing the passport, it’s possible to download the same data you’ve just seen, plus the digital signature of the issuing authority confirming it’s genuine. There’s also Extended Access Control, where the idea is that more sensitive data such as fingerprints is protected by keys that the issuing authority only provides to parties such as other countries’ immigration departments. Thus any random person who knows the document number, the owner’s birth date and the passport’s expiry date (that’s what comprises the BAC key) can use this to read basic data and download the photo (there are multiple Android apps that do just this), while it’s not possible to take a powerful scanner to an airport and load lots of passports of passers-by. Downloading the fingerprints and other such data requires special keys which are, in theory, distributed by some secure channels among proper authorities. I’ve heard, without proof, that this process involves many hurdles and my country (Ukraine) simply hasn’t shared such keys with any other countries.
The data on your passport chip is encrypted, but the encryption key is the machine-readable data on the personal data page (see e.g. [this slide deck from ICAO](https://www.icao.int/Meetings/TAG-MRTD/Documents/Tag-Mrtd-18/Kinneging.pdf)). So it is useless if someone just reads the chip alone, but if they also can see the personal data page, then they can also decrypt the contents of the chip. There are Android apps which can read the passport chip, and require you to scan the data page with the camera, then read the chip with the phone's NFC reader. It will be very obvious if someone is doing this to your passport.
10,306,328
``` class LogUtil<T> : ILogUtility { log4net.ILog log; public LogUtil() { log = log4net.LogManager.GetLogger(typeof(T).FullName); } public void Log(LogType logtype, string message) { Console.WriteLine("logging coming from class {0} - message {1} " , typeof(T).FullName, message); } } public class Logger { ILogUtility _logutility; public Logger(ILogUtility logutility) { _logutility = logutility; } public void Log(LogType logtype, string message) { _logutility.Log(logtype, message); } } ``` I need to have the functionality to be flexible and have the ability to remove the LogUtil class in the future and use some thing else. So I write LoggerUtility wrapper class as follows: ``` class LoggerUtility<T> { Logger logger; public LoggerUtility() { LogUtil<T> logutil = new LogUtil<T>(); logger = new Logger(logutil); } public void Log(LogType logtype, string message) { logger.Log(logtype, message); } } ``` My client code as follows: ``` public class TestCode { public void test() { new LoggerUtility<TestCode>().Log(LogType.Info, "hello world"); } } ``` To get loose coupling from LogUtil, I end up writing 2 wrapper classes Logger and LoggerUtility. So in the future, if I have to add another method in the ILogUtility, I would have to add that method to Logger class and then LoggerUtility. What is the best way to write LoggerUtility so that I could write the client code as follows: ``` new LoggerUtility<TestCode>().Log(LogType.Info, "hello world"); ``` Please let me know. Thanks
2012/04/24
[ "https://Stackoverflow.com/questions/10306328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71422/" ]
It looks like you're adding a level of abstraction where there really doesn't need to be one. If we start with your end result, LoggerUtility just needs to have an interface that it can use to log things based on the `LogType` parameter. Your `Logger` class, as its currently written, is just a thin wrapper around the `ILogUtility` interface. So why bother adding that layer? Why can't the `Logger` class use an `ILogUtility` instance directly? You could even go one step further and define your interface as `ILogUtility<T>` and know that when you create a `LoggerUtility<Foo>` that the instance of the logger it will use will be based on the Foo class. But honestly, I think you may just be reinventing the wheel here. Take a look at [Common Logging for .NET](http://netcommon.sourceforge.net/). It will probably ease what you're trying to do and make more sense in the long run.
You don't need a second wrapper, you need either a factory or to use a dependency injection framework to construct an appropriate wrapper around log4net. Using Ninject, and modifying your interface, you can do ``` kernel.Bind(typeof(ILogUtility<>)).To(typeof(Log4NetUtil<>); ``` and instantiate it as ``` var logger = kernel.Get<ILogUtility<MyClass>>(); ``` where the logger interface/class are: ``` public interface ILogUtility<T> where T : class { void Log(LogType logtype, string message); } public class Log4NetUtil<T> : ILogUtility<T> where T : class { log4net.ILog log; public LogUtil() { log = log4net.LogManager.GetLogger(typeof(T).FullName); } public void Log(LogType logtype, string message) { Console.WriteLine("logging coming from class {0} - message {1} " , typeof(T).FullName, message); } } ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can make x even, by using floor division and then multiplication: ``` x = (x // 2) * 2 ``` x will then be rounded to the previous even integer or stay the same if it was even before. If you want to round it to the following even integer you need to do: ``` x = ((x + 1) // 2) * 2 ``` This can be improved further by using shifting operators: ``` x = (x >> 1) << 1 #Alternative 1 x = ((x + 1) >> 1) << 1 #Alternative 2 ``` Examples: ``` #Alternative 1 x = 9 x = (x >> 1) << 1 #x is now 8 #Alternative 2 x = 9 x = ((x + 1) >> 1) << 1 #x is now 10 ``` The second one is probably more suitable for you
You can do it this way: ``` >>> for n in range((x + 1) // 2 * 2, y+1, 2): print(n) ``` The first argument to `range` forces it to be the next even number if it is odd. The last argument goes up in twos.
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can make x even, by using floor division and then multiplication: ``` x = (x // 2) * 2 ``` x will then be rounded to the previous even integer or stay the same if it was even before. If you want to round it to the following even integer you need to do: ``` x = ((x + 1) // 2) * 2 ``` This can be improved further by using shifting operators: ``` x = (x >> 1) << 1 #Alternative 1 x = ((x + 1) >> 1) << 1 #Alternative 2 ``` Examples: ``` #Alternative 1 x = 9 x = (x >> 1) << 1 #x is now 8 #Alternative 2 x = 9 x = ((x + 1) >> 1) << 1 #x is now 10 ``` The second one is probably more suitable for you
You can use reminder to get the correct range: ``` def print_event_for(min_, max_): reminder = min_ % 2 for i in range(min_+reminder, max_+reminder, 2): print(i) print_event_for(5, 12) ``` Output: ``` 6 8 10 12 ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
one way is by using while, that takes the start and end range in ``` for each in range(int(input()),int(input())): while each%2 == 0: print (each) break; ```
``` def printEvenfor(x,y): return list(range(((x+1) // 2) * 2,y+1, 2)) printEvenfor(9,16) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
one way is by using while, that takes the start and end range in ``` for each in range(int(input()),int(input())): while each%2 == 0: print (each) break; ```
Try this: ```py x = x+x%2 for num in range (x,y+1,2): print (num) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can use reminder to get the correct range: ``` def print_event_for(min_, max_): reminder = min_ % 2 for i in range(min_+reminder, max_+reminder, 2): print(i) print_event_for(5, 12) ``` Output: ``` 6 8 10 12 ```
The following function will do what you want. I use `round` to force the boundaries to be even in order to get start the range on an even number. ``` def print_even_between(x, y): x = round(x / 2) * 2 y = round(y / 2) * 2 for i in range(x, y, 2): print(i) print(y) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can use reminder to get the correct range: ``` def print_event_for(min_, max_): reminder = min_ % 2 for i in range(min_+reminder, max_+reminder, 2): print(i) print_event_for(5, 12) ``` Output: ``` 6 8 10 12 ```
Try this: ```py x = x+x%2 for num in range (x,y+1,2): print (num) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
one way is by using while, that takes the start and end range in ``` for each in range(int(input()),int(input())): while each%2 == 0: print (each) break; ```
Hacky but fun: multiplying strings with zero. ``` >>> low, high = int(input()), int(input()) 5 13 >>> for n in range(low, high + 1): ... print('{}\n'.format(n)*(not n%2), end='') ... 6 8 10 12 ``` Odd numbes are not printed because the string is multiplied with `False` (acting as zero).
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can make x even, by using floor division and then multiplication: ``` x = (x // 2) * 2 ``` x will then be rounded to the previous even integer or stay the same if it was even before. If you want to round it to the following even integer you need to do: ``` x = ((x + 1) // 2) * 2 ``` This can be improved further by using shifting operators: ``` x = (x >> 1) << 1 #Alternative 1 x = ((x + 1) >> 1) << 1 #Alternative 2 ``` Examples: ``` #Alternative 1 x = 9 x = (x >> 1) << 1 #x is now 8 #Alternative 2 x = 9 x = ((x + 1) >> 1) << 1 #x is now 10 ``` The second one is probably more suitable for you
Try this: ```py x = x+x%2 for num in range (x,y+1,2): print (num) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can use reminder to get the correct range: ``` def print_event_for(min_, max_): reminder = min_ % 2 for i in range(min_+reminder, max_+reminder, 2): print(i) print_event_for(5, 12) ``` Output: ``` 6 8 10 12 ```
``` def printEvenfor(x,y): return list(range(((x+1) // 2) * 2,y+1, 2)) printEvenfor(9,16) ```
55,535,138
I have a homework to do in Python class and was given this question: > > Make a program that gets 2 numbers from the user, and prints all even > numbers in the range of those 2 numbers, you can only use as many for > statements as you want, but can't use another loops or if statement. > > > I understand that I need to use this code: ``` for num in range (x,y+1,2): print (num) ``` but without any `if` statements, I can't check if the value `x` inserted is even or odd, and if the user inserted the number `5` as `x`, all the prints will be odd numbers. I also tried to enter each number to a tuple or an array, but I still can't check if the first number is even to start printing. ``` def printEvenFor(x,y): evenNumbers =[] for i in range (x,y+1): evenNumbers.append(i) print (evenNumbers[::2]) ``` or ``` def printEvenFor(x,y): for i in range (x,y+1,2): print(i,",") ``` I expect the output of `printEvenFor(5,12)` to be `6,8,10,12` but it is `5,7,9,11`
2019/04/05
[ "https://Stackoverflow.com/questions/55535138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10301715/" ]
You can make x even, by using floor division and then multiplication: ``` x = (x // 2) * 2 ``` x will then be rounded to the previous even integer or stay the same if it was even before. If you want to round it to the following even integer you need to do: ``` x = ((x + 1) // 2) * 2 ``` This can be improved further by using shifting operators: ``` x = (x >> 1) << 1 #Alternative 1 x = ((x + 1) >> 1) << 1 #Alternative 2 ``` Examples: ``` #Alternative 1 x = 9 x = (x >> 1) << 1 #x is now 8 #Alternative 2 x = 9 x = ((x + 1) >> 1) << 1 #x is now 10 ``` The second one is probably more suitable for you
Hacky but fun: multiplying strings with zero. ``` >>> low, high = int(input()), int(input()) 5 13 >>> for n in range(low, high + 1): ... print('{}\n'.format(n)*(not n%2), end='') ... 6 8 10 12 ``` Odd numbes are not printed because the string is multiplied with `False` (acting as zero).
111,580
Torque seal is a lacquer-like product used in critical applications after a screw is tightened to provide a visual indication if the screw comes loose. Considering that a terminal screw on an electrical device coming loose can give you a Bad Day™, is it legal to use torque seal or an equivalent product (nail polish is said to work in a pinch) on electrical device terminal screws to visually indicate loosening? Or is there something in Code that would prohibit such a practice?
2017/04/06
[ "https://diy.stackexchange.com/questions/111580", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/27099/" ]
I don't know of any restrictions for the use you are proposing. In fact I have used it myself. Mostly for time clocks so if we can tell if someone is jacking with it.
I have never used this product, but often make a sharpie mark, which IME is a very common practice, and never raises an eyebrow. Since the amount is so small, I don't think there's a danger of fumes around the equipment while it cures, or introducing a combustible into the interior of the equipment. I think since there is no rule specifically restricting making identifying marks, labels, etc. inside the panel, there is nothing that prohibits torque seal on terminals.
13,125,284
In the code below, I am applying a different background color to all even rows by dynamically assigning the class "even" to them using javascript. I am calling the alternamte() function onload of the body tag. At first, I was using getElementById to get the table object and my code worked fine. However, I am suppose to apply this styling to ALL tables on my page, so I need to use get element by tag name. Once I made the chane to getElementByTagName, my code stopped working and I have been trying to find out the root of the problem for a while now with no success. I was wondering if someone can help me understand why my code stopped working after I made the change to getElementByTagName? ``` <script type="text/javascript"> function alternate(){ var table = document.getElementsByTagName("table"); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } </script> ```
2012/10/29
[ "https://Stackoverflow.com/questions/13125284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
It's [getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName), plural. It returns a HTMLCollection ``` var table = document.getElementsByTagName("table")[0]; ``` (if you're confident that there's a `<table>` on the page.) If you want to do things to *all* the `<table>` elements, you'd have to do something like this: ``` var tables = document.getElementsByTagName("table"); for (var ti = 0; ti < tables.length; ++ti) { var rows = tables[ti].getElementsByTagName("tr"); for(var i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } ```
Use `getElementsByTagName` instead of `getElementByTagName` (getElementsByTagName return multiple node elements ) ``` var table = document.getElementsByTagName("table")[0], trs, rl; vat tl= table.length; while(tl--){ trs = tables[tl].getElementsByTagName("tr"); rl = trs.length; while(rl--){ if(rl % 2 == 0){ trs[rl].className = "even"; } } } ```
13,125,284
In the code below, I am applying a different background color to all even rows by dynamically assigning the class "even" to them using javascript. I am calling the alternamte() function onload of the body tag. At first, I was using getElementById to get the table object and my code worked fine. However, I am suppose to apply this styling to ALL tables on my page, so I need to use get element by tag name. Once I made the chane to getElementByTagName, my code stopped working and I have been trying to find out the root of the problem for a while now with no success. I was wondering if someone can help me understand why my code stopped working after I made the change to getElementByTagName? ``` <script type="text/javascript"> function alternate(){ var table = document.getElementsByTagName("table"); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } </script> ```
2012/10/29
[ "https://Stackoverflow.com/questions/13125284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
Use `getElementsByTagName` instead of `getElementByTagName` (getElementsByTagName return multiple node elements ) ``` var table = document.getElementsByTagName("table")[0], trs, rl; vat tl= table.length; while(tl--){ trs = tables[tl].getElementsByTagName("tr"); rl = trs.length; while(rl--){ if(rl % 2 == 0){ trs[rl].className = "even"; } } } ```
getElementsByTagName() returns an array matching the selector. Hence try ``` var table = getElementsByTagName('table')[indexnumber]; ```
13,125,284
In the code below, I am applying a different background color to all even rows by dynamically assigning the class "even" to them using javascript. I am calling the alternamte() function onload of the body tag. At first, I was using getElementById to get the table object and my code worked fine. However, I am suppose to apply this styling to ALL tables on my page, so I need to use get element by tag name. Once I made the chane to getElementByTagName, my code stopped working and I have been trying to find out the root of the problem for a while now with no success. I was wondering if someone can help me understand why my code stopped working after I made the change to getElementByTagName? ``` <script type="text/javascript"> function alternate(){ var table = document.getElementsByTagName("table"); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } </script> ```
2012/10/29
[ "https://Stackoverflow.com/questions/13125284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316524/" ]
It's [getElementsByTagName()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName), plural. It returns a HTMLCollection ``` var table = document.getElementsByTagName("table")[0]; ``` (if you're confident that there's a `<table>` on the page.) If you want to do things to *all* the `<table>` elements, you'd have to do something like this: ``` var tables = document.getElementsByTagName("table"); for (var ti = 0; ti < tables.length; ++ti) { var rows = tables[ti].getElementsByTagName("tr"); for(var i = 0; i < rows.length; i++){ //change style of even rows //(odd integer values, since we're counting from zero) if(i % 2 == 0){ rows[i].className = "even"; } } } ```
getElementsByTagName() returns an array matching the selector. Hence try ``` var table = getElementsByTagName('table')[indexnumber]; ```
41,862,030
So I needed to use the code of the subprocess module to add some functionality I needed. When I was trying to compile the \_subprocess.c file, it gives this error message: `Error 1 error C2086: 'PyTypeObject sp_handle_type' : redefinition` This is the code part which is relevant from `_subprocess.c` file: ``` typedef struct { PyObject_HEAD HANDLE handle; } sp_handle_object; staticforward PyTypeObject sp_handle_type; static PyObject* sp_handle_new(HANDLE handle) { sp_handle_object* self; self = PyObject_NEW(sp_handle_object, &sp_handle_type); if (self == NULL) return NULL; self->handle = handle; return (PyObject*)self; } #if defined(MS_WIN32) && !defined(MS_WIN64) #define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle) #define PY_HANDLE_PARAM "l" #else #define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) #define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { HANDLE handle; if (!PyArg_ParseTuple(args, ":Detach")) return NULL; handle = self->handle; self->handle = INVALID_HANDLE_VALUE; /* note: return the current handle, as an integer */ return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { if (!PyArg_ParseTuple(args, ":Close")) return NULL; if (self->handle != INVALID_HANDLE_VALUE) { CloseHandle(self->handle); self->handle = INVALID_HANDLE_VALUE; } Py_INCREF(Py_None); return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { if (self->handle != INVALID_HANDLE_VALUE) CloseHandle(self->handle); PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { { "Detach", (PyCFunction)sp_handle_detach, METH_VARARGS }, { "Close", (PyCFunction)sp_handle_close, METH_VARARGS }, { NULL, NULL } }; static PyObject* sp_handle_getattr(sp_handle_object* self, char* name) { return Py_FindMethod(sp_handle_methods, (PyObject*)self, name); } static PyObject* sp_handle_as_int(sp_handle_object* self) { return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; statichere PyTypeObject sp_handle_type = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "_subprocess_handle", sizeof(sp_handle_object), 0, (destructor)sp_handle_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)sp_handle_getattr,/*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ &sp_handle_as_number, /*tp_as_number */ 0, /*tp_as_sequence */ 0, /*tp_as_mapping */ 0 /*tp_hash*/ };` ``` Also I've found that: ``` #define staticforward static #define statichere static ``` I don't understand what am I doing wrong. Any help would be appreciated. Btw (I'm not sure if it's relevant), I'm using Visual Studio Professional 2013 to compile this file.
2017/01/25
[ "https://Stackoverflow.com/questions/41862030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5372734/" ]
**Notes**: * I'm talking about *Python 2.7* here (since in newer versions, the *subprocess* module no longer has an own *C* implementation for *Win*) * *Python 2.7* is built (officially) using *VStudio2008 (9.0)* according to [[Python.Wiki]: WindowsCompilers](https://wiki.python.org/moin/WindowsCompilers). Building it with a newer (or better: different) version, might yield some other (and harder to find) errors. For example, when I built it with *VStudio 2010 (10.0)* (I used the built version to run a complex set of (*.py\**) scripts), I had some trouble at *runtime* when encountering socket related errors because of some mismatches between *errno* and *WSA\** codes, that were changed between the 2 versions When I tested, I couldn't understand why you encountered the issue and I didn't, then for a while I forgot about it, then when you posted the last comment, it started eating me alive again. As I said I was able to successfully compile the file using *VStudio 2010 / 2013*. Trying to compile the same (this was only an assumption) code with different results -> the *way* that code is compiled might differ. Therefore, I started investigating for other possible definition places for *staticforward* and *statichere* (besides lines *878* / *879* of *object.h*) due to conditional macros: ***#if***, ***#ifdef***, ... . But, I couldn't find any. So, I added some simpler statements: ```c staticforward int i; statichere int i = 2; ``` then, I manually replaced the defines: ```c static int i; static int i = 2; ``` in *\_subprocess.c* (by coincidence, I added them at line *#137* - just before `statichere PyTypeObject sp_handle_type = {` - fact that prevented me to figure out the problem at this point), and it still compiled!!! Next step, I pasted the above lines in another solution that I had open (in a *.cpp* source file), and I was able to reproduce the error. So, I payed more attention to the compiler flags (I copy/pasted from the *x86 Debug* settings of the projects automatically converted by *VStudio* from the ones found in the *PCbuild* folder): * *VStudio 2013* > > > ```bat > /GS > /analyze- > /W3 > /Gy > /Zc:wchar_t > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Python" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Modules\zlib" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\Include" > /I"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PC" > /Zi > /Gm- > /Od > /Fd"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\vc120.pdb" > /fp:precise > /D "_USRDLL" > /D "Py_BUILD_CORE" > /D "Py_ENABLE_SHARED" > /D "MS_DLL_ID=\"2.7-32\"" > /D "WIN32" > /D "_WIN32" > /D "_DEBUG" > /D "_WINDLL" > /errorReport:prompt > /GF > /WX- > /Zc:forScope > /Gd > /Oy- > /Oi > /MDd > /Fa"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\" > /nologo > /Fo"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\" > /Fp"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.11-vs2k13\PCbuild\obj\win32_Debug\pythoncore\python27_d.pch" > > ``` > > * *VStudio 2010* > > > ```bat > /I"..\Python" > /I"..\Modules\zlib" > /I"..\Include" > /I"..\PC" > /Zi > /nologo > /W3 > /WX- > /Od > /Oy- > /D "_USRDLL" > /D "Py_BUILD_CORE" > /D "Py_ENABLE_SHARED" > /D "WIN32" > /D "_DEBUG" > /D "_WIN32" > /D "_WINDLL" > /GF > /Gm- > /MDd > /GS > /Gy > /fp:precise > /Zc:wchar_t > /Zc:forScope > /Fp"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\pythoncore.pch" > /Fa"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\" > /Fo"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\" > /Fd"E:\Work\Dev\Fati\WinBuild\OPSWpython27\src\Python-2.7.10-vcbuild\PCbuild\Win32-temp-Debug\pythoncore\vc100.pdb" > /Gd > /analyze- > /errorReport:queue > > ``` > > and then it struck me: It's the **way of how the file is compiled: *C* vs. *C++*** (the [[MS.Docs]: /Tc, /Tp, /TC, /TP (Specify Source File Type)](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2013/032xwy55(v=vs.120)) flag). Of course, compiling *\_subprocess.c* as *C++* would spit your error. Check [[SO]: Creating a dynamically allocated struct with a 2D dynamically allocated string (@CristiFati's answer)](https://stackoverflow.com/questions/41918914/creating-a-dynamically-allocated-struct-with-a-2d-dynamically-allocated-string/41922266#41922266), for (a little bit) more details, and how the same mistake triggered very different errors.
Ok I found an answer. It turns out that the definition of `staticforward` should have been `extern` instead of `static`. My compiler didn't know how to handle it. I guess in other compilers it works ok.
45,094,992
I need to append a new item to the end of a list. Here is what I tried: ``` (define my-list (list '1 2 3 4)) (let ((new-list (append my-list (list 5))))) new-list ``` I expect to see: ``` (1 2 3 4 5) ``` But I receive: > > let: bad syntax (missing binding pair5s or body) in (let ((new-list (append my-list (list 5))))) > > >
2017/07/14
[ "https://Stackoverflow.com/questions/45094992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8305676/" ]
Your problem is mostly of syntactical nature. The `let` expression in Scheme has the form `(let (binding pairs) body)`. In your example code, while you do have a binding that should work, you don't have a body. For it to work, you need to change it to ``` (let ((new-list (append my-list (list 5)))) new-list) ``` In my DrRacket 6.3 this evaluates to what you would expect it to: `'(1 2 3 4 5)`.
A `let` makes a local variable that exists for the duration of the `let` form. Thus ```scm (let ((new-list (append my-list '(5)))) (display new-list) ; prints the new list ) ; ends the let, new-list no longer exist new-list ; error since new-list is not bound ``` Your error message tells you that you have no expression in the `let` body which is a requirement. Since I added one in my code it's allowed. However now you get an error when you try evaluating `new-list` since it doesn't exist outside the `let` form. Here is the Algol equivalent (specifically in JS) ```js const myList = [1,2,3,4]; { // this makes a new scope const newList = myList.concat([5]); // at the end of the scope newList stops existing } newList; // throws RefereceError since newList doesn't exist outside the block it was created. ``` Since you already tried using `define` you can do that instead and it will create a variable in the global or function scope: ```scm (define my-list '(1 2 3 4)) (define new-list (append my-list (list 5))) new-list ; ==> (1 2 3 4 5) ```
59,080
I want to re-edit my question so that it will come in latest questions again and you all experts can look and help me. But i forgot my actual login id i used to post for the question. This is the link to my actual question. [My actual question](https://stackoverflow.com/questions/2854989/dsnless-connection-for-aruna-db/3370865#3370865) I deeply apologize for my action here if it is a violation of SO community ethics.
2010/07/30
[ "https://meta.stackexchange.com/questions/59080", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/-1/" ]
No worries, we're glad to see you care about your question. Did you insert your email address when you created that account? If so, have a look at this: <https://stackoverflow.com/users/account-recovery> As pointed out by George in the actual question, you can also have a moderator merge your new account with the old one, so you can access all old data again. And finally, you can also drop a message to the SO team by email and explain your situation. I'm sure they'll find a way to help you. Hope that helps :)
You [are a registered user](https://stackoverflow.com/users/309131/vijay), do you remember if you used OpenID or made an account directly? If OpenID, Flag your question for moderator and ask them to e-mail you the OpenID URL associated with your account, if you provided your e-mail when filling out your profile. That should jog your memory enough to login. You may need to do password recovery with the OpenID provider if you can't remember it. If that doesn't work, e-mail ***[email protected]***
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application. In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC. [Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timezone-for-applications-on-windows-azure.aspx)
The SQL databases on the `Azure` cloud are pegged against `Greenwich Mean Time(GMT) or Coordinated Universal Time(UTC)` however many applications are using `DateTime.Now` which is the time according to the regional settings specified on the host machine. Sometimes this is not an issue when the DateTime is not used for any time spanning or comparisons and instead for display only. However if you migrate an existing Database to SQL Azure using the dates populated via `GETDATE()` or `DateTime.Now` you will have an offset, in your case it’s 7 hours during Daylight Saving Time or 8 hours during Standard Time.
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application. In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC. [Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timezone-for-applications-on-windows-azure.aspx)
In this modern times where infrastructure is scaled globally, it is good idea to save data in UTC and convert to a timezone based on users location preference. Please refere: <https://learn.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netframework-4.7.2>
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
Azure SQL Databases are always UTC, regardless of the data center. You'll want to handle time zone conversion at your application. In this scenario, since you want to compare "now" to a data column, make sure `AcceptedDate` is also stored in UTC. [Reference](http://blogs.msdn.com/b/cie/archive/2013/07/29/manage-timezone-for-applications-on-windows-azure.aspx)
I created a simple function that returns the correct UK time whether in DST or not. It can be adapted for other time zones where DST kicks in. ```sql CREATE FUNCTION [dbo].[f_CurrentDateTime]() RETURNS DATETIME AS BEGIN RETURN DATEADD(HOUR,CONVERT(INT,(SELECT is_currently_dst FROM sys.time_zone_info WHERE 1=1 AND NAME = 'GMT Standard Time')),GETDATE()) END ```
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
The SQL databases on the `Azure` cloud are pegged against `Greenwich Mean Time(GMT) or Coordinated Universal Time(UTC)` however many applications are using `DateTime.Now` which is the time according to the regional settings specified on the host machine. Sometimes this is not an issue when the DateTime is not used for any time spanning or comparisons and instead for display only. However if you migrate an existing Database to SQL Azure using the dates populated via `GETDATE()` or `DateTime.Now` you will have an offset, in your case it’s 7 hours during Daylight Saving Time or 8 hours during Standard Time.
In this modern times where infrastructure is scaled globally, it is good idea to save data in UTC and convert to a timezone based on users location preference. Please refere: <https://learn.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netframework-4.7.2>
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
The SQL databases on the `Azure` cloud are pegged against `Greenwich Mean Time(GMT) or Coordinated Universal Time(UTC)` however many applications are using `DateTime.Now` which is the time according to the regional settings specified on the host machine. Sometimes this is not an issue when the DateTime is not used for any time spanning or comparisons and instead for display only. However if you migrate an existing Database to SQL Azure using the dates populated via `GETDATE()` or `DateTime.Now` you will have an offset, in your case it’s 7 hours during Daylight Saving Time or 8 hours during Standard Time.
I created a simple function that returns the correct UK time whether in DST or not. It can be adapted for other time zones where DST kicks in. ```sql CREATE FUNCTION [dbo].[f_CurrentDateTime]() RETURNS DATETIME AS BEGIN RETURN DATEADD(HOUR,CONVERT(INT,(SELECT is_currently_dst FROM sys.time_zone_info WHERE 1=1 AND NAME = 'GMT Standard Time')),GETDATE()) END ```
27,711,123
I have a svg.php file with some shapes. ``` <rect onclick="window.location='search.php?filter=1'" width="50" height="50"> <rect onclick="window.location='search.php?filter=2'" width="50" height="50"> ``` Search.php ``` div class="container"> <textarea class="search" id="search_id"></textarea> <div id="result"></div> <?php include("svg.php"); ?> </div> //This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html <script type="text/javascript"> $(function(){ $(".search").keyup(function() { var search_id = $(this).val(); var dataString = 'search='+ search_id; if (search_id=='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).hide(); } }); }; if(search_id!='') { $.ajax({ type: "POST", url: "search_database.php", data: dataString, cache: false, success: function(html) { $("#result").html(html).show(); } }); }return false; }); jQuery("#result").live("click",function(e){ var $clicked = $(e.target); var $name = $clicked.find('.name').html(); var decoded = $("<div/>").html($name).text(); $('#search_id').val(decoded); }); jQuery(document).live("click", function(e) { var $clicked = $(e.target); if (! $clicked.hasClass("search")){ jQuery("#result").fadeOut(); } }); $('#search_id').click(function(){ jQuery("#result").fadeIn(); }); }); </script> Then a search_database.php $search = isset($_GET['filter']) ? $_GET["filter"] : 1; echo $search; //echos "2". if ($search=="1") { echo $search; //enters if, and it's not supposed to, and echos "1" Select * from table; } ``` Search\_database.php ``` $search = isset($_GET['filter']) ? $_GET["filter"] : "1"; echo $search //echos "2"; if ($search=="1") { $q = $_POST['search']; $q_length = strlen($q); $sql = <<<SQL SELECT * FROM table LIMIT 6 SQL; if(!$result = $con->query($sql)){ die('There was an error running the query [' . $con->error . ']'); } while($row = $result->fetch_array()) { ?> <div class="show_search"> <?php echo $row['name'] ?> </a> </div> <?php } } ?> ``` I'm on `search.php?filter=2` and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1". I'm not defining the $search variable anywhere else. Thank you for your help.
2014/12/30
[ "https://Stackoverflow.com/questions/27711123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3906855/" ]
I created a simple function that returns the correct UK time whether in DST or not. It can be adapted for other time zones where DST kicks in. ```sql CREATE FUNCTION [dbo].[f_CurrentDateTime]() RETURNS DATETIME AS BEGIN RETURN DATEADD(HOUR,CONVERT(INT,(SELECT is_currently_dst FROM sys.time_zone_info WHERE 1=1 AND NAME = 'GMT Standard Time')),GETDATE()) END ```
In this modern times where infrastructure is scaled globally, it is good idea to save data in UTC and convert to a timezone based on users location preference. Please refere: <https://learn.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netframework-4.7.2>
46,768,071
I'm trying to use the hash algorithms provided by the openssl library. I have openssl and libssl-dev installed. The version is 1.1.0f. I try to run the example code of the openssl.org site: ``` #include <stdio.h> #include <openssl/evp.h> int main(int argc, char *argv[]){ EVP_MD_CTX *mdctx; const EVP_MD *md; char mess1[] = "Test Message\n"; char mess2[] = "Hello World\n"; unsigned char md_value[EVP_MAX_MD_SIZE]; int md_len, i; if(!argv[1]) { printf("Usage: mdtest digestname\n"); exit(1); } md = EVP_get_digestbyname(argv[1]); if(!md) { printf("Unknown message digest %s\n", argv[1]); exit(1); } mdctx = EVP_MD_CTX_new(); EVP_DigestInit_ex(mdctx, md, NULL); EVP_DigestUpdate(mdctx, mess1, strlen(mess1)); EVP_DigestUpdate(mdctx, mess2, strlen(mess2)); EVP_DigestFinal_ex(mdctx, md_value, &md_len); EVP_MD_CTX_free(mdctx); printf("Digest is: "); for (i = 0; i < md_len; i++) printf("%02x", md_value[i]); printf("\n"); exit(0); } ``` I try to compile this with: ``` gcc digest_example.c -lcrypto -lssl ``` And the compiler gives the error: ``` digest_example.c:(.text+0xbc): undefined reference to `EVP_MD_CTX_new' digest_example.c:(.text+0x138): undefined reference to `EVP_MD_CTX_free' collect2: error: ld returned 1 exit status ``` And honestly, I'm clueless. I installed and reinstalled OpenSSL 2 times from the website by compiling it. Additionally, all the other commands make no problem. Just these two. Do I have to use other libraries when linking? Thanks for your help.
2017/10/16
[ "https://Stackoverflow.com/questions/46768071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8783607/" ]
You seem to be using an older version of openssl (< 1.1.0). Maybe you have downloaded and installed the newer version, but your linker seems to find and use an older version of your openssl library. `EVP_MD_CTX_new()` in 1.1.0 has replaced `EVP_MD_CTX_create()` in 1.0.x. `EVP_MD_CTX_free()` in 1.1.0 has replaced `EVP_MD_CTX_destroy()` in 1.0.x. You might try to use the older versions of these functions or make sure, that your linker really uses the >= 1.1.0 version of the openssl library.
> > The version is 1.1.0f. I try to run the example code of the openssl.org site ... > > > I installed and reinstalled OpenSSL 2 times from the website by compiling it ... > > > I believe OpenSSL 1.1.0 installs into `/usr/local/ssl`. Headers are located at `/usr/local/ssl/include` and libs are located at `/usr/local/ssl/lib`. You need to compile and link with: ``` gcc -I /usr/local/ssl digest_example.c -Wl,-L,/usr/local/lib -lssl -lcrypto ``` In fact, because Linux paths are f\*\*k'd up, your need to add an RPATH so you link to the proper libraries at runtime (not compile time). So you really need the following because Linux still can't get it right after 30 years or so: ``` gcc -I /usr/local/ssl digest_example.c -Wl,-rpath,/usr/local/lib -Wl,-L,/usr/local/lib -lssl -lcrypto ``` You still need to get the order of the libraries right because LD is a single pass linker. Your command linked with the system's version of OpenSSL, which is 1.0.2. ``` gcc digest_example.c -lcrypto -lssl ``` The order of the libraries was wrong, however. The libraries should have been called out as `-lssl -lcrypto`.
3,373,668
I'm new to android development and as a pet project I wanted to try and connect to an bluetooth device using the HID profile using an android phone. The phone I'll be using is the vibrant and according to samsung it doesn't support the HID Profile ( <http://ars.samsung.com/customer/usa/jsp/faqs/faqs_view_us.jsp?SITE_ID=22&PG_ID=2&PROD_SUB_ID=557&PROD_ID=560&AT_ID=281257> ). Now my question is this, where does this "profile" reside? Is it on the hardware level or on the software level ( I assume the latter from other sources that I have read ). And if it is the latter, can HID implementation be created using RFCOMM communication over bluetooth (this is the only seemingly viable method I can see in the android bluetooth API). I just want to make sure I understand the technology before I try and implement something that may not be possible. Thanks in advance.
2010/07/30
[ "https://Stackoverflow.com/questions/3373668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305682/" ]
With an HTTP DELETE, the URI should fully identify the resource to be deleted. Sending additional data in the request body is unexpected, [and on App Engine, unsupported](http://code.google.com/p/googleappengine/issues/detail?id=601#c5): > > Indeed, when the appspot frontends see > a DELETE request that includes an > body, such as your app, they return a > 501. But, if you remove the body then it will serve a 200. > > > Based on the subsequent discussion, it looks like they decided 400 was more appropriate than 501. In any event, if you omit the body and move your entity key into the URI, you should be fine.
I've seen this happen when the site authenticating doesn't resolve multiple browser users properly or adequately. In ChromeOS the fix is to sign out entirely, and access the site when only the primary identity has been authenticated. Examples: Gmail, and Ingress.
3,373,668
I'm new to android development and as a pet project I wanted to try and connect to an bluetooth device using the HID profile using an android phone. The phone I'll be using is the vibrant and according to samsung it doesn't support the HID Profile ( <http://ars.samsung.com/customer/usa/jsp/faqs/faqs_view_us.jsp?SITE_ID=22&PG_ID=2&PROD_SUB_ID=557&PROD_ID=560&AT_ID=281257> ). Now my question is this, where does this "profile" reside? Is it on the hardware level or on the software level ( I assume the latter from other sources that I have read ). And if it is the latter, can HID implementation be created using RFCOMM communication over bluetooth (this is the only seemingly viable method I can see in the android bluetooth API). I just want to make sure I understand the technology before I try and implement something that may not be possible. Thanks in advance.
2010/07/30
[ "https://Stackoverflow.com/questions/3373668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305682/" ]
With an HTTP DELETE, the URI should fully identify the resource to be deleted. Sending additional data in the request body is unexpected, [and on App Engine, unsupported](http://code.google.com/p/googleappengine/issues/detail?id=601#c5): > > Indeed, when the appspot frontends see > a DELETE request that includes an > body, such as your app, they return a > 501. But, if you remove the body then it will serve a 200. > > > Based on the subsequent discussion, it looks like they decided 400 was more appropriate than 501. In any event, if you omit the body and move your entity key into the URI, you should be fine.
[Drew Sears' Answer](https://stackoverflow.com/a/3375122/6124909) is the most probable issue. However in our case, there was a GET request which was having an empty Request body `{}` which resulted in the `400 - Bad Request` Error with the following message: > > Your client has issued a malformed or illegal request. That’s all we > know. > > > GET Request is not supposed to have a request body at all.
3,373,668
I'm new to android development and as a pet project I wanted to try and connect to an bluetooth device using the HID profile using an android phone. The phone I'll be using is the vibrant and according to samsung it doesn't support the HID Profile ( <http://ars.samsung.com/customer/usa/jsp/faqs/faqs_view_us.jsp?SITE_ID=22&PG_ID=2&PROD_SUB_ID=557&PROD_ID=560&AT_ID=281257> ). Now my question is this, where does this "profile" reside? Is it on the hardware level or on the software level ( I assume the latter from other sources that I have read ). And if it is the latter, can HID implementation be created using RFCOMM communication over bluetooth (this is the only seemingly viable method I can see in the android bluetooth API). I just want to make sure I understand the technology before I try and implement something that may not be possible. Thanks in advance.
2010/07/30
[ "https://Stackoverflow.com/questions/3373668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305682/" ]
[Drew Sears' Answer](https://stackoverflow.com/a/3375122/6124909) is the most probable issue. However in our case, there was a GET request which was having an empty Request body `{}` which resulted in the `400 - Bad Request` Error with the following message: > > Your client has issued a malformed or illegal request. That’s all we > know. > > > GET Request is not supposed to have a request body at all.
I've seen this happen when the site authenticating doesn't resolve multiple browser users properly or adequately. In ChromeOS the fix is to sign out entirely, and access the site when only the primary identity has been authenticated. Examples: Gmail, and Ingress.
31,843,925
I have a query in Linq that needs to be dynamically adjustable based on some values a user selects in a form. My query looks as follows: ``` (from data in DbContext.CoacheeData group data by data.UserId into g select new LeaderboardEntry { Name = g.FirstOrDefault().UserName, Value = g.Sum(data => data.Steps), }); ``` I would like two aspects of this query to be dynamic: * The aggregate function used to calculate the value (could be sum, average or max) * The column used to calculate the value (see below) I've been trying - and failing - to use Linq expressions for this, but I keep getting runtime errors. I'm pretty new at Linq, so I'm probably doing something stupid. Below is an excerpt from the CoacheeData class. If it helps, all of the properties are numbers. All floats even, with the exception of Steps. ``` public class CoacheeData { [Key] public long Id { get; set; } [Required] [ForeignKey("User")] public string UserId { get; set; } public virtual ApplicationUser User { get; set; } public DateTime Date { get; set; } //Each of these properties should be selectable by the query public int Steps { get; set; } public float Distance { get; set; } public float CaloriesBurned { get; set; } //...etc } ``` EDIT: I was asked what I'd tried, below are the most relevant things I think: ----------------------------------------------------------------------------- ``` Func<CoacheeData, int> testLambda = (x) => x.Steps; //Used inside the query like this: Value = g.Sum(testLambda), ``` This throws an exception ("Internal .NET Framework Data Provider error 1025."), which I think is normal because you can't use lambda's directly in Linq to SQL. Correct me if I'm wrong. So I tried with an expression: ``` Expression<Func<CoacheeData, int>> varSelectExpression = (x) => x.Steps; //And in the query: Value = g.Sum(varSelectExpression.Compile()), ``` Throws the same error 1025, which is working as intended because the Compile() call changes the expression into a lambda again, in my understanding. However I can't omit the Compile() call, because then the Linq code doesn't compile. No idea how to fix this. I tried similar things for the sum, I suspect my errors (and the solution) will be comparable. I will add more info later if needed.
2015/08/05
[ "https://Stackoverflow.com/questions/31843925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4500048/" ]
If I understand this correctly, you wish to get the most recently liked photos of a particular user. This can be done using the Instagram API - but only when that particular user has authenticated your app. You can use the following endpoint: > > GET /users/self/media/liked > > > Here the API call would be : > > <https://api.instagram.com/v1/users/self/media/liked?access_token=ACCESS-TOKEN> > > > This will give you the list of recent media liked by the owner of the ACCESS-TOKEN. More details on the Instagram API here : > > <https://www.instagram.com/developer/endpoints/users/#get_users_feed_liked> > > >
Unfortunately no, you can't. This feature is only available on the Instagram app following [this steps](https://help.instagram.com/367550509992787) > > To view the 300 most-recent posts you've liked, go to your account > settings in the app and then tap Posts You've Liked. You won't be able > to view posts you've liked on the web. > > >
42,318,634
I am trying to print a list from mysql table to express page. app.js uses routes.js. there I have get for users profile page ``` //profile app.get('/profile', isLoggedIn, function(req, res){ var courses = []; connection.query('SELECT courseID FROM studentCourses WHERE userID = ?', [req.user], function(err, rows){ for(var i=0; i<rows.length; i++){ courses.push(rows[i]); } for(var j=0; j< courses.length; j++){ connection.query('SELECT name FROM courses WHERE courseID = ?', [courses[j]], function(err, rows2){ list = rows2[j]; }); } }); res.render('profile', { user : req.user // get the user out of session and pass to template }, { courses : list } ); }); ``` my mysql tables users: id, username, password courses: id, name studentCourses: id, userid, courseid I am trying to list all course names that a user with id 2 have for example. Cant find a descent tutorial for nodejs and mysql. This is as far as i could go but couldnt make it work. Probably its just a wrong way. Any help listing that table to a ejs web template would be nice. Thanks
2017/02/18
[ "https://Stackoverflow.com/questions/42318634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7488770/" ]
`x` in `main()` is a local variable that is *independent* from the `x` variable in `getheight()`. You are returning the new value from the latter but areignoring the returned value. Set `x` in `main` from the function call result: ``` while x not in range (1,23): x = getheight() if x in range (1,23): break ``` You also need to fix your `getheight()` function to return an *integer*, not a string: ``` def getheight(): x = input("Give me a positive integer no more than 23 \n") return int(x) ```
Return does not mean that it will automatically update whatever variable name in main matches the return variable. If you do not store this return value, the return value will be gone. Hence you must do ``` x=getheight() ``` to update your variable x
66,999,934
I have 2 icons in divs and 1 link which works as a button ```css .A { width: 50px; height: 50px; border: 1px solid black; display: inline-flex; justify-content: center; align-items: center; margin: 5px; } a { text-decoration: none; } .B { width: 100px; height: 50px; } /* when i change font-size for example to 10px then the element moves down a bit*/ .A span { text-transform: uppercase; color: black; font-size: 10px; } ``` ```html <script src="https://kit.fontawesome.com/4254229804.js" crossorigin="anonymous"></script> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> ``` here is a link to codepen <https://codepen.io/hanzus/pen/GRrMbbm> Everything is centered when a font size of span element of "sign up" link is 16px, but when I change it for example to 10px then link moves a bit down and it is not on the same line with other divs with facebook and youtube links. How do I get these links on the same line when I change a font-size of 1 element?
2021/04/08
[ "https://Stackoverflow.com/questions/66999934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10766879/" ]
Wrap in flex: ```css .container { display: flex; } ``` ```html <div class="container"> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> </div> ``` [Codepen](https://codepen.io/tauzN/pen/poRWMrB)
I know I am a bit a late to the party, but it is possible to make it simpler: ```css .container { display: inline-flex; width: 300px; height: 50px; } .container a { width: 33%; margin: 5px; border: 1px solid black; display:inline-flex; justify-content:center; align-items:center; font-size: 16px; } ``` ```html <div class="container"> <a href="#"> <i class="fab fa-facebook-f"></i> </a> <a href="#"> <i class="fab fa-youtube"></i> </a> <a href="#"> <span>sign up</span> </a> </div> ```
66,999,934
I have 2 icons in divs and 1 link which works as a button ```css .A { width: 50px; height: 50px; border: 1px solid black; display: inline-flex; justify-content: center; align-items: center; margin: 5px; } a { text-decoration: none; } .B { width: 100px; height: 50px; } /* when i change font-size for example to 10px then the element moves down a bit*/ .A span { text-transform: uppercase; color: black; font-size: 10px; } ``` ```html <script src="https://kit.fontawesome.com/4254229804.js" crossorigin="anonymous"></script> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> ``` here is a link to codepen <https://codepen.io/hanzus/pen/GRrMbbm> Everything is centered when a font size of span element of "sign up" link is 16px, but when I change it for example to 10px then link moves a bit down and it is not on the same line with other divs with facebook and youtube links. How do I get these links on the same line when I change a font-size of 1 element?
2021/04/08
[ "https://Stackoverflow.com/questions/66999934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10766879/" ]
Wrap in flex: ```css .container { display: flex; } ``` ```html <div class="container"> <a href="#"> <div class="A"> <i class="fab fa-facebook-f"></i> </div> </a> <a href="#"> <div class="A"> <i class="fab fa-youtube"></i> </div> </a> <a href="#"> <div class="A B"> <span>sign up</span> </div> </a> </div> ``` [Codepen](https://codepen.io/tauzN/pen/poRWMrB)
You should only add "flex-direction: column;" for your CSS code. ``` .container{ display: flex; flex-direction: column; } .A { width:50px; height: 50px; border: 1px solid black; display:inline-flex; justify-content:center; align-items:center; margin: 5px; } a { text-decoration:none; } .B { width: 100px; height: 50px; } .A span { text-transform: uppercase; color:black; font-size: 10px; } ```
15,988,638
I have a class called TileView which extends UIView. In another view I create 9 TileView objects and display them on the screen. Below is an example of 1 of them ``` tile1 = [[TileView alloc] initWithFrame:CGRectMake(20,20, 100, 150) withImageNamed:@"tile1.png" value: 1 isTileFlipped: NO]; ``` A user can touch any of the tiles. When a tile is touched it is "turned over" - the image is named to a plain brown tile and `isTileFlipped` is set to 'YES'. Now comes the part I'm stuck on: There is a confirm button. When the confirm button is pressed, it takes all the tiles that are flipped and adds them to an array called `acceptedTiles`. After confirm is pressed I need to make sure that the tiles in `acceptedTiles` cannot be pressed or interacted with. I am at a loss as to what would be the best way to do this. Here is `touchesBegan` so you can get an idea of what is happening. ``` - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ int currentTileCount = [(BoxView *)self.superview getTileCount]; int currentTileValue = [self getTileValue]; int tilecount; if (!isFlipped) { [image setImage:[UIImage imageNamed:@"tileflipped.png"]]; isFlipped = YES; tilecount = currentTileCount + currentTileValue; [(BoxView *)self.superview setTileCount:tilecount]; [(BoxView *)self.superview addToArray:self index:currentTileValue-1]; } else { [image setImage:[UIImage imageNamed:imageNamed]]; isFlipped = NO; tilecount = currentTileCount - (int)currentTileValue; [(BoxView *)self.superview setTileCount:tilecount]; [(BoxView *)self.superview removeFromArray: currentTileValue-1]; } } ```
2013/04/13
[ "https://Stackoverflow.com/questions/15988638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1424638/" ]
If all you want is the tiles not to be interacted with, surely simply: ``` for (UIView *tile in acceptedTiles) { [tile setUserInteractionEnabled:NO]; } ``` If that doesn't meet your requirements, please elaborate. It seems perfect for you.
If you didn't want to change your code too much you could check if the view was added to `acceptedTiles` before you do anything else in `touchesBegan:withEvent`, and if it was just return. However, I wonder why you aren't using a `UITapGestureRecognizer` here instead? If you did you could set a delegate that implemented the `gestureRecognizerShouldBegin:` method where you could check if the view was in `acceptedTiles` there instead of mixing it in with your other tap recognition logic.
34,810,451
I have this conditions ``` if (txtBoxFatherHusbandName.Text != "" || txtBoxName.Text != "" || txtBoxNICNo.Text != "") { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ``` all three textboxes are empty with no text in it but still the conditions is getting executed. why ?
2016/01/15
[ "https://Stackoverflow.com/questions/34810451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5700366/" ]
You have to use [`String.IsNullOrWhiteSpace()`](https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28v=vs.110%29.aspx) to check them here, because user may press spaces in that case there can be propblems, so you should be writing if like following to tackle with empty textboxes: ``` if (!String.IsNullOrWhiteSpace(txtBoxFatherHusbandName.Text) || .......) ```
``` if (!string.IsNullOrWhiteSpace(txtBoxFatherHusbandName.Text) || !string.IsNullOrWhiteSpace(txtBoxName.Text) || !string.IsNullOrWhiteSpace(txtBoxNICNo.Text)) { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ```
34,810,451
I have this conditions ``` if (txtBoxFatherHusbandName.Text != "" || txtBoxName.Text != "" || txtBoxNICNo.Text != "") { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ``` all three textboxes are empty with no text in it but still the conditions is getting executed. why ?
2016/01/15
[ "https://Stackoverflow.com/questions/34810451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5700366/" ]
Use following statement in if condition ``` if(!string.IsNullOrEmpty(txtBoxFatherHusbandName.Text.Trim())) ```
``` if (!string.IsNullOrWhiteSpace(txtBoxFatherHusbandName.Text) || !string.IsNullOrWhiteSpace(txtBoxName.Text) || !string.IsNullOrWhiteSpace(txtBoxNICNo.Text)) { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ```
34,810,451
I have this conditions ``` if (txtBoxFatherHusbandName.Text != "" || txtBoxName.Text != "" || txtBoxNICNo.Text != "") { ShowMsgBox("Please first <b>Save/Update</b> the data being entered in mandatory fields"); txtBoxFatherHusbandName.Focus(); return; } ``` all three textboxes are empty with no text in it but still the conditions is getting executed. why ?
2016/01/15
[ "https://Stackoverflow.com/questions/34810451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5700366/" ]
You have to use [`String.IsNullOrWhiteSpace()`](https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace%28v=vs.110%29.aspx) to check them here, because user may press spaces in that case there can be propblems, so you should be writing if like following to tackle with empty textboxes: ``` if (!String.IsNullOrWhiteSpace(txtBoxFatherHusbandName.Text) || .......) ```
Use following statement in if condition ``` if(!string.IsNullOrEmpty(txtBoxFatherHusbandName.Text.Trim())) ```
29,139,964
Given a SQL query variable, i.e., ``` string mySQLQuery = "SELECT TableA.Field1, TableA.Field2,..., TableB.Field1, TableB.Field2,.... FROM TableA LEFT OUTER JOIN TableB ON TableA.Field1 = TableB.Field1" ``` Is there any straight way I can extract the fields and the table names within the query in two lists? so: List "Fields": * All fields From table A, table B (and others I could add by joining) with their table prefix (even if there were only one table in a simple 'SELECT \* FROM TableA', I'd still need the 'TableA.' prefix). * All fields From table B with their table prefix, by adding them to the list in the usual fieldList.Add() way through looping. List "Tables": * All tables involved in the query in the usual tablesList.Add() way through looping. My first approach would be to make a lot of substrings and comparisons, i.e., finding the FROM, then trimming left, the substring until the first blank space, then the JOIN, then trimming, then the first substring until the space..., but that doesn't seem the right way. **REEDIT** I know I can get all the fields from INFORMATION\_SCHEMA.COLUMNS with all the properties (that comes later), but the problem is that for that query I need the tables to be known. My steps should be: 1. The query "SELECT [fields] FROM [tables]" comes from a Multiline Textbox so I can write a SQL Query to fetch the fields I'd like. I take the string by txtMyQuery.Text property. 2. Find the field in the SELECT query, and find what table belongs to in the FROM clause. 3. Store the field like [Table].[Field]in a string list List strFields = new List() by the strFields.Add() method; 4. Then, iterate through the list in a way like: ``` for (int i = 0; i < fieldList.Count; i++) { string mySqlQuery = "SELECT Table_Name, Column_Name, Data_Type FROM INFORMATION_SCHEMA.COLUMNS WHERE (COLUMN_NAME + "." + TABLE_NAME) ='" + fieldList[i] + "'"; //Commit query, get results in a gridview, etc. } ```
2015/03/19
[ "https://Stackoverflow.com/questions/29139964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162164/" ]
I found out where the problem came from. Since the content loaded in the “div” element changed its height 2 times with each press of the button, the height of the page body changed as well. This was the cause of the scrolling. I fixed the height of the “div” element in the css file: ``` div#result {height: 200px;} ``` This solved the problem.
Good, for the answer and also good if you give your code in jsfiddle. Still no issue, recently I have done the same thing. By default it same position if you click on button, but if you have anchor tag, then it will automatically goes on top. There is so many things to stay or scroll on desired position. [window.scrollTo(0, 0);](http://www.w3schools.com/jsref/met_win_scrollto.asp) ``` function buttonclick(isfirsttimeload) { if (typeof isfirsttimeload!= "undefined") window.scrollTo(0, 0); else location.hash = '#asearchresult'; //this is hidden anchortag's id, which scrolldown on click. } ``` <http://www.w3schools.com/jsref/prop_loc_hash.asp> [Using window.location.hash in jQuery](https://stackoverflow.com/questions/7880669/using-window-location-hash-in-jquery)
29,139,964
Given a SQL query variable, i.e., ``` string mySQLQuery = "SELECT TableA.Field1, TableA.Field2,..., TableB.Field1, TableB.Field2,.... FROM TableA LEFT OUTER JOIN TableB ON TableA.Field1 = TableB.Field1" ``` Is there any straight way I can extract the fields and the table names within the query in two lists? so: List "Fields": * All fields From table A, table B (and others I could add by joining) with their table prefix (even if there were only one table in a simple 'SELECT \* FROM TableA', I'd still need the 'TableA.' prefix). * All fields From table B with their table prefix, by adding them to the list in the usual fieldList.Add() way through looping. List "Tables": * All tables involved in the query in the usual tablesList.Add() way through looping. My first approach would be to make a lot of substrings and comparisons, i.e., finding the FROM, then trimming left, the substring until the first blank space, then the JOIN, then trimming, then the first substring until the space..., but that doesn't seem the right way. **REEDIT** I know I can get all the fields from INFORMATION\_SCHEMA.COLUMNS with all the properties (that comes later), but the problem is that for that query I need the tables to be known. My steps should be: 1. The query "SELECT [fields] FROM [tables]" comes from a Multiline Textbox so I can write a SQL Query to fetch the fields I'd like. I take the string by txtMyQuery.Text property. 2. Find the field in the SELECT query, and find what table belongs to in the FROM clause. 3. Store the field like [Table].[Field]in a string list List strFields = new List() by the strFields.Add() method; 4. Then, iterate through the list in a way like: ``` for (int i = 0; i < fieldList.Count; i++) { string mySqlQuery = "SELECT Table_Name, Column_Name, Data_Type FROM INFORMATION_SCHEMA.COLUMNS WHERE (COLUMN_NAME + "." + TABLE_NAME) ='" + fieldList[i] + "'"; //Commit query, get results in a gridview, etc. } ```
2015/03/19
[ "https://Stackoverflow.com/questions/29139964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4162164/" ]
I found out where the problem came from. Since the content loaded in the “div” element changed its height 2 times with each press of the button, the height of the page body changed as well. This was the cause of the scrolling. I fixed the height of the “div” element in the css file: ``` div#result {height: 200px;} ``` This solved the problem.
You have to call this function on page load. ``` limit – The number of records to display per request. offset – The starting pointer of the data. busy – Check if current request is going on or not. The main trick for this scroll down pagination is binding the window scroll event and checking with the data container height $(document).ready(function() { $(window).scroll(function() { // make sure u give the container id of the data to be loaded in. if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) { busy = true; offset = limit + offset; displayRecords(limit, offset); } }); }) <script type="text/javascript"> var limit = 10 var offset = 0; function displayRecords(lim, off) { $.ajax({ type: "GET", async: false, url: "getrecords.php", data: "limit=" + lim + "&offset=" + off, cache: false, beforeSend: function() { $("#loader_message").html("").hide(); $('#loader_image').show(); }, success: function(html) { $('#loader_image').hide(); $("#results").append(html); if (html == "") { $("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show() } else { $("#loader_message").html('<button class="btn btn-default" type="button">Load more data</button>').show(); } } }); } $(document).ready(function() { // start to load the first set of data displayRecords(limit, offset); $('#loader_message').click(function() { // if it has no more records no need to fire ajax request var d = $('#loader_message').find("button").attr("data-atr"); if (d != "nodata") { offset = limit + offset; displayRecords(limit, offset); } }); }); </script> ``` Implementing with php ie getrecords.php ``` <?php require_once("config.php"); $limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10; $offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0; $sql = "SELECT countries_name FROM countries WHERE 1 ORDER BY countries_name ASC LIMIT $limit OFFSET $offset"; try { $stmt = $DB->prepare($sql); $stmt->execute(); $results = $stmt->fetchAll(); } catch (Exception $ex) { echo $ex->getMessage(); } if (count($results) > 0) { foreach ($results as $res) { echo '<h3>' . $res['countries_name'] . '</h3>'; } } ?> ```
422,149
I have a Windows 7 Ultimate machine where the wireless adapter all of a sudden started having trouble connecting to wireless networks. Whenever I go to a new place and try to connect to a wireless network, it says that the DNS server is not responding, and tells me to go unplug the router and try again. After several locations in a row telling me this, I began to realize something was wrong with my adapter, not the routers. I am no longer asked to identify the security level for any new networks (Work, Home, or Public) like I used to be (it defaults to Public now - with the park bench icon). Often, resetting the router doesn't even work. Running the Windows 7 troubleshooter doesn't give me anything better than the advice to reset the router. However, the adapter will still connect to the wireless network at my main office without any problems. Does anyone know why a wireless network adapter can get so finicky so suddenly? Thanks!
2012/05/08
[ "https://superuser.com/questions/422149", "https://superuser.com", "https://superuser.com/users/133169/" ]
It really depends on the case you have. I would personally get one of solid state picoPSU things and power the PC through a battery. Charge up a capacitor while the car is running, then when the car shuts off let it slowly drain through a resistor to ground and when the capacitor is empty get a mosfet to poke the "power button" pins for it to go into automatic powerdown Note: I would try to avoid going DC(car) to AC(inverter/UPS) to DC(pc) as you'll loose alot of power that way and inverters always pull power even if they are not powering anything
I think, given the sheer form factor of a M-ITX case you would be better off getting some soft of UPS that is plugged into the car battery and working out how to do a graceful shutdown if the ignition has been cut for more than x minutes. You could try and bodge a load of batteries into a hard disk space but that probably wouldn't be a high enough current/voltage to power a PC. Also consider a laptop. Inbuilt battery. See if you can find a model that can also take an external secondary battery.
14,018,088
I have a jBoss 5.1.0-GA running a server, it was running find. But I copied whole jboss to another server, (by using tar). When I start new jBoss, it give a "user null is NOT authenticated", here is the stack trace ``` [ExceptionUtil] ConnectionFactoryEndpoint[jboss.messaging.connectionfactory:service=ConnectionFactory] createFailoverConnectionDelegate [nb-z2y983bh-1-4b8983bh-kwpr33-100j3] javax.jms.JMSSecurityException: User null is NOT authenticated at org.jboss.jms.server.jbosssx.JBossASSecurityMetadataStore.authenticate(JBossASSecurityMetadataStore.java:223) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:93) at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:27) at com.sun.jmx.mbeanserver.MBeanIntrospector.invokeM(MBeanIntrospector.java:208) at com.sun.jmx.mbeanserver.PerInterface.invoke(PerInterface.java:120) at com.sun.jmx.mbeanserver.MBeanSupport.invoke(MBeanSupport.java:262) at javax.management.StandardMBean.invoke(StandardMBean.java:391) at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164) at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:668) at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210) at $Proxy260.authenticate(Unknown Source) at org.jboss.jms.server.endpoint.ServerConnectionFactoryEndpoint.createConnectionDelegateInternal(ServerConnectionFactoryEndpoint.java:233) at org.jboss.jms.server.endpoint.ServerConnectionFactoryEndpoint.createConnectionDelegate(ServerConnectionFactoryEndpoint.java:171) at org.jboss.jms.server.endpoint.advised.ConnectionFactoryAdvised.org$jboss$jms$server$endpoint$advised$ConnectionFactoryAdvised$createConnectionDelegate$aop(ConnectionFactoryAdvised.java:108) at org.jboss.jms.server.endpoint.advised.ConnectionFactoryAdvised.createConnectionDelegate(ConnectionFactoryAdvised.java) at org.jboss.jms.wireformat.ConnectionFactoryCreateConnectionDelegateRequest.serverInvoke(ConnectionFactoryCreateConnectionDelegateRequest.java:91) at org.jboss.jms.server.remoting.JMSServerInvocationHandler.invoke(JMSServerInvocationHandler.java:143) at org.jboss.remoting.ServerInvoker.invoke(ServerInvoker.java:891) at org.jboss.remoting.transport.local.LocalClientInvoker.invoke(LocalClientInvoker.java:106) at org.jboss.remoting.Client.invoke(Client.java:1724) at org.jboss.remoting.Client.invoke(Client.java:629) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate.org$jboss$jms$client$delegate$ClientConnectionFactoryDelegate$createConnectionDelegate$aop(ClientConnectionFactoryDelegate.java:171) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate$createConnectionDelegate_N3019492359065420858.invokeTarget(ClientConnectionFactoryDelegate$createConnectionDelegate_N3019492359065420858.java) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:111) at org.jboss.jms.client.container.StateCreationAspect.handleCreateConnectionDelegate(StateCreationAspect.java:81) at org.jboss.aop.advice.org.jboss.jms.client.container.StateCreationAspect_z_handleCreateConnectionDelegate_31070867.invoke(StateCreationAspect_z_handleCreateConnectionDelegate_31070867.java) at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:102) at org.jboss.jms.client.delegate.ClientConnectionFactoryDelegate.createConnectionDelegate(ClientConnectionFactoryDelegate.java) at org.jboss.jms.client.JBossConnectionFactory.createConnectionInternal(JBossConnectionFactory.java:205) at org.jboss.jms.client.JBossConnectionFactory.createQueueConnection(JBossConnectionFactory.java:101) at org.jboss.jms.client.JBossConnectionFactory.createQueueConnection(JBossConnectionFactory.java:95) at org.jboss.resource.adapter.jms.inflow.dlq.AbstractDLQHandler.setupDLQConnection(AbstractDLQHandler.java:137) at org.jboss.resource.adapter.jms.inflow.dlq.AbstractDLQHandler.setup(AbstractDLQHandler.java:83) at org.jboss.resource.adapter.jms.inflow.dlq.JBossMQDLQHandler.setup(JBossMQDLQHandler.java:48) at org.jboss.resource.adapter.jms.inflow.JmsActivation.setupDLQ(JmsActivation.java:413) at org.jboss.resource.adapter.jms.inflow.JmsActivation.setup(JmsActivation.java:351) at org.jboss.resource.adapter.jms.inflow.JmsActivation$SetupActivation.run(JmsActivation.java:729) at org.jboss.resource.work.WorkWrapper.execute(WorkWrapper.java:205) at org.jboss.util.threadpool.BasicTaskWrapper.run(BasicTaskWrapper.java:260) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) 12:01:34,859 ERROR [ExceptionUtil] ConnectionFactoryEndpoint[jboss.messaging.connectionfactory:service=ConnectionFactory] createFailoverConnectionDelegate [mb-z2y983bh-1-4b8983bh-kwpr33-100j3] ``` Can somebody help ?
2012/12/24
[ "https://Stackoverflow.com/questions/14018088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479203/" ]
Solved the problem, that was happened when we are going to solve some other problem, that is com.arjuna transaction issue, in that jboss keep throwing messages non stop, to resolve that issue, some posts recommended delete the 'data' folder in jBoss, when we delete that, the hypersonic database script inside the data folder is also deleted, therefore the user Null issue came out, so what we did was restored the hypersonic db script and now it's working fine.
One other possibility is that the data-source specified in the `DatabaseServerLoginModule` bean, which is configured in "messaging-jboss-beans.xml", does not match the data-source you are using for JMS. This would probably occur when you have replaced the "hsqldb-persistence-service.xml" file in the "deploy/messaging" directory of your server, with a customized persistence service file configured to the database you wish to use for JMS (e.g. "postgresql-persistence-service.xml"). If you do so, you will need to make sure that the value of the `dsJndiName` module option of the `DatabaseServerLoginModule` bean matches the JNDI name of the data-store in the new "-persistence-service.xml" file. Simply replace `java:/DefaultDS` with your data-source JNDI name (e.g. `java:/MysqlDB` or whatever). Reference: <http://www.mail-archive.com/[email protected]/msg59720.html>
46,782,347
I am trying to output SQL as XML to match the exact format as the following ``` <?xml version="1.0" encoding="utf-8"?> <ProrateImport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.aldi- sued.com/Logistics/Shipping/ProrateImport/20151009"> <Prorates> <Prorate> <OrderTypeId>1</OrderTypeId> <DeliveryDate>2015-10-12T00:00:00+02:00</DeliveryDate> <DivNo>632</DivNo> <ProrateUnit>1</ProrateUnit> <ProrateProducts> <ProrateProduct ProductCode="8467"> <ProrateItems> <ProrateItem StoreNo="1"> <Quantity>5</Quantity> </ProrateItem> <ProrateItem StoreNo="2"> <Quantity>5</Quantity> </ProrateItem> <ProrateItem StoreNo="3"> <Quantity>5</Quantity> </ProrateItem> </ProrateItems> </ProrateProduct> </ProrateProducts> </Prorate> </Prorates> </ProrateImport> ``` Here is my query: ``` SELECT OrderTypeID, DeliveryDate, DivNo, ProrateUnit, (SELECT ProductOrder [@ProductCode], (SELECT ProrateItem [@StoreNo], CAST(Quantity AS INT) [Quantity] FROM ##Result2 T3 WHERE T3.DivNo = T2.DivNo AND T3.DivNo = T1.DivNo AND T3.DeliveryDate = T2.DeliveryDate AND T3.DeliveryDate = T1.DeliveryDate AND T3.ProductOrder = t2.ProductOrder FOR XML PATH('ProrateItem'), TYPE, ROOT('ProrateItems') ) FROM ##Result2 T2 WHERE T2.DivNo = T1.DivNo AND T2.DeliveryDate = T1.DeliveryDate FOR XML PATH('ProrateProduct'), TYPE, ROOT('ProrateProducts') ) FROM ##Result2 T1 GROUP BY OrderTypeID, DeliveryDate, DivNo, ProrateUnit FOR XML PATH('Prorate'), TYPE, ROOT('Prorates') ``` How do I add in the Following and have the ProrateImport/20151009" change to the current date? ``` <?xml version="1.0" encoding="utf-8"?> <ProrateImport xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schema.aldi- sued.com/Logistics/Shipping/ProrateImport/20151009"> ``` This is my first time I have used XML
2017/10/17
[ "https://Stackoverflow.com/questions/46782347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8787739/" ]
When defining `sum''`, you have defined what it means for two empty lists, and for two non-empty lists, but you haven't defined what it means for two lists, only one of which is empty. This is what the compiler is telling you via that error message. Simply add definitions of what `sum''` means whenever left list is empty and the right list is not, and vice versa: ``` sum'' (x:xs) [] = ... sum'' [] (y:ys) = ... ```
Well in Haskell, actually for what you need there is the [`ZipList`](https://hackage.haskell.org/package/base-4.10.0.0/docs/Control-Applicative.html#t:ZipList) type and you may use it to simply do as follows; ``` import Control.Applicative addLists :: Num a => [a] -> [a] -> [a] addLists xs ys = getZipList $ (+) <$> ZipList xs <*> ZipList ys *Main> addLists [3] [1,2,3] [4] ```
484,819
Let $X\_1, X\_2 , \dots, X\_n$ be i.i.d observations from $N(\theta, \theta)$ (where $\theta$ is the variance). I intend to find the minimal sufficient statistics (M.S.S) for the joint distribution. My steps ultimately lead me to the following: $\dfrac{f\_\theta(x)}{f\_\theta(y)} = \text{exp}{ \left\{ \dfrac{-1}{2\theta} \left[ \left(\sum x\_i^2 - \sum y\_i^2 \right) + 2\theta \left( \sum y\_i - \sum x\_i \right) \right] \right) }$. My M.S.S are therefore $\left( \sum x\_i^2 , \sum x\_i \right)$ Am I on track?
2020/08/26
[ "https://stats.stackexchange.com/questions/484819", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/48950/" ]
It turns out that after further expansion, the above becomes $\dfrac{f\_\theta(x)}{f\_\theta(y)} = \exp \left\{ - \left[ \dfrac{1}{2\theta} \left( \sum x\_i^2 - \sum y\_i^2 \right) + \left( \sum y\_i - \sum x\_i \right) \right] \right\}$. Since it is only the first term that depends on $\theta$, the M.S.S is $\sum x\_i^2$.
By writing the joint density in exponential family form we find $$ f(x,\theta) = \frac1{\sqrt{2\pi}} \exp\left\{ -\frac{n}{2}\log\theta - \frac1{2\theta} \sum\_i x\_i^2 + \sum\_i x\_i -n\theta^2 \right\} $$ and then the result follows by general exponential family theory, as noted in comments.
56,605,977
I mean for example use a normal case switch but instead of the case being selected by a user being chosen randomly ``` def switch_demo(argument):     switcher = {         1: "January",         2: "February",         3: "March",         4: "April",         5: "May",         6: "June",         7: "July",         8: "August",         9: "September",         10: "October",         11: "November",         12: "December"     } ``` and somehow make it random to choose, i mean the case is chosen randomly. For example: generate a random number this being the number of the case or something like that.
2019/06/14
[ "https://Stackoverflow.com/questions/56605977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I don't know if I understand what you wanted to do with it, but you don't need to do it, you could do it like this: ``` import random months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] rand_month_choice = random.choice(months) print(rand_month_choice) #prints the random choice ```
This is very possible, but there are probably better ways of going about it. For example, you could simply go: ```py from random import randint month = randint(1,12) case (month)... ``` I would suggest using a list to store this information, since this isn't really an appropriate use-case (no pun intended) for cases. Example 2 would be my choice since it's fast, understandable and easy to type. **Example 1** ```py from random import randint months = ["January","February","March","April","May","June","July","August","September","October","November","December"] months_string = months[randint(0,11)] # 0-11 because the list starts from index 0 ``` **Example 2** ```py from random import choice months = ["January","February","March","April","May","June","July","August","September","October","November","December"] monthstring = choice(months) ```
267,026
I'm running a script within a script, release.sh and caller.sh (caller.sh calls release.sh). Both are bash. release.sh contains a bunch of conditions with 'exit 1' for errors. caller.sh contains a line that goes "./release.sh", then a checks for the exit code of release.sh - if $? is greater than 0 then echo "release.sh screwed up" and exits. ``` ./release.sh if [ $? -gt "0" ] ; then echo "release_manager exited with errors, please see the release log." exit 1 else echo "release manager is done." fi ``` Recently I've decided to log release.sh, and so the line in caller.sh goes: ``` ./release.sh 2>&1 | tee release.txt ``` Because of the pipe, $? is the exit code of 'tee release.txt' , which always comes out as 0, regardless of the previous command :-( I have to check for release.sh errors and stop the caller from proceeding, but I also really need that log. Is there a way to get the exit code of the command **before** last? Or a different way to log the release script in the same command? I'm not really in charge of release.sh, I'd rather not change it.
2016/03/02
[ "https://unix.stackexchange.com/questions/267026", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137597/" ]
Since you are using bash you can set in the script the option: ``` set -o pipefail ``` > > The pipeline's return status is the value of the last (rightmost) command > to exit with a non-zero status, or zero if all commands exit successfully. > > > Alternatively, immediately after the piped command you can look at builtin variable value `${PIPESTATUS[0]}` for the exit code of the first command in the pipe. > > PIPESTATUS: An array variable containing a list of exit > status values from the processes in the most-recently-executed foreground > pipeline (which may contain only a single command). > > >
May I suggest rewriting it like that: ``` ./release.sh > release.txt 2>&1 ``` and then ``` echo $? ``` would return the correct exit status
20,523,881
Is there any event, to append to the following listener, that will tell me if a radio button is already clicked? ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { console.log($(this)) budgetType = $(this).val(); }); ``` My problem is that, on page reload, if the radio box is already checked, the `change` listener won't work, and I didn't find any listener that will help me with that issue. Any ideas? Update ------ I'm aware that I could write an `if/else` syntax and see which is checked, but I was wondering if there is any other listener that I could append to `change` one, and avoid writing that extra syntax. <http://jsfiddle.net/S93XB/1/>
2013/12/11
[ "https://Stackoverflow.com/questions/20523881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971392/" ]
``` $('input[type=radio]').is(':checked') ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/> or try this one ``` $('input[type=radio]').prop('checked', true); ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/1/> It will work, you can execute this onload to get the first value and use it in an if else block.
Try this : ``` $('input[type=radio]').is(':checked') ``` Or ``` $('input[type=radio]').prop('checked') === true; ``` Or ``` $('input[type=radio]').attr('checked') === 'checked'; ```
20,523,881
Is there any event, to append to the following listener, that will tell me if a radio button is already clicked? ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { console.log($(this)) budgetType = $(this).val(); }); ``` My problem is that, on page reload, if the radio box is already checked, the `change` listener won't work, and I didn't find any listener that will help me with that issue. Any ideas? Update ------ I'm aware that I could write an `if/else` syntax and see which is checked, but I was wondering if there is any other listener that I could append to `change` one, and avoid writing that extra syntax. <http://jsfiddle.net/S93XB/1/>
2013/12/11
[ "https://Stackoverflow.com/questions/20523881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971392/" ]
``` $('input[type=radio]').is(':checked') ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/> or try this one ``` $('input[type=radio]').prop('checked', true); ``` Try this code here: <http://jsfiddle.net/afzaal_ahmad_zeeshan/rU2Fc/1/> It will work, you can execute this onload to get the first value and use it in an if else block.
Trigger the change event on load: ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { var isChecked = $(this).is(":checked"); console.log($(this).val()+" "+isChecked); budgetType = $(this).val(); }); $('input[name="import_export"]:checked').trigger('change'); ``` <http://jsfiddle.net/eLGaB/>
20,523,881
Is there any event, to append to the following listener, that will tell me if a radio button is already clicked? ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { console.log($(this)) budgetType = $(this).val(); }); ``` My problem is that, on page reload, if the radio box is already checked, the `change` listener won't work, and I didn't find any listener that will help me with that issue. Any ideas? Update ------ I'm aware that I could write an `if/else` syntax and see which is checked, but I was wondering if there is any other listener that I could append to `change` one, and avoid writing that extra syntax. <http://jsfiddle.net/S93XB/1/>
2013/12/11
[ "https://Stackoverflow.com/questions/20523881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971392/" ]
Trigger the change event on load: ``` var budgetType; $(document).on('change', 'input[name="import_export"]', function() { var isChecked = $(this).is(":checked"); console.log($(this).val()+" "+isChecked); budgetType = $(this).val(); }); $('input[name="import_export"]:checked').trigger('change'); ``` <http://jsfiddle.net/eLGaB/>
Try this : ``` $('input[type=radio]').is(':checked') ``` Or ``` $('input[type=radio]').prop('checked') === true; ``` Or ``` $('input[type=radio]').attr('checked') === 'checked'; ```
2,755,102
Fifty years ago, we were taught to calculate square roots one digit at a time with pencil and paper (and in my case, an eraser was also required). That was before calculators with a square root button were available. (And a square root button is an incredibly powerful doorway to the calculation of other functions.) While trying to refresh that old skill, I found that the square root of 0.1111111.... was also a repeating decimal, 0.3333333.... Also, the square root of 0.4444444..... is 0.66666666..... My question: are there any other rational numbers whose square roots have repeating digit patterns? (with the repeating digit other than 9 or 0, of course)? The pattern might be longer than the single digit in the above examples.
2018/04/26
[ "https://math.stackexchange.com/questions/2755102", "https://math.stackexchange.com", "https://math.stackexchange.com/users/133895/" ]
A real as repeating digit patterns iff it is a rational. Your question is then under which conditions the square root of a rational $r$ is rational. The answer (see [here](https://math.stackexchange.com/questions/448172/what-rational-numbers-have-rational-square-roots/448180#448180)) is that $r$ must be the square of a rational. So $\sqrt{x}$ as a repeating pattern iff there exist integers $p$ and $q$ such that: $$x=\frac{p^2}{q^2}$$
Any repeating digit pattern *must* be rational, so take a rational number $\frac{p}{q}$, and square it to get $\frac{p^2}{q^2}$, and there you have it! It's worth noting that, in the examples you gave, $\sqrt{0.1111...} = \sqrt{\frac{1}{9}} = \sqrt{\frac{1}{3^2}} = \frac{1}{3}$, and $\sqrt{0.44444...} = \sqrt{\frac{4}{9}} = \sqrt{\frac{2^2}{3^2}} = \frac{2}{3}$.
2,755,102
Fifty years ago, we were taught to calculate square roots one digit at a time with pencil and paper (and in my case, an eraser was also required). That was before calculators with a square root button were available. (And a square root button is an incredibly powerful doorway to the calculation of other functions.) While trying to refresh that old skill, I found that the square root of 0.1111111.... was also a repeating decimal, 0.3333333.... Also, the square root of 0.4444444..... is 0.66666666..... My question: are there any other rational numbers whose square roots have repeating digit patterns? (with the repeating digit other than 9 or 0, of course)? The pattern might be longer than the single digit in the above examples.
2018/04/26
[ "https://math.stackexchange.com/questions/2755102", "https://math.stackexchange.com", "https://math.stackexchange.com/users/133895/" ]
Just take your favorite rational number with a repeating decimal: $$\frac{1}{11} = .09090909\ldots.$$ Square it: $$\frac{1}{121} = .00826446280991735537190082644628099173553719\ldots,$$ and you've created an example. This one has period 21 and its square root has period 2.
Any repeating digit pattern *must* be rational, so take a rational number $\frac{p}{q}$, and square it to get $\frac{p^2}{q^2}$, and there you have it! It's worth noting that, in the examples you gave, $\sqrt{0.1111...} = \sqrt{\frac{1}{9}} = \sqrt{\frac{1}{3^2}} = \frac{1}{3}$, and $\sqrt{0.44444...} = \sqrt{\frac{4}{9}} = \sqrt{\frac{2^2}{3^2}} = \frac{2}{3}$.
2,755,102
Fifty years ago, we were taught to calculate square roots one digit at a time with pencil and paper (and in my case, an eraser was also required). That was before calculators with a square root button were available. (And a square root button is an incredibly powerful doorway to the calculation of other functions.) While trying to refresh that old skill, I found that the square root of 0.1111111.... was also a repeating decimal, 0.3333333.... Also, the square root of 0.4444444..... is 0.66666666..... My question: are there any other rational numbers whose square roots have repeating digit patterns? (with the repeating digit other than 9 or 0, of course)? The pattern might be longer than the single digit in the above examples.
2018/04/26
[ "https://math.stackexchange.com/questions/2755102", "https://math.stackexchange.com", "https://math.stackexchange.com/users/133895/" ]
Every rational number has either eventually repeating or terminating decimals. Therefore if your $x$ is a square of a rational number, $\sqrt x$ will either terminate or have eventually repeating decimals. For example $ 1/36 =.0277777777\ldots$ and its square root is $$ \sqrt { .0277777777\ldots} = 0.166666666\ldots$$ or $$\sqrt {.049382716049382716049\ldots} = 0.22222222222222222222 \ldots$$
Any repeating digit pattern *must* be rational, so take a rational number $\frac{p}{q}$, and square it to get $\frac{p^2}{q^2}$, and there you have it! It's worth noting that, in the examples you gave, $\sqrt{0.1111...} = \sqrt{\frac{1}{9}} = \sqrt{\frac{1}{3^2}} = \frac{1}{3}$, and $\sqrt{0.44444...} = \sqrt{\frac{4}{9}} = \sqrt{\frac{2^2}{3^2}} = \frac{2}{3}$.
84,956
I am researching this company <https://boldip.com/> How do I verify that 1. It's even a real law firm 2. It's credible 3. It's great at its practice
2022/10/02
[ "https://law.stackexchange.com/questions/84956", "https://law.stackexchange.com", "https://law.stackexchange.com/users/46457/" ]
As to #1, the US Patent and Trademark Office has a [patent practitioner search](https://oedci.uspto.gov/OEDCI/practitionerSearchEntry) where you can verify if someone is a registered patent practitioner. If so, it means they passed a [registration process] that evaluates their "legal, scientific, and technical qualifications, as well as good moral character and reputation", as well as a multiple-choice exam. I looked up a few of the attorneys listed on [the firm's About Us page](https://boldip.com/about-us/) and they show up as registered. So this seems like a good indication that they are a "real law firm". This does not address whether they are "credible" (I'm not sure what that means), or how to evaluate the firm's quality, and I will leave it to someone else to answer that.
1. The lawyer makes the law firm. If there is at least one lawyer who will sign off on any advice and representation on behalf of the client in a company, in other words, they provide legal services under the lead of a lawyer, and its formally established, it is — potentially besides of any other services they may provide per state law — a law firm. Accordingly, you may want to look at the individual attorneys track records (state bar disciplinary history) which may at least give a hint about the individual composition of the firm from this perspective. (The Auditor of State of California simply [declared](https://www.auditor.ca.gov/reports/2022-030/index.html) the Cal. State Bar to practically doing nothing about attorney misconduct, and acting as a cover-up agency for attorneys, and while I’m not sure about the practices in other states, I’d not put my hopes up high) At times, incorporation or tax documents will list the scope of services a company provides, but typically even there one will on mot find “Any legal activity” or similar wording. In many states law firms are given a special designation and will be entitled tot the company form “professional corporation” or P.C. for short; however, that may not everywhere be the case in the U.S. Do note, patent agents may prosecute patents before the USPTO, the Patent and Trademark Administrative Board (PTAB), but not before the Federal Circuit or the U.S. Supreme Court; in a patent dispute, you will need a patent attorney, not an agent. 2. The test of the pudding is the eating. You can read reviews about law firms, but be mindful of the fact that both Google and Yelp will take down reviews of the really nasty stuff on lawyers regardless if a judge declared that a review is substantially factual. You will simply not find reasons of the one-star reviews, the type of things you want to know to judge a law firm's trustworthiness and loyalty to their clients. It’s probably good practice to act according to the specific nature of the interaction within the relationship in terms of whether or not interest surely or necessarily align or not. And if not, proceed with caution. 3. That’s probably even harder without not only knowing the patents they gained and lost, but the prior art around those patents, the actual scope of the invention provided by the inventor or inventors, and the scope of patent issued which tends to require some rather in-depth understanding of various fields of science and technology other than the legal aspect. It’s important to know that “approval rates” may be misleading for many reasons: A law firm may simply refuse a case they are not confident they wouldn’t win (that *might* be a good test of that anecdotal pudding relative to whether or not a patent could be obtained *based on how one presents it to a law firm*); another issue, although it’s probably less probable, frankly, it is really hard to not be able to squeeze something out of a utility idea that at least in the most extremely narrowest sense would not pass obviousness. In other words, one may obtain a completely useless patent with no commercial value, and even the USPTO will probably gladly approved it if it’s narrow enough in hope one would keep paying the maintenance fees. I have not come across law firms that would run a scheme to get approvals at all costs, typically the client has enough discretion on the high-level strategizing to decide whether or not to pursue a patent whatever narrow it may be, or call it as the result would be worthless even with a grant. **The most important thing is** an average-income individual or first inventor is generally best off spending the time to educate themselves to understand patent drafting at least to the extent that they would feel confident to file a provisional application as though they themselves would have to follow up on it, and file the non-provisional on it. (Of course, this on the balance of the competitiveness of the field and expectable probability of someone filing first and rendering one’s application obvious or rarely but even worse: Not novel) There is no much wiggle room in the scope of the claims, and the overall description or specification of the patent in a non-provisional relative to its parent provisional. One must go in with knowing that however narrow they managed to squeeze out the invention and it’s exemplary embodiments in the provisional, that will be the widest breadth of the non-provisional. If one drafts it as though they would then file it as though they would then have to follow through with the non-provisional on the premise that anything left out is lost (unless of course one files another patent application before the publication of the non-provisional), then that’s the material one wants a patent attorney to see. Patent attorneys typically work with big companies who have in-house patent attorneys and their engineers are also thoroughly educated in drafting patents. When their application lands before their in-house or outside counsel, it is almost in shape and form. One simply must thoroughly understand the prior art, that’s a work you just can’t afford paying a lawyer for. In-house attorneys will do it, or outside counsels for multiple tens of thousands if it came to that but it does not, because the engineers do that job before the drafts get before a lawyer or patent agent. The specific law firm in question: It would probably be the decades U.S. patent law scam if this law firm would not be a law firm, and even if only one of the attorneys listed as such would not have been admitted and in good standing with the USPTO and/or the Federal Circuit that would be quite the story too. As @Nate Eldredge informed that doesn’t seem to be the case, and one may view individual attorneys to have been registered and/or to be in good standing with the USPTO.
69,155,288
I'm supposed to write a LIFO (last in first out) class for chars, which can be edited by Pop and Add functions and seen by Peek function or foreach. Class is working on array to be more optimalized, but foreach for some reason's not working. I tried to make function GetEnumerator based on return value of \_arr.GetEnumerator() function, but it was not working, because when I printed item, in console was shown TestApp.LIFO, so I made this, but now foreach won't print a single item and by debuging \_i value on Reset function is 0. Can someone say why is it happening and suggest solution? ``` using System; using System.Collections; using System.Collections.Generic; namespace TestApp { internal class LIFO : IEnumerator, IEnumerable { public LIFO(int size) { _arr = new char[size]; _index = 0; } public LIFO(char[] arr) { _arr = arr.Clone() as char[]; _index = 0; } public char Peek() => _index == 0 ? '\0' : _arr[_index - 1]; public bool Add(char c) { if (_index == _arr.Length) return false; try { _arr[_index] = c; } catch (Exception) { return false; } ++_index; return true; } public void Pop() { if (_index == 0) return; _arr[--_index] = '\0'; } private int _i; public IEnumerator GetEnumerator() => this; public bool MoveNext() => --_i > -1; public void Reset() => _i = _index - 1; public object Current => _arr[_i]; private int _index; private readonly char[] _arr; } } ``` In Program.cs: ``` using System; namespace TestApp { internal static class Program { private static void Main() { LIFO l = new(17); l.Add('k'); l.Add('h'); l.Add('c'); foreach (var item in l) Console.WriteLine(l); } } } ```
2021/09/12
[ "https://Stackoverflow.com/questions/69155288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16832655/" ]
The issue is that `Reset` is not called. It is no longer needed but the interface is not changed due to backwards compatibility. Since new iterators implemented using `yield return` is actually required to throw an exception if `Reset` is called, no code is expected to call this method anymore. As such, your iterator index variable, `_i`, is never initialized and stays at 0. The first call to `MoveNext` steps it below 0 and then returns `false`, ending the `foreach` loop before it even started. You should always decouple the iterators from your actual collection as it should be safe to enumerate the same collection twice in a nested manner, storing the index variable as an instance variable in your collection prevents this. You can, however, simplify the enumerator implementation vastly by using [yield return](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) like this: ``` public class LIFO : IEnumerable { ... public IEnumerator GetEnumerator() { for (int i = _index - 1; i >= 0; i--) yield return _arr[i]; } } ``` You can then remove the `_i` variable, the `MoveNext` and `Reset` methods, as well as the `Current` property. If you first want to make your existing code working, with the above note I made about nesting enumerators, you can change your `GetEnumerator` and `Reset` methods as follows: ``` public IEnumerator GetEnumerator() { Reset(); return this; } public void Reset() => _i = _index; ``` Note that you have to reset the `_i` variable to one step past the last (first) value as you're decrementing it inside `MoveNext`. If you don't, you'll ignore the last item added to the LIFO stack.
Your index counter variable using get values in \_arr array (it is \_i) and index varible that doing increase and decrease operations on it (it is \_index) are different. Because of that your for loop never iterate your collection. I fix the code with some addition here. I hope it's helpful. LIFO.cs ``` using System; using System.Collections; using System.Collections.Generic; namespace TestApp { internal class LIFO : IEnumerator, IEnumerable { public LIFO(int size) { _arr = new char[size]; _index = 0; } public LIFO(char[] arr) { _arr = arr.Clone() as char[]; _index = 0; } public int Count() => _index; public char Peek() => _index == 0 ? '\0' : _arr[_index - 1]; public bool Add(char c) { if (_index == _arr.Length) return false; try { _arr[_index] = c; } catch (Exception) { return false; } ++_index; _i = _index; return true; } public void Pop() { if (_index == 0) return; _arr[--_index] = '\0'; _i = _index; } public IEnumerator GetEnumerator() => (IEnumerator)this; public bool MoveNext() => --_index > -1; public void Reset() => _index = _i; public object Current { get => _arr[_index]; } private int _index; private int _i; private readonly char[] _arr; } } ``` Program.cs ``` using System; namespace TestApp { internal static class Program { private static void Main() { LIFO l = new LIFO(17); l.Add('k'); l.Add('h'); l.Add('c'); Console.WriteLine("Count: " + l.Count()); foreach (var i in l) Console.WriteLine(i); l.Reset(); foreach (var i in l) Console.WriteLine(i); } } } ```
18,647,942
Is there's a way to get the indices properly from a Pymel/Maya API function? I know Pymel has a function called `getEdges()` however according to their docs this get's them from the selected face, however I just need them from the selected edges. Is this possible?
2013/09/06
[ "https://Stackoverflow.com/questions/18647942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683943/" ]
While your answer will work theodox, I did find a much simpler resolution, after some serious digging! Turns out, hiding and not very well documented, was a function ironically called `indices()`, I did search for this but nothing came up in the docs. **Pymel** `selection[0].indices()[0]` The above will give us the integer of the selected edge. Simple and elegant!
Do you mean you just the expanded list of selected edges? That's just FilterExpand -sm 32 or cmds.filterExpand(sm=32) or pm.filterExpand(sm=32) on an edge selection. Those commands are always strings, you grab the indices out them with a regular expression: ``` # where objs is a list of edges, for example cmds.ls(sl=True) on an edge selection cList = "".join(cmds.filterExpand( *objs, sm=32)) outList = set(map ( int, re.findall('\[([0-9]+)\]', cList ) ) ) ``` which will give you a set containing the integer indices of the edges (I use sets so its easy to do things like find edges common to two groups without for loops or if tests)
62,972,549
Im working an a project using Tkinter right now. Whenever I input 'Japan', it prints out: ``` [('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')] ``` I'm not really sure if that's a list or if it's a tuple? I want to seperate all of that data thats seperated by the commas into different variables. Heres what I have so far. If you see any other holes in my code help would greatly be appreciated. Thanks! ``` def subby(): answer=country_name.get() l_answer = answer.capitalize() sql_command = "SELECT * FROM covid WHERE `name` = ?;" values = (l_answer,) cursor.execute(sql_command,values) data = cursor.fetchall() print (data) users0.set(data[0]) users1.set(data[1]) users2.set(data[2]) users3.set(data[3]) users4.set(data[4]) users5.set(data[5]) ```
2020/07/18
[ "https://Stackoverflow.com/questions/62972549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The 'problem' arises because of the change in tsconfig files (solutions style tsconfig) that comes with Typescript 3.9 and Angular 10. More info here : <https://github.com/microsoft/TypeScript/issues/39632> <https://docs.google.com/document/d/1eB6cGCG_2ircfS5GzpDC9dBgikeYYcMxghVH5sDESHw/edit#> **Solution style tsconfig impact in Angular 10** > > In TypeScript 3.9, the concept of solutions style tsconfig was > introduced, in Angular we saw the potentiation and possibility of > fixing long outstanding issues such as incorrectly having test typings > in components files. In Angular CLI version 10 we adopted scaffolded > new and migrated existing workspaces to use solution-style Typescript > configuration. > > > When having an unreferenced file, this will not be part of any > TypeScript program, this is because Angular CLI scaffolds tsconfig > using the files option as opposed to include and exclude. > > > 1. Unreferenced files don’t inherit compiler options > > > When having an unreferenced file, this will not be part of any TypeScript program > and Language service will fallback to use the inferred project configuration. > > > Below find an example of changes that will be required in the application > tsconfig file (tsconfig.app.json). Changes to other tsconfig files will also > be needed. > > > Current tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "files": [ > "src/main.ts", > "src/polyfills.ts" > ], > "include": [ > "src/**/*.d.ts" > ] > } > > ``` > > Proposed tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "include": [ > "src/**/*.ts" > ], > "exclude": [ > "src/test.ts", > "src/**/*.spec.ts", > "src/**/*.server*", > "src/**/*.worker.ts" > ] > } > > ``` > >
This is a bizarre behaviour I have also come across with WebStorm. All I can say is that after a while (couldn't tell you what triggers the IDE to understand properly), the warning disappears and everything goes back to normal.
62,972,549
Im working an a project using Tkinter right now. Whenever I input 'Japan', it prints out: ``` [('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')] ``` I'm not really sure if that's a list or if it's a tuple? I want to seperate all of that data thats seperated by the commas into different variables. Heres what I have so far. If you see any other holes in my code help would greatly be appreciated. Thanks! ``` def subby(): answer=country_name.get() l_answer = answer.capitalize() sql_command = "SELECT * FROM covid WHERE `name` = ?;" values = (l_answer,) cursor.execute(sql_command,values) data = cursor.fetchall() print (data) users0.set(data[0]) users1.set(data[1]) users2.set(data[2]) users3.set(data[3]) users4.set(data[4]) users5.set(data[5]) ```
2020/07/18
[ "https://Stackoverflow.com/questions/62972549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is a bizarre behaviour I have also come across with WebStorm. All I can say is that after a while (couldn't tell you what triggers the IDE to understand properly), the warning disappears and everything goes back to normal.
A comment at the end of the first post in @Wolf359's answer led me to a simple workaround, in the event that your issue is cause by the `tsconfig.json` being split into `tsconfig.base.json` and `tsconfig.app.json`: add a `tsconfig.json` consisting solely of `{ "extends": "./tsconfig.base.json" }` (I have commented likewise on his link as well).
62,972,549
Im working an a project using Tkinter right now. Whenever I input 'Japan', it prints out: ``` [('Japan', '23,473', 0.0, 985.0, '3,392', '19,096')] ``` I'm not really sure if that's a list or if it's a tuple? I want to seperate all of that data thats seperated by the commas into different variables. Heres what I have so far. If you see any other holes in my code help would greatly be appreciated. Thanks! ``` def subby(): answer=country_name.get() l_answer = answer.capitalize() sql_command = "SELECT * FROM covid WHERE `name` = ?;" values = (l_answer,) cursor.execute(sql_command,values) data = cursor.fetchall() print (data) users0.set(data[0]) users1.set(data[1]) users2.set(data[2]) users3.set(data[3]) users4.set(data[4]) users5.set(data[5]) ```
2020/07/18
[ "https://Stackoverflow.com/questions/62972549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The 'problem' arises because of the change in tsconfig files (solutions style tsconfig) that comes with Typescript 3.9 and Angular 10. More info here : <https://github.com/microsoft/TypeScript/issues/39632> <https://docs.google.com/document/d/1eB6cGCG_2ircfS5GzpDC9dBgikeYYcMxghVH5sDESHw/edit#> **Solution style tsconfig impact in Angular 10** > > In TypeScript 3.9, the concept of solutions style tsconfig was > introduced, in Angular we saw the potentiation and possibility of > fixing long outstanding issues such as incorrectly having test typings > in components files. In Angular CLI version 10 we adopted scaffolded > new and migrated existing workspaces to use solution-style Typescript > configuration. > > > When having an unreferenced file, this will not be part of any > TypeScript program, this is because Angular CLI scaffolds tsconfig > using the files option as opposed to include and exclude. > > > 1. Unreferenced files don’t inherit compiler options > > > When having an unreferenced file, this will not be part of any TypeScript program > and Language service will fallback to use the inferred project configuration. > > > Below find an example of changes that will be required in the application > tsconfig file (tsconfig.app.json). Changes to other tsconfig files will also > be needed. > > > Current tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "files": [ > "src/main.ts", > "src/polyfills.ts" > ], > "include": [ > "src/**/*.d.ts" > ] > } > > ``` > > Proposed tsconfig.app.json > > > > ``` > { > "extends": "./tsconfig.base.json", > "compilerOptions": { > ... > }, > "include": [ > "src/**/*.ts" > ], > "exclude": [ > "src/test.ts", > "src/**/*.spec.ts", > "src/**/*.server*", > "src/**/*.worker.ts" > ] > } > > ``` > >
A comment at the end of the first post in @Wolf359's answer led me to a simple workaround, in the event that your issue is cause by the `tsconfig.json` being split into `tsconfig.base.json` and `tsconfig.app.json`: add a `tsconfig.json` consisting solely of `{ "extends": "./tsconfig.base.json" }` (I have commented likewise on his link as well).
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
[This paper](http://iopscience.iop.org/0004-637X/683/2/1207/fulltext/) (Batyrin and Laughlin, 2008) seems to indicate that we are doomed.
in a conference in Paris, Jacques Féjoz said (and i quote from memory) that the big planets seem to be stable, while the small ones chaotic. if i remember well, it was based on numerical evidence, intuition and the known results on the stability of the planar many-body problem...
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
[This paper](http://iopscience.iop.org/0004-637X/683/2/1207/fulltext/) (Batyrin and Laughlin, 2008) seems to indicate that we are doomed.
The work of Wisdom is relevant (for example, see <http://rspa.royalsocietypublishing.org/content/413/1844/109.short>) but not conclusive. Numerical work suggests overall stability over very long time periods.
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
Due to chaotic behaviour of the Solar System, it is not possible to precisely predict the evolution of the Solar System over 5 Gyr and the question of its long-term stability can only be answered in a statistical sense. For example, in <http://www.nature.com/nature/journal/v459/n7248/full/nature08096.html> (Existence of collisional trajectories of Mercury, Mars and Venus with the Earth, by J. Laskar and M. Gastineau) 2501 orbits with different initial conditions all consistent with our present knowledge of the parameters of the Solar System were traced out in computer simulations up to 5 Gyr. The main finding of the paper is that one percent of the solutions lead to a large enough increase in Mercury's eccentricity to allow its collisions with Venus or the Sun. Probably the most surprising result of the paper (see also <http://arxiv.org/abs/1209.5996>) is that in a pure Newtonian world the probability of collisions within 5 Gyr grows to 60 percent and therefore general relativity is crucial for long-term stability of the inner solar system. Many questions remain, however, about reliability of the present day consensus that the odds for the catastrophic destabilization of the inner planets are in the order of a few percent. I do not know if the effects of galactic tidal perturbations or possible perturbations from passing stars are taken into account. Also different numerical algorithms lead to statistically different results (see, for example, <http://arxiv.org/abs/1506.07602>). Some interesting historical background of solar system stability studies can be found in <http://arxiv.org/abs/1411.4930> (Michel Henon and the Stability of the Solar System, by Jacques Laskar).
[This paper](http://iopscience.iop.org/0004-637X/683/2/1207/fulltext/) (Batyrin and Laughlin, 2008) seems to indicate that we are doomed.
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
Due to chaotic behaviour of the Solar System, it is not possible to precisely predict the evolution of the Solar System over 5 Gyr and the question of its long-term stability can only be answered in a statistical sense. For example, in <http://www.nature.com/nature/journal/v459/n7248/full/nature08096.html> (Existence of collisional trajectories of Mercury, Mars and Venus with the Earth, by J. Laskar and M. Gastineau) 2501 orbits with different initial conditions all consistent with our present knowledge of the parameters of the Solar System were traced out in computer simulations up to 5 Gyr. The main finding of the paper is that one percent of the solutions lead to a large enough increase in Mercury's eccentricity to allow its collisions with Venus or the Sun. Probably the most surprising result of the paper (see also <http://arxiv.org/abs/1209.5996>) is that in a pure Newtonian world the probability of collisions within 5 Gyr grows to 60 percent and therefore general relativity is crucial for long-term stability of the inner solar system. Many questions remain, however, about reliability of the present day consensus that the odds for the catastrophic destabilization of the inner planets are in the order of a few percent. I do not know if the effects of galactic tidal perturbations or possible perturbations from passing stars are taken into account. Also different numerical algorithms lead to statistically different results (see, for example, <http://arxiv.org/abs/1506.07602>). Some interesting historical background of solar system stability studies can be found in <http://arxiv.org/abs/1411.4930> (Michel Henon and the Stability of the Solar System, by Jacques Laskar).
in a conference in Paris, Jacques Féjoz said (and i quote from memory) that the big planets seem to be stable, while the small ones chaotic. if i remember well, it was based on numerical evidence, intuition and the known results on the stability of the planar many-body problem...
210,779
> > **Is the Solar System stable?** > > > You can see [this](https://en.wikipedia.org/wiki/Stability_of_the_Solar_System) Wikipedia page. In May 2015 I was at the conference of Cedric Villani at Sharif university of technology with this title: "Of planets, stars and eternity (stabilization and long-time behavior in classical celestial mechanics)" , at the end of this conference one of the students asked him this question and he laughed strangely(!) with no convincing answer! **Edit**: The purpose of "long-time" is timescale more than [Lyapunov time](https://en.wikipedia.org/wiki/Lyapunov_time), hence billions of years.
2015/07/04
[ "https://mathoverflow.net/questions/210779", "https://mathoverflow.net", "https://mathoverflow.net/users/-1/" ]
Due to chaotic behaviour of the Solar System, it is not possible to precisely predict the evolution of the Solar System over 5 Gyr and the question of its long-term stability can only be answered in a statistical sense. For example, in <http://www.nature.com/nature/journal/v459/n7248/full/nature08096.html> (Existence of collisional trajectories of Mercury, Mars and Venus with the Earth, by J. Laskar and M. Gastineau) 2501 orbits with different initial conditions all consistent with our present knowledge of the parameters of the Solar System were traced out in computer simulations up to 5 Gyr. The main finding of the paper is that one percent of the solutions lead to a large enough increase in Mercury's eccentricity to allow its collisions with Venus or the Sun. Probably the most surprising result of the paper (see also <http://arxiv.org/abs/1209.5996>) is that in a pure Newtonian world the probability of collisions within 5 Gyr grows to 60 percent and therefore general relativity is crucial for long-term stability of the inner solar system. Many questions remain, however, about reliability of the present day consensus that the odds for the catastrophic destabilization of the inner planets are in the order of a few percent. I do not know if the effects of galactic tidal perturbations or possible perturbations from passing stars are taken into account. Also different numerical algorithms lead to statistically different results (see, for example, <http://arxiv.org/abs/1506.07602>). Some interesting historical background of solar system stability studies can be found in <http://arxiv.org/abs/1411.4930> (Michel Henon and the Stability of the Solar System, by Jacques Laskar).
The work of Wisdom is relevant (for example, see <http://rspa.royalsocietypublishing.org/content/413/1844/109.short>) but not conclusive. Numerical work suggests overall stability over very long time periods.
71,301,486
I am scraping and modifying content from a website. The website consists of broken images that I need to fix. My JSON looks something like this ``` [ { "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"brokenURL1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"brokenURL2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"brokenURL3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"brokenURL4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"brokenURL5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"brokenURL6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"brokenURL7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"brokenURL8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"brokenURL9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"brokenURL10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"brokenURL11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] ``` I have the image links and I want to replace every instance of the src link with the a href link. So the end result would look something like this. ``` [ { "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"url1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"url2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"url3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"url4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"url5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"url6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"url7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"url8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"url9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"url10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"url11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] ``` I also have random links that are not associated with images and are just links like in post 1, 2 and 4. Is there any way to do this with Javascript? Thanks
2022/02/28
[ "https://Stackoverflow.com/questions/71301486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17074732/" ]
Consider using the [`DOMParser`](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser) utility to create a document from your html string. Then you can use the typical DOM methods (notably, `querySelectorAll`) to find the relevant elements and then to execute your replacement. Eg, something like: ``` const parser = new DOMParser(); const doc = parser.parseFromString(html_string_here, "text/html") doc.querySelectorAll("a > img").forEach(img => img.setAttribute("src", img.parentElement.getAttribute("href"))) ``` Using your example data, you might write it like so: ```js const example_data = [{ "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"brokenURL1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"brokenURL2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"brokenURL3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"brokenURL4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"brokenURL5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"brokenURL6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"brokenURL7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"brokenURL8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"brokenURL9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"brokenURL10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"brokenURL11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ] const parser = new DOMParser(); const fixed_links_data = example_data.map(item => { return { ...item, post_content: item.post_content.map(html => { const doc = parser.parseFromString(html, "text/html"); doc.querySelectorAll("a > img").forEach(img => img.setAttribute("src", img.parentElement.getAttribute("href"))); return doc.body.innerHTML; }), } }); console.log("Final Result:", fixed_links_data) ```
```js var arr = [ { "post_title": "post 1", "post_link": "link 1", "post_date": "@1550725200", "post_content": [ "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna <a href=\"somelink.com\">aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<a href=\"url1.jpg\"><img src=\"brokenURL1.jpg\" alt=\"\"></a><a href=\"url2.jpg\"><img src=\"brokenURL2.jpg\" alt=\"\"></a><a href=\"url3.jpg\"><img src=\"brokenURL3.jpg\" alt=\"\"></a><a href=\"url4.jpg\"><img src=\"brokenURL4.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 2", "post_link": "link 2", "post_date": "@1550725200", "post_content": [ "<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, <a href=\"somelink.com\">similique</a> sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.<a href=\"url5.jpg\"><img src=\"brokenURL5.jpg\" alt=\"\"></a><a href=\"url6.jpg\"><img src=\"brokenURL6.jpg\" alt=\"\"></a><a href=\"url7.jpg\"><img src=\"brokenURL7.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 3", "post_link": "link 3", "post_date": "@1550725200", "post_content": [ "<p>Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. <a href=\"url8.jpg\"><img src=\"brokenURL8.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } }, { "post_title": "post 4", "post_link": "link 4", "post_date": "@1550725200", "post_content": [ "<p>Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis <a href=\"somelink.com\">doloribus asperiores repellat</a>.<a href=\"url9.jpg\"><img src=\"brokenURL9.jpg\" alt=\"\"></a><a href=\"url10.jpg\"><img src=\"brokenURL10.jpg\" alt=\"\"></a><a href=\"url11.jpg\"><img src=\"brokenURL11.jpg\" alt=\"\"></a></p>" ], "custom": { "image": "thumbnail.jpg" } } ]; arr.forEach(function(item) { item.post_content[0] = item.post_content[0].replace(/(<img src=")([^]+?)(\d.jpg)/g, '$1url$3'); }); ``` or use <https://www.npmjs.com/package/cheerio> deal with
618,483
I am using the `amsmath` package. My code is ``` \begin{center} \left $\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}$ \end{center} \begin{center} \right $\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}$ \end{center} ``` Thanks for any help!
2021/10/10
[ "https://tex.stackexchange.com/questions/618483", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/254367/" ]
* Please, always provide complete small document called MWE (Minimal Working Example) which reproduce your problem. * your question is not entirely clear, so I guess, that you after the following: [![enter image description here](https://i.stack.imgur.com/V6mKz.png)](https://i.stack.imgur.com/V6mKz.png) MWE: ``` \documentclass{article} \usepackage{amsmath} \begin{document} \[ \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}% \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix} \] \end{document} ``` Comparison of above code with your code fragment shows, that it contain a lot of clutter: `\left`, `right`, `\begin{center} ... \end{center}`. In above MWE used symbols `\[` and `\]` switch from "text mode" to "math mode". They are equivalent to `\begin{equation*}` and `\end{equation*}` respectively.
I have created a minimal working example (with a comma between the two matrices) to have **the matrices on the same line in LaTeX.** However I would to use a small matrix when you use `$...$`. ``` \documentclass[a4paper,12pt]{article} \usepackage{amsmath,amssymb} \begin{document} Some $\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}, \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}$ test after two matrices. \[\begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}, \quad \begin{bmatrix} u_1 & u_2\\ u_3 & u_4 \end{bmatrix}\] \end{document} ``` [![enter image description here](https://i.stack.imgur.com/61zAU.png)](https://i.stack.imgur.com/61zAU.png) Using `bsmallmatrix` enviroment with `mathtools` package. ``` \documentclass[a4paper,12pt]{article} \usepackage{mathtools}% for "bsmallmatrix" environment \usepackage{amssymb} \begin{document} Some $\begin{bsmallmatrix} u_1 & u_2\\ u_3 & u_4 \end{bsmallmatrix},\begin{bsmallmatrix} u_1 & u_2\\ u_3 & u_4 \end{bsmallmatrix}$ test after two matrices. \end{document} ``` [![enter image description here](https://i.stack.imgur.com/yZj6y.png)](https://i.stack.imgur.com/yZj6y.png)
302,744
When using the Book module, is there any limit on the number of child items that can be added to a book parent node?
2021/04/28
[ "https://drupal.stackexchange.com/questions/302744", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/98004/" ]
Yes, books in Drupal 8 and 9 have a maximum depth of 9, which is the value of the [`BookManager::BOOK_MAX_DEPTH`](https://api.drupal.org/api/drupal/core%21modules%21book%21src%21BookManager.php/constant/BookManager%3A%3ABOOK_MAX_DEPTH/8.8.x) constant. ```php const BOOK_MAX_DEPTH = 9; ```
If your question isn't about the hierarchy levels but the number of nodes that can be added in any level here's a question and answer with a lot more information: [How to increase book weight range for a same-level chapters](https://drupal.stackexchange.com/questions/272952/how-to-increase-book-weight-range-for-a-same-level-chapters) You can recreate the Book features with Entity reference fields if this is a very serious limitation for you.
19,800,821
Before I debug my code, I would like to know why there's an error occurred when I call the function? It says "NameError: name 'stDigs' is not defined". I've tried using "avgUntilLetter(0123a)" and "avgUntilLetter("0123a")" but none of them works. Help me plz! This function receives as input one string containing digits or letters. The function should return one float number contaning the average calculated considering all the digits in the string starting form the first position and considerign all digits until one letter is found or until reaching the end of the string. An example: avgUntilLetter('0123a456') should return 1.5 ``` def avgUntilLetter (stDigs): num = 0 each_char = stDigs[num] while each_char.isdigit() == True and num < len(stDigs): num = num + 1 each_char = stDigs[num] digits = stDigs[0:num] avg = sum(digits)/len(digits) return avg avgUntilLetter(stDigs) ``` --- Yes, I know there are a lot errors needed to be solved. I just need to solve it one at a time. When I call the function using "avgUntilLetter ("0123a")", the defined error disappeared but a type error popped up. Hmm.. I'm still keeping trying it.
2013/11/05
[ "https://Stackoverflow.com/questions/19800821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2958352/" ]
There are several problems in your code: 1. You can end up trying to access `stDigs[len(stDigs)]` because `num < len(stDigs)` might be true, but you then add 1 before using it as an index. 2. `sum(digits)` won't work because `digits` is a string. Just loop over the string *directly* instead of using a `while` loop, add up the digits in the loop: ``` def avgUntilLetter(stDigs): total = i = 0 for i, each_char in enumerate(stDigs): if not each_char.isdigit(): break total += float(each_char) if i: return total / i return 0.0 ``` This handles edge-cases as well: ``` >>> avgUntilLetter('0123a456') 1.5 >>> avgUntilLetter('') 0.0 >>> avgUntilLetter('abc') 0.0 ```
The `TypeError` comes from this line: ``` avg = sum(digits)/len(digits) ``` because the one before it makes `digits` a string. And, you can't use `sum` on strings. You can fix your code by changing the above line to: ``` # `avg = float(sum(map(int, digits)))/len(digits)` if you are on Python 2.x avg = sum(map(int, digits))/len(digits) ``` --- However, you can do this job a lot easier and more efficiently with a [list comprehension](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) and [`itertools.takewhile`](http://docs.python.org/2/library/itertools.html#itertools.takewhile): ``` >>> from itertools import takewhile >>> def avgUntilLetter(stDigs): ... digits = [int(x) for x in takewhile(str.isdigit, stDigs)] ... return sum(digits)/len(digits) if digits else 0.0 ... >>> avgUntilLetter('0123a456') 1.5 >>> avgUntilLetter('123456789') 5 >>> avgUntilLetter('a1') 0.0 >>> avgUntilLetter('') 0.0 >>> ``` Note that the above code is for Python 3.x. To convert it to Python 2.x., change the return-statement to this: ``` return float(sum(digits))/len(digits) if digits else 0.0 ``` You need `float` in there because of how Python 2.x handles division.
19,800,821
Before I debug my code, I would like to know why there's an error occurred when I call the function? It says "NameError: name 'stDigs' is not defined". I've tried using "avgUntilLetter(0123a)" and "avgUntilLetter("0123a")" but none of them works. Help me plz! This function receives as input one string containing digits or letters. The function should return one float number contaning the average calculated considering all the digits in the string starting form the first position and considerign all digits until one letter is found or until reaching the end of the string. An example: avgUntilLetter('0123a456') should return 1.5 ``` def avgUntilLetter (stDigs): num = 0 each_char = stDigs[num] while each_char.isdigit() == True and num < len(stDigs): num = num + 1 each_char = stDigs[num] digits = stDigs[0:num] avg = sum(digits)/len(digits) return avg avgUntilLetter(stDigs) ``` --- Yes, I know there are a lot errors needed to be solved. I just need to solve it one at a time. When I call the function using "avgUntilLetter ("0123a")", the defined error disappeared but a type error popped up. Hmm.. I'm still keeping trying it.
2013/11/05
[ "https://Stackoverflow.com/questions/19800821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2958352/" ]
There are several problems in your code: 1. You can end up trying to access `stDigs[len(stDigs)]` because `num < len(stDigs)` might be true, but you then add 1 before using it as an index. 2. `sum(digits)` won't work because `digits` is a string. Just loop over the string *directly* instead of using a `while` loop, add up the digits in the loop: ``` def avgUntilLetter(stDigs): total = i = 0 for i, each_char in enumerate(stDigs): if not each_char.isdigit(): break total += float(each_char) if i: return total / i return 0.0 ``` This handles edge-cases as well: ``` >>> avgUntilLetter('0123a456') 1.5 >>> avgUntilLetter('') 0.0 >>> avgUntilLetter('abc') 0.0 ```
`stDigs` is not assigned to any value. ``` avgUntilLetter([]) stDigs = [] avgUntilLetter(stDigs) ``` In you case, it's a string, jsut set `stDigs` to a string first. ``` stDigs = "" avgUntilLetter(stDigs) ```
532,311
Say I have 2 continuous variables (x & y) in a logit model. I want to test the following hypotheses in the model: 1. For low values of x, increasing the value of y will increase the value of the response variable 2. For high values of x, increasing the value of y will decrease the value of the response variable Is there a way to specify this using interaction terms? I have only used interaction terms in which y has a linear impact on the effect of x on the response variable.
2021/06/26
[ "https://stats.stackexchange.com/questions/532311", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/223309/" ]
In my comment I wrote that you could model the kind of nonlinearity you describe with a model such as the below model, which incorporates a "multiplicative interaction term." $$\text{logit}({y\_i}) = \beta\_0 + \beta\_{x}x\_{i} + \beta\_{z}z\_{i} + \beta\_{xz}xz\_{i} + \varepsilon\_{i}$$ Consider such a model where: * $y\_i$ is the value of the dependent (response) variable for the $i^{\text{th}}$ subject, * $x\_i$ is the value of the independent variable $x$ for the $i^{\text{th}}$ subject, * $z\_i$ is the value of the independent variable $z$ for the $i^{\text{th}}$ subject, * $xz\_{i}$ is the value of the product of $x$ and $z$ for the $i^{\text{th}}$ subject, and * $\varepsilon\_i$ is the value of the model residual for the $i^{\text{th}}$ subject. Let's assume that $x$ and $y$ are continuous variables, but that $z$ is a nominal ($0/1$) variable. If $z=0$ then $\beta\_{z}z\_{i}=0$ and $\beta\_{z}xz\_{i}=0$, and the above model reduces to a simple bivariate logit regression of $y$ onto $x$, where $\beta\_0$ is the $y$ intercept, and $\beta\_{x}$ is how much the log-odds of $y$ changes given a 1-unit increase in $x$. However, if $z\_{i}=1$, then the $y$ intercept becomes $\beta\_0 + \beta\_{z}z\_{i}$ or $\beta\_0 + \beta\_{z}$ (since $z=1$). (Right? Because if $z\_{i}=1$ then you add $\beta\_{z}$, which is a scalar constant, to $\beta\_{0}$: another scalar constant.) Similarly, the effect on the log-odds of $y$ of a 1-unit increase of $x$ becomes $\beta\_{x} + \beta\_{xz}$. (Right? Because if $z =1$, then $\beta\_{xz}xz\_{i} = \beta\_{xz}x\_{i}$, so when $x$ increases by 1-unit, the log-odds of $y$ changes by $\beta\_{x}$, but also by $\beta\_{xz}$.) Application of this kind of mutiplicative interaction model is not limited to $z$ being nominal, however: $z$ can be continuous as well, in which case you simply need to plug the the specific value of $z$ to understand the effect of $x$ on the log-odds of $y$ and vice versa. **With multiplicative interactions neither the effect of $\boldsymbol{x}$ nor the effect of $\boldsymbol{z}$ on $\boldsymbol{y}$ can be understood independently of one another.** **Example** In the below graph we see two logistic curves of $y$ as modeled on $z$, the black one for values of $x = 0.1$ (i.e. "low"), and the red one for values of $x = 0.9$ (i.e. "high"). When $x$ is low the effect of $z$ on the log odds of $y$ is positive (i.e. as $z$ increases, the log odds of $y$ increases). When $x$ is high the effect of $z$ on the log odds of $y$ is negative (i.e. as $z$ increases, the log odds of $y$ decreases). This speaks precisely to your original question. The numerical specification of this relationship is: $$\text{logit}({y\_i}) = 1.25x\_{i} + 2z\_{i} - 3.75xz\_{i}$$ Notice that by substituting $x\_i = 0.1$, the (black line) model simplifies to one where the effect of $z$ is *positive*: $$\begin{align\*}\text{logit}({y\_i}) & = 1.25\times 0.1 + 2z\_{i} - 3.75\times 0.1 \times z\_{i}\\ & = 0.125 + 2z\_{i} - 0.375z\_{i}\\ & = 0.125 + 1.625z\_{i}\end{align\*}$$ And notice that by substituting $x\_i = 0.9$, the (red line) model simplifies to one where the effect of $z$ is *negative*: $$\begin{align\*}\text{logit}({y\_i}) & = 1.25 \times 0.9 + 2z\_{i} - 3.75 \times 0.9 \times z\_{i}\\ & = 1.125 + 2z\_{i} - 3.375z\_{i}\\ & = 1.125 - 1.375z\_{i}\end{align\*}$$ [![Graph of Y vs Z when X is low (black) and high (red)](https://i.stack.imgur.com/yXU9u.png)](https://i.stack.imgur.com/yXU9u.png)
It seems to me that you want: 1. A two-way interaction, $XZ$, between $X$ and $Z$. This will estimate the expected change in the response for a 1 unit change in $X$, when $Z$ also changes by 1 unit. 2. If you want this two-way interaction also to also vary with $X$ then you can interact the two-way interaction with $X$, which will be $X^2Z$. This 3-way interaction will estimate the expected change in the response for a 1 unit change in $X$ when the interaction $XZ$ also changes by 1 unit.
532,311
Say I have 2 continuous variables (x & y) in a logit model. I want to test the following hypotheses in the model: 1. For low values of x, increasing the value of y will increase the value of the response variable 2. For high values of x, increasing the value of y will decrease the value of the response variable Is there a way to specify this using interaction terms? I have only used interaction terms in which y has a linear impact on the effect of x on the response variable.
2021/06/26
[ "https://stats.stackexchange.com/questions/532311", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/223309/" ]
In my comment I wrote that you could model the kind of nonlinearity you describe with a model such as the below model, which incorporates a "multiplicative interaction term." $$\text{logit}({y\_i}) = \beta\_0 + \beta\_{x}x\_{i} + \beta\_{z}z\_{i} + \beta\_{xz}xz\_{i} + \varepsilon\_{i}$$ Consider such a model where: * $y\_i$ is the value of the dependent (response) variable for the $i^{\text{th}}$ subject, * $x\_i$ is the value of the independent variable $x$ for the $i^{\text{th}}$ subject, * $z\_i$ is the value of the independent variable $z$ for the $i^{\text{th}}$ subject, * $xz\_{i}$ is the value of the product of $x$ and $z$ for the $i^{\text{th}}$ subject, and * $\varepsilon\_i$ is the value of the model residual for the $i^{\text{th}}$ subject. Let's assume that $x$ and $y$ are continuous variables, but that $z$ is a nominal ($0/1$) variable. If $z=0$ then $\beta\_{z}z\_{i}=0$ and $\beta\_{z}xz\_{i}=0$, and the above model reduces to a simple bivariate logit regression of $y$ onto $x$, where $\beta\_0$ is the $y$ intercept, and $\beta\_{x}$ is how much the log-odds of $y$ changes given a 1-unit increase in $x$. However, if $z\_{i}=1$, then the $y$ intercept becomes $\beta\_0 + \beta\_{z}z\_{i}$ or $\beta\_0 + \beta\_{z}$ (since $z=1$). (Right? Because if $z\_{i}=1$ then you add $\beta\_{z}$, which is a scalar constant, to $\beta\_{0}$: another scalar constant.) Similarly, the effect on the log-odds of $y$ of a 1-unit increase of $x$ becomes $\beta\_{x} + \beta\_{xz}$. (Right? Because if $z =1$, then $\beta\_{xz}xz\_{i} = \beta\_{xz}x\_{i}$, so when $x$ increases by 1-unit, the log-odds of $y$ changes by $\beta\_{x}$, but also by $\beta\_{xz}$.) Application of this kind of mutiplicative interaction model is not limited to $z$ being nominal, however: $z$ can be continuous as well, in which case you simply need to plug the the specific value of $z$ to understand the effect of $x$ on the log-odds of $y$ and vice versa. **With multiplicative interactions neither the effect of $\boldsymbol{x}$ nor the effect of $\boldsymbol{z}$ on $\boldsymbol{y}$ can be understood independently of one another.** **Example** In the below graph we see two logistic curves of $y$ as modeled on $z$, the black one for values of $x = 0.1$ (i.e. "low"), and the red one for values of $x = 0.9$ (i.e. "high"). When $x$ is low the effect of $z$ on the log odds of $y$ is positive (i.e. as $z$ increases, the log odds of $y$ increases). When $x$ is high the effect of $z$ on the log odds of $y$ is negative (i.e. as $z$ increases, the log odds of $y$ decreases). This speaks precisely to your original question. The numerical specification of this relationship is: $$\text{logit}({y\_i}) = 1.25x\_{i} + 2z\_{i} - 3.75xz\_{i}$$ Notice that by substituting $x\_i = 0.1$, the (black line) model simplifies to one where the effect of $z$ is *positive*: $$\begin{align\*}\text{logit}({y\_i}) & = 1.25\times 0.1 + 2z\_{i} - 3.75\times 0.1 \times z\_{i}\\ & = 0.125 + 2z\_{i} - 0.375z\_{i}\\ & = 0.125 + 1.625z\_{i}\end{align\*}$$ And notice that by substituting $x\_i = 0.9$, the (red line) model simplifies to one where the effect of $z$ is *negative*: $$\begin{align\*}\text{logit}({y\_i}) & = 1.25 \times 0.9 + 2z\_{i} - 3.75 \times 0.9 \times z\_{i}\\ & = 1.125 + 2z\_{i} - 3.375z\_{i}\\ & = 1.125 - 1.375z\_{i}\end{align\*}$$ [![Graph of Y vs Z when X is low (black) and high (red)](https://i.stack.imgur.com/yXU9u.png)](https://i.stack.imgur.com/yXU9u.png)
X1 = I(x>a) X2= I (x<b) Logit (Response ) = beta0 + betax \* x + betay \* x + betax1y \* X1 \* y + betax2y \* X2 \* y Then X1*y is activated when x is above a, X2* y when x is below b. You can exclude betay*y if you think that response is only through y*x terms. A and b are exogenous parameters in this model, so either outside knowledge or additional testing on which fit best is needed.
532,311
Say I have 2 continuous variables (x & y) in a logit model. I want to test the following hypotheses in the model: 1. For low values of x, increasing the value of y will increase the value of the response variable 2. For high values of x, increasing the value of y will decrease the value of the response variable Is there a way to specify this using interaction terms? I have only used interaction terms in which y has a linear impact on the effect of x on the response variable.
2021/06/26
[ "https://stats.stackexchange.com/questions/532311", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/223309/" ]
It seems to me that you want: 1. A two-way interaction, $XZ$, between $X$ and $Z$. This will estimate the expected change in the response for a 1 unit change in $X$, when $Z$ also changes by 1 unit. 2. If you want this two-way interaction also to also vary with $X$ then you can interact the two-way interaction with $X$, which will be $X^2Z$. This 3-way interaction will estimate the expected change in the response for a 1 unit change in $X$ when the interaction $XZ$ also changes by 1 unit.
X1 = I(x>a) X2= I (x<b) Logit (Response ) = beta0 + betax \* x + betay \* x + betax1y \* X1 \* y + betax2y \* X2 \* y Then X1*y is activated when x is above a, X2* y when x is below b. You can exclude betay*y if you think that response is only through y*x terms. A and b are exogenous parameters in this model, so either outside knowledge or additional testing on which fit best is needed.
64,526,055
I am currently setting up a project that is based on Python Flask (with Flask Migrate) with a PostgreSQL DB. I am working in a small team and have some questions regarding database updates. As far as I am aware, If I update the database schema in Flask, I will have to perform a `flask db migrate` and `flask db upgrade` to apply the changes. And others that receives my update executes a `flask db upgrade` to receive the schema changes. All is well but if I have updated rows in the database, how do I propagate the schema changes and data changes to my peers? If I `migrate and upgrade` my flask database followed by exporting a dump with `psql`, when my peers receive the updates, do they simply import the data dump? Or do they have to perform a `flask db upgrade` as well? If so, which one comes first? `flask db upgrade` followed by dump import, or dump import followed by a `flask db upgrade`? I am not sure if simply importing the data dump with updated schema will mess up the migration commits in Flask Migrate. Not sure if this is the right place to ask but I hope I am able to find some answers here. Thanks in advance! Edit: So far I am updating data in the database by dropping the database and recreating it with the dump, but I have yet to try it with any schema changes (project is progressing, a little slowly..) Edit 2: Forgot to mention that all instances of PostgreSQL are hosted locally on our own machines
2020/10/25
[ "https://Stackoverflow.com/questions/64526055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10448741/" ]
To understand your error, you have to know what strings are. Strings in java are arrays of char: ``` char[] example = {'H', 'E', 'L', 'L', 'O'); ``` You can manipulate strings in a similar why to arrays. Arrays first index is 0 and max Index length - 1 Let now assume the above example is an instance of String and you do: ``` example.subString (0, 3) // Return value would be "HEL". example.subString (0, 10) // StringIndexOutOfBoundsException ``` To prevent this, you have to use whats ever come first. Your cap at 17 or the cap defined by the length of the string. ``` example.subString (0, Math.min(17, example.length())); ``` While there is no built in function in Thymeleaf, you can use the special T(...) operator to call static methods (allowing you to use Java's Math.max(...) in your Thymeleaf). ``` <div th:with="maxNumber=${T(Math).min(8,12)}"> <p th:text=${maxNumber}></p> </div> ``` --- As mentioned in the comments, there is a more Thymeleaf special method to approach your goal: [I want to abbreviate a string with Thymeleaf](https://stackoverflow.com/questions/49897473/i-want-to-abbreviate-a-string-with-thymeleaf)
You can also use a condition to take care of out of bounds e.g. ``` <span th:if="${post.content.length()>17}"> <span th:utext="${#strings.substring(post.content,0,17)}"></span> </span> <span th:if="${post.content.length()<17}"> <span th:utext="${#strings.substring(post.content,0,post.content.length())}"></span> </span> ```
13,956,983
Here is the website I'm working on: I can get the image not to stretch by removing height: 481px; but then I lose the caption and squares below the image and it moves around if the images are different heights. I've tried messing around with positioning, but I haven't found a solution.
2012/12/19
[ "https://Stackoverflow.com/questions/13956983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/753250/" ]
There are several ways you can solve this. A cleaner solution, as @Sven pointed out, would be to use the tag `<div>` instead of `<img>` and use the images as `background` for the div. Or, you can use the CCS clip property to crop all your images to the same size, while maintaining their original proportions: ``` img {clip:rect(0px,60px,200px,0px)} ``` *(check this link for documentation on clip:* <http://www.w3schools.com/cssref/pr_pos_clip.asp>*)* The fastest solution for you at this point however (the one that needs less changes on your actual code) might be to use the absolute positioning, only, instead applying it to the div `.text-box` apply it to his parent `.slider-cont-wrapper`.: ``` .slider-cont-wrapper {position:absolute; top:100px; right:100px} ``` *(change `top:` and `right:` to measures that suit your layout)*
Well, if images don't have the same proportion, no matter what you do, you'll never get different image sizes fit perfectly in the same spot. so, what do you want?
58,979
I'm looking at a [bike for sale](https://www.likessale.com/index.php?route=product/product&product_id=1&path=1_2) on Likessale. It seems way too good to be true, based on a [Google search](https://www.google.com/search?rlz=1C1CHBF_enUS713US714&biw=1920&bih=969&tbm=shop&ei=yu1EXKutG4bI_QaqyYSQBA&q=Diamond%20Release%205%20C&oq=Diamond%20Release%205%20C&gs_l=psy-ab.3...5260.6700.0.7517.8.7.0.0.0.0.186.594.2j3.5.0....0...1c.1.64.psy-ab..4.1.104...0i13k1.0.AfXZDxKv7aQ#spd=13111342335810783757) for prices for the same bike. Has anyone bought a bike here or can verify whether or not this is a scam? I looked up [likessale.com on WHOIS](https://whois.icann.org/en/lookup?name=likessale.com), and it appeared to be registered only a week ago. It seems fishy that there are reviews from before that.
2019/01/20
[ "https://bicycles.stackexchange.com/questions/58979", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/40943/" ]
I'm confident to call it a scam. The same bike is on Amazon for $2162 to $3856 USD. [https://www.amazon.com/Diamondback-Bicycles-Podium-Vitesse-Carbon/dp/B01HHQ1BWA/ref=pd\_lpo\_sbs\_200\_t\_1](https://rads.stackoverflow.com/amzn/click/B01HHQ1BWA) Manufacturer gives it a MSRP of $3700 USD. To expect to pay 5% of that price is **MASSIVELY suspicious**. --- Also notice the site lists MTB-style frame sizes (Small-15.5/Medium-17/Large-19/XL-21), where the bike is built in metric sizes (XS 50; S 52; M 54; L 56; XL 58cm) --- I see the word "diamondback" never appears on the remote web site at all in text - it only appears on the bike photos which appear to be lifted from standard advertising materials. **TL;DR** Yes its a scam. Send your money at your risk. If you ever do get a bike delivered, it will be an inferior knockoff product. Just don't.
Don't give money to likesale.com. I made a purchase on 18 January 2019 and I should've done some research before. I also wondered how they could have reviews posted from september when the site is only a week old. I've emailed the website and even sent an email to the owner email address provided through the domain info. Haven't received any info, and will post any new info I find out. I'm pissed and have to decided to spend some time giving this particular scam as much hell as I can.
58,979
I'm looking at a [bike for sale](https://www.likessale.com/index.php?route=product/product&product_id=1&path=1_2) on Likessale. It seems way too good to be true, based on a [Google search](https://www.google.com/search?rlz=1C1CHBF_enUS713US714&biw=1920&bih=969&tbm=shop&ei=yu1EXKutG4bI_QaqyYSQBA&q=Diamond%20Release%205%20C&oq=Diamond%20Release%205%20C&gs_l=psy-ab.3...5260.6700.0.7517.8.7.0.0.0.0.186.594.2j3.5.0....0...1c.1.64.psy-ab..4.1.104...0i13k1.0.AfXZDxKv7aQ#spd=13111342335810783757) for prices for the same bike. Has anyone bought a bike here or can verify whether or not this is a scam? I looked up [likessale.com on WHOIS](https://whois.icann.org/en/lookup?name=likessale.com), and it appeared to be registered only a week ago. It seems fishy that there are reviews from before that.
2019/01/20
[ "https://bicycles.stackexchange.com/questions/58979", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/40943/" ]
I'm confident to call it a scam. The same bike is on Amazon for $2162 to $3856 USD. [https://www.amazon.com/Diamondback-Bicycles-Podium-Vitesse-Carbon/dp/B01HHQ1BWA/ref=pd\_lpo\_sbs\_200\_t\_1](https://rads.stackoverflow.com/amzn/click/B01HHQ1BWA) Manufacturer gives it a MSRP of $3700 USD. To expect to pay 5% of that price is **MASSIVELY suspicious**. --- Also notice the site lists MTB-style frame sizes (Small-15.5/Medium-17/Large-19/XL-21), where the bike is built in metric sizes (XS 50; S 52; M 54; L 56; XL 58cm) --- I see the word "diamondback" never appears on the remote web site at all in text - it only appears on the bike photos which appear to be lifted from standard advertising materials. **TL;DR** Yes its a scam. Send your money at your risk. If you ever do get a bike delivered, it will be an inferior knockoff product. Just don't.
I also made an online purchase two weeks ago and I've not received the product or shipping information to track the delivery. I've not received replies to my emails and I don't have telephone numbers. If somebody knows what I can do, please tell me. --- This post was originally made in Spanish, as follows. Yo tambien he realizado una compra en linea hace dos semanas atras y no he recibido ni el producto, ni la cadena de envoi para rastreo del producto ni mucho menos recibo mensajes de contestacion al correo que mencionan, no tienen numeros telefonicos, si alguien sabe que puedo hacer por favor hacermelo saber.
1,051,944
I have been using AWS SES for a year now for my SaaS. I added DKIM, SPF and DMARC. Yet some people are still not receiving emails. I provide instructions for them to add my domain to their safe senders list. That seems to resolve it. I would like to avoid end-users having to do that. I am wondering if using a dedicated IP would help to improve delivery. Anyone has experience with that?
2021/02/01
[ "https://serverfault.com/questions/1051944", "https://serverfault.com", "https://serverfault.com/users/615222/" ]
Yes, technically you can modify files in the underling volume, but Gluster will **not** be notified about your changes, and therefore they may not be replicated to other Gluster nodes. This is **very much not recommended**, and could mean that your servers end up with different underlying files, which can lead to unpredictable behaviour/data loss.
Once I have several files copied directly to the brick, is there any way to make Gluster be aware about those new files?
38,882,128
So here's what I'm trying to accomplish: I have a client facing page that loads, and when that happens I automatically run a series of 4 quick tests, if any of those tests fail I update the HCresults variable. .aspx ``` <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <script language="javascript" src="script/XmlHttp.js?vers=<%=VersionInfo %>" type="text/javascript"></script> <script src="client_scripts/JQuery/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> var HCresults = ""; </script> </asp:Content> ``` I want to access the value of HCresults after the page finishes loading from my code behind page. Is there a way to do this?
2016/08/10
[ "https://Stackoverflow.com/questions/38882128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993239/" ]
You can write a webmethod in your code behind; pseudo code: ``` public static var HCresultsCS; [webmethod] public static void grabHCresults(var HCresultsfromJS) { HCresultsCS= HCresultsfromJS; } ``` make an AJAX post to this webmethod with HCresults you're setting on a test failure as parameter; Access the HCresultsCS from CS now. Check for nulls! I can't comment This link might be helpful: <http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx>
Unfortunately not using JS, you can store the value in a `hiddenfield` however to retrieve in C#. Make sure that you set the attribute `runat = "server"` for the control. I should also mention you'll use `element.value = value` to assign the value.
20,671,989
I've just just recently begun to learn how to write Javascript, started a few weeks ago. Right now I'm working on making an interactive story. The way I've been planning on making the story is having the user answer a prompt question, and the answer to the prompt will trigger the next part of the story to be shown in a textbox. So as of now, I have my prompts down and the if/else statements that will reveal the answer. I can't figure out how to make the next part of the story show up in the textbox. The only thing I can really think of right now is using console.log, but that won't work quite right. Any suggestions on how to do this?
2013/12/19
[ "https://Stackoverflow.com/questions/20671989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3117439/" ]
Given that there is no code to reference, here's a mock-up example: ``` document.getElementById("myTextArea").value = prompt("Foo?"); ``` Assuming you would have a textarea like this ``` <textarea id="myTextArea"></textarea> ``` its text would then be set to whatever the user entered, for instance, ``` bar ``` [jsFiddle](http://jsfiddle.net/XuwUK/3/)
If all you're doing is putting story information in the `textarea` then you shouldn't be using it, just use a `div` instead and put the story text in there. Have the div initially set to `display: none` and once they get the question right, set it to `display: block` using JS!
22,926,466
I have a verry unusual problem, none of my static files are loaded `404` is thrown. To note, I use my production environment with `DEBUG=False` set so the static files are entirely served by the `nginx` server. > > settings/production.py > > > ``` STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') STATIC_URL = '/static/' DEBUG = TEMPLATE_DEBUG = False ``` > > nginx/sites-enabled/myapp > > > ``` server { listen 80; ## listen for ipv4; this line is default and implied server_name myapp.com; access_log /var/log/nginx/myapp.log; error_log /var/log/nginx/myapp.log; root /home/apps/myapp/; location / { gzip_static on; include uwsgi_params; uwsgi_pass 127.0.0.1:3031; } location /static/ { # STATIC_URL alias /home/apps/myapp/static/; # STATIC_ROOT expires 30d; } location /media/ { # MEDIA_URL alias /home/apps/myapp/media/; # MEDIA_ROOT expires 30d; } } ``` > > myapp.log > > > ``` 2014/04/08 04:20:11 [error] 22178#0: *590 open() "/home/apps/myapp/staticgrappelli/stylesheets/mueller/grid/output.css" failed (2: No such file or directory), client: 77.89.196.6, server: myapp.com, request: "GET /static/grappelli/stylesheets/mueller/grid/output.css HTTP/1.1", host: "myapp.com", referrer: "http://myapp.com/admin/" 77.89.196.6 - - [08/Apr/2014:04:20:11 +0200] "GET /static/grappelli/stylesheets/mueller/grid/output.css HTTP/1.1" 404 200 "http://myapp.com/admin/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36" ``` Please note that missing `/` between my static root `/home/apps/myapp/static` and application static files `grappelli/stylesheets/mueller/grid/output.css` in this example. Does anyone have a clue regarding why this happens and how to fix it? **UPDATE (SOLUTION)** OK, the problem is that `Django's` static files are served by default from `www.myapp.com/static/` folder so there is no reason specifying the `/static/` folder in the `nginx` configuration file. So if anyone else has the same problem, just remove the following part from `nginx/sites-enabled/myapp` file: ``` location /static/ { # STATIC_URL alias /home/apps/myapp/static/; # STATIC_ROOT expires 30d; } location /media/ { # MEDIA_URL alias /home/apps/myapp/media/; # MEDIA_ROOT expires 30d; } ```
2014/04/08
[ "https://Stackoverflow.com/questions/22926466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389448/" ]
OK, the problem is that `Django's` static files are served by default from `www.myapp.com/static/` folder so there is no reason specifying the `/static/` folder in the `nginx` configuration file. So if anyone else has the same problem, just remove the following part from `nginx/sites-enabled/myapp` file: ``` location /static/ { # STATIC_URL alias /home/apps/myapp/static/; # STATIC_ROOT expires 30d; } location /media/ { # MEDIA_URL alias /home/apps/myapp/media/; # MEDIA_ROOT expires 30d; } ```
Have you ran python manage.py collectstatic on your server? Make sure the file is in the static root directory.
53,835,266
I new in MXGraph usage (by javascript) and I'm trying to drag and drop an image (png) from toolbar. Starting from toolbar.html example I able to add a new icon in the toolbar but I don't how to add a custom image in the graph. Could anyone tell me how I can do it?
2018/12/18
[ "https://Stackoverflow.com/questions/53835266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6283217/" ]
Here is the code sample to add icons/images in sidebar and create drag and drop source. 1. Call function to set Image source and Labels/Html. ``` // Adds sidebar icons. // // NOTE: For non-HTML labels a simple string as the third argument // and the alternative style as shown in configureStylesheet should // be used. For example, the first call to addSidebar icon would // be as follows: // addSidebarIcon(graph, sidebar, 'Website', 'images/icons48/earth.png'); addSidebarIcon(graph, sidebar, '<h1 style="margin:0px;">Website</h1><br>'+ '<img src="images/icons48/earth.png" width="48" height="48">'+ '<br>'+ '<a href="http://www.jgraph.com" target="_blank">Browse</a>', 'images/icons48/earth.png'); addSidebarIcon(graph, sidebar, '<h1 style="margin:0px;">Process</h1><br>'+ '<img src="images/icons48/gear.png" width="48" height="48">'+ '<br><select><option>Value1</option><option>Value2</option></select><br>', 'images/icons48/gear.png'); addSidebarIcon(graph, sidebar, '<h1 style="margin:0px;">Keys</h1><br>'+ '<img src="images/icons48/keys.png" width="48" height="48">'+ '<br>'+ '<button onclick="mxUtils.alert(\'generate\');">Generate</button>', 'images/icons48/keys.png'); addSidebarIcon(graph, sidebar, '<h1 style="margin:0px;">New Mail</h1><br>'+ '<img src="images/icons48/mail_new.png" width="48" height="48">'+ '<br><input type="checkbox"/>CC Archive', 'images/icons48/mail_new.png'); addSidebarIcon(graph, sidebar, '<h1 style="margin:0px;">Server</h1><br>'+ '<img src="images/icons48/server.png" width="48" height="48">'+ '<br>'+ '<input type="text" size="12" value="127.0.0.1"/>', 'images/icons48/server.png'); ``` 2. Function to add images in side bar, drag and drop source ``` function addSidebarIcon(graph, sidebar, label, image) { // Function that is executed when the image is dropped on // the graph. The cell argument points to the cell under // the mousepointer if there is one. var funct = function(graph, evt, cell, x, y) { var parent = graph.getDefaultParent(); var model = graph.getModel(); var v1 = null; model.beginUpdate(); try { // NOTE: For non-HTML labels the image must be displayed via the style // rather than the label markup, so use 'image=' + image for the style. // as follows: v1 = graph.insertVertex(parent, null, label, // pt.x, pt.y, 120, 120, 'image=' + image); v1 = graph.insertVertex(parent, null, label, x, y, 120, 120); v1.setConnectable(false); // Presets the collapsed size v1.geometry.alternateBounds = new mxRectangle(0, 0, 120, 40); // Adds the ports at various relative locations var port = graph.insertVertex(v1, null, 'Trigger', 0, 0.25, 16, 16, 'port;image=editors/images/overlays/flash.png;align=right;imageAlign=right;spacingRight=18', true); port.geometry.offset = new mxPoint(-6, -8); var port = graph.insertVertex(v1, null, 'Input', 0, 0.75, 16, 16, 'port;image=editors/images/overlays/check.png;align=right;imageAlign=right;spacingRight=18', true); port.geometry.offset = new mxPoint(-6, -4); var port = graph.insertVertex(v1, null, 'Error', 1, 0.25, 16, 16, 'port;image=editors/images/overlays/error.png;spacingLeft=18', true); port.geometry.offset = new mxPoint(-8, -8); var port = graph.insertVertex(v1, null, 'Result', 1, 0.75, 16, 16, 'port;image=editors/images/overlays/information.png;spacingLeft=18', true); port.geometry.offset = new mxPoint(-8, -4); } finally { model.endUpdate(); } graph.setSelectionCell(v1); } // Creates the image which is used as the sidebar icon (drag source) var img = document.createElement('img'); img.setAttribute('src', image); img.style.width = '48px'; img.style.height = '48px'; img.title = 'Drag this to the diagram to create a new vertex'; sidebar.appendChild(img); var dragElt = document.createElement('div'); dragElt.style.border = 'dashed black 1px'; dragElt.style.width = '120px'; dragElt.style.height = '120px'; // Creates the image which is used as the drag icon (preview) var ds = mxUtils.makeDraggable(img, graph, funct, dragElt, 0, 0, true, true); ds.setGuidesEnabled(true); }; ``` Please check [ports.html](https://jgraph.github.io/mxgraph/javascript/examples/ports.html) example, you will have a clear picture.
This worked for me: ``` addVertex('static/images/Icon_Image.svg', 30, 40, 'shape=image;image=static/images/Icon_Image.svg;'); ``` where, addVertex function has the syntax function(icon, w, h, style) with var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style); Reference: source code of <https://jgraph.github.io/mxgraph/javascript/examples/fixedicon.html>
67,174,874
I am calling a fortran function sgesv() of lapack library for solving linear equations for unknown vector from my CUDA C routine. As per the general rule I am declaring the function as sgesv\_() and invoking it in the main() function passing the variables by reference. I am following the commands to compile and execute as: ``` nvcc -Wno-deprecated-gpu-targets -c test_CCUDA3.cu gfortran -Wno-main -fno-second-underscore -fPIE -L"/usr/local/lib" -llapack test_CCUDA3.o -L"/usr/local/cuda/lib64" -I /usr/local/include -lcudart -lcuda -lstdc++ -lcublas ./a.out ``` There is no compilation error. However, while linking the object files I get the following error even though I recomplied with -fPIE: ``` /usr/bin/ld: test_CCUDA3.o: relocation R_X86_64_32 against `.rodata' can not be used when making a PIE object; recompile with -fPIE collect2: error: ld returned 1 exit status ``` Declaration and Invoking the function is as follows: ``` extern void sgesv_(int, int, float (*)[2], int, float [], float [2], int, int *); // sgesv(2, 1, aa, 2, pivot, &bb, 2, &rc); int main() { ................ ................ float aa[2][2],bb[2],pivot[2]; int rc; ........... ........... aa[0][0]=3.; aa[1][0]=1.; aa[0][1]=.6667; aa[1][1]=.3333; bb[0]=5.; bb[1]=6.; sgesv_(2, 1, aa, 2, pivot, bb, 2, &rc); ................. ................. } ``` Any help on executing the code will be much appreciated. Fairly a beginner in CUDA. I am calling this fortran library function in the main() not in the device code. Please note: I tested the compilation and running the code on normal C rather than with CUDA C. It gave me no error and execution gave me accurate solution.
2021/04/20
[ "https://Stackoverflow.com/questions/67174874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15068888/" ]
I believe you might have hit this issue [#861878 nvidia-cuda-toolkit: nvcc needs to pass -fpie to compiler](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=861878). The proposed solution is to use `nvcc --compiler-options -fpie` but see also the respones and other points. It is important to consider your versions of CUDA and GCC.
Couple of things/findings: `nvcc --compiler-options -fpie` is the right syntax and it did resolve the issue. @VladimirF thank you for providing that answer for me. extern "C" ... declaration also required for compiling and executing for as \*.cu. However, declaration is not needed at all rather it is redundant for compiling and executing \*.c with **linking to fortran library with C interface**. @RobertCrovella thanks for your input. The above steps resolved my this particular issue.
73,428,442
I need to get the absolute path of a file in python, i already tried `os.path.abspath(filename)` in my code like this: ```py def encrypt(filename): with open(filename, 'rb') as toencrypt: content = toencrypt.read() content = Fernet(key).encrypt(content) with open(filename, "wb") as toencrypt: toencrypt.write(content) def checkfolder(folder): for file in os.listdir(folder): fullpath = os.path.abspath(file) if file != "decrypt.py" and file != "encrypt.py" and file != "key.txt" and not os.path.isdir(file): print(fullpath) encrypt(fullpath) elif os.path.isdir(file) and not file.startswith("."): checkfolder(fullpath) ``` the problem is that `os.path.abspath(filename)` doesn't really get the absolute path, it just attach the current working directory to the filename which in this case is completely useless. how can i do this?
2022/08/20
[ "https://Stackoverflow.com/questions/73428442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19400931/" ]
If you want to control something over time in Pygame you have two options: 1. Use [`pygame.time.get_ticks()`](https://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks) to measure time and and implement logic that controls the object depending on the time. 2. Use the timer event. Use [`pygame.time.set_timer()`](https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer) to repeatedly create a [`USEREVENT`](https://www.pygame.org/docs/ref/event.html) in the event queue. Change object states when the event occurs. For a timer event you need to define a unique user events id. The ids for the user events have to be between `pygame.USEREVENT` (24) and `pygame.NUMEVENTS` (32). In this case `pygame.USEREVENT+1` is the event id for the timer event. Receive the event in the event loop: ```py def spawn_ship(): # [...] def main(): spawn_ship_interval = 5000 # 5 seconds spawn_ship_event_id = pygame.USEREVENT + 1 # 1 is just as an example pygame.time.set_timer(spawn_ship_event_id, spawn_ship_interval) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == spawn_ship_event_id: spawn_ship() ``` Also see [Spawning multiple instances of the same object concurrently in python](https://stackoverflow.com/questions/62112754/spawning-multiple-instances-of-the-same-object-concurrently-in-python/62112894#62112894) and [How to run multiple while loops at a time in Pygame](https://stackoverflow.com/questions/65263318/how-to-run-multiple-while-loops-at-a-time-in-pygame/65263396#65263396).
You could try making spawn\_ship async, then use a thread so it doesn't affect the main loop ```py import threading def main(): threading.Timer(5.0, spawn_ship).start() async def spawn_ship(): # ... ```
31,952,948
I am new to Swift and I want to know how to dismiss the current view controller and go to another view. My storyboard is like the following: MainMenuView -> GameViewController -> GameOverView. I want to dismiss the GameViewController to go to the GameOverView, not to the MainMenuView. I use the following code in my MainMenuView: ``` @IBAction func StartButton(sender: UIButton) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("GameViewController") as! GameViewController self.presentViewController(nextViewController, animated:true, completion:nil) restGame() } ``` In the GameViewController, I use this code, but it doesn't dismiss the GameViewController. ``` let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("GameOverView") as! GameOverView self.presentViewController(nextViewController, animated:true, completion:nil) ``` This is My GameOverView Code : ``` class GameOverView: UIViewController{ // save the presenting ViewController var presentingViewController :UIViewController! = self.presentViewController override func viewDidLoad() { super.viewDidLoad() } @IBAction func ReplayButton(sender: UIButton) { restGame() didPressClose() } @IBAction func ReturnMainMenu(sender: UIButton) { Data.GameStarted = 1 self.dismissViewControllerAnimated(false) { // go back to MainMenuView as the eyes of the user self.presentingViewController.dismissViewControllerAnimated(false, completion: nil); } /* let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("MainScene") as! MainScene self.presentViewController(nextViewController, animated:true, completion:nil)*/ } func restGame(){ Data.score = 0 Data.GameHolder = 3 Data.GameStarted = 1 Data.PlayerLife = 3.0 Data.BonusHolder = 30 Data.BonusTimer = 0 } func didPressClose() { self.self.dismissViewControllerAnimated(true, completion:nil) } override func shouldAutorotate() -> Bool { return false } deinit{ print("GameOverView is being deInitialized."); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } } ``` Any suggestions?
2015/08/11
[ "https://Stackoverflow.com/questions/31952948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4724949/" ]
What you can do is let the `GameOverView` be presented, after all when you presenting it the `GameViewController` is below in the hierarchy, and then in your `GameOverView` run the following code to close both when you want to dismiss the `GameOverView`, like in the following way: ``` @IBAction func ReturnMainMenu(sender: UIButton) { // save the presenting ViewController var presentingViewController: UIViewController! = self.presentingViewController self.dismissViewControllerAnimated(false) { // go back to MainMenuView as the eyes of the user presentingViewController.dismissViewControllerAnimated(false, completion: nil) } } ``` The above code need to be called when you want to dismiss the `GameOverView`. I hope this help you.
The below code will take you to the main VC, Here's a tried and tested piece of code. ``` self.view.window!.rootViewController?.dismiss(animated: false, completion: nil) ```