qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
14,183,478 |
I would like to know if someone could explain me what happens exactly when we call a "render".
Let me introduce you my problem:
**This is my action:**
```
public function actionIndex()
{
$new_user = new CustomUser;
$new_person = new CustomPerson;
$tab_person = $this->getListPerson();
$this->render('index',array('tab'=>$tab_person,
'user'=>$new_user,
'person'=>$new_person));
}
```
**And this is my index view:**
```
.
.
.
</p> <br/>
<?php $this->renderPartial('person-form', array('person'=>$person,
'user' =>$user ));
?>
```
So my problem is that the loading page time is very long.
If I put a
>
> die("die");
>
>
>
just befor the render in my actionIndex or at the end of my view (after the renderPartial) the execution is very fast. I'll see "die"(and my index page if I put the statement at the end of it) after 0.3 second. But if I put it after my render or I don't put it, then my page is going to be loaded correctly but in 4-5 secondes.
So I think I didn't understand very well what happens after a render. I repeat if I stop the execution at the end of my view page it's very fast, but at the end of my action it's very slow. I thought about js and css, but after looking into I didn't see anything and Firebug shows me that these files are loaded very quickly.
And if I put the "die()" statment at the end of my layout main.php it's very fast as well.

So I know that render will show the page and wrap it in the layout but is there another thing which maybe could make the action very slow?
If anybody has an idea about my problem I would be very grateful.
Sorry if I did mistakes, English is not my mothertongue.
Thank you for reading me, have a good day :)
Michaël
|
2013/01/06
|
[
"https://Stackoverflow.com/questions/14183478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751045/"
] |
I cannot post formatted code in a comment, hence this new answer.
@sea\_gull is right - you need indeed to call the new DAO. The reason for it being this is a new type, so the Content Delivery storage mechanism won't know what to do with it. You have to call it somehow (potentially from a deployer module, but not necessarily). I used a unit test for calling it (just to provie that it works).
This is my sample unit test code I use to call the storage extension with:
```java
package com.tridion.extension.search.test;
import static org.junit.Assert.fail;
import java.util.Date;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tridion.broker.StorageException;
import com.tridion.storage.StorageManagerFactory;
import com.tridion.storage.extension.search.PublishAction;
import com.tridion.storage.extension.search.PublishActionDAO;
/**
* @author Mihai Cadariu
*/
public class DAOTestCase {
private final Logger log = LoggerFactory.getLogger(DAOTestCase.class);
/**
* Test method for
* {@link com.tridion.storage.extension.search.PublishActionDAO#store(com.tridion.storage.search.PublishAction)}.
*/
@Test
public void testDAO() {
try {
log.debug("Get PublishActionDAO");
PublishActionDAO publishActionDAO = (PublishActionDAO) StorageManagerFactory.getDefaultDAO("PublishAction");
log.debug("Create new PublishAction bean");
PublishAction publishAction = new PublishAction();
publishAction.setAction("testStore action");
publishAction.setContent("testStore content");
publishAction.setTcmUri("testStore tcmUri");
publishAction.setUrl("testStore url");
publishAction.setCreationDate(new Date());
// Store
log.debug("Store bean");
publishAction = publishActionDAO.store(publishAction);
log.debug("Stored bean " + publishAction);
long id = publishAction.getId();
// FindByPrimaryKey
log.debug("Find PublishAction by PK=" + id);
publishAction = publishActionDAO.findByPrimaryKey(id);
log.debug("Found bean " + publishAction);
if (publishAction == null) {
log.error("Cannot find bean");
fail("TestFindByPrimaryKey failed: cannot retrieve object with pk " + id);
}
log.debug("Modifying bean content");
String content = publishAction.getContent();
content += "\r\nMODIFIED " + new Date();
publishAction.setContent(content);
// Update
log.debug("Update bean");
publishActionDAO.update(publishAction);
// Remove
log.debug("Remove bean");
publishActionDAO.remove(id);
} catch (StorageException se) {
log.debug("TestDAO failed: Exception occurred " + se);
fail("TestDAO failed: Exception occurred " + se);
se.printStackTrace();
}
}
}
```
If you call the code from a Deployer extension, this is the sample code I used:
```java
public class PageDeployModule extends PageDeploy {
private final Logger log = LoggerFactory.getLogger(PageDeployModule.class);
public PageDeployModule(Configuration config, Processor processor) throws ConfigurationException {
super(config, processor);
}
/**
* Process the page to be published
*/
@Override
protected void processPage(Page page, File pageFile) throws ProcessingException {
log.debug("Called processPage");
super.processPage(page, pageFile);
processItem(page);
}
private void processItem(Page page) {
log.debug("Called processItem");
try {
SearchConfiguration config = SearchConfiguration.getInstance();
String externalUrl = config.getExternalAccessUrl() + page.getURLPath();
String internalUrl = config.getInternalAccessUrl() + page.getURLPath();
PublishAction publishAction = new PublishAction();
publishAction.setAction("Publish");
publishAction.setTcmUri(page.getId().toString());
publishAction.setUrl(externalUrl);
publishAction.setContent(Utils.getPageContent(internalUrl));
PublishActionDAO publishActionDAO = (PublishActionDAO) StorageManagerFactory.getDefaultDAO("PublishAction");
publishAction = publishActionDAO.store(publishAction);
log.debug("Stored bean " + publishAction);
} catch (StorageException se) {
log.error("Exception occurred " + se);
}
}
}
```
You can use the same approach for the PageUndeploy, where you mark the action as "Unpublish".
|
More information needed:
1) What actually you are publishing while wanted to get invoked these methods - A Dynamic CP or a Page
2) From where you have received this code? I did not see any "create" method in your code...from where did you receive this code
In your previous post related to the "No named Bean loaded" error; Nuno has mentioned for one discussion on Tridion Forum (also given the forum link over there) started by Pankaj Gaur (i.e. me)...did you referred that?
Please note, If your Constructor is getting called, then there is no issue in your configuration at least; it is either the code or the mismatch in the type that you are publishing.
Also Note that, if you are trying to re-publish something without making any change, the Storage Extension might not get loaded (or the methods might not get invoked); so my suggestion during debuging, publsh always after making some changes in your presentation.
I hope it helps, else share the skeleton code along with the JAR file, and I will try t
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
From 《现代汉语词典》: (I'm omitting other unrelated descriptions of either word)
>
> 次: 用于反复出现或可能反复出现的事情
>
>
> 遍: 一个动作从开始到结束的整个过程称为一遍
>
>
>
Which is saying that 次 is used for things that (may) happen/appear/... repeatedly.
And 遍 refers to the whole process (from the beginning to the end) of an action.
---
The following explaination may be not that accurate:
次 seems to be saying that how many times you started to do something, but not quite care about how it persists.
In 2), the full action is required (from begin to end) so it is 遍。
In 3), the first blank, if he did twice consecutively, then it is 一次, but 两遍. Each 遍 is the full process from begin to end. If he did it once in the morning, but once in the afternoon, it is 两次. So maybe either is OK. For 下遍, it is not OK for me. But you can say 下一遍.
1), 4), 5) are all describing how many time a thing happened/happens/will happen, so they are all 次.
|
It may help to think of 遍 as "repetition" and 次 as "occurrence". The reading, writing (Sentence 2) and tai chi (sentence 3) all require repetitions of the same action, whereas the others are simply occurrences, not repetitions of the same thing.
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
From 《现代汉语词典》: (I'm omitting other unrelated descriptions of either word)
>
> 次: 用于反复出现或可能反复出现的事情
>
>
> 遍: 一个动作从开始到结束的整个过程称为一遍
>
>
>
Which is saying that 次 is used for things that (may) happen/appear/... repeatedly.
And 遍 refers to the whole process (from the beginning to the end) of an action.
---
The following explaination may be not that accurate:
次 seems to be saying that how many times you started to do something, but not quite care about how it persists.
In 2), the full action is required (from begin to end) so it is 遍。
In 3), the first blank, if he did twice consecutively, then it is 一次, but 两遍. Each 遍 is the full process from begin to end. If he did it once in the morning, but once in the afternoon, it is 两次. So maybe either is OK. For 下遍, it is not OK for me. But you can say 下一遍.
1), 4), 5) are all describing how many time a thing happened/happens/will happen, so they are all 次.
|
>
> (1) 杰希给马克打了两\_次\_电话,马克都没接。
>
>
> (2) 今天的作业是:读五\_遍\_课文,写十\_遍\_生词。
>
>
> (3) 今天马克一个人打了两\_次\_太极拳,下\_次\_他打算和阿里一起打。
>
>
> (4) 我们一个学期考五\_次\_试,现在已经考了三\_次\_了。
>
>
> (5) 上课的时候马克看了二十\_遍\_表。
>
>
>
遍 implies the completion of an action from beginning to end, such as reading a book or watching a film from beginning to end.
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
From 《现代汉语词典》: (I'm omitting other unrelated descriptions of either word)
>
> 次: 用于反复出现或可能反复出现的事情
>
>
> 遍: 一个动作从开始到结束的整个过程称为一遍
>
>
>
Which is saying that 次 is used for things that (may) happen/appear/... repeatedly.
And 遍 refers to the whole process (from the beginning to the end) of an action.
---
The following explaination may be not that accurate:
次 seems to be saying that how many times you started to do something, but not quite care about how it persists.
In 2), the full action is required (from begin to end) so it is 遍。
In 3), the first blank, if he did twice consecutively, then it is 一次, but 两遍. Each 遍 is the full process from begin to end. If he did it once in the morning, but once in the afternoon, it is 两次. So maybe either is OK. For 下遍, it is not OK for me. But you can say 下一遍.
1), 4), 5) are all describing how many time a thing happened/happens/will happen, so they are all 次.
|
Is it only me to think that, if in real scenario, either is ok.
用“次”或“遍”填空。
(1) 杰希给马克打了两\_\_\_电话,马克都没接。
次, but in practical, Chinese will use 遍
(2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
遍, I don't why, we just use it.
(3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
次 grammatically, but we use 遍
(4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
次
(5) 上课的时候马克看了二十\_\_\_表。
次 grammatically, but we use 遍
There is not too much grammar cause, just convention and behaviour.
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
It may help to think of 遍 as "repetition" and 次 as "occurrence". The reading, writing (Sentence 2) and tai chi (sentence 3) all require repetitions of the same action, whereas the others are simply occurrences, not repetitions of the same thing.
|
>
> (1) 杰希给马克打了两\_次\_电话,马克都没接。
>
>
> (2) 今天的作业是:读五\_遍\_课文,写十\_遍\_生词。
>
>
> (3) 今天马克一个人打了两\_次\_太极拳,下\_次\_他打算和阿里一起打。
>
>
> (4) 我们一个学期考五\_次\_试,现在已经考了三\_次\_了。
>
>
> (5) 上课的时候马克看了二十\_遍\_表。
>
>
>
遍 implies the completion of an action from beginning to end, such as reading a book or watching a film from beginning to end.
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
It may help to think of 遍 as "repetition" and 次 as "occurrence". The reading, writing (Sentence 2) and tai chi (sentence 3) all require repetitions of the same action, whereas the others are simply occurrences, not repetitions of the same thing.
|
Is it only me to think that, if in real scenario, either is ok.
用“次”或“遍”填空。
(1) 杰希给马克打了两\_\_\_电话,马克都没接。
次, but in practical, Chinese will use 遍
(2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
遍, I don't why, we just use it.
(3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
次 grammatically, but we use 遍
(4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
次
(5) 上课的时候马克看了二十\_\_\_表。
次 grammatically, but we use 遍
There is not too much grammar cause, just convention and behaviour.
|
29,756 |
The question comes from a problem from my Chinese book which asks to choose 次 and 遍 to fill in the blanks ([photo of the original](https://i.stack.imgur.com/1tp4n.jpg)). I transcribe it below:
>
> 用“次”或“遍”填空。
>
> (1) 杰希给马克打了两\_\_\_电话,马克都没接。
>
> (2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
>
> (3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
>
> (4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
>
> (5) 上课的时候马克看了二十\_\_\_表。
>
>
>
I feel like that most (all?) of them could be either 次 or 遍 without it being a problem. The only exception is in (3), where I would more naturally say 下次 (but Baidu suggests [下遍](https://www.baidu.com/s?wd=%E4%B8%8B%E9%81%8D) is also okay).
From dict.cn:
* [次](http://dict.cn/%E6%AC%A1) (cì) = number (of times), and
* [遍](http://dict.cn/%E9%81%8D) (biàn) = turn, a time.
So they really feel like synonyms.
**Question**: How do I determine whether to use 次 (cì) or 遍 (biàn) in these sentences?
(Note that this is not for assessment; I'm not officially enrolled in a Chinese class, but attend class regardless.)
|
2018/05/11
|
[
"https://chinese.stackexchange.com/questions/29756",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/8099/"
] |
Is it only me to think that, if in real scenario, either is ok.
用“次”或“遍”填空。
(1) 杰希给马克打了两\_\_\_电话,马克都没接。
次, but in practical, Chinese will use 遍
(2) 今天的作业是:读五\_\_\_课文,写十\_\_\_生词。
遍, I don't why, we just use it.
(3) 今天马克一个人打了两\_\_\_太极拳,下\_\_\_他打算和阿里一起打。
次 grammatically, but we use 遍
(4) 我们一个学期考五\_\_\_试,现在已经考了三\_\_\_了。
次
(5) 上课的时候马克看了二十\_\_\_表。
次 grammatically, but we use 遍
There is not too much grammar cause, just convention and behaviour.
|
>
> (1) 杰希给马克打了两\_次\_电话,马克都没接。
>
>
> (2) 今天的作业是:读五\_遍\_课文,写十\_遍\_生词。
>
>
> (3) 今天马克一个人打了两\_次\_太极拳,下\_次\_他打算和阿里一起打。
>
>
> (4) 我们一个学期考五\_次\_试,现在已经考了三\_次\_了。
>
>
> (5) 上课的时候马克看了二十\_遍\_表。
>
>
>
遍 implies the completion of an action from beginning to end, such as reading a book or watching a film from beginning to end.
|
26,221,102 |
I have a method:
```
+ (id) showModalFromController: (UIViewController*) controller
{
AxEmpAuthorizationController * autorizationController = [[self.class alloc] initWithNibName:NSStringFromClass(self.class) bundle:nil];
[autorizationController performSelectorOnMainThread: @selector(showModalFromController:) withObject: controller waitUntilDone: YES];
return [autorizationController authorelease];
}
```
and I had a category `AxEmpAuthorizationController+CustomLoginVC.h` in which I have override the method:
```
- (void) showModalFromController: (UIViewController*) controller
{
NavigationTopViewController* navigationController = [[NavigationTopViewController allocWithZone: NULL] initWithRootViewController: self];
[controller presentModalViewController: navigationController animated: ![self.class isMain]];
[navigationController release];
}
```
The problem is that the method in category is never called, and I can't find the issue. Any help?
|
2014/10/06
|
[
"https://Stackoverflow.com/questions/26221102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2042311/"
] |
One issue here is you aren't overriding the method. The selectors will be the same (I believe) - @selector(showModalFromController:), but the method is not. For one they have different return types, another is one is a class method (starts with '+') and once is an instance method (starts with '-').
You need to make sure your replacement method has the signature:
```
+ (id) showModalFromController: (UIViewController*) controller
```
rather than
```
- (void) showModalFromController: (UIViewController*) controller
```
Once you've sorted this out, you're one step closer.
As rmaddy commented above, you probably don't want to use a category to override a method.
If you're trying to replace behavior, consider subclassing and using your new subclass in the places you need it.
If you're trying to do something stealthy - replacing this method throughout your application, consider method swizzling (consider this option very carefully).
|
You have misunderstood what categories are; categories are not subclasses. Your reference to "the main class" is incorrect. Categories provide you with the ability to break up your source code for readability, or to extend classes that are otherwise already set in stone.
That is to say that if you were to take all of the source from all of your categories and put it in the same `@implementation` block (maybe separated with `#pragma mark -` for grouping consistency), it should read with logical correctness. The code that you have written transforms from:
```
@implementation SomeClass
+ (id) showModalFromController: (UIViewController*) controller
{
AxEmpAuthorizationController * autorizationController = [[self.class alloc] initWithNibName:NSStringFromClass(self.class) bundle:nil];
[autorizationController performSelectorOnMainThread: @selector(showModalFromController:) withObject: controller waitUntilDone: YES];
return [autorizationController authorelease];
}
@end
@implementation SomeClass (MyCategory)
- (void) showModalFromController: (UIViewController*) controller
{
NavigationTopViewController* navigationController = [[NavigationTopViewController allocWithZone: NULL] initWithRootViewController: self];
[controller presentModalViewController: navigationController animated: ![self.class isMain]];
[navigationController release];
}
@end
```
into this:
```
@implementation SomeClass
+ (id) showModalFromController: (UIViewController*) controller
{
AxEmpAuthorizationController * autorizationController = [[self.class alloc] initWithNibName:NSStringFromClass(self.class) bundle:nil];
[autorizationController performSelectorOnMainThread: @selector(showModalFromController:) withObject: controller waitUntilDone: YES];
return [autorizationController authorelease];
}
#pragma mark - MyCategory
- (void) showModalFromController: (UIViewController*) controller
{
NavigationTopViewController* navigationController = [[NavigationTopViewController allocWithZone: NULL] initWithRootViewController: self];
[controller presentModalViewController: navigationController animated: ![self.class isMain]];
[navigationController release];
}
@end
```
You are misusing selector names by defining two selectors with the same name in the same class. If you want to override the static method, you should be using a subclass. If you want a different method in the same class, use a different selector name.
|
7,614,177 |
My application involves lot of questions to be asked to the installer, the visual studio allows only a predefined set of controls for the installation wizard, Is there a way to add lot more controls to our Installation Wizard. can you help me out here?
|
2011/09/30
|
[
"https://Stackoverflow.com/questions/7614177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822522/"
] |
How about using [CSS expressions](http://msdn.microsoft.com/en-us/library/ms537634%28v=vs.85%29.aspx):
```
div {
display: inline-block;
width: inherit;
/* min-width for good browsers */
min-width: 800px;
/* CSS expression for older IE */
width: expression(document.body.clientWidth < 800? "800px": "auto");
}
```
Example here: [min-width CSS expression hack](http://jsfiddle.net/vnX6t/5/). The yellow background is the outer div
the dotted line is the inner element so the div keeps size properties of it's child :)
|
In IE6 *min-width*, *max-width*, *min-height* and *max-height* properties does not work. You can create a conditional stylesheet and use *width* for IE6 and *min-width* for the other browsers.
|
7,614,177 |
My application involves lot of questions to be asked to the installer, the visual studio allows only a predefined set of controls for the installation wizard, Is there a way to add lot more controls to our Installation Wizard. can you help me out here?
|
2011/09/30
|
[
"https://Stackoverflow.com/questions/7614177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/822522/"
] |
How about using [CSS expressions](http://msdn.microsoft.com/en-us/library/ms537634%28v=vs.85%29.aspx):
```
div {
display: inline-block;
width: inherit;
/* min-width for good browsers */
min-width: 800px;
/* CSS expression for older IE */
width: expression(document.body.clientWidth < 800? "800px": "auto");
}
```
Example here: [min-width CSS expression hack](http://jsfiddle.net/vnX6t/5/). The yellow background is the outer div
the dotted line is the inner element so the div keeps size properties of it's child :)
|
You can target IE6 by using underscore hack. Example:
```
<div style="min-width:800px;_width:800px;">...</div>
```
For max-width/height, you have to use IE-proprietary expression() property: <http://www.svendtofte.com/code/max_width_in_ie/>
|
67,131,766 |
Is anyone able to help me with this error I'm making a with a Coronavirus tracker twitter bot with python. It basically scrapes data from <https://www.worldometers.info/coronavirus/> and post updates on twitter.
The problem I'm having is to do with the scheduler on line 5 & 24.
Traceback (most recent call last):
File "C:\Users\Abdul\Documents\CoronavirusBot\twitter\_bot.py", line 5, in
import schedule
File "C:\Users\Abdul\Documents\CoronavirusBot\schedule.py", line 24, in
schedule.every().day.at("19:51").do(submit\_tweet)
AttributeError: partially initialized module 'schedule' has no attribute 'every' (most likely due to a circular import)
**Twitter\_bot.py**
```
from config import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
import tweepy
import requests
import schedule
import time
from lxml import html
def create_tweet():
response = requests.get('https://www.worldometers.info/coronavirus/')
doc = html.fromstring(response.content)
total, deaths, recovered = doc.xpath('//div[@class="maincounter-number"]/span/text()')
tweet = f'''Coronavirus Latest Updates
Total cases: {total}
Recovered: {recovered}
Deaths: {deaths}
Source: https://www.worldometers.info/coronavirus/
#coronavirus #covid19 #coronavirusnews #coronavirusupdates
'''
return tweet
if __name__ == '__main__':
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# Create API object
api = tweepy.API(auth)
try:
api.verify_credentials()
print('Authentication Successful')
except:
print('Error while authenticating API')
sys.exit(1)
while True:
schedule.run_pending()
time.sleep(1)
tweet = create_tweet()
api.update_status(tweet)
print('Tweet successful')
else:
print('error') ```
**Schedule.py**
```import schedule
#define function create tweet
#auth and create tweet
def submit_tweet(*args, **kwargs): #Add the needed args here
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
# Create API object
api = tweepy.API(auth)
try:
api.verify_credentials()
print('Authentication Successful')
except:
print('Error while authenticating API')
sys.exit(1)
tweet = create_tweet()
api.update_status(tweet)
print('Tweet successful')
schedule.every().day.at("21:19").do(submit_tweet)
while True:
schedule.run_pending()
time.sleep(1)
```
|
2021/04/16
|
[
"https://Stackoverflow.com/questions/67131766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This happens your python code file name is 'schedule.py'. If you change the file name to another one, you will no longer see the error.
|
you should not use schedule(shcedule.py) for your file name
|
60,769,778 |
good day, Im trying to create a program that reads a XML file then puts it into an arrayList and displays each name. The output is blank, there no names appearing, how do read the objects in the file when its a string and how can I get the names of the XML into the array?
```
import java.beans.*;
import java.io.*;
import javax.swing.JOptionPane;
import java.util.*;
import java.lang.ArrayIndexOutOfBoundsException;
public class ReadNamesFromXML
{
public static void main(String[] args)
{
try {
XMLDecoder decoder = new XMLDecoder(new
FileInputStream("lab10.xml"));
ArrayList<String> names = new ArrayList<>();
System.out.println(names);
}
catch (FileNotFoundException e){
JOptionPane.showMessageDialog(null,"Not found");
}
catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(null,"Not found");
}
}
}
```
XMl file:
```
<java version="1.8.0_144" class="java.beans.XMLDecoder">
<string>Harry</string>
<string>Ron</string>
<string>Hermione</string>
<string>Luna</string>
<string>Draco</string>
<string>Neville</string>
<string>Seamus</string>
<string>Ginny</string>
<string>Fred</string>
<string>George</string>
</java>
```
|
2020/03/20
|
[
"https://Stackoverflow.com/questions/60769778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12729796/"
] |
You can use
```
String.replaceAll("[unwanted chars]","");
```
Refer [replaceAll tutorial page](https://www.javatpoint.com/java-string-replaceall) for more details especially on the escape characters.
These things will work on predefined symbols only, in order to make your system intelligent and keep on updating itself with every new invalid symbol encountered you will need to write a method to store such new symbols in an appropriate data structure while handling the relevant exceptions.
|
You can't process any data unless you know what data you need to process. This applies to your task just as to any other. If you want to process dirty data, you need to specify what kind of dirt you expect to encounter and how you propose to deal with it. That will determine the approach adopted.
It may be that the kind of processing you need to do can be done by an existing library such as TagSoup or validator.nu. Or it might be that it can be done using regular expressions. Without a specification of the task, we can't know.
Consider an example. Suppose the input file contains `"< < < < > > > >"` What would you want your program to do with it?
***...LATER***
From your comment it sounds as if the HTML is "well formed but not valid", to borrow XML terminology. This means you could consider an XSLT solution:
```
<xsl:apply-templates select="saxon:parse-html('input.bad.html')"/>
```
...
```
<xsl:template match="a/@href | */@class | */@id | .... (:all valid attributes:)">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="@* (: attributes not in the above list :)">
<!-- no action (drop the attribute) -->
</xsl:template>
```
`saxon:parse-html()` is a Saxon XSLT extension. With other processors there may be some other way of parsing HTML into an XML DOM and using the XML DOM as input to the processor.
|
471,546 |
from <https://arxiv.org/abs/1401.0118>
If we have a function $J(X,Y)$ of two random variables $X$ and $Y$ and we want to compute the expectation $\mathbb E\_{p(X,Y)}[J(X,Y)]$.
We define $\hat J(X)= \mathbb E\_{p(Y)}[J(X,Y)\mid X]$.
Note that: $$\mathbb E\_{p(X,Y)}[J(X,Y)] = \mathbb E\_{p(X)} [\hat J(X)]$$
So we can use $\hat J(X)$ instead of $J(X, Y)$ in a Monte-Carlo Estimate.
For the variance holds (variance reduction)
$$
var(\hat J(X)) = var(J(X,Y)) - \mathcal E[(J(X,Y) - \hat J(X))^2]
$$
Here I have one questions:
* How can we prove that (variance reduction)? In the paper, no proof is given.
Here is one proof of this question (from [this link](https://stats.stackexchange.com/questions/381518/variance-of-rao-blackwellization-for-monte-carlo-estimate-of-expectation/381539#381539)):
The variance reduction follows from the [the law of total variance](https://ocw.mit.edu/resources/res-6-012-introduction-to-probability-spring-2018/part-i-the-fundamentals/MITRES_6_012S18_L13AS.pdf). Suppose that $W,Z$ are two random variables, then it follows that
$$
\mathbb{V}(W)=\mathbb{V}(\mathbb{E}(W\vert Z))+\mathbb{E}(\mathbb{V}(W\vert Z))
$$
then, replace $W$ by $J(X,Y)$ and $\mathbb{E}(W\vert Z)$ by $\hat{J}(X)$ and we obtain:
$$
\mathbb{V}(J(X,Y))=\mathbb{V}(\hat{J}(X))+\mathbb{E}(\mathbb{V}(J(X,Y)\vert X))
$$
Notice that the second summand on the right hand side is given by
$$\mathbb{V}(J(X,Y)\vert X)=\mathbb{E}(J(X,Y)^2\vert X)-(\mathbb{E}J(X,Y)\vert X)^2=\mathbb{E}(J(X,Y)^2\vert X)-\hat{J}(X)^2
$$
plug into the ANOVA identity, solve with respect to $\mathbb{V}(\hat{J}(X)$ to obtain
$$
\mathbb{V}(\hat{J}(X))=\mathbb{V}(J(X,Y))-\left(\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2)\right)=\mathbb{V}(J(X,Y))-\mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
as desired.
======================== end proof ==========================
But the can't follow the idea of the last line:
$$
\mathbb{V}(J(X,Y))-\left(\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2)\right)=\mathbb{V}(J(X,Y))-\mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
why the following equality holds?
$$
\mathbb{E}(J(X,Y)^2)-\mathbb{E}(\hat{J}(X)^2) = \mathbb{E}\left(\left(J(X,Y)-\hat{J}(X)\right)^2\right)
$$
Thanks.
|
2020/06/11
|
[
"https://stats.stackexchange.com/questions/471546",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/266255/"
] |
The distinction between a crossed and nested is related the arrangement of the factors and the factors' levels and not whether the levels are continuous or categorical.
>
> From paraphased from Wikipedia: "A fully crossed experiment whose
> design consists of two or more factors, each with possible values or
> "levels", and whose experimental units take on all possible
> combinations of these levels across all such factors.
>
>
>
As long as all of the combinations of all factors' levels are possible it is considered a fully crossed designed.
|
Whether an experiment is crossed or nested really depends on the structuring of the factor levels. Factors could either be crossed with other factors or nested within other factors.
|
71,199,624 |
So I'm trying to get all the possible combinations of rolling two dice `n` number of times.
Currently I have:
```
# Get all possible rolls with two dice
d <- list(1, 2, 3, 4, 5, 6)
rolls <- lapply(apply(expand.grid(d, d), 1, identity), unlist)
# Get all possible ways to roll two dice twice
trials <-lapply(apply(expand.grid(rolls, rolls), 1, identity), unlist)
```
`d` stores all possible values you can get on a single dice. `rolls` stores all possible outcomes of rolling two dice at the same time. And `trials` stores all possible outcomes of rolling two dice at the same time, twice in a row.
I can modify the last line as
```
trials <-lapply(apply(expand.grid(rolls, rolls, rolls), 1, identity), unlist)
```
to get all possible outcomes of rolling two dice at the same time, three times in a row, but I cannot figure out how to make the number of times variable, so that I could pass some arbitrary number `n` and get all possible outcomes of rolling two dice at the same time, an `n` number of times in a row
|
2022/02/20
|
[
"https://Stackoverflow.com/questions/71199624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17296565/"
] |
Since noone suggested a chain of commands yet, and in case you did not craft it yourself already :
```
git config alias.findall '!f() { echo -e "\nFound in refs:\n"; git for-each-ref refs/ | grep $1; echo -e "\nFound in commit messages:\n"; git log --all --oneline --grep="$1"; echo -e "\nFound in commit contents:\n"; git log --all --oneline -S "$1"; }; f'
```
It chains these three commands :
```
# for branches and tags we use for-each-ref and pipe the result to grep
git for-each-ref refs/ | grep $1
# for commit messages we use the grep option for log
git log --all --oneline --grep="$1"
# and for commit contents, the log command has the -S option
git log --all --oneline -S "$1"
```
So now you can just do
```
git findall something
```
|
You can try printing everything to the terminal, and then searching output with your terminal application:
```
git log -5000 -p --all --decorate --oneline --graph
```
For performance reasons, this is limited to 5,000 commits.
[](https://i.stack.imgur.com/GZ7vh.png)
There's a bit more noise/information than originally requested, but this can be beneficial - for example, you can now search commit hashes, timestamps, author names. You can intuitively search for deleted files, etc.
|
155,295 |
I want to get all orders using REST Api.
I am using this code but it's not returning any result.
**Request:**
```
$this->get('rest/V1/orders?searchCriteria[filter_groups][0][filters][0][field]=entity_id');
```
**Response:**
[](https://i.stack.imgur.com/tjEld.png)
How to get all orders using REST Api?
|
2017/01/18
|
[
"https://magento.stackexchange.com/questions/155295",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/19026/"
] |
I got the solution for this. I passed my request like:
`$this->get('rest/V1/orders?searchCriteria=entity_id');`
and for getting all orders without any filter. Use below code:
`$this->get('rest/V1/orders?searchCriteria');`
|
Ideally next request must be valid to get all orders
```
$this->get('rest/V1/orders');
```
But you get error instead
```
{"message":"%fieldName is a required field.","parameters":{"fieldName":"searchCriteria"}}
```
Error occurred because request is processed by
```
\Magento\Sales\Api\OrderRepositoryInterface::getList(\Magento\Framework\Api\SearchCriteria $searchCriteria)
```
and `$searchCriteria` argument is required.
You can skip value for this parameter. Next request must be valid too.
```
$this->get('rest/V1/orders?searchCriteria');
```
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
It has no type. It's just a token which the preprocessor will put into the source code before passing the code to the compiler. You can do this (ridiculous) thing to declare a variable called `x5000`:
```
#define APPEND(x,y) x ## y
int main() {
int APPEND(x,5000);
x5000 = 3;
}
```
The preprocessor turns that into this before passing it the compiler proper:
```
int main() {
int x5000;
x5000 = 3;
}
```
So, just because you see `5000` in a macro, it doesn't mean it needs to be numeric in any way.
|
Yes, you can assume it's an `int`.
Well, actually all the other answers are correct. It's not C, it's just
a directive that tells the preprocessor to do some textual
substitutions, and as such it has no type. However, if you do not do any
funky things with it (like the ## preprocessor trick), you will
typically use `MAXLINE` like some kind of constant, and the preprocessor
will replace it with `5000` which is indeed an explicit constant. And
constants do have type: `5000` is an `int`. A constant written as a
decimal integer, with no suffix (like U or L), will be interpreted by
the compiler as an `int`, `long int` or `unsigned long int`: the first
of these types that fits.
But this has of course nothing to do with the preprecessor. You could
rewrite your question as “what is the type of `5000`?”, with no
`#define`.
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
It has no type. It is a simple text substitution. The text 5000 will be dropped in place wherever MAXLINE appears as a token.
For example:
```
int a = MAXLINE;
```
will put the value 5000 in `a`.
While
```
char *MAXLINE2 = "MAXLINE";
```
will not result in
```
char *50002 = "5000";
```
So, if you want type-checking, macro's are not the way to go. You will want to declare static constants instead, that way type-checking is done by the compiler.
For information on the differences between `static`, `const`, and `#define`, there are many sources, including this question: [Static, define, and const in C](https://stackoverflow.com/questions/2611063/static-define-and-const-in-c)
|
`MAXLINE` is not a variable at all. In fact, it is not C syntax. Part of the compilation process runs a preprocessor before the compiler, and one of the actions the preprocessor takes is to replace instances of `MAXLINE` tokens in the source file with whatever comes after `#define MAXLINE` (5000 in the question's code).
Aside: another common way you use the preprocessor in your code is with the `#include` directive, which the preprocessor simply replaces with the preprocessed contents of the included file.
Example
=======
Let's look at an example of the compilation process in action. Here's a file, `foo.c`, that will be used in the examples:
```
#define VALUE 4
int main()
{
const int x = VALUE;
return 0;
}
```
I use `gcc` and `cpp` ([the C preprocessor](http://gcc.gnu.org/onlinedocs/cpp/)) for the examples, but you can probably do this with whatever compiler suite you have, with different flags, of course.
Compilation
-----------
First, let's compile `foo.c` with `gcc -o foo.c`. What happened? It worked; you should now have an executable `foo`.
Preprocessing only
------------------
You can tell `gcc` to only preprocess and not do any compilation. If you do `gcc -E foo.c`, you will get the preprocessed file on standard out. Here's what it produces:
```
# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "foo.c"
int main()
{
const int x = 4;
return 0;
}
```
Notice that the first line of `main` has replaced `VALUE` with `4`.
You may be wondering what the first four lines are. Those are called linemarkers, and you can read more about them in [Preprocessor Output](http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output).
Compilation without preprocessing
---------------------------------
As far as I know, you cannot outright skip preprocessing in `gcc`, but a couple approaches exist to tell it that a file has already been preprocessed. Even if you do this, however, it will remove macros present in the file because they are not for compiler consumption. You can see what the compiler works with in this situation with `gcc -E -fpreprocessed foo.c`:
```
.
.
.
.
int main()
{
const int x = VALUE;
return 0;
}
```
*Note: I put the dots in at the top; pretend those are blank lines (I had to put them there to get those lines to be displayed by SO).*
This file clearly will not compile (try `gcc -fpreprocessed foo.c` to find out) because `VALUE` is present in the source, but not defined anywhere.
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
the compiler never sees that line of code, a preprocessor runs before the actual compilation and replace those macros with their literal values, see link below for more information
<http://www.cplusplus.com/doc/tutorial/preprocessor/>
|
We call this macro or preprocessor, which is used to string-replace source file contents. Read this: <https://en.wikipedia.org/wiki/C_macro>
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
(Very!) Broadly, your C compiler is going to perform 3 tasks when executed:
1. Run a preprocessing pass over your source files,
2. Run a compiler over the preprocessed source files
3. Run a linker over the resulting object files.
Lines starting with a `#`, like the line
```
#define MAXLINE 5000
```
is handled by the preprocessor phase. (simplistically) The preprocessor will parse a file and perform text substitutions for any macros that it detects. There is no concept of types within the preprocessor.
Suppose that you have the following lines in your source file:
```
#define MAXLINE 5000
int someVariable = MAXLINE; // line 2
char someString[] = "MAXLINE"; // line 3
```
The preprocessor will detect the macro `MAXLINE` on line 2, and will perform a text substitution. Note that on line 3 `"MAXLINE"` is not treated as a macro as it is a string literal.
After the preprocessor phase has completed, the compilation phase will only see the following:
```
int someVariable = 5000; // line 2
char someString[] = "MAXLINE"; // line 3
```
(comments have been left in for clarity, but are normally removed by the preprocessor)
You can probably use an option on the compiler to be able to inspect the output of the preprocessor. In gcc the `-E` option will do this.
Note that while the preprocessor has no concept of type, there is no reason that you can't include a type in your macro for completeness. e.g.
```
#define MAXLINE ((int)5000)
```
|
It has no type. It's just a token which the preprocessor will put into the source code before passing the code to the compiler. You can do this (ridiculous) thing to declare a variable called `x5000`:
```
#define APPEND(x,y) x ## y
int main() {
int APPEND(x,5000);
x5000 = 3;
}
```
The preprocessor turns that into this before passing it the compiler proper:
```
int main() {
int x5000;
x5000 = 3;
}
```
So, just because you see `5000` in a macro, it doesn't mean it needs to be numeric in any way.
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
the compiler never sees that line of code, a preprocessor runs before the actual compilation and replace those macros with their literal values, see link below for more information
<http://www.cplusplus.com/doc/tutorial/preprocessor/>
|
It has no type. It's just a token which the preprocessor will put into the source code before passing the code to the compiler. You can do this (ridiculous) thing to declare a variable called `x5000`:
```
#define APPEND(x,y) x ## y
int main() {
int APPEND(x,5000);
x5000 = 3;
}
```
The preprocessor turns that into this before passing it the compiler proper:
```
int main() {
int x5000;
x5000 = 3;
}
```
So, just because you see `5000` in a macro, it doesn't mean it needs to be numeric in any way.
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
It has no type. It's just a token which the preprocessor will put into the source code before passing the code to the compiler. You can do this (ridiculous) thing to declare a variable called `x5000`:
```
#define APPEND(x,y) x ## y
int main() {
int APPEND(x,5000);
x5000 = 3;
}
```
The preprocessor turns that into this before passing it the compiler proper:
```
int main() {
int x5000;
x5000 = 3;
}
```
So, just because you see `5000` in a macro, it doesn't mean it needs to be numeric in any way.
|
We call this macro or preprocessor, which is used to string-replace source file contents. Read this: <https://en.wikipedia.org/wiki/C_macro>
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
`MAXLINE` is not a variable at all. In fact, it is not C syntax. Part of the compilation process runs a preprocessor before the compiler, and one of the actions the preprocessor takes is to replace instances of `MAXLINE` tokens in the source file with whatever comes after `#define MAXLINE` (5000 in the question's code).
Aside: another common way you use the preprocessor in your code is with the `#include` directive, which the preprocessor simply replaces with the preprocessed contents of the included file.
Example
=======
Let's look at an example of the compilation process in action. Here's a file, `foo.c`, that will be used in the examples:
```
#define VALUE 4
int main()
{
const int x = VALUE;
return 0;
}
```
I use `gcc` and `cpp` ([the C preprocessor](http://gcc.gnu.org/onlinedocs/cpp/)) for the examples, but you can probably do this with whatever compiler suite you have, with different flags, of course.
Compilation
-----------
First, let's compile `foo.c` with `gcc -o foo.c`. What happened? It worked; you should now have an executable `foo`.
Preprocessing only
------------------
You can tell `gcc` to only preprocess and not do any compilation. If you do `gcc -E foo.c`, you will get the preprocessed file on standard out. Here's what it produces:
```
# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "foo.c"
int main()
{
const int x = 4;
return 0;
}
```
Notice that the first line of `main` has replaced `VALUE` with `4`.
You may be wondering what the first four lines are. Those are called linemarkers, and you can read more about them in [Preprocessor Output](http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output).
Compilation without preprocessing
---------------------------------
As far as I know, you cannot outright skip preprocessing in `gcc`, but a couple approaches exist to tell it that a file has already been preprocessed. Even if you do this, however, it will remove macros present in the file because they are not for compiler consumption. You can see what the compiler works with in this situation with `gcc -E -fpreprocessed foo.c`:
```
.
.
.
.
int main()
{
const int x = VALUE;
return 0;
}
```
*Note: I put the dots in at the top; pretend those are blank lines (I had to put them there to get those lines to be displayed by SO).*
This file clearly will not compile (try `gcc -fpreprocessed foo.c` to find out) because `VALUE` is present in the source, but not defined anywhere.
|
We call this macro or preprocessor, which is used to string-replace source file contents. Read this: <https://en.wikipedia.org/wiki/C_macro>
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
It has no type. It is a simple text substitution. The text 5000 will be dropped in place wherever MAXLINE appears as a token.
For example:
```
int a = MAXLINE;
```
will put the value 5000 in `a`.
While
```
char *MAXLINE2 = "MAXLINE";
```
will not result in
```
char *50002 = "5000";
```
So, if you want type-checking, macro's are not the way to go. You will want to declare static constants instead, that way type-checking is done by the compiler.
For information on the differences between `static`, `const`, and `#define`, there are many sources, including this question: [Static, define, and const in C](https://stackoverflow.com/questions/2611063/static-define-and-const-in-c)
|
(Very!) Broadly, your C compiler is going to perform 3 tasks when executed:
1. Run a preprocessing pass over your source files,
2. Run a compiler over the preprocessed source files
3. Run a linker over the resulting object files.
Lines starting with a `#`, like the line
```
#define MAXLINE 5000
```
is handled by the preprocessor phase. (simplistically) The preprocessor will parse a file and perform text substitutions for any macros that it detects. There is no concept of types within the preprocessor.
Suppose that you have the following lines in your source file:
```
#define MAXLINE 5000
int someVariable = MAXLINE; // line 2
char someString[] = "MAXLINE"; // line 3
```
The preprocessor will detect the macro `MAXLINE` on line 2, and will perform a text substitution. Note that on line 3 `"MAXLINE"` is not treated as a macro as it is a string literal.
After the preprocessor phase has completed, the compilation phase will only see the following:
```
int someVariable = 5000; // line 2
char someString[] = "MAXLINE"; // line 3
```
(comments have been left in for clarity, but are normally removed by the preprocessor)
You can probably use an option on the compiler to be able to inspect the output of the preprocessor. In gcc the `-E` option will do this.
Note that while the preprocessor has no concept of type, there is no reason that you can't include a type in your macro for completeness. e.g.
```
#define MAXLINE ((int)5000)
```
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
(Very!) Broadly, your C compiler is going to perform 3 tasks when executed:
1. Run a preprocessing pass over your source files,
2. Run a compiler over the preprocessed source files
3. Run a linker over the resulting object files.
Lines starting with a `#`, like the line
```
#define MAXLINE 5000
```
is handled by the preprocessor phase. (simplistically) The preprocessor will parse a file and perform text substitutions for any macros that it detects. There is no concept of types within the preprocessor.
Suppose that you have the following lines in your source file:
```
#define MAXLINE 5000
int someVariable = MAXLINE; // line 2
char someString[] = "MAXLINE"; // line 3
```
The preprocessor will detect the macro `MAXLINE` on line 2, and will perform a text substitution. Note that on line 3 `"MAXLINE"` is not treated as a macro as it is a string literal.
After the preprocessor phase has completed, the compilation phase will only see the following:
```
int someVariable = 5000; // line 2
char someString[] = "MAXLINE"; // line 3
```
(comments have been left in for clarity, but are normally removed by the preprocessor)
You can probably use an option on the compiler to be able to inspect the output of the preprocessor. In gcc the `-E` option will do this.
Note that while the preprocessor has no concept of type, there is no reason that you can't include a type in your macro for completeness. e.g.
```
#define MAXLINE ((int)5000)
```
|
Yes, you can assume it's an `int`.
Well, actually all the other answers are correct. It's not C, it's just
a directive that tells the preprocessor to do some textual
substitutions, and as such it has no type. However, if you do not do any
funky things with it (like the ## preprocessor trick), you will
typically use `MAXLINE` like some kind of constant, and the preprocessor
will replace it with `5000` which is indeed an explicit constant. And
constants do have type: `5000` is an `int`. A constant written as a
decimal integer, with no suffix (like U or L), will be interpreted by
the compiler as an `int`, `long int` or `unsigned long int`: the first
of these types that fits.
But this has of course nothing to do with the preprecessor. You could
rewrite your question as “what is the type of `5000`?”, with no
`#define`.
|
8,584,387 |
So I made a soundboard for the hospital I work for, it plays different respitory sounds for the RT's to listen too for furthering education and for trainees. I can stop and start the sounds fine. The problem Im having is when the sound is complete. You have to tap any button twice to play the next sound. So I am wondering how you would reset soundfiles upon completion. I am pretty new to obj-c and my gut is telling me to implement NSTime, however I cant figure out how to do it, or if this is even what I want to do.
Thanks in advance!
```
- (IBAction)play {
if (soundIsPlaying == YES) {
[audioplayer release];
soundIsPlaying = NO;
}
else if (soundIsPlaying == NO) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"breathe1" ofType:@"wav"];
audioplayer=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioplayer.delegate = self;
audioplayer.volume = 1.2;
audioplayer.numberOfLoops = 0;
[audioplayer play];
soundIsPlaying = YES;
}
}
```
|
2011/12/21
|
[
"https://Stackoverflow.com/questions/8584387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/839526/"
] |
the compiler never sees that line of code, a preprocessor runs before the actual compilation and replace those macros with their literal values, see link below for more information
<http://www.cplusplus.com/doc/tutorial/preprocessor/>
|
`MAXLINE` is not a variable at all. In fact, it is not C syntax. Part of the compilation process runs a preprocessor before the compiler, and one of the actions the preprocessor takes is to replace instances of `MAXLINE` tokens in the source file with whatever comes after `#define MAXLINE` (5000 in the question's code).
Aside: another common way you use the preprocessor in your code is with the `#include` directive, which the preprocessor simply replaces with the preprocessed contents of the included file.
Example
=======
Let's look at an example of the compilation process in action. Here's a file, `foo.c`, that will be used in the examples:
```
#define VALUE 4
int main()
{
const int x = VALUE;
return 0;
}
```
I use `gcc` and `cpp` ([the C preprocessor](http://gcc.gnu.org/onlinedocs/cpp/)) for the examples, but you can probably do this with whatever compiler suite you have, with different flags, of course.
Compilation
-----------
First, let's compile `foo.c` with `gcc -o foo.c`. What happened? It worked; you should now have an executable `foo`.
Preprocessing only
------------------
You can tell `gcc` to only preprocess and not do any compilation. If you do `gcc -E foo.c`, you will get the preprocessed file on standard out. Here's what it produces:
```
# 1 "foo.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "foo.c"
int main()
{
const int x = 4;
return 0;
}
```
Notice that the first line of `main` has replaced `VALUE` with `4`.
You may be wondering what the first four lines are. Those are called linemarkers, and you can read more about them in [Preprocessor Output](http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output).
Compilation without preprocessing
---------------------------------
As far as I know, you cannot outright skip preprocessing in `gcc`, but a couple approaches exist to tell it that a file has already been preprocessed. Even if you do this, however, it will remove macros present in the file because they are not for compiler consumption. You can see what the compiler works with in this situation with `gcc -E -fpreprocessed foo.c`:
```
.
.
.
.
int main()
{
const int x = VALUE;
return 0;
}
```
*Note: I put the dots in at the top; pretend those are blank lines (I had to put them there to get those lines to be displayed by SO).*
This file clearly will not compile (try `gcc -fpreprocessed foo.c` to find out) because `VALUE` is present in the source, but not defined anywhere.
|
194,956 |
I want to use [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)#Distribution_and_variants) for a part of my game and I want to know if it's legal or not.
|
2021/07/31
|
[
"https://gamedev.stackexchange.com/questions/194956",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/153990/"
] |
The answer depends on whether you are talking about the game mechanic (a grid where selecting the wrong square means you die, selecting other squares shows you how man neighbouring squares are like this) or the artwork / look and feel of a specific implementation of a game.
* Game mechanics can’t be copyrighted, but may be patented (I’m not aware of anything covering minesweeper).
* Artwork, names etc can and are copyrightable.
See this [question](https://gamedev.stackexchange.com/questions/1653/how-closely-can-a-game-legally-resemble-another) for some good information.
And as always, if you want proper legal advice, ask a lawyer not me
|
**I am not a lawyer. This is not legal advice. These are just my personal observations of the past. I accept no legal responsibility for any damages to you whatsoever.**
Many companies tried to sue other developers in the past for making a game with similar mechanics. Majority of those failed, and it will likely stay that way. Trying to claim game mechanics are intellectual property is like trying to claim chord progressions of a song are intellectual property. It just doesn't make sense.
Unless you make a literal clone of the original minesweeper (read: stealing game assets), then I would say you are fine.
I would suggest asking this question on [law.se](https://law.stackexchange.com/) for actual legal advice. Most of us here are game developers, not lawyers. We can only talk about personal experiences and those usually vary from person to person.
|
194,956 |
I want to use [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)#Distribution_and_variants) for a part of my game and I want to know if it's legal or not.
|
2021/07/31
|
[
"https://gamedev.stackexchange.com/questions/194956",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/153990/"
] |
The answer depends on what you mean by "using minesweeper" and possibly what legal issue you're concerned about. If you're literally taking the code from Minesweeper and using it in your game, then that's probably a copyright violation (the original game probably isn't in the public domain, and it would be difficult to make a fair use claim). If you're merely using game mechanics that are equivalent, or close to it, to Minesweeper, that's not illegal.
>
> The principle laid down in Baker v. Selden was later codified in the Copyright Act of 1976, which says clearly: “In no case does copyright protection for an original work of authorship extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery, regardless of the form in which it is described, explained, illustrated, or embodied in such work.”6 Thus, the idea-expression dichotomy that is fundamental to copyright law can be traced back to Baker v. Selden.
>
>
> Therefore, the systems or processes that make up the core of a game—generally referred to as the “game mechanics”—are not subject to copyright, even though the written rules, game board, card artwork, and other elements—often referred to as the “theme” of the game—may be.
>
>
>
<https://www.americanbar.org/groups/intellectual_property_law/publications/landslide/2014-15/march-april/not-playing-around-board-games-intellectual-property-law>
So the idea is not protected, but the expression is. That means that if you copy the artwork, etc., that can be a violation.
There may be patent issues, however, and the actual name "Minesweeper" is likely trademarked, so you should avoid referring to with that name.
|
The answer depends on whether you are talking about the game mechanic (a grid where selecting the wrong square means you die, selecting other squares shows you how man neighbouring squares are like this) or the artwork / look and feel of a specific implementation of a game.
* Game mechanics can’t be copyrighted, but may be patented (I’m not aware of anything covering minesweeper).
* Artwork, names etc can and are copyrightable.
See this [question](https://gamedev.stackexchange.com/questions/1653/how-closely-can-a-game-legally-resemble-another) for some good information.
And as always, if you want proper legal advice, ask a lawyer not me
|
194,956 |
I want to use [Minesweeper](https://en.wikipedia.org/wiki/Minesweeper_(video_game)#Distribution_and_variants) for a part of my game and I want to know if it's legal or not.
|
2021/07/31
|
[
"https://gamedev.stackexchange.com/questions/194956",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/153990/"
] |
The answer depends on what you mean by "using minesweeper" and possibly what legal issue you're concerned about. If you're literally taking the code from Minesweeper and using it in your game, then that's probably a copyright violation (the original game probably isn't in the public domain, and it would be difficult to make a fair use claim). If you're merely using game mechanics that are equivalent, or close to it, to Minesweeper, that's not illegal.
>
> The principle laid down in Baker v. Selden was later codified in the Copyright Act of 1976, which says clearly: “In no case does copyright protection for an original work of authorship extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery, regardless of the form in which it is described, explained, illustrated, or embodied in such work.”6 Thus, the idea-expression dichotomy that is fundamental to copyright law can be traced back to Baker v. Selden.
>
>
> Therefore, the systems or processes that make up the core of a game—generally referred to as the “game mechanics”—are not subject to copyright, even though the written rules, game board, card artwork, and other elements—often referred to as the “theme” of the game—may be.
>
>
>
<https://www.americanbar.org/groups/intellectual_property_law/publications/landslide/2014-15/march-april/not-playing-around-board-games-intellectual-property-law>
So the idea is not protected, but the expression is. That means that if you copy the artwork, etc., that can be a violation.
There may be patent issues, however, and the actual name "Minesweeper" is likely trademarked, so you should avoid referring to with that name.
|
**I am not a lawyer. This is not legal advice. These are just my personal observations of the past. I accept no legal responsibility for any damages to you whatsoever.**
Many companies tried to sue other developers in the past for making a game with similar mechanics. Majority of those failed, and it will likely stay that way. Trying to claim game mechanics are intellectual property is like trying to claim chord progressions of a song are intellectual property. It just doesn't make sense.
Unless you make a literal clone of the original minesweeper (read: stealing game assets), then I would say you are fine.
I would suggest asking this question on [law.se](https://law.stackexchange.com/) for actual legal advice. Most of us here are game developers, not lawyers. We can only talk about personal experiences and those usually vary from person to person.
|
58,654,408 |
I used bootstrap 4 to design the blog page. Design is well but when I am using wp\_posts design not working properly.
```
<?php
global $post;
$events = array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'events',
'posts_per_page' => 4,
);
$arr_posts = new WP_Query( $events );
$myposts = get_posts( $events );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<div class="row single-event">
<div class="col-6 p-0 m-0">
<?php
if ( has_post_thumbnail() ) :
the_post_thumbnail();
endif;
?>
</div>
<div class="col-6 event-desc">
<a href="<?php the_permalink(); ?>" class="event-title d-block"><?php the_title() ?></a>
<p class="exerpt">
<?php if ( is_category() || is_archive() ) {
echo excerpt(30);
} else {
echo content(30);
}
?>
</p>
<p class="date">Event Date: <span><?php echo get_the_date('F j, Y'); ?></span></p>
<a href="<?php the_permalink(); ?>" class="btn btn-sm btn-outline-primary">Learn More..</a>
</div>
</div>
<?php endforeach;
wp_reset_postdata();
?>
```
Here is my site <https://rccsl.com/events/>
Please help. Thanks in advance.
|
2019/11/01
|
[
"https://Stackoverflow.com/questions/58654408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11142309/"
] |
Not Sure but it seems you forgot to add Role in start up.cs file
```
services.AddDefaultIdentity<UserViewModel>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DbContext>();
```
Please find below link for more reference.
<http://qaru.site/questions/16512353/store-does-not-implement-iuserrolestoretuser-aspnet-core-21-identity>
|
Remove the line below:
services.AddTransient, UserStore>();
|
23,955,063 |
I would like to calculate the similarity between 2 sentences and I need the percentage value which says "how good" they match with each other. Sentences like,
```
1. The red fox is moving on the hill.
2. The black fox is moving in the bill.
```
I was considering about `Levenshtein distance` but I am not sure about this because it says it is for finding similarity between "2 words". So can this `Levenshtein distance`help me or what other method can help me? I will be using JavaScript.
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23955063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
Try this [solution](http://jsfiddle.net/kAZwB/33/) for `JS string diff`
|
this is what i would do depending on how important this is. if this is medium to low priority here is a simple algo.
1. scan all sentences and see how often a word occurs.
2. filter out the most common words like the ones in 30% of sentences , i.e. don't count these. so at the as would hopefully not be counted.
3. then do your bag of words comparison.
But the context in why you want to do this is really important. i.e. the example you gave us could be for students learning english etc. i.e. theres different algorithms i would use if i was trying to see if crowd sourced users are describing the same paragraph vs if article topics are similar enough for a suggested reading section.
|
23,955,063 |
I would like to calculate the similarity between 2 sentences and I need the percentage value which says "how good" they match with each other. Sentences like,
```
1. The red fox is moving on the hill.
2. The black fox is moving in the bill.
```
I was considering about `Levenshtein distance` but I am not sure about this because it says it is for finding similarity between "2 words". So can this `Levenshtein distance`help me or what other method can help me? I will be using JavaScript.
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23955063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
Try this [solution](http://jsfiddle.net/kAZwB/33/) for `JS string diff`
|
Use [Jaccard index](http://en.wikipedia.org/wiki/Jaccard_index). You can find implementations in any language, including JavaScript ([here](https://github.com/ecto/jaccard) is one, didn't test it personally though).
|
23,955,063 |
I would like to calculate the similarity between 2 sentences and I need the percentage value which says "how good" they match with each other. Sentences like,
```
1. The red fox is moving on the hill.
2. The black fox is moving in the bill.
```
I was considering about `Levenshtein distance` but I am not sure about this because it says it is for finding similarity between "2 words". So can this `Levenshtein distance`help me or what other method can help me? I will be using JavaScript.
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23955063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
Try this [solution](http://jsfiddle.net/kAZwB/33/) for `JS string diff`
|
A common Method to compute the similarity of two sentences is to cosine similiarity. Don't know if there an implemenatation in JavaScript exists. The cosine similiarity looks on words and not of single letters. The web is full of explenations for example [here](http://www.blog.computergodzilla.com/2012/12/what-is-cosine-similarity.html).
|
23,955,063 |
I would like to calculate the similarity between 2 sentences and I need the percentage value which says "how good" they match with each other. Sentences like,
```
1. The red fox is moving on the hill.
2. The black fox is moving in the bill.
```
I was considering about `Levenshtein distance` but I am not sure about this because it says it is for finding similarity between "2 words". So can this `Levenshtein distance`help me or what other method can help me? I will be using JavaScript.
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23955063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
Use [Jaccard index](http://en.wikipedia.org/wiki/Jaccard_index). You can find implementations in any language, including JavaScript ([here](https://github.com/ecto/jaccard) is one, didn't test it personally though).
|
this is what i would do depending on how important this is. if this is medium to low priority here is a simple algo.
1. scan all sentences and see how often a word occurs.
2. filter out the most common words like the ones in 30% of sentences , i.e. don't count these. so at the as would hopefully not be counted.
3. then do your bag of words comparison.
But the context in why you want to do this is really important. i.e. the example you gave us could be for students learning english etc. i.e. theres different algorithms i would use if i was trying to see if crowd sourced users are describing the same paragraph vs if article topics are similar enough for a suggested reading section.
|
23,955,063 |
I would like to calculate the similarity between 2 sentences and I need the percentage value which says "how good" they match with each other. Sentences like,
```
1. The red fox is moving on the hill.
2. The black fox is moving in the bill.
```
I was considering about `Levenshtein distance` but I am not sure about this because it says it is for finding similarity between "2 words". So can this `Levenshtein distance`help me or what other method can help me? I will be using JavaScript.
|
2014/05/30
|
[
"https://Stackoverflow.com/questions/23955063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1379286/"
] |
Use [Jaccard index](http://en.wikipedia.org/wiki/Jaccard_index). You can find implementations in any language, including JavaScript ([here](https://github.com/ecto/jaccard) is one, didn't test it personally though).
|
A common Method to compute the similarity of two sentences is to cosine similiarity. Don't know if there an implemenatation in JavaScript exists. The cosine similiarity looks on words and not of single letters. The web is full of explenations for example [here](http://www.blog.computergodzilla.com/2012/12/what-is-cosine-similarity.html).
|
3,901,848 |
I'd like to use
<http://www.visualsvn.com/server/>
which installs simply on windows. But I'd like to know if I could copy it if needed on a linux server with apache subversion server installed. How can I be sure that the versions of format are the same ?
|
2010/10/10
|
[
"https://Stackoverflow.com/questions/3901848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/310291/"
] |
As djechelon says, VisualSVN just uses the standard SVN protocol; you can dump your repos via the Windows command prompt - the following will dump your whole repo and all revisions:
```
svnadmin dump your/repos/path > /your/repo/here.dump
```
|
You can!
SVN is de-facto standard protocol. VisualSVN is 100% SVN-compatible, so it also works with Linux clients
I don't know exactly how to dump a VisualSVN repo, but once you do so you can do svnadmin load from Linux. See if you have a "dump" option in your GUI, or... well... RTFM :)
More info on backup and restore: <http://wiki.archlinux.org/index.php/Subversion_backup_and_restore>
|
7,314,703 |
I need to set custom colors to my UINavigationBar buttons.
I'm doing the following thing(RGB func is a define):
```
- (void)viewWillAppear:(BOOL)animated
{
for (UIView *view in self.navigationController.navigationBar.subviews)
if ([[[view class] description] isEqualToString:@"UINavigationButton"])
[(UINavigationButton *)view setTintColor:RGB(22.0,38.0,111.0)];
}
```
Everything looks fine on app load. after leaving the view and getting back the color returns to default.
Secondly I need to set the same colour to UISegmentedControl to a pressed button.
|
2011/09/06
|
[
"https://Stackoverflow.com/questions/7314703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611206/"
] |
Here's one way:
```
[[theNavigationBar.subviews objectAtIndex:1] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[[theNavigationBar.subviews objectAtIndex:2] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
```
However, HUGE, caveat. This is highly likely to break on a future OS release and is not recommended.
At the very least you should perform a lot of testing and make sure you your assumptions of the subview layout of the navigation bar are correct.
or
You can change the color by changing the tintColor property of the UINavigationBar
```
myBar.tintColor = [UIColor greenColor];
```
or
You can follow the below link
<http://www.skylarcantu.com/blog/2009/11/05/changing-colors-of-uinavigationbarbuttons/>
|
For IOS5 will have to use ["setBackgroundImage:forBarMetrics:"](http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UINavigationBar_Class/Reference/UINavigationBar.html)
try this code to apply all UINavigationItem / UINavigationBar
```
if([[UINavigationBar class] respondsToSelector:@selector(appearance)]){ //iOS >=5.0
//use for UINavigationBar Custom image.
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithNamed:@"navImage.png"] forBarMetrics:UIBarMetricsDefault];
//use for UINavigationItem custom color
[[UINavigationBar appearance] setTintColor:[UIColor greenColor]];
}
```
|
7,314,703 |
I need to set custom colors to my UINavigationBar buttons.
I'm doing the following thing(RGB func is a define):
```
- (void)viewWillAppear:(BOOL)animated
{
for (UIView *view in self.navigationController.navigationBar.subviews)
if ([[[view class] description] isEqualToString:@"UINavigationButton"])
[(UINavigationButton *)view setTintColor:RGB(22.0,38.0,111.0)];
}
```
Everything looks fine on app load. after leaving the view and getting back the color returns to default.
Secondly I need to set the same colour to UISegmentedControl to a pressed button.
|
2011/09/06
|
[
"https://Stackoverflow.com/questions/7314703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/611206/"
] |
[Change UINavigationItem colour](http://www.skylarcantu.com/blog/2009/11/05/changing-colors-of-uinavigationbarbuttons/"Changing colors of UINavigationBarButtons") and [to set same color to UISegmentControl](http://chris-software.com/index.php/tag/uisegmentedcontrol/) will help you to reach to your destination.
[**Here**](https://github.com/samvermette/SVSegmentedControl) is a sample code for to set color to UISegmentControl.
|
For IOS5 will have to use ["setBackgroundImage:forBarMetrics:"](http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UINavigationBar_Class/Reference/UINavigationBar.html)
try this code to apply all UINavigationItem / UINavigationBar
```
if([[UINavigationBar class] respondsToSelector:@selector(appearance)]){ //iOS >=5.0
//use for UINavigationBar Custom image.
[[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithNamed:@"navImage.png"] forBarMetrics:UIBarMetricsDefault];
//use for UINavigationItem custom color
[[UINavigationBar appearance] setTintColor:[UIColor greenColor]];
}
```
|
52,871,388 |
I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.
I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:
`<img id="target" src="images/">samplevalue.png</img>`
I need to do like it this:
`<img id="target" src="images/samplevalue.png" />`
Sample parameter: `param1=samplevalue.png`
here's the code:
**html**
```
<div id="block1"></div>
<img id="target" src=""/>
```
**jQuery/Javascript**
```
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return decodeURIComponent(pair[1].replace(/\+/g, " "));
}
}
return decodeURIComponent(pair[1]);
}
document.getElementById("block1").innerHTML =
getQueryVariable("param1");
$(document).ready(function() {
$("img#target").attr("src", "images/").html($("#block1").html());
});
```
Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.
Any help on this is highly appreciated.
Thank you very much in advance.
|
2018/10/18
|
[
"https://Stackoverflow.com/questions/52871388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725229/"
] |
You have to add the returned value from the function as part of the attribute `src`.
With `.html($("#block1").html())` on the image element, you are trying to set html on th image which is actually invalid:
Change the function to:
```
$(document).ready(function() {
var urlPart = getQueryVariable();
$("img#target").attr("src", "images/" + urlPart);
});
```
**Please Note:**
Since you are already using jQuery, I will suggest you not to mix JavaScript & jQuery if possible, like:
```
document.getElementById("block1").innerHTML = getQueryVariable("param1");
```
Could be easily written:
```
$('#block1').text(getQueryVariable("param1")); //text() is preferred when dealing with text content
```
|
```
$("img#target").attr("src", "images/"+$("#block1").html());
```
|
52,871,388 |
I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.
I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:
`<img id="target" src="images/">samplevalue.png</img>`
I need to do like it this:
`<img id="target" src="images/samplevalue.png" />`
Sample parameter: `param1=samplevalue.png`
here's the code:
**html**
```
<div id="block1"></div>
<img id="target" src=""/>
```
**jQuery/Javascript**
```
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return decodeURIComponent(pair[1].replace(/\+/g, " "));
}
}
return decodeURIComponent(pair[1]);
}
document.getElementById("block1").innerHTML =
getQueryVariable("param1");
$(document).ready(function() {
$("img#target").attr("src", "images/").html($("#block1").html());
});
```
Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.
Any help on this is highly appreciated.
Thank you very much in advance.
|
2018/10/18
|
[
"https://Stackoverflow.com/questions/52871388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725229/"
] |
You should do it like this :
```
$(document).ready(function() {
var param1 = getQueryVariable("param1");
$("img#target").attr("src", "images/"+param1);
$("#block1").html(param1);
});
```
Put your param into a variable and then use it to change your SRC attribute and to put the content into your div.
|
```
$("img#target").attr("src", "images/"+$("#block1").html());
```
|
52,871,388 |
I am trying to get parameter value from the url, add it inside a div and then clone that value inside the img src attribute.
I can get the parameter value inside a div, and get it to clone as well but it's doing it like this:
`<img id="target" src="images/">samplevalue.png</img>`
I need to do like it this:
`<img id="target" src="images/samplevalue.png" />`
Sample parameter: `param1=samplevalue.png`
here's the code:
**html**
```
<div id="block1"></div>
<img id="target" src=""/>
```
**jQuery/Javascript**
```
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return decodeURIComponent(pair[1].replace(/\+/g, " "));
}
}
return decodeURIComponent(pair[1]);
}
document.getElementById("block1").innerHTML =
getQueryVariable("param1");
$(document).ready(function() {
$("img#target").attr("src", "images/").html($("#block1").html());
});
```
Even if adding the parameter value straight inside the img src attribute is fine too than adding first inside the div.
Any help on this is highly appreciated.
Thank you very much in advance.
|
2018/10/18
|
[
"https://Stackoverflow.com/questions/52871388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2725229/"
] |
You have to add the returned value from the function as part of the attribute `src`.
With `.html($("#block1").html())` on the image element, you are trying to set html on th image which is actually invalid:
Change the function to:
```
$(document).ready(function() {
var urlPart = getQueryVariable();
$("img#target").attr("src", "images/" + urlPart);
});
```
**Please Note:**
Since you are already using jQuery, I will suggest you not to mix JavaScript & jQuery if possible, like:
```
document.getElementById("block1").innerHTML = getQueryVariable("param1");
```
Could be easily written:
```
$('#block1').text(getQueryVariable("param1")); //text() is preferred when dealing with text content
```
|
You should do it like this :
```
$(document).ready(function() {
var param1 = getQueryVariable("param1");
$("img#target").attr("src", "images/"+param1);
$("#block1").html(param1);
});
```
Put your param into a variable and then use it to change your SRC attribute and to put the content into your div.
|
23,272,695 |
I'm working on MySQL Workbench Version 6.1 (6.1.4.11773 build 1454). I see too bugs in Workbench. But there are issue only on using gui. There are no bug or issue with codes, query so manually. I cant change auto increment with checkbox of alter table. But i can change with codes. I can't set foreign key without codes. There is a checkbox issue of setting foreign key referenced column. But I can set same foreign key with codes. And When I set a Datatype look like "INT(11)", It's working but then It's looking this "(11)". I see a lot of thing like these. Are these bugs?
|
2014/04/24
|
[
"https://Stackoverflow.com/questions/23272695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3450409/"
] |
if you run mysql workbench in Turkish locale, it will not work correctly. Create a table with "INT" fields. Then save it. then try to alter the table. it will only display (11) as the field type. Because in Turkish locale, i and I are different letters. (corresponding to ı and İ) and this causes a problems while trying to create foreign keys. because it cannot find any columns with type (11).
Go to your **Server->Options File** and change these options to
1. Character-server-file => utf8
2. Collation-server => utf8\_general\_ci
It worked for me.
|
As I mentioned [here](https://stackoverflow.com/questions/23276172/mysql-workbench-integer-datatype-bugint-changes-11) before, I could only solved the issue with changing the "Regional format" setting of Windows 10 OS from "Turkish (Turkey)" to "English (United states)".
|
176,572 |
I am stumped...I have not had an electrical problem in my family room and have lived in this home for 11 years...until a few days ago. A few days ago I plugged a laptop charge cord (new and in normal condition) into an outlet in this circuit and it didn't work. I checked the breaker and it wasn't tripped so i flipped it OFF then back ON 2-3 times without remedy. Next, a single gang floor receptacle in that same circuit of 6 outlets, showed reverse polarity with my outlet tester. I checked it because for a long time the lamp that was plugged into this outlet has had a make/break intermittent connection at the plug/receptacle prong location with no concern for the outlet itself or it's wires being loose. I replaced the floor outlet (white to silver screw and black to copper with ground to green screw) thinking this could be shorting-out the circuit and the tester then showed all outlets in this circuit as OPEN NEUTRAL. I had not seen that previously and never had an issue with any outlets in this circuit...not even the outlet that first caught my attention with the laptop charge cord not powering on. I plugged the lamp in to this same floor outlet and it illuminated for 2 seconds then turned off. The entire circuit has not worked since the laptop charge cord failure.
Since then, I have checked ALL SIX circuit outlets, replaced all six receptacles using screw connections and not using stab connections, visibly checked all box wire connections (and all look very good). I then checked all other outlets in my home and all test 'Normal'. I even looked in my attics and crawl space. I looked for GFCI's that might have been tripped but all are normal (even turned them OFF then back ON). I turned my breaker for this circuit OFF then ON many times. I removed my panel door and made sure that this circuits black hot wire was screwed tightly to the breaker then followed this black wire to the romex panel entry location, located it's paired white neutral wire, followed that white wire to the panel bar it is screwed into and made sure it's connection is tight (both were affixed appropriately). I even checked and tightened ALL other wire screws on both panel bars. I was stumped...I even reversed the black and white wires in the floor outlet i installed just in case the manufacturer, Hubbell, made an error in assembly with the copper and silver screw locations. Of course, that showed reverse polarity so i returned that single gang receptacle to it's original and intended configuration (white on silver and black on copper).
End result, my family room circuit tests OPEN NEUTRAL despite my doing everything I know to do. This is a first floor room with a vaulted ceiling and no electrical outlets in this circuit outside of this one room (I tested). My crawl space, below, is clean and dry with no visible signs of wire damage. My panel screws are tight. My outlets have been replaced with new ones and screw connections were made tightly.
I also tried two different three prong testers with the same results. After reading some comments, i checked my attic where there is an attic vent fan that i know has been in disrepair for years...but it is on a different circuit and unrelated (when i turned off the family room circuit in question then tested the attic fan romex for current it is still hot)...so i assume this wouldn't relate to the open neutral family room circuit issue.
I am at a complete loss and would really appreciate any help.
|
2019/10/16
|
[
"https://diy.stackexchange.com/questions/176572",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/108147/"
] |
No never; you can never split a cable like that.
What you can do is transition to EMT conduit and individual THHN wires, which will pack nicely in EMT conduit.
I would start by heading to a proper electrical supply house for a **cable clamp** that is a proper fit for your large cable. You need a proper electrical supply because they have both the depth of stock and knowledge. Home Depot etc. will sell you the wrong thing with a smile.
Next, I would buy a large steel box, say 4-11/16" square deep, or 6" square, with knockouts that will fit that cable clamp.
I would use EMT metal conduit to plumb out of a knockout on the service panel, to a convenient location. This can be just a foot or two. There, install the box. Use the largest size EMT the panel knockout can accept (3/4", surely) and correct fittings. If the junction box hole is too large, they make special washers to solve that, but then, you can't use the EMT as ground path, so run a #10 ground wire.
There should be a #10-32 tapped hole in the back of the box for a grounding screw. If you are wiring a ground wire through the EMT, pigtail off this.
Then, you terminate your cable in the large junction box in the normal way (give yourself 12" of wire length). Terminate the ground wire to the box chassis or other grounds.
For each of the hot and neutral wires, obtain the appropriate gauge copper THHN/THWN-2 wires with enough length to reach the breaker, run through the EMT and give 12" spare length in the box. You need one white or gray for the neutral, and two of any other color but green. Black and black is fine.
Run the three individual THHN wires through the EMT conduit, terminate one end at the breaker or neutral bar. Inside the box tie the individual wires to the wires of the cable.
Three THHN copper wires of #6 will certainly fit in a 3/4" EMT conduit, and are good for 70A. This is more than #6 cable.
If the wires are small enough, you can use large wire nuts for the splice, otherwise use right-sized Polaris style connectors. If your cable is aluminum, that is fine but you must use Polaris.
|
By "thick outdoor rated cable", do you mean the rubber insulated cord that is used for TEMPORARY connections and extension cords? Because if so, it is illegal for you to use this cord in any way as a permanent installation connected to your breaker panel, connector or not, conduit or no conduit.
|
71,285,354 |
I have a program where I need to append two `Vec<u8>` before they are are serialized.
Just to be sure how to do it, I made this example program:
```rust
let a: Vec<u8> = vec![1, 2, 3, 4, 5, 6];
let b: Vec<u8> = vec![7, 8, 9];
let c = [a, b].concat();
println!("{:?}", c);
```
Which works perfectly. The issue is now when I have to implement it in my own project.
Here I need to write a function, the function takes a struct as input that looks like this:
```
pub struct Message2 {
pub ephemeral_key_r: Vec<u8>,
pub c_r: Vec<u8>,
pub ciphertext2: Vec<u8>,
}
```
and the serialalization function looks like this:
```rust
pub fn serialize_message_2(msg: &Message2) -> Result<Vec<u8>> {
let c_r_and_ciphertext = [msg.c_r, msg.ciphertext2].concat();
let encoded = (
Bytes::new(&msg.ephemeral_key_r),
Bytes::new(&c_r_and_ciphertext),
);
Ok(cbor::encode_sequence(encoded)?)
}
```
The first issue that arises here is that it complains that `msg.ciphertext2` and `msg.c_r` are moved values. This makes sense, so I add an `&` in front of both of them.
However, when I do this, the call to `concat()` fails, with this type error:
```none
util.rs(77, 59): method cannot be called on `[&std::vec::Vec<u8>; 2]` due to unsatisfied trait bounds
```
So, when I borrow the values, then the expression `[&msg.c_r, &msg.ciphertext2]` becomes an array of two vec's, which there is not a `concat()` defined for.
I also tried calling clone on both vectors:
```rust
let c_r_and_ciphertext = [msg.c_r.clone(), msg.ciphertext2.clone()].concat();
```
and this actually works out!
But now I'm just wondering, why does borrowing the values change the types?
and is there any things to think about when slapping on `clone` to values that are moved, and where I cannot borrow for some reason?
|
2022/02/27
|
[
"https://Stackoverflow.com/questions/71285354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17083575/"
] |
The reasons on why `.concat()` behaves as it does are a bit awkward.
To be able to call `.concat()`, the `Concat` trait must be implemented. It [is implemented](https://doc.rust-lang.org/stable/std/slice/trait.Concat.html#implementors) on slices of strings, and slices of `V`, where `V` can be `Borrow`ed as slices of copyable `T`.
First, you're calling `concat` on an array, not a slice. However, auto-borrowing and [unsize coercion](https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions) are applied when [calling](https://doc.rust-lang.org/reference/expressions/method-call-expr.html) a function with `.`. This turns the `[V; 2]` into a `&[V]` (where `V = Vec<u8>` in the working case and `V = &Vec<u8>` in the non-workin case). Try calling `Concat::concat([a, b])` and you'll notice the difference.
So now is the question whether `V` can be borrowed as/into some `&[T]` (where `T = u8` in your case). Two possibilities exist:
* [There is](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#impl-Borrow%3C%5BT%5D%3E) an `impl<T> Borrow<[T]> for Vec<T>`, so `Vec<u8>` can be turned into `&[u8]`.
* [There is](https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html#impl-Borrow%3CT%3E) an `impl<'_, T> Borrow<T> for &'_ T`, so if you already have a `&[u8]`, that can be used.
However, there is no `impl<T> Borrow<[T]> for &'_ Vec<T>`, so concatting `[&Vec<_>]` won't work.
So much for the theory, on the practical side: You can avoid the `clone`s by using `[&msg.c_r[..], &msg.ciphertext2[..]].concat()`, because you'll be calling `concat` on `&[&[u8]]`. The `&x[..]` is a neat trick to turn the `Vec`s into slices (by slicing it, without slicing anything off…). You can also do that with `.borrow()`, but that's a bit more awkward, since you may need an extra type specification: `[msg.c_r.borrow(), msg.ciphertext2.borrow()].concat::<u8>()`
|
I tried to reproduce your error message, which this code does:
```
fn main() {
let a = vec![1, 2];
let b = vec![3, 4];
println!("{:?}", [&a, &b].concat())
}
```
gives:
```
error[E0599]: the method `concat` exists for array `[&Vec<{integer}>; 2]`, but its trait bounds were not satisfied
--> src/main.rs:4:31
|
4 | println!("{:?}", [&a, &b].concat())
| ^^^^^^ method cannot be called on `[&Vec<{integer}>; 2]` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`[&Vec<{integer}>]: Concat<_>`
```
It is a simple matter of helping the compiler to see that `&a` works perfectly fine as a slice, by calling it `&a[..]`:
```
fn main() {
let a = vec![1, 2];
let b = vec![3, 4];
println!("{:?}", [&a[..], &b[..]].concat())
}
```
>
> why does borrowing the values change the types?
>
>
>
Borrowing changes a type into a reference to that same type, so `T` to `&T`. These types are related, but are not the same.
>
> is there any things to think about when slapping on clone to values that are moved, and where I cannot borrow for some reason?
>
>
>
Cloning is a good way to sacrifice performance to make the borrow checker happy. It (usually) involves copying the entire memory that is cloned, but if your code is not performance critical (which most code is not), then it may still be a good trade-off...
|
61,755,360 |
I am successfully able to make a reusable stateful widget and added text but don't know about how to make reusable gesture detector
```
class HomeScreen extends StatefulWidget {
final String collectionName;
HomeScreen(this.collectionName);
@override
_HomeScreenState createState() => _HomeScreenState();
}
```
---
```
Text(widget.collectionName)
```
How to use a gesture detector like **TEXT** ????
|
2020/05/12
|
[
"https://Stackoverflow.com/questions/61755360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9963996/"
] |
I think what you want to do is add GestureDetector to your text and pass the function via HomeScreen. If that's what you are looking for then
```
class HomeScreen extends StatefulWidget {
final String collectionName;
final VoidCallBack onTap;
HomeScreen(this.collectionName,this.onTap);
@override
_HomeScreenState createState() => _HomeScreenState();
}
```
Your Text widget will be updated as
```
GestureDetector(
onTap:widget.onTap,
child:Text(widget.collectionName)
);
```
|
Example of how you can do this...
Make this..
```
Widget gestureDetectorforText(dynamic theText){
return GestureDetector(
onTap: your function here..
child: Text(theText)
);
}
```
So using that code means that you need to pass your widget.collectionName into it..
So whenever you call the widget gestureDetector()
You pass the widget.collection name into it like this..
`gesturedetector(widget.collectionName);`
|
32,129,795 |
I have a URL in a query string value that is similar to this one:
```
example.com/?p1=a1&p2=a2
```
And I have a query sting on my website that takes the URL and redirects to a certain page. Like this:
```
mysite.com/?url=example.com/?p1=a1&p2=a2
```
But the query string is misinterpreted. How can I separate the query string in the value URL from the actual URL? I have tried encoding the question marks and ampersands, but the page is missing the content from the value URL.
**EDIT:**
This is how I get the URL, through a javascript:
```
function nameps(url) {
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
```
|
2015/08/20
|
[
"https://Stackoverflow.com/questions/32129795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5249613/"
] |
how does the `url` value get passed to the javascript? That is the place you should be url-encoding the whole URL, to make
```
example.com/?p1=a1&p2=a2
```
be inputted into the javascript on your site as
```
example.com%2F%3Fp1%3Da1%26p2%3Da2
```
You will need to adjust your regex in your javascript to deal with this change in format or alternatively use a javascript url decoding function such as `decodeuri` .
[decodeURI()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI)
such as on your site:
```
function nameps(url) {
url = decodeURI(url); ///new line decodes the previously encoded URL
url = url.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + url + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) return "";
else {
return results[1];
}
}
```
This would also involve however you pass the `url` value to the function above, would have to include the line :
```
url = encodeURI(url);
```
In order to correctly encode and format the address given.
|
I wouldn't try to get too complicated with the query string. Instead of this:
```
mysite.com/?url=example.com/?p1=a1&p2=a2
```
I would do this:
```
mysite.com/?url=example.com&p1=a1&p2=a2
```
Then I would parse it up and rebuild the secondary url from the components.
Trying to pack a query string in a query string is asking for trouble. I wouldn't waste any time trying to get it to work that way.
|
7,886,504 |
I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
```
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
```
passes.
This test
```
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
```
fails:
```
Value of: address >> (4*8)
Actual: 4294967295
Expected: 0u
```
It seems that the variable is treated like a signed value, and thus results in sign-extension. (0xffffffff is 4294967295 in decimal).
Can anyone spot the difference?
|
2011/10/25
|
[
"https://Stackoverflow.com/questions/7886504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] |
It is undefined behaviour to shift a value greater than or equal the size in bits of the left operand (§5.8¶1). (I assume `unsigned long` is 32 bits from your comments about 0xfffffff being the expected result if you consider sign extension.)
Still, there's probably something that `ASSERT_EQ` does that causes the difference, as it works fine on GCC 4.5 [with good old `assert`](http://ideone.com/G3rOm).
|
Both those tests [pass on gcc-4.3.4](http://ideone.com/7Q1SZ) with plain old `assert`.
|
7,886,504 |
I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
```
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
```
passes.
This test
```
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
```
fails:
```
Value of: address >> (4*8)
Actual: 4294967295
Expected: 0u
```
It seems that the variable is treated like a signed value, and thus results in sign-extension. (0xffffffff is 4294967295 in decimal).
Can anyone spot the difference?
|
2011/10/25
|
[
"https://Stackoverflow.com/questions/7886504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] |
I think that this is all down to undefined behaviour. I believe that in bitwise shifts the results are undefined if the right operand is greater than or equal to the number of bits in the left operand.
|
Both those tests [pass on gcc-4.3.4](http://ideone.com/7Q1SZ) with plain old `assert`.
|
7,886,504 |
I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
```
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
```
passes.
This test
```
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
```
fails:
```
Value of: address >> (4*8)
Actual: 4294967295
Expected: 0u
```
It seems that the variable is treated like a signed value, and thus results in sign-extension. (0xffffffff is 4294967295 in decimal).
Can anyone spot the difference?
|
2011/10/25
|
[
"https://Stackoverflow.com/questions/7886504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] |
If `unsigned long` is 32 bits, then the behavior of shifting it by 32 bits is undefined. Quoting the C++ 2003 standard:
>
> The behavior is undefined if the right operand is negative, or greater
> than or equal to the length in bits of the promoted left operand.
>
>
>
Apparently the compile-time and run-time evaluations are done differently -- which is perfectly valid as long as they yield the same results in cases where it's defined.
(If `unsigned long` is wider than 32 bits on your system, this doesn't apply.)
|
Both those tests [pass on gcc-4.3.4](http://ideone.com/7Q1SZ) with plain old `assert`.
|
7,886,504 |
I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
```
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
```
passes.
This test
```
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
```
fails:
```
Value of: address >> (4*8)
Actual: 4294967295
Expected: 0u
```
It seems that the variable is treated like a signed value, and thus results in sign-extension. (0xffffffff is 4294967295 in decimal).
Can anyone spot the difference?
|
2011/10/25
|
[
"https://Stackoverflow.com/questions/7886504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] |
It is undefined behaviour to shift a value greater than or equal the size in bits of the left operand (§5.8¶1). (I assume `unsigned long` is 32 bits from your comments about 0xfffffff being the expected result if you consider sign extension.)
Still, there's probably something that `ASSERT_EQ` does that causes the difference, as it works fine on GCC 4.5 [with good old `assert`](http://ideone.com/G3rOm).
|
I think that this is all down to undefined behaviour. I believe that in bitwise shifts the results are undefined if the right operand is greater than or equal to the number of bits in the left operand.
|
7,886,504 |
I'm working with gcc 4.4.5, and have some difficulties in understanding the right shift operator on plain simple unsigned values...
This test
```
ASSERT_EQ( 0u, (unsigned long)(0xffffffff) >> (4*8) );
```
passes.
This test
```
unsigned long address = 0xffffffff;
ASSERT_EQ( 0u, address >> (4*8) );
```
fails:
```
Value of: address >> (4*8)
Actual: 4294967295
Expected: 0u
```
It seems that the variable is treated like a signed value, and thus results in sign-extension. (0xffffffff is 4294967295 in decimal).
Can anyone spot the difference?
|
2011/10/25
|
[
"https://Stackoverflow.com/questions/7886504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] |
It is undefined behaviour to shift a value greater than or equal the size in bits of the left operand (§5.8¶1). (I assume `unsigned long` is 32 bits from your comments about 0xfffffff being the expected result if you consider sign extension.)
Still, there's probably something that `ASSERT_EQ` does that causes the difference, as it works fine on GCC 4.5 [with good old `assert`](http://ideone.com/G3rOm).
|
If `unsigned long` is 32 bits, then the behavior of shifting it by 32 bits is undefined. Quoting the C++ 2003 standard:
>
> The behavior is undefined if the right operand is negative, or greater
> than or equal to the length in bits of the promoted left operand.
>
>
>
Apparently the compile-time and run-time evaluations are done differently -- which is perfectly valid as long as they yield the same results in cases where it's defined.
(If `unsigned long` is wider than 32 bits on your system, this doesn't apply.)
|
159,007 |
On one particular machine I often need to run `sudo` commands every now and then.
I am fine with entering password on `sudo` in most of the cases.
However there are **three `sudo` commands** I want to run **without entering password**:
* `sudo reboot`
* `sudo shutdown -r now`
* `sudo shutdown -P now`
How can I exclude these commands from password protection to `sudo`?
|
2012/07/03
|
[
"https://askubuntu.com/questions/159007",
"https://askubuntu.com",
"https://askubuntu.com/users/65496/"
] |
Use the `NOPASSWD` directive
----------------------------
You can use the `NOPASSWD` directive in your [`/etc/sudoers` file](http://manpages.ubuntu.com/manpages/precise/en/man5/sudoers.5.html).
If your user is called `user` and your host is called `host` you could add these lines to `/etc/sudoers`:
```
user host = (root) NOPASSWD: /sbin/shutdown
user host = (root) NOPASSWD: /sbin/reboot
```
This will allow the user `user` to run the desired commands on `host` without entering a password. All other [`sudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/sudo.8.html)ed commands will still require a password.
The commands specified in the `sudoers` file *must* be fully qualified (i.e. using the absolute path to the command to run) as described in the [`sudoers` man page](http://manpages.ubuntu.com/manpages/precise/en/man5/sudoers.5.html). Providing a relative path is considered a syntax error.
If the command ends with a trailing `/` character and points to a directory, the user will be able to run any command in that directory (but not in any sub-directories therein). In the following example, the user `user` can run any command in the directory `/home/someuser/bin/`:
```
user host = (root) NOPASSWD: /home/someuser/bin/
```
**Note:** Always use the command [`visudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/visudo.8.html) to edit the `sudoers` file to make sure you do not lock yourself out of the system – just in case you accidentally write something incorrect to the `sudoers` file. `visudo` will save your modified file to a temporary location and will *only* overwrite the real `sudoers` file if the modified file can be parsed without errors.
Using `/etc/sudoers.d` instead of modifying `/etc/sudoers`
----------------------------------------------------------
As an alternative to editing the `/etc/sudoers` file, you could add the two lines to a new file in `/etc/sudoers.d` e.g. `/etc/sudoers.d/shutdown`. This is an elegant way of separating different changes to the `sudo` rights and also leaves the original `sudoers` file untouched for easier upgrades.
**Note:** Again, you should use the command [`visudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/visudo.8.html) to edit the file to make sure you do not lock yourself out of the system:
```
sudo visudo -f /etc/sudoers.d/shutdown
```
This also automatically ensures that the owner and permissions of the new file is set correctly.
If `sudoers` is messed up
-------------------------
If you did not use `visudo` to edit your files and then accidentally messed up `/etc/sudoers` or messed up a file in `/etc/sudoers.d` then you will be locked out of `sudo`.
The solution could be to fix the files using [`pkexec`](http://manpages.ubuntu.com/manpages/precise/en/man1/pkexec.1.html) which is an alternative to `sudo`.
To fix `/etc/sudoers`:
```
pkexec visudo
```
To fix `/etc/sudoers.d/shutdown`:
```
pkexec visudo -f /etc/sudoers.d/shutdown
```
If the ownership and/or permissions are incorrect for any `sudoers` file, the file will be ignored by `sudo` so you might also find yourself locked out in this situation. Again, you can use `pkexec` to fix this.
The correct permissions should be like this:
```
$ ls -l /etc/sudoers.d/shutdown
-r--r----- 1 root root 86 Jul 16 15:37 /etc/sudoers.d/shutdown
```
Use `pkexec` like this to fix [ownership and permissions](https://help.ubuntu.com/community/FilePermissions):
```
pkexec chown root:root /etc/sudoers.d/shutdown
pkexec chmod 0440 /etc/sudoers.d/shutdown
```
|
Sorry but there's so much confusion over this and some really complicated answers, that i feel i must weigh in here before someone misunderstands and does something crazy.
**Using visudo!!**
```
visudo
```
Add the following lines to the config:
```
ALL ALL=NOPASSWD: /sbin/reboot,/sbin/shutdown
```
This allows the commands, reboot and shutdown with any parameters to be executed from any user. The first "ALL" refers to the users, so it means ALL users. The second ALL refers to ALL hosts.
For a more verbose explanation see `man sudoers` as this provides further examples and these examples are several pages down but they are actually there if you dig deep enough.
Please stackexchange, just give simple, succinct answers.
|
159,007 |
On one particular machine I often need to run `sudo` commands every now and then.
I am fine with entering password on `sudo` in most of the cases.
However there are **three `sudo` commands** I want to run **without entering password**:
* `sudo reboot`
* `sudo shutdown -r now`
* `sudo shutdown -P now`
How can I exclude these commands from password protection to `sudo`?
|
2012/07/03
|
[
"https://askubuntu.com/questions/159007",
"https://askubuntu.com",
"https://askubuntu.com/users/65496/"
] |
Use the `NOPASSWD` directive
----------------------------
You can use the `NOPASSWD` directive in your [`/etc/sudoers` file](http://manpages.ubuntu.com/manpages/precise/en/man5/sudoers.5.html).
If your user is called `user` and your host is called `host` you could add these lines to `/etc/sudoers`:
```
user host = (root) NOPASSWD: /sbin/shutdown
user host = (root) NOPASSWD: /sbin/reboot
```
This will allow the user `user` to run the desired commands on `host` without entering a password. All other [`sudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/sudo.8.html)ed commands will still require a password.
The commands specified in the `sudoers` file *must* be fully qualified (i.e. using the absolute path to the command to run) as described in the [`sudoers` man page](http://manpages.ubuntu.com/manpages/precise/en/man5/sudoers.5.html). Providing a relative path is considered a syntax error.
If the command ends with a trailing `/` character and points to a directory, the user will be able to run any command in that directory (but not in any sub-directories therein). In the following example, the user `user` can run any command in the directory `/home/someuser/bin/`:
```
user host = (root) NOPASSWD: /home/someuser/bin/
```
**Note:** Always use the command [`visudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/visudo.8.html) to edit the `sudoers` file to make sure you do not lock yourself out of the system – just in case you accidentally write something incorrect to the `sudoers` file. `visudo` will save your modified file to a temporary location and will *only* overwrite the real `sudoers` file if the modified file can be parsed without errors.
Using `/etc/sudoers.d` instead of modifying `/etc/sudoers`
----------------------------------------------------------
As an alternative to editing the `/etc/sudoers` file, you could add the two lines to a new file in `/etc/sudoers.d` e.g. `/etc/sudoers.d/shutdown`. This is an elegant way of separating different changes to the `sudo` rights and also leaves the original `sudoers` file untouched for easier upgrades.
**Note:** Again, you should use the command [`visudo`](http://manpages.ubuntu.com/manpages/precise/en/man8/visudo.8.html) to edit the file to make sure you do not lock yourself out of the system:
```
sudo visudo -f /etc/sudoers.d/shutdown
```
This also automatically ensures that the owner and permissions of the new file is set correctly.
If `sudoers` is messed up
-------------------------
If you did not use `visudo` to edit your files and then accidentally messed up `/etc/sudoers` or messed up a file in `/etc/sudoers.d` then you will be locked out of `sudo`.
The solution could be to fix the files using [`pkexec`](http://manpages.ubuntu.com/manpages/precise/en/man1/pkexec.1.html) which is an alternative to `sudo`.
To fix `/etc/sudoers`:
```
pkexec visudo
```
To fix `/etc/sudoers.d/shutdown`:
```
pkexec visudo -f /etc/sudoers.d/shutdown
```
If the ownership and/or permissions are incorrect for any `sudoers` file, the file will be ignored by `sudo` so you might also find yourself locked out in this situation. Again, you can use `pkexec` to fix this.
The correct permissions should be like this:
```
$ ls -l /etc/sudoers.d/shutdown
-r--r----- 1 root root 86 Jul 16 15:37 /etc/sudoers.d/shutdown
```
Use `pkexec` like this to fix [ownership and permissions](https://help.ubuntu.com/community/FilePermissions):
```
pkexec chown root:root /etc/sudoers.d/shutdown
pkexec chmod 0440 /etc/sudoers.d/shutdown
```
|
The answer mentioning to set a *host* confused me, as I want to be able to have a *sudo* user be able to run privileged commands without requiring to consider such "host aspect"; any host should work, hence I use the special `ALL` reserved word.
Let's assume you want all *sudo* users (i.e., Unix users which are members of the Unix group *sudo*) to run the following commands as [*superuser*](https://en.wikipedia.org/wiki/Superuser) (*root*) without having to enter their passwords:
* `sudo iftop`
* `sudo dbus-monitor --system`
First find out the executable's full path using `which`:
* `which iftop` > `/usr/sbin/iftop`
* `which dbus-monitor` > `/usr/bin/dbus-monitor`
Assuming the main *sudo* configuration file `etc/sudoers` contains the following directive (an Ubuntu default) ...
```
#includedir /etc/sudoers.d
```
... then it is a best practice to add your configuration in its own separate file within the `/etc/sudoers.d/` directory, e.g. `/etc/sudoers.d/customizations`. This way, you will not run into problems when an update to the original *sudo* package wants to change the original `/etc/sudoers` file and the package manager notices conflicting edits done by you.
Run the following command to create and edit your own *sudo* customization file:
```
sudo visudo -f /etc/sudoers.d/customizations
```
Using the `visudo` command makes sure that there are no syntax erros in the file when saving it - syntax errors would otherwise make *sudo* fail to read all its configuration files, thereby breaking any subsequent `sudo` usage, effectively locking you out from any superuser usage, including fixing the syntax erros.
Now add the following lines to this file and save it:
```
%sudo ALL=NOPASSWD: /usr/sbin/iftop
%sudo ALL=NOPASSWD: /usr/bin/dbus-monitor --system
```
The `%sudo` at the beginning of these lines indicate they are rules for all members of group ("`%`") *sudo*.
Changes to *sudo* configuration files, including new files within the `/etc/sudoers.d/` directory, take effect immediately - no sudo "restart" required.
Now notice what happens when running the following commands: (for testing purposes, any current *sudo* ticket, i.e. the timespan without requiring to reenter the password, can be directly revoked/timed-out by executing `sudo -k`)
* `iftop`: fails with `You don't have permission to capture on that device (socket: Operation not permitted)`. This is because running the configured commands without the `sudo` prefix behave unprivileged as usual.
* `sudo iftop`: this command will now run successfully without requiring a password.
* `sudo iftop -B` ("*display bandwidth in bytes*"): this command will also run successfully without requiring a password, because, as `man sudoers` explains, "*a simple file name [without parameters, in the configuration file] allows the user to run the command with any arguments they wish.*"
* `sudo dbus-monitor`: the system will ask for password, because, as `man sudoers` explains, "*if a [command, in the configuration file] has associated command line arguments, then the arguments in the [command] must match exactly those given by the user on the command line (or match the wildcards if there are any).*"
* `sudo dbus-monitor --system`: this command will now run successfully without requiring a password.
* `sudo dbus-monitor --system --foo`: the system will ask for password, as the arguments don't match the configuration.
Coming back to the initial question, for all users in the *sudo* group to be allowed to run the following commands without asking for their passwords ...
```
sudo reboot
sudo shutdown -r now
sudo shutdown -P now
```
... create a sudo configuration file with the following content (assuming Ubuntu standard locations for the executables `reboot` and `shutdown`):
```
%sudo ALL=NOPASSWD: /usr/sbin/reboot
%sudo ALL=NOPASSWD: /usr/sbin/shutdown -r now
%sudo ALL=NOPASSWD: /usr/sbin/shutdown -P now
```
Notice with this configuration, any *sudo* user can now also run `sudo reboot ...` **with any arguments, flags, and parameters** without having to provide a password, including e.g. `sudo reboot --poweroff --force`.
If this is not desired, but instead only `sudo reboot` **without any arguments/flags/parameters** shall be allowed, its configuration line has to be changed to ...
```
%sudo ALL=NOPASSWD: /usr/sbin/reboot ""
```
... because as `man sudoers` explains: "*you can specify "" to indicate that the command may only be run without command line arguments.*"
|
159,007 |
On one particular machine I often need to run `sudo` commands every now and then.
I am fine with entering password on `sudo` in most of the cases.
However there are **three `sudo` commands** I want to run **without entering password**:
* `sudo reboot`
* `sudo shutdown -r now`
* `sudo shutdown -P now`
How can I exclude these commands from password protection to `sudo`?
|
2012/07/03
|
[
"https://askubuntu.com/questions/159007",
"https://askubuntu.com",
"https://askubuntu.com/users/65496/"
] |
Sorry but there's so much confusion over this and some really complicated answers, that i feel i must weigh in here before someone misunderstands and does something crazy.
**Using visudo!!**
```
visudo
```
Add the following lines to the config:
```
ALL ALL=NOPASSWD: /sbin/reboot,/sbin/shutdown
```
This allows the commands, reboot and shutdown with any parameters to be executed from any user. The first "ALL" refers to the users, so it means ALL users. The second ALL refers to ALL hosts.
For a more verbose explanation see `man sudoers` as this provides further examples and these examples are several pages down but they are actually there if you dig deep enough.
Please stackexchange, just give simple, succinct answers.
|
The answer mentioning to set a *host* confused me, as I want to be able to have a *sudo* user be able to run privileged commands without requiring to consider such "host aspect"; any host should work, hence I use the special `ALL` reserved word.
Let's assume you want all *sudo* users (i.e., Unix users which are members of the Unix group *sudo*) to run the following commands as [*superuser*](https://en.wikipedia.org/wiki/Superuser) (*root*) without having to enter their passwords:
* `sudo iftop`
* `sudo dbus-monitor --system`
First find out the executable's full path using `which`:
* `which iftop` > `/usr/sbin/iftop`
* `which dbus-monitor` > `/usr/bin/dbus-monitor`
Assuming the main *sudo* configuration file `etc/sudoers` contains the following directive (an Ubuntu default) ...
```
#includedir /etc/sudoers.d
```
... then it is a best practice to add your configuration in its own separate file within the `/etc/sudoers.d/` directory, e.g. `/etc/sudoers.d/customizations`. This way, you will not run into problems when an update to the original *sudo* package wants to change the original `/etc/sudoers` file and the package manager notices conflicting edits done by you.
Run the following command to create and edit your own *sudo* customization file:
```
sudo visudo -f /etc/sudoers.d/customizations
```
Using the `visudo` command makes sure that there are no syntax erros in the file when saving it - syntax errors would otherwise make *sudo* fail to read all its configuration files, thereby breaking any subsequent `sudo` usage, effectively locking you out from any superuser usage, including fixing the syntax erros.
Now add the following lines to this file and save it:
```
%sudo ALL=NOPASSWD: /usr/sbin/iftop
%sudo ALL=NOPASSWD: /usr/bin/dbus-monitor --system
```
The `%sudo` at the beginning of these lines indicate they are rules for all members of group ("`%`") *sudo*.
Changes to *sudo* configuration files, including new files within the `/etc/sudoers.d/` directory, take effect immediately - no sudo "restart" required.
Now notice what happens when running the following commands: (for testing purposes, any current *sudo* ticket, i.e. the timespan without requiring to reenter the password, can be directly revoked/timed-out by executing `sudo -k`)
* `iftop`: fails with `You don't have permission to capture on that device (socket: Operation not permitted)`. This is because running the configured commands without the `sudo` prefix behave unprivileged as usual.
* `sudo iftop`: this command will now run successfully without requiring a password.
* `sudo iftop -B` ("*display bandwidth in bytes*"): this command will also run successfully without requiring a password, because, as `man sudoers` explains, "*a simple file name [without parameters, in the configuration file] allows the user to run the command with any arguments they wish.*"
* `sudo dbus-monitor`: the system will ask for password, because, as `man sudoers` explains, "*if a [command, in the configuration file] has associated command line arguments, then the arguments in the [command] must match exactly those given by the user on the command line (or match the wildcards if there are any).*"
* `sudo dbus-monitor --system`: this command will now run successfully without requiring a password.
* `sudo dbus-monitor --system --foo`: the system will ask for password, as the arguments don't match the configuration.
Coming back to the initial question, for all users in the *sudo* group to be allowed to run the following commands without asking for their passwords ...
```
sudo reboot
sudo shutdown -r now
sudo shutdown -P now
```
... create a sudo configuration file with the following content (assuming Ubuntu standard locations for the executables `reboot` and `shutdown`):
```
%sudo ALL=NOPASSWD: /usr/sbin/reboot
%sudo ALL=NOPASSWD: /usr/sbin/shutdown -r now
%sudo ALL=NOPASSWD: /usr/sbin/shutdown -P now
```
Notice with this configuration, any *sudo* user can now also run `sudo reboot ...` **with any arguments, flags, and parameters** without having to provide a password, including e.g. `sudo reboot --poweroff --force`.
If this is not desired, but instead only `sudo reboot` **without any arguments/flags/parameters** shall be allowed, its configuration line has to be changed to ...
```
%sudo ALL=NOPASSWD: /usr/sbin/reboot ""
```
... because as `man sudoers` explains: "*you can specify "" to indicate that the command may only be run without command line arguments.*"
|
13,660,459 |
How to write a script in AHK that pastes a text, waits one minute, then pastes again?
AHK=AutoHotKey
Not for spamming, it's for one of my own web projects.
I should specify: the script needs to paste a text, press return, wait one minute then paste again. If it doesn't press return it doesn't work.
|
2012/12/01
|
[
"https://Stackoverflow.com/questions/13660459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/693798/"
] |
SetTimer is better than sleep for something like this.
```
#Persistent
; Put this wherever you want, like inside a hotkey
; Either set the clipboard to some text, or just remove this
; to use what's already there
Clipboard = This is some text to paste
SendInput ^v{Enter}
last_text := Clipboard
SetTimer, RePaste, 60000
return
RePaste:
; The clipboard can change in a minute, right?
; so we use the text we had before
tmp := clipboard
Clipboard := last_text
SendInput ^v{Enter}
; And restore what the user had
Clipboard := tmp
return
; Put this somewhere, like in a hotkey, to turn off the timer
SetTimer, RePaste, off
```
|
```
#NoEnv
Loop
{
SendInput, ^v
Sleep, 60000
}
Capslock::ExitApp
```
Press caps lock to stop pasting. For text defined in code:
```
#NoEnv
Loop
{
SendInput, This is the text I want to send{Enter}
Sleep, 60000
}
Capslock::ExitApp
```
|
39,996,955 |
I am trying to create a custom menu element by using this in the Page TSConfig:
```
TCEFORM.tt_content {
menu_type.addItems.101 = My Menu
}
```
And this in Setup:
```
temp.my_menu = HMENU
temp.my_menu {
special = list
special.value.field = pages
1 = TMENU
1 {
wrap = <ul> | </ul>
NO = 1
NO.wrapItemAndSub = <li>|</li>
}
}
tt_content.menu.20.101 < temp.my_menu
```
But I get 'Oops, an error occurred!' where the menu should be.
It will render fine if I remove the Fluid includes in the template but then all the other content elements give errors.
Is there any way to have a typoscript menu element at the same time as fluid styled content?
Or if I really have to, how do I add a custom fluid menu template?
|
2016/10/12
|
[
"https://Stackoverflow.com/questions/39996955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369794/"
] |
A naive (but quick to implement) approach: run `uname -a` first and push that into a variable. Then check if that output contains "Ubuntu".
If so, you should be using the ":" as separator; otherwise ";" should do.
And if you want to be prepared for other platforms in the future; instead of doing a simple if/else; you might want to check what `uname -a` has to say on cygwin; to setup some `$SEPARATOR_CHAR` variable using a bash [switch](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html) statement.
|
Just to provide the final solution:
I just tested `uname -s` on Ubuntu, Mac, and Windows running cygwin and came up with following script:
```
if [ "$(uname)" == "Darwin" ]; then
# Do something under Mac OS X platform
SEP=":"
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]; then
# Do something under GNU/Linux platform
SEP=":"
elif [ "$(expr substr $(uname -s) 1 6)" == "CYGWIN" ]; then
# Do something under Windows NT platform
SEP=";"
fi
```
|
25,344,667 |
I have a game that is sold on Steam, and as such uses the Steamworks SDK. This has an automatic error-collecting tool [as described briefly here](http://www.steampowered.com/steamworks/developmenttools.php).
Every time my game generates an unhandled exception, it is logged on the tool's web site. I've noticed that when the crash occurs on MY development build, the logged crash includes filenames and line numbers. However, when the crash occurs on a user machine, this info is absent.
* Is this probably because I have the PDBs on my machine but not the user's machine?
* Are there any compilation flags that might bake limited information into the EXE, so that the error reporting tool might be able to grab it?
I realize this is a bit of a longshot question and asked in relation to a specific tool. I asked because I'm hoping there is general knowledge (about compilation flags, etc) which I can apply to my specific situation.
|
2014/08/16
|
[
"https://Stackoverflow.com/questions/25344667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986620/"
] |
I don't know Steamworks SDK, but will at least try to explain common usage of preprocessor `NDEBUG`, `_DEBUG`, `__FILE__` and `__LINE__` on classic `assert.h` (taken from Windows SDK / VC include):
```
#include <crtdefs.h>
#undef assert
#ifdef NDEBUG
#define assert(_Expression) ((void)0)
#else
#ifdef __cplusplus
extern "C" {
#endif
_CRTIMP void __cdecl _wassert(_In_z_ const wchar_t * _Message, _In_z_ const wchar_t *_File, _In_ unsigned _Line);
#ifdef __cplusplus
}
#endif
#define assert(_Expression) (void)( (!!(_Expression)) || (_wassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), __LINE__), 0) )
#endif /* NDEBUG */
```
**Release Build** usually disables asserts by defining `NDEBUG` while **Debug Build** usually leave `NDEBUG` undefined (to enable asserts) and include `_DEBUG` for additional checks (while ***Work Build*** may have both undefined). Look at the definition of assert:
```
#define assert(_Expression) (void)( (!!(_Expression)) \
|| (_wassert(_CRT_WIDE(#_Expression), \
_CRT_WIDE(__FILE__), __LINE__), 0) )
```
***If everything else fails*** (defining/undefining `NDEBUG` / `_DEBUG`) **you can use `__FILE__` and `__LINE__` yourself** - to include that in whatever message string you are passing to the engine (or to those exceptions you may throw).
|
I'm going to presume you export code in Release Mode in Visual Studio, as opposed to Debug.
Visual Studio removes (by optimizing) some debugging elements, such as Memory Logging (\_CrtDumpMemoryLeaks), but I am not an expert in what it does and doesn't remove. I would start with the link below, which covers debugging in release mode.
<http://msdn.microsoft.com/en-us/library/fsk896zz.aspx>
|
41,619,686 |
I have a Toggle switch. I want not to check or uncheck the toggle at first. To be precise, toggle will be checked or unchecked based on a server response which is why I need to use `preventDefault`.
I have used `ionChange()` instead of `click()` event handler. But with `ionChange` handler, the `cancelable` or `defaultPrevented` property does not exists. So, it raises error that `preventDefault()` is not a function. However, with simple click handler, it does not raise any error but does not work either. I have also tried with `stopPropagation()`.
Here is the code.
**HTML:**
```
<ion-item>
<ion-toggle [(ngModel)]="appliance.state" (ionChange)="applianceChange($event)"></ion-toggle>
</ion-item>
```
**TS:**
```
import { Component, EventEmitter } from '@angular/core';
@Component({
selector: 'appliances',
templateUrl: 'appliances.html'
})
export class ApplianceModule {
constructor(){}
applianceChange(event: Event){
event.preventDefault();
}
}
```
|
2017/01/12
|
[
"https://Stackoverflow.com/questions/41619686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3397015/"
] |
If you don't want to use `socket.io`, you can use `AJAX` calls but I think it's the more painful way...
If you use `socket.io`, there are great examples on their GitHub : [Chat example](https://github.com/socketio/socket.io/tree/master/examples/chat).
In your NodeJS :
```js
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', incremental);
socket.emit('update-value', incremental); // Emit on the opened socket.
incremental++;
}, 1000);
});
```
This code should be start in your application.
And in your view :
```html
<html>
<body>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
```
My code isn't complete but shows the essential to know.
|
Try Templating and template engines.
Template engine are stuff that enable you to pass variables to Templates. These engines render the template file, with data you provide in form of HTML page.
I will suggest you to try 'ejs', as it very closely signify HTML files. ejs template are simply HTML syntax with placefolder for you to pass Data.
But that will require you to refresh the page continously after regular time. So you can try 'AJAX' which let you refresh part of page, simultaneously sends and receives data from server
|
39,576,760 |
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
```
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
```
And this is the test:
```
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
```
It crash when try to do `context.getResources().getString(R.string.sInicialLunes))`
If I put 'Mon' instead of `context.getResources().getString(R.string.sInicialLunes))` or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
```
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
```
Thanks
|
2016/09/19
|
[
"https://Stackoverflow.com/questions/39576760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4869917/"
] |
If you are using `Context` only for obtaining `String` resource, I would go by mocking only `getResources().getString()` part like this (see JUnit4 notation):
```
@RunWith(MockitoJUnitRunner.class)
public class AlertaPOJOTest {
@Mock
Context mMockContext;
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
when(mMockContext.getString(R.string.sInicialLunes))
.thenReturn(INITIAL_LUNES);
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
}
```
There are many reasons to stay with JVM tests, most important one, they are running quicker.
|
You don't have a real android Context while you are using JVM unit test. For your case, maybe you can try Android Instrumentation Test, typically it is implemented in the "androidTest" directory of your project.
|
39,576,760 |
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
```
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
```
And this is the test:
```
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
```
It crash when try to do `context.getResources().getString(R.string.sInicialLunes))`
If I put 'Mon' instead of `context.getResources().getString(R.string.sInicialLunes))` or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
```
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
```
Thanks
|
2016/09/19
|
[
"https://Stackoverflow.com/questions/39576760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4869917/"
] |
You don't have a real android Context while you are using JVM unit test. For your case, maybe you can try Android Instrumentation Test, typically it is implemented in the "androidTest" directory of your project.
|
If you use [MockK](https://mockk.io/) it's the same.
```
@RunWith(AndroidJUnit4::class)
class YourClassUnitTest : TestCase() {
@MockK
private lateinit var resources: Resources
@Before
public override fun setUp() {
MockKAnnotations.init(this)
}
@Test
fun test() {
every {
resources.getQuantityString(R.plurals.age, YEARS, YEARS)
} returns AGE
every {
resources.getString(
R.string.surname,
SURNAME
)
} returns TITLE
// Assume you test this method that returns data class
// (fields are calculated with getQuantityString and getString)
val data = getData(YEARS, SURNAME)
assertEquals(AGE, data.age)
assertEquals(TITLE, data.title)
}
companion object {
const val YEARS = 10
const val AGE = "$YEARS years"
const val SURNAME = "Johns"
const val TITLE = "Mr. $SURNAME"
}
}
```
See also [Skip a parameter in MockK unit test, Kotlin](https://stackoverflow.com/questions/71676134/skip-a-parameter-in-mockk-unit-test-kotlin) to get a result of string resources for any data.
|
39,576,760 |
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
```
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
```
And this is the test:
```
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
```
It crash when try to do `context.getResources().getString(R.string.sInicialLunes))`
If I put 'Mon' instead of `context.getResources().getString(R.string.sInicialLunes))` or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
```
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
```
Thanks
|
2016/09/19
|
[
"https://Stackoverflow.com/questions/39576760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4869917/"
] |
If you are using `Context` only for obtaining `String` resource, I would go by mocking only `getResources().getString()` part like this (see JUnit4 notation):
```
@RunWith(MockitoJUnitRunner.class)
public class AlertaPOJOTest {
@Mock
Context mMockContext;
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
when(mMockContext.getString(R.string.sInicialLunes))
.thenReturn(INITIAL_LUNES);
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
}
```
There are many reasons to stay with JVM tests, most important one, they are running quicker.
|
Untested: would it work to use the below, and probably targetContext?
```
android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
```
|
39,576,760 |
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
```
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
```
And this is the test:
```
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
```
It crash when try to do `context.getResources().getString(R.string.sInicialLunes))`
If I put 'Mon' instead of `context.getResources().getString(R.string.sInicialLunes))` or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
```
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
```
Thanks
|
2016/09/19
|
[
"https://Stackoverflow.com/questions/39576760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4869917/"
] |
If you are using `Context` only for obtaining `String` resource, I would go by mocking only `getResources().getString()` part like this (see JUnit4 notation):
```
@RunWith(MockitoJUnitRunner.class)
public class AlertaPOJOTest {
@Mock
Context mMockContext;
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
when(mMockContext.getString(R.string.sInicialLunes))
.thenReturn(INITIAL_LUNES);
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
}
```
There are many reasons to stay with JVM tests, most important one, they are running quicker.
|
If you use [MockK](https://mockk.io/) it's the same.
```
@RunWith(AndroidJUnit4::class)
class YourClassUnitTest : TestCase() {
@MockK
private lateinit var resources: Resources
@Before
public override fun setUp() {
MockKAnnotations.init(this)
}
@Test
fun test() {
every {
resources.getQuantityString(R.plurals.age, YEARS, YEARS)
} returns AGE
every {
resources.getString(
R.string.surname,
SURNAME
)
} returns TITLE
// Assume you test this method that returns data class
// (fields are calculated with getQuantityString and getString)
val data = getData(YEARS, SURNAME)
assertEquals(AGE, data.age)
assertEquals(TITLE, data.title)
}
companion object {
const val YEARS = 10
const val AGE = "$YEARS years"
const val SURNAME = "Johns"
const val TITLE = "Mr. $SURNAME"
}
}
```
See also [Skip a parameter in MockK unit test, Kotlin](https://stackoverflow.com/questions/71676134/skip-a-parameter-in-mockk-unit-test-kotlin) to get a result of string resources for any data.
|
39,576,760 |
I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
```
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
```
And this is the test:
```
@Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
```
It crash when try to do `context.getResources().getString(R.string.sInicialLunes))`
If I put 'Mon' instead of `context.getResources().getString(R.string.sInicialLunes))` or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
```
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
```
Thanks
|
2016/09/19
|
[
"https://Stackoverflow.com/questions/39576760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4869917/"
] |
Untested: would it work to use the below, and probably targetContext?
```
android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
```
|
If you use [MockK](https://mockk.io/) it's the same.
```
@RunWith(AndroidJUnit4::class)
class YourClassUnitTest : TestCase() {
@MockK
private lateinit var resources: Resources
@Before
public override fun setUp() {
MockKAnnotations.init(this)
}
@Test
fun test() {
every {
resources.getQuantityString(R.plurals.age, YEARS, YEARS)
} returns AGE
every {
resources.getString(
R.string.surname,
SURNAME
)
} returns TITLE
// Assume you test this method that returns data class
// (fields are calculated with getQuantityString and getString)
val data = getData(YEARS, SURNAME)
assertEquals(AGE, data.age)
assertEquals(TITLE, data.title)
}
companion object {
const val YEARS = 10
const val AGE = "$YEARS years"
const val SURNAME = "Johns"
const val TITLE = "Mr. $SURNAME"
}
}
```
See also [Skip a parameter in MockK unit test, Kotlin](https://stackoverflow.com/questions/71676134/skip-a-parameter-in-mockk-unit-test-kotlin) to get a result of string resources for any data.
|
49,547,282 |
I am trying to stub `os.Stat` and `ioutil.ReadFile(path)` as used the code below or if you like here on go playground [1]
```
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func AssignFileValueFrom(path string, val *string) {
var (
tempValue []byte
err error
)
if _, err = os.Stat(path); err == nil {
if err != nil {
fmt.Println("There was a os stat error:", err)
}
tempValue, err = ioutil.ReadFile(path)
if err != nil {
fmt.Println("There was an io read error:", err)
}
*val = strings.TrimSpace(string(tempValue))
}
}
```
I have used testify and tried following the example here [2]
```
package main
import (
"testing"
"github.com/stretchr/testify/mock"
)
type osMock struct {
mock.Mock
}
func (o osMock) Stat(path string) (interface{}, error) {
return nil, nil
}
func TestAssignFileValueFrom(t *testing.T) {
var test string
osm := new(osMock)
osm.On(`Stat`, `./.test`).Return([]byte(`1`), nil)
AssignFileValueFrom(`./.test`, &test)
// assert.Equal(t, `1`, test)
osm.AssertExpectations(t)
}
```
What am I not doing correctly??
[1] <https://play.golang.org/p/xcbdMkMwoBN>
[2] <https://github.com/stretchr/testify#mock-package>
|
2018/03/29
|
[
"https://Stackoverflow.com/questions/49547282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4154266/"
] |
It worked for me with below query :
```
INSERT INTO mydata (col1, col2)
values(123,(SELECT col2 FROM (SELECT col2 FROM mydata) a));
```
|
Look This :
```
SELECT ID FROM Dealer WHERE Name='Enertia'
```
this query not return id of this name in db ..
|
3,357,740 |
Let $n\geq4$ be a positive integer and let $S=\{1,2,\ldots,n\}$. Find the number of functions $f:S\to S$ whose image has cardinality at most $n-3$.
---
I'm trying to do this using inclusion-exclusion. Immediately we know that the total # of functions is $n^n$. So then I want to subtract off the number of functions whose image has cardinality $n,n-1$, and $n-2$. The # of functions whose image has cardinality $n$ is akin to counting bijections based on the domain and codomain, so it's $n!$. The # of functions whose image has cardinality $n-1$ is a bit more complicated. I have $n$ choices for which element does not get hit in the codomain, and since functions are everywhere defined I have $n$ choices for which 1 element in my domain is "doubling up" via that particular map. So for this "block" I think it's $n^2$. Finally for the $n-2$ case, I have $\binom{n}{2}$ options for which 2 elements are missed, and I think I have again $\binom{n}{2}$ options for which elements get paired up.... So the answer is $n^n-n!-n^2-\binom{n}{2}^2$?
---
I'm betting what's wrong is I'm not imposing enough structure on what the maps do. I need to ensure, and only count the functions that *surject* onto $n-1$ and $n-2$. I'm stuck. If I'm correct about what I'm missing, then the answer will use Stirling numbers. So I think the answer is $n^n−n!−S(n,n−1)∗(n−1)!−S(n,n−2)∗(n−2)!$.
|
2019/09/15
|
[
"https://math.stackexchange.com/questions/3357740",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/286370/"
] |
* Number of functions whose image has cardinality $n-1$: there are $n$ ways to choose the number that is not in the image, and $n-1$ ways to choose which number is "mapped to twice" in the image. Finally there are $n!/2$ ways to assign these image elements as the targets of each domain element. So we have $n(n-1) n!/2$.
* Number of functions whose image has cardinality $n-2$: there are $\binom{n}{2}$ ways to choose the two numbers not in the image. Then one of two things can happen.
+ Two of the $n-2$ remaining numbers are "mapped to twice": there are $\binom{n-2}{2}$ ways to choose these two numbers. Finally there are $n!/4$ ways to assign these image elements as the targets of each domain element. So we have $\binom{n}{2} \binom{n-2}{2} n!/4$.
+ One of the $n-2$ remaining numbers is "mapped to three times": there are $n-2$ ways to choose this number. Then there are $n!/6$ ways to assign these image elements as the targets of each domain element. So we have $\binom{n}{2}(n-2) n!/6$.
|
Quite interestingly, the solution that angryavian provided matches (numerically, for small $n$'s tested) my answer with a slight tweak:
I failed to account for the number of options for which elements to disregard when looking at the Stirling numbers of the second kind. So, using Stirling numbers, the answer should be
$$n^n-n!-n!S(n,n-1)-\binom{n}{2}S(n,n-2)(n-2)!$$
|
1,714,480 |
I created my first public server - an SFTP server hosted on google cloud. I was checking the auth log during the 2nd day of testing and noticed that I'm getting 4-10 hits from random people every minute!! 3700 failed requests in 16 hrs - this seems ridiculous, so I want to know if there is any way to stop them. I have almost zero experience with firewalls - I was hoping to avoid defaulting to reject everyone and only allow whitelisted IPs, but maybe I'll have to consider it.
```bsh
Apr 4 13:34:05 nfp sshd[12034]: Failed password for invalid user tjkim from 134.122.9.249 port 48930 ssh2
Apr 4 13:34:13 nfp sshd[12107]: Failed password for invalid user barman from 198.58.119.132 port 39626 ssh2
Apr 4 13:34:16 nfp sshd[12119]: Failed password for invalid user rscreen from 203.205.37.233 port 33740 ssh2
Apr 4 13:34:16 nfp sshd[12121]: Failed password for invalid user oakda from 164.90.194.36 port 41566 ssh2
Apr 4 13:34:18 nfp sshd[12123]: Failed password for invalid user lia from 43.130.60.190 port 46610 ssh2
Apr 4 13:34:20 nfp sshd[12125]: Failed password for invalid user hongphong from 193.106.60.145 port 33020 ssh2
Apr 4 13:34:23 nfp sshd[12127]: Failed password for invalid user uucpsh from 157.245.101.31 port 59112 ssh2
Apr 4 13:34:27 nfp sshd[12129]: Failed password for invalid user legaltech from 43.154.249.125 port 33970 ssh2
Apr 4 13:34:51 nfp sshd[12132]: Failed password for invalid user dhamu from 164.90.198.71 port 36212 ssh2
Apr 4 13:34:57 nfp sshd[12134]: Failed password for invalid user onapp from 115.182.105.68 port 46286 ssh2
```
Any guidance for a newbie?
|
2022/04/04
|
[
"https://superuser.com/questions/1714480",
"https://superuser.com",
"https://superuser.com/users/312100/"
] |
* `Ctrl`+`H`
* Find what: `^.*<.+?>.*$(*SKIP)(*F)|.`
* Replace with: `LEAVE EMPTY`
* **CHECK** *Wrap around*
* **CHECK** *Regular expression*
* **UNCHECK** `. matches newline`
* `Replace all`
**Explanation:**
```none
^ # begining of line
.* # 0 or more any character
<.+?> # any tag
.* # 0 or more any character
$ # end of line
(*SKIP) # skip this match
(*F) # and declare a failure
| # OR
. # any character
```
**Screenshot (before):**
[](https://i.stack.imgur.com/2ghQw.png)
**Screenshot (after):**
[](https://i.stack.imgur.com/55N5N.png)
|
Use the following:
* `Ctrl`+`H`
* Find what: `^((?!<p class=.+</p>).)*$`
* Replace with: `LEAVE EMPTY`
* **CHECK** *Match case*
* **CHECK** *Wrap around*
* **CHECK** *Regular expression*
* **UNCHECK** `. matches newline`
* `Replace all`
**OR**
* Find what: `^((?!<p class=).)*$`
* Replace with: `LEAVE EMPTY`
|
1,714,480 |
I created my first public server - an SFTP server hosted on google cloud. I was checking the auth log during the 2nd day of testing and noticed that I'm getting 4-10 hits from random people every minute!! 3700 failed requests in 16 hrs - this seems ridiculous, so I want to know if there is any way to stop them. I have almost zero experience with firewalls - I was hoping to avoid defaulting to reject everyone and only allow whitelisted IPs, but maybe I'll have to consider it.
```bsh
Apr 4 13:34:05 nfp sshd[12034]: Failed password for invalid user tjkim from 134.122.9.249 port 48930 ssh2
Apr 4 13:34:13 nfp sshd[12107]: Failed password for invalid user barman from 198.58.119.132 port 39626 ssh2
Apr 4 13:34:16 nfp sshd[12119]: Failed password for invalid user rscreen from 203.205.37.233 port 33740 ssh2
Apr 4 13:34:16 nfp sshd[12121]: Failed password for invalid user oakda from 164.90.194.36 port 41566 ssh2
Apr 4 13:34:18 nfp sshd[12123]: Failed password for invalid user lia from 43.130.60.190 port 46610 ssh2
Apr 4 13:34:20 nfp sshd[12125]: Failed password for invalid user hongphong from 193.106.60.145 port 33020 ssh2
Apr 4 13:34:23 nfp sshd[12127]: Failed password for invalid user uucpsh from 157.245.101.31 port 59112 ssh2
Apr 4 13:34:27 nfp sshd[12129]: Failed password for invalid user legaltech from 43.154.249.125 port 33970 ssh2
Apr 4 13:34:51 nfp sshd[12132]: Failed password for invalid user dhamu from 164.90.198.71 port 36212 ssh2
Apr 4 13:34:57 nfp sshd[12134]: Failed password for invalid user onapp from 115.182.105.68 port 46286 ssh2
```
Any guidance for a newbie?
|
2022/04/04
|
[
"https://superuser.com/questions/1714480",
"https://superuser.com",
"https://superuser.com/users/312100/"
] |
* `Ctrl`+`H`
* Find what: `^.*<.+?>.*$(*SKIP)(*F)|.`
* Replace with: `LEAVE EMPTY`
* **CHECK** *Wrap around*
* **CHECK** *Regular expression*
* **UNCHECK** `. matches newline`
* `Replace all`
**Explanation:**
```none
^ # begining of line
.* # 0 or more any character
<.+?> # any tag
.* # 0 or more any character
$ # end of line
(*SKIP) # skip this match
(*F) # and declare a failure
| # OR
. # any character
```
**Screenshot (before):**
[](https://i.stack.imgur.com/2ghQw.png)
**Screenshot (after):**
[](https://i.stack.imgur.com/55N5N.png)
|
Use the following:
* `Ctrl`+`H`
* Find what: `^[^</>\r\n]+$`
* Replace with: `LEAVE EMPTY`
* **CHECK** *Match case*
* **CHECK** *Wrap around*
* **CHECK** *Regular expression*
* **UNCHECK** `. matches newline`
* `Replace all`
|
50,723,581 |
I am working on a simple program to see if a file "test-2018-06-04-1358.txt" exists in a directory using airflow. I have two issues.
A) I want to use the variable datestr in my regex. Not sure how to do that.
B) Secondly, Where does my print(filename) show up in airflow UI? I checked my view log but nothing showed up.
```
def checksFile():
d = datetime.today()-timedelta(days=1)
datestr = '{:%Y-%m-%d}'.format(d)
for filename in os.listdir('/mnt/volume/home/aabraham/'):
match = re.search('(test)-(2018-06-04)-(\d+)(\.txt)', filename)
print(filename)
if not match:
raise AirflowException("File not Found")
```
|
2018/06/06
|
[
"https://Stackoverflow.com/questions/50723581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9877725/"
] |
You cannot use `print` in the same fashion as in the console.
To see logging entries in the `Log` page use `logging.info`. Maybe you need to `import logging`.
|
To answer the regex question, just add the strings together:
```
match = re.search('(test)-(' + datestr + ')-(\d+)(\.txt)', filename)
```
This will only work if `datestr` doesn't contain any regex literals.
|
3,321 |
I've got some data on genomic regions of interest in a bedgraph-like format from the *Mus musculus* [mm10] genome, and would like to find out the nearest gene to these regions.
Some of the regions will reside within a gene (in which case I'd like to know that they're *within* a gene), some regions may reside within multiple genes (in which case I'd like to know all gene names), and some regions are not within a gene (in which case I'd like to know the closest gene: the shortest sequence gap between either end of the gene and either end of the tagged genomic region. In this case I want to do an unstranded search, because it's possible that I might have regions describing suppressing transcripts. Here's some example data:
```
Ref Start End fwd rev
chrX 73716152 73716152 0 -2
chrX 167207094 167209162 0 -3
chrY 30770844 30772724 3 0
chr1 24613189 24613641 0 3
chr1 24613971 24614812 0 4
chr1 35788729 35789387 -5 0
chr1 93151586 93160225 0 -2
chr1 107511454 107525597 -2 0
chr1 130882067 130887413 0 -3
chr1 134182466 134189942 2 0
chr1 135818954 135832956 -2 0
chr1 149520498 149521157 0 -3
chr1 166166500 166166500 -2 0
chr2 5379059 5379374 0 -2
chr2 32379110 32381837 0 -2
chr2 32381854 32381858 0 -2
chr2 32384633 32384633 0 -2
chr2 32384636 32387773 0 -3
chr2 120539390 120563799 0 -2
chr2 125946785 125975527 2 0
chr2 127633311 127633684 0 -2
chr2 127634841 127656210 0 -3
chr2 164562717 164562717 -2 0
chr2 164562719 164562720 -2 0
chr2 164568498 164568499 -2 0
chr2 181188007 181188388 -2 0
```
I'd like to add another 'Gene' column to this table that gives the official names of the nearest gene(s) for each region defined by `<Ref>:<Start>-<End>`.
|
2018/01/16
|
[
"https://bioinformatics.stackexchange.com/questions/3321",
"https://bioinformatics.stackexchange.com",
"https://bioinformatics.stackexchange.com/users/73/"
] |
You're looking for `bedtools closest`, which thankfully defaults both considering overlapping genes and outputting all hits in case of ties.
```
bedtools closest -a foo.txt -b genes.bed | awk '{foo = sprintf("%s:%i-%i", $6, $7, $8); OFS="\t"; print $1, $2, $3, $4, $5, foo}'
```
You'll need to strip the header and ensure the file is sorted. I've piped the output to `awk` to reformat things. The output then is something like:
```
chr1 24613189 24613641 0 3 chr1:24613188-24613971
chr1 24613971 24614812 0 4 chr1:24613973-24614651
chr1 35788729 35789387 -5 0 chr1:35806973-35810462
chr1 93151586 93160225 0 -2 chr1:93151348-93160948
chr1 93151586 93160225 0 -2 chr1:93151582-93160870
chr1 107511454 107525597 -2 0 chr1:107511422-107525598
```
Those results are for the Gencode M15 release (the BED file I used has transcripts rather than genes, so you'll get a bit different coordinates). As an aside, the gene name would normally be output as well, just add column 9 to the output.
|
With the prompting from @Devon\_Ryan's answer, I came up with a solution that worked well for me. I downloaded the mm10 RefSeq gene locations from [UCSC](https://genome.ucsc.edu/cgi-bin/hgTables) [Fields: chrom, txStart, txEnd, name2], and sorted both input files using `bedtools sort`. From there the `bedtools closest` command got me almost to where I wanted to go:
```
(echo -e "Chr\tStart\tEnd\tfwd\trev\tm_Chr\tm_Start\tm_End\tGene\tDistance";
bedtools closest -d -a regions.bed -b NCBI_RefSeq_mm10.bed) > annotated.tsv
```
Output example:
```
Chr Start End fwd rev m_Chr m_Start m_End Gene Distance
chrX 73716152 73716152 0 -2 chrX 73686177 73716204 Bcap31 0
chrX 73716152 73716152 0 -2 chrX 73686177 73717815 Bcap31 0
chrX 73716152 73716152 0 -2 chrX 73686177 73716401 Bcap31 0
chrX 73716152 73716152 0 -2 chrX 73686177 73716502 Bcap31 0
chrX 167207094 167209162 0 -3 chrX 167207092 167213479 Tmsb4x 0
chrX 167207094 167209162 0 -3 chrX 167207093 167209218 Tmsb4x 0
chrY 30770844 30772724 3 0 chrY 30725674 30738546 Gm29582 32299
chr1 24613189 24613641 0 3 chr1 24257682 24587535 Col19a1 25655
chr1 24613189 24613641 0 3 chr1 24257682 24587535 Col19a1 25655
chr1 24613189 24613641 0 3 chr1 24257682 24587535 Col19a1 25655
chr1 24613189 24613641 0 3 chr1 24257682 24587535 Col19a1 25655
chr1 24613971 24614812 0 4 chr1 24257682 24587535 Col19a1 26437
chr1 24613971 24614812 0 4 chr1 24257682 24587535 Col19a1 26437
chr1 24613971 24614812 0 4 chr1 24257682 24587535 Col19a1 26437
chr1 24613971 24614812 0 4 chr1 24257682 24587535 Col19a1 26437
chr1 35788729 35789387 -5 0 chr1 35869594 35881164 1110002O04Rik 80208
chr1 93151586 93160225 0 -2 chr1 93151353 93160935 2310007B03Rik 0
chr1 93151586 93160225 0 -2 chr1 93151353 93160957 2310007B03Rik 0
chr1 93151586 93160225 0 -2 chr1 93151354 93160948 2310007B03Rik 0
chr1 93151586 93160225 0 -2 chr1 93151354 93160870 2310007B03Rik 0
chr1 107511454 107525597 -2 0 chr1 107500891 107525600 Serpinb2 0
chr1 107511454 107525597 -2 0 chr1 107511422 107525600 Serpinb2 0
chr1 107511454 107525597 -2 0 chr1 107511509 107525600 Serpinb2 0
chr1 130882067 130887413 0 -3 chr1 130882073 130887411 Il24 0
chr1 134182466 134189942 2 0 chr1 134182169 134190031 Chil1 0
chr1 134182466 134189942 2 0 chr1 134182403 134190031 Chil1 0
chr1 134182466 134189942 2 0 chr1 134182408 134190031 Chil1 0
chr1 135818954 135832956 -2 0 chr1 135818597 135833341 Lad1 0
chr1 149520498 149521157 0 -3 chr1 149410728 149449931 Gm29398 70568
chr1 166166500 166166500 -2 0 chr1 166130459 166166510 Gpa33 0
chr2 5379059 5379374 0 -2 chr2 5293456 5676046 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293456 5714762 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293456 5714762 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293456 5714762 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293458 5383533 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293458 5569754 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293458 5601302 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5293458 5715350 Camk1d 0
chr2 5379059 5379374 0 -2 chr2 5298992 5715357 Camk1d 0
chr2 32379110 32381837 0 -2 chr2 32379100 32381915 1110008P14Rik 0
chr2 32381854 32381858 0 -2 chr2 32379100 32381915 1110008P14Rik 0
chr2 32384633 32384633 0 -2 chr2 32384636 32387739 Lcn2 3
chr2 32384636 32387773 0 -3 chr2 32384636 32387739 Lcn2 0
chr2 120539390 120563799 0 -2 chr2 120506829 120563831 Zfp106 0
chr2 120539390 120563799 0 -2 chr2 120507433 120563851 Zfp106 0
chr2 120539390 120563799 0 -2 chr2 120507433 120563853 Zfp106 0
chr2 125946785 125975527 2 0 chr2 125859108 125984298 Galk2 0
chr2 125946785 125975527 2 0 chr2 125859228 125983587 Galk2 0
chr2 125946785 125975527 2 0 chr2 125866111 125983587 Galk2 0
chr2 125946785 125975527 2 0 chr2 125866218 125983587 Galk2 0
chr2 125946785 125975527 2 0 chr2 125866219 125983587 Galk2 0
chr2 125946785 125975527 2 0 chr2 125866222 125984298 Galk2 0
chr2 125946785 125975527 2 0 chr2 125920565 125983587 Galk2 0
chr2 127633311 127633684 0 -2 chr2 127633225 127656695 Mal 0
chr2 127633311 127633684 0 -2 chr2 127633225 127656695 Mal 0
chr2 127634841 127656210 0 -3 chr2 127633225 127656695 Mal 0
chr2 127634841 127656210 0 -3 chr2 127633225 127656695 Mal 0
chr2 164562717 164562717 -2 0 chr2 164562560 164568510 Wfdc2 0
chr2 164562717 164562717 -2 0 chr2 164562715 164568506 Wfdc2 0
chr2 164562719 164562720 -2 0 chr2 164562560 164568510 Wfdc2 0
chr2 164562719 164562720 -2 0 chr2 164562715 164568506 Wfdc2 0
chr2 164568498 164568499 -2 0 chr2 164562560 164568510 Wfdc2 0
chr2 164568498 164568499 -2 0 chr2 164562715 164568506 Wfdc2 0
chr2 181188007 181188388 -2 0 chr2 181187221 181188506 Ppdpf 0
chr2 181188007 181188388 -2 0 chr2 181187342 181188504 Ppdpf 0
```
After that it was just a matter of aggregating the gene names for each unique region with a quick R script:
```
library(dplyr);
data.tbl <-
read.delim("annotated.tsv") %>%
group_by(Chr, Start, End, fwd, rev) %>%
summarise(Genes = paste(unique(Gene), collapse=","), Distance=min(Distance));
write.table(data.tbl, "collapsed_annotated.tsv",
sep="\t", row.names=FALSE, quote=FALSE);
```
Collapsed output example:
```
Chr Start End fwd rev Genes Distance
chr1 24613189 24613641 0 3 Col19a1 25655
chr1 24613971 24614812 0 4 Col19a1 26437
chr1 35788729 35789387 -5 0 1110002O04Rik 80208
chr1 93151586 93160225 0 -2 2310007B03Rik 0
chr1 107511454 107525597 -2 0 Serpinb2 0
chr1 130882067 130887413 0 -3 Il24 0
chr1 134182466 134189942 2 0 Chil1 0
chr1 135818954 135832956 -2 0 Lad1 0
chr1 149520498 149521157 0 -3 Gm29398 70568
chr1 166166500 166166500 -2 0 Gpa33 0
chr2 5379059 5379374 0 -2 Camk1d 0
chr2 32379110 32381837 0 -2 1110008P14Rik 0
chr2 32381854 32381858 0 -2 1110008P14Rik 0
chr2 32384633 32384633 0 -2 Lcn2 3
chr2 32384636 32387773 0 -3 Lcn2 0
chr2 120539390 120563799 0 -2 Zfp106 0
chr2 125946785 125975527 2 0 Galk2 0
chr2 127633311 127633684 0 -2 Mal 0
chr2 127634841 127656210 0 -3 Mal 0
chr2 164562717 164562717 -2 0 Wfdc2 0
chr2 164562719 164562720 -2 0 Wfdc2 0
chr2 164568498 164568499 -2 0 Wfdc2 0
chr2 181188007 181188388 -2 0 Ppdpf 0
chrX 73716152 73716152 0 -2 Bcap31 0
chrX 167207094 167209162 0 -3 Tmsb4x 0
chrY 30770844 30772724 3 0 Gm29582 32299
```
|
3,321 |
I've got some data on genomic regions of interest in a bedgraph-like format from the *Mus musculus* [mm10] genome, and would like to find out the nearest gene to these regions.
Some of the regions will reside within a gene (in which case I'd like to know that they're *within* a gene), some regions may reside within multiple genes (in which case I'd like to know all gene names), and some regions are not within a gene (in which case I'd like to know the closest gene: the shortest sequence gap between either end of the gene and either end of the tagged genomic region. In this case I want to do an unstranded search, because it's possible that I might have regions describing suppressing transcripts. Here's some example data:
```
Ref Start End fwd rev
chrX 73716152 73716152 0 -2
chrX 167207094 167209162 0 -3
chrY 30770844 30772724 3 0
chr1 24613189 24613641 0 3
chr1 24613971 24614812 0 4
chr1 35788729 35789387 -5 0
chr1 93151586 93160225 0 -2
chr1 107511454 107525597 -2 0
chr1 130882067 130887413 0 -3
chr1 134182466 134189942 2 0
chr1 135818954 135832956 -2 0
chr1 149520498 149521157 0 -3
chr1 166166500 166166500 -2 0
chr2 5379059 5379374 0 -2
chr2 32379110 32381837 0 -2
chr2 32381854 32381858 0 -2
chr2 32384633 32384633 0 -2
chr2 32384636 32387773 0 -3
chr2 120539390 120563799 0 -2
chr2 125946785 125975527 2 0
chr2 127633311 127633684 0 -2
chr2 127634841 127656210 0 -3
chr2 164562717 164562717 -2 0
chr2 164562719 164562720 -2 0
chr2 164568498 164568499 -2 0
chr2 181188007 181188388 -2 0
```
I'd like to add another 'Gene' column to this table that gives the official names of the nearest gene(s) for each region defined by `<Ref>:<Start>-<End>`.
|
2018/01/16
|
[
"https://bioinformatics.stackexchange.com/questions/3321",
"https://bioinformatics.stackexchange.com",
"https://bioinformatics.stackexchange.com/users/73/"
] |
You're looking for `bedtools closest`, which thankfully defaults both considering overlapping genes and outputting all hits in case of ties.
```
bedtools closest -a foo.txt -b genes.bed | awk '{foo = sprintf("%s:%i-%i", $6, $7, $8); OFS="\t"; print $1, $2, $3, $4, $5, foo}'
```
You'll need to strip the header and ensure the file is sorted. I've piped the output to `awk` to reformat things. The output then is something like:
```
chr1 24613189 24613641 0 3 chr1:24613188-24613971
chr1 24613971 24614812 0 4 chr1:24613973-24614651
chr1 35788729 35789387 -5 0 chr1:35806973-35810462
chr1 93151586 93160225 0 -2 chr1:93151348-93160948
chr1 93151586 93160225 0 -2 chr1:93151582-93160870
chr1 107511454 107525597 -2 0 chr1:107511422-107525598
```
Those results are for the Gencode M15 release (the BED file I used has transcripts rather than genes, so you'll get a bit different coordinates). As an aside, the gene name would normally be output as well, just add column 9 to the output.
|
Another option is [BEDOPS `closest-features`](http://bedops.readthedocs.io/en/latest/content/reference/set-operations/closest-features.html), which efficiently locates nearest annotations, overlapping or otherwise.
```
$ closest-features --closest --delim '\t' intervals.bed genes.bed > answer.bed
```
It's easy to reformat output by piping to `awk`, say.
If files are very large, you can parallelize work into "map-reduce" form by specifying the chromosome name as an option:
```
$ closest-features --chrom chr1 --closest --delim '\t' intervals.bed genes.bed > answer.chr1.bed
$ closest-features --chrom chr2 --closest --delim '\t' intervals.bed genes.bed > answer.chr2.bed
...
```
To reduce, just `bedops -u` all the `answer.*.bed` files.
Running these per-chromosome jobs in parallel makes the work take about as long as searching `chr1`, which tends to be the largest chromosome.
|
68,076,494 |
Hi a Java newbie here.
I hava a linked list like this
```
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(5);
list.add(4);
list.add(2);
System.out.println(list);
}
```
I am trying to find a way to find the max value in this linked list and cut the list from that max value until the end and paste it at the front of the linked list.
To clarify, for the example case, I would like the list to look something like this.
```
[5,4,2,1,2]
```
It would be appreciated if there would be any way of doing this.
Thank you in advance!!
|
2021/06/22
|
[
"https://Stackoverflow.com/questions/68076494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14519267/"
] |
Inside your `Image` folder create a index.js file and import all images like this
```
export const image1 = require('./image1.jpg')
export const image2 = require('./image2.jpg')
export const image3 = require('./image3.jpg')
export const image4 = require('./image4.jpg')
```
then inside your Class you can import images and use those images to create image array
```
import {image1,image2,image3,image4} from './images'
const items=[
{ name: image1},
{ name: image2 },
{ name: image3 },
{ name: image4 },
]
```
then you can use it like this
```
<FlatGrid
itemDimension={150}
data={items}
spacing={10}
windowSize={300}
renderItem={({ item }) => (
<View>
<Image
source={item.name}
/>
<Text>
{item.name}
</Text>
</View>
)}
/>
```
|
```
const images = {
applemusic: require("../ui/icons/AppleMusic.png"),
discord: require("../ui/icons/discord.png")
}
export default images;
```
Should works!
I have tried some similar code.It works as the pic show.
```
const images = {
test: require("../assets/test.png"),
splash: require("../assets/splash.png"),
icon: require("../assets/icon.png")
}
export default images
```
```
function Feed() {
const list = ["icon", "test", "splash"];
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Feed!</Text>
<TouchableOpacity
style={{
alignItems: "center",
justifyContent: "center",
width: 200,
height: 50,
backgroundColor: "green"
}}
onPress={
() => {
DeviceEventEmitter.emit("ADD_COUNT")
}
}
>
<Text>add</Text>
</TouchableOpacity>
{
list.map((name) => {
return (
<Image
source={Images[name]}
style={{ width: 100, height: 100 }}
/>
)
})
}
</View>
);
}
```
[](https://i.stack.imgur.com/FmBXv.png)
|
55,845,481 |
I'm making an api call that pulls the desired endpoints from ...url/articles.json and transforms it into a csv file. My problem here is that the ['labels\_name'] endpoint is a string with multiple values.(an article might have multiple labels)
How can I pull multiple values of a string without getting this error . `"File "articles_labels.py", line 40, in <module>
decode_3 = unicodedata.normalize('NFKD', article_label)
TypeError: normalize() argument 2 must be str, not list"`?
```
import requests
import csv
import unicodedata
import getpass
url = 'https://......./articles.json'
user = ' '
pwd = ' '
csvfile = 'articles_labels.csv'
output_1 = []
output_1.append("id")
output_2 = []
output_2.append("title")
output_3 = []
output_3.append("label_names")
output_4 = []
output_4.append("link")
while url:
response = requests.get(url, auth=(user, pwd))
data = response.json()
for article in data['articles']:
article_id = article['id']
decode_1 = int(article_id)
output_1.append(decode_1)
for article in data['articles']:
title = article['title']
decode_2 = unicodedata.normalize('NFKD', title)
output_2.append(decode_2)
for article in data['articles']:
article_label = article['label_names']
decode_3 = unicodedata.normalize('NFKD', article_label)
output_3.append(decode_3)
for article in data['articles']:
article_url = article['html_url']
decode_3 = unicodedata.normalize('NFKD', article_url)
output_3.append(decode_3)
print(data['next_page'])
url = data['next_page']
print("Number of articles:")
print(len(output_1))
with open(csvfile, 'w') as fp:
writer = csv.writer(fp,dialect = 'excel')
writer.writerows([output_1])
writer.writerows([output_2])
writer.writerows([output_3])
writer.writerows([output_4])
```
|
2019/04/25
|
[
"https://Stackoverflow.com/questions/55845481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11033942/"
] |
>
> My problem here is that the ['labels\_name'] endpoint is a string with multiple values.(an article might have multiple labels) How can I pull multiple values of a string
>
>
>
It's a list not a string, so you don't have "a string with multiple values" you have a list of multiple strings, already, as-is.
The question is what you want to do with them, CSV certainly isn't going to handle that, so you must decide on a way to serialise a list of strings to a single string e.g. by joining them together (with some separator like space or comma) or by just picking the first one (beware to handle the case where there is none), … either way the issue is not really technical.
|
[unicodedata.normalize](https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize) takes a unicode string, and not a list as the error says. The correct way to use `unicodedata.normalize` will be (example taken from [How does unicodedata.normalize(form, unistr) work?](https://stackoverflow.com/questions/14682397/how-does-unicodedata-normalizeform-unistr-work)
```
from unicodedata import normalize
print(normalize('NFD', u'\u00C7'))
print(normalize('NFC', u'C\u0327'))
#Ç
#Ç
```
Hence you need to make sure that `unicodedata.normalize('NFKD', title)` has title as a unicode string
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
`SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME = 'column_name'`
|
If you need to check all tables, you may have to list the tables first:
```
SHOW TABLES FROM database_name;
```
Then, loop through the tables (in code, e.g., PHP), and execute this query:
```
SHOW COLUMNS FROM database_name.table_name LIKE 'mycol';
```
This will return a result if the column exists on the table.
You can also select directly from the information\_schema, but I have found this to be very slow in some cases with MySQL and large databases.
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
`SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME = 'column_name'`
|
```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
please check above code with your database
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
`SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME = 'column_name'`
|
```
SELECT * FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME ='table_name' AND COLUMN_NAME = 'col_name'
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
`SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND COLUMN_NAME = 'column_name'`
|
Use the information schema
```
select *
from information_schema.tables
where table_name = 'employee'
and table_schema = 'test';
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
If you need to check all tables, you may have to list the tables first:
```
SHOW TABLES FROM database_name;
```
Then, loop through the tables (in code, e.g., PHP), and execute this query:
```
SHOW COLUMNS FROM database_name.table_name LIKE 'mycol';
```
This will return a result if the column exists on the table.
You can also select directly from the information\_schema, but I have found this to be very slow in some cases with MySQL and large databases.
|
```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
please check above code with your database
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
If you need to check all tables, you may have to list the tables first:
```
SHOW TABLES FROM database_name;
```
Then, loop through the tables (in code, e.g., PHP), and execute this query:
```
SHOW COLUMNS FROM database_name.table_name LIKE 'mycol';
```
This will return a result if the column exists on the table.
You can also select directly from the information\_schema, but I have found this to be very slow in some cases with MySQL and large databases.
|
```
SELECT * FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME ='table_name' AND COLUMN_NAME = 'col_name'
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
If you need to check all tables, you may have to list the tables first:
```
SHOW TABLES FROM database_name;
```
Then, loop through the tables (in code, e.g., PHP), and execute this query:
```
SHOW COLUMNS FROM database_name.table_name LIKE 'mycol';
```
This will return a result if the column exists on the table.
You can also select directly from the information\_schema, but I have found this to be very slow in some cases with MySQL and large databases.
|
Use the information schema
```
select *
from information_schema.tables
where table_name = 'employee'
and table_schema = 'test';
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
please check above code with your database
```
|
```
SELECT * FROM INFORMATION_SCHEMA.columns WHERE TABLE_NAME ='table_name' AND COLUMN_NAME = 'col_name'
```
|
17,321,088 |
I have a huge database and a column name that I am not sure if it exists in any of my tables.
How can I check its existance?
|
2013/06/26
|
[
"https://Stackoverflow.com/questions/17321088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2481383/"
] |
```
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
please check above code with your database
```
|
Use the information schema
```
select *
from information_schema.tables
where table_name = 'employee'
and table_schema = 'test';
```
|
56,691,613 |
I have `n` networks, each with the same input / output. I want to randomly select one of the outputs according to a categorical distribution. [Tfp.Categorical](https://www.tensorflow.org/probability/api_docs/python/tfp/distributions/Categorical) outputs only integers and I tried to do something like
```
act_dist = tfp.distributions.Categorical(logits=act_logits) # act_logits are all the same, so the distribution is uniform
rand_out = act_dist.sample()
x = nn_out1 * tf.cast(rand_out == 0., dtype=tf.float32) + ... # for all my n networks
```
But `rand_out == 0.` is always false, as well as the other conditions.
Any idea for achieving what I need?
|
2019/06/20
|
[
"https://Stackoverflow.com/questions/56691613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/754136/"
] |
You might also look at MixtureSameFamily, which does a gather under the covers for you.
```
nn_out1 = tf.expand_dims(nn_out1, axis=2)
...
outs = tf.concat([nn_out1, nn_nout2, ...], axis=2)
probs = tf.tile(tf.reduce_mean(tf.ones_like(nn_out1), axis=1, keepdims=True) / n, [1, n]) # trick to have ones of shape [None,1]
dist = tfp.distributions.MixtureSameFamily(
mixture_distribution=tfp.distributions.Categorical(probs=probs),
components_distribution=tfp.distributions.Deterministic(loc=outs))
x = dist.sample()
```
|
I think you need to use tf.equal, because Tensor == 0 is always False.
Separately though, you might want to use OneHotCategorical. For training, you might also try using RelaxedOneHotCategorical.
|
30,131,326 |
I am using `TableTools` and `DataTables v1.10` in same page.
My main page has table and empty div for modal.
```
<div id="resultDiv">
<table id="mainTable"> ... </table>
<div id="detailModal">
<div id="detailModal-content"></div>
</div>
</div>
<script>
$(document).ready(function () {
var mainTable = $('#mainTable').DataTable({
"dom": 'T<"clear">lrtip',
"tableTools": { ... },
"columns": [
{
"data": null,
"render": function(data, type, row, meta) {
return '<a href="" onClick="return loadDetail(' + data.id + ')">Details</a>';
}
},
....
],
........
});
});
function loadDetail(id) {
$.ajax({
async: false,
url: ...,
success: function(respose) {
var tableInstance = TableTools.fnGetInstance('detailTable');
console.log(tableInstance); //null
}
});
}
</script>
```
Separate detail page has another table which get rendered in `detailModal-content` div.
```
<table id="detailTable">
</table>
<script>
$(document).ready(function () {
var mainDetailTable = $jq11('#detailTable').DataTable({
"dom": 'T<"clear">ltipr',
"tableTools": { ... },
..............
});
});
</script>
```
Here first `TableTools` of `mainTable` is working fine but for second table it is not working (I can click button but clicking on it doesn't create xls file). I am trying to solve this by calling `fnResizeButtons()` after table created as suggested [here](https://stackoverflow.com/questions/8424253/tabletools-export-not-working-in-datatables-on-multiple-jquery-tabs). But `tableInstance` is null.
Any suggestion?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30131326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035943/"
] |
From what I can tell you're having problems with TableTools (not the DataTable) not working on the table which is in the modal?
I've had similar issues myself and it's down to the table being initialised when it's invisible and something to do with the Flash, it can be fixed and this is what I used to fix a similar issue with tables on different bootstrap tabs not having functional TableTools except on the table which was initially visible:
```
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target_id = $(e.target).attr("href");
var jqTable = $(target_id).find("table");
var oTableTools = TableTools.fnGetInstance( jqTable[0] );
if (oTableTools != null && oTableTools.fnResizeRequired()){
/* A resize of TableTools' buttons and DataTables' columns is only required on the
* first visible draw of the table
*/
jqTable.dataTable().fnAdjustColumnSizing();
oTableTools.fnResizeButtons();
}
});
```
Of course, you'll have to grab the table instance on the `shown.bs.modal` or whatever other event shows your modal but that should fix the TableTools issue.
Hope that helps.
|
Your function `loadDetail()` doesn't load response into `<div id="detailModal-content"></div>`, therefore second table doesn't get initialized.
Corrected `loadDetail()` function should look something like:
```
function loadDetail(id) {
$.ajax({
async: false,
url: '/script.php',
data: { 'id' : id },
success: function(response){
$('#detailModal-content').html(response);
}
});
}
```
|
30,131,326 |
I am using `TableTools` and `DataTables v1.10` in same page.
My main page has table and empty div for modal.
```
<div id="resultDiv">
<table id="mainTable"> ... </table>
<div id="detailModal">
<div id="detailModal-content"></div>
</div>
</div>
<script>
$(document).ready(function () {
var mainTable = $('#mainTable').DataTable({
"dom": 'T<"clear">lrtip',
"tableTools": { ... },
"columns": [
{
"data": null,
"render": function(data, type, row, meta) {
return '<a href="" onClick="return loadDetail(' + data.id + ')">Details</a>';
}
},
....
],
........
});
});
function loadDetail(id) {
$.ajax({
async: false,
url: ...,
success: function(respose) {
var tableInstance = TableTools.fnGetInstance('detailTable');
console.log(tableInstance); //null
}
});
}
</script>
```
Separate detail page has another table which get rendered in `detailModal-content` div.
```
<table id="detailTable">
</table>
<script>
$(document).ready(function () {
var mainDetailTable = $jq11('#detailTable').DataTable({
"dom": 'T<"clear">ltipr',
"tableTools": { ... },
..............
});
});
</script>
```
Here first `TableTools` of `mainTable` is working fine but for second table it is not working (I can click button but clicking on it doesn't create xls file). I am trying to solve this by calling `fnResizeButtons()` after table created as suggested [here](https://stackoverflow.com/questions/8424253/tabletools-export-not-working-in-datatables-on-multiple-jquery-tabs). But `tableInstance` is null.
Any suggestion?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30131326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035943/"
] |
Your function `loadDetail()` doesn't load response into `<div id="detailModal-content"></div>`, therefore second table doesn't get initialized.
Corrected `loadDetail()` function should look something like:
```
function loadDetail(id) {
$.ajax({
async: false,
url: '/script.php',
data: { 'id' : id },
success: function(response){
$('#detailModal-content').html(response);
}
});
}
```
|
watch out if you're table header is already a table,
then use **jqTable[1]** or even better ***jqTable.get(1)***
|
30,131,326 |
I am using `TableTools` and `DataTables v1.10` in same page.
My main page has table and empty div for modal.
```
<div id="resultDiv">
<table id="mainTable"> ... </table>
<div id="detailModal">
<div id="detailModal-content"></div>
</div>
</div>
<script>
$(document).ready(function () {
var mainTable = $('#mainTable').DataTable({
"dom": 'T<"clear">lrtip',
"tableTools": { ... },
"columns": [
{
"data": null,
"render": function(data, type, row, meta) {
return '<a href="" onClick="return loadDetail(' + data.id + ')">Details</a>';
}
},
....
],
........
});
});
function loadDetail(id) {
$.ajax({
async: false,
url: ...,
success: function(respose) {
var tableInstance = TableTools.fnGetInstance('detailTable');
console.log(tableInstance); //null
}
});
}
</script>
```
Separate detail page has another table which get rendered in `detailModal-content` div.
```
<table id="detailTable">
</table>
<script>
$(document).ready(function () {
var mainDetailTable = $jq11('#detailTable').DataTable({
"dom": 'T<"clear">ltipr',
"tableTools": { ... },
..............
});
});
</script>
```
Here first `TableTools` of `mainTable` is working fine but for second table it is not working (I can click button but clicking on it doesn't create xls file). I am trying to solve this by calling `fnResizeButtons()` after table created as suggested [here](https://stackoverflow.com/questions/8424253/tabletools-export-not-working-in-datatables-on-multiple-jquery-tabs). But `tableInstance` is null.
Any suggestion?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30131326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4035943/"
] |
From what I can tell you're having problems with TableTools (not the DataTable) not working on the table which is in the modal?
I've had similar issues myself and it's down to the table being initialised when it's invisible and something to do with the Flash, it can be fixed and this is what I used to fix a similar issue with tables on different bootstrap tabs not having functional TableTools except on the table which was initially visible:
```
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target_id = $(e.target).attr("href");
var jqTable = $(target_id).find("table");
var oTableTools = TableTools.fnGetInstance( jqTable[0] );
if (oTableTools != null && oTableTools.fnResizeRequired()){
/* A resize of TableTools' buttons and DataTables' columns is only required on the
* first visible draw of the table
*/
jqTable.dataTable().fnAdjustColumnSizing();
oTableTools.fnResizeButtons();
}
});
```
Of course, you'll have to grab the table instance on the `shown.bs.modal` or whatever other event shows your modal but that should fix the TableTools issue.
Hope that helps.
|
watch out if you're table header is already a table,
then use **jqTable[1]** or even better ***jqTable.get(1)***
|
566,346 |
I am trying to construct an audio amplifier circuit as below(which is not working). Is there any modification can be done in order for it to work?
From my understanding, the signal from the input V1/microphone will be amplified at the collector of Q1 and same signal will be amplified at emitter Q3 as well but in opposite polarity(correct me if I'm wrong). This signal is then sent to differential amplifier circuit to get twice the amplified input signal by using a pair of Darlington construction that can then get further amplify by a gain but it is not working?
[](https://i.stack.imgur.com/OSBfs.jpg)
|
2021/05/21
|
[
"https://electronics.stackexchange.com/questions/566346",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/286188/"
] |
You have given enough parameters to design the required filter:
* source termination 50 ohms
* load termination 50 ohms
* bandwidth 200 kHz
* center frequency 1.81 Mhz
Any number of "applets" can design this filter. I have used "ttc08" that was included with EMRFD *Experimental Methods for Radio Frequency Design*. One is given a choice of inductor values (all inductors are the same). Capacitor values are internally calculated to achieve the desired filter.
In this case, a "standard value" inductor of 4.7 uH is chosen. One must be careful to choose a low-loss inductor so that its "Q" is far higher than the filter "Q". The filter Q in this case is roughly center frequency divided by bandwidth (about ten). An inductor Q of about 100 is assumed. Capacitor Q is usually assumed infinite at this low frequency:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fCt7zJ.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Could this be built with surface-mount components? 4.7uH of sufficiently-high Q might be a bit of a problem sourcing.
Those odd-value capacitors may have to be parallel or series combinations of standard values. All component tolerances should be tight with this fairly high-Q filter. Filter bandwidth is slightly less than the desired 200 kHz due to finite component Q. A filter having higher Q than 10 might benefit from trimming components added to C2, C6. All capacitor values here are fairly well-defined by bulk capacitors. At higher frequency, stray coupling and stray capacitance make trimmers/tuning mandatory.
LTspice is a good tool to verify a filter. One can vary component tolerances to gain a sense of how badly filter characteristics are degraded. But LTspice is not adequate to show how a filter should be constructed to reduce component-to-component coupling, or estimating reactance of printed-circuit traces that you *think are inconsequential*. **That** is a matter of experience.
It may seem that this filter differs from the capacitive-tap matching used in the OP's schematic. It is really not so different...C1 and C2 have roughly similar ratio to OP's C1 & C2.
What is missing from OP's schematic is the 50 ohm source resistance. Note that V1 generates a voltage that divides between R1 (50 ohms) and R5 (50 ohms), so that filter output within the pass band never rises above 0.5V when V1 is 1V. The resistive losses of the three inductors add about another 1 dB attenuation to this -6dB. (total of -7dB)
[](https://i.stack.imgur.com/yL8Yw.png)
---
A brain fart caused me to choose the (above) filter's center frequency to be 1.81 MHz., instead of geometric mean of lower & upper frequency edge - which should be near 1.9 MHz. That's \$ \sqrt{1.8 \times 2.0} \$
This error is an opportunity to see how/which components change value, and by how much. Re-evaluating the resulting filter helps give you a feeling for component sensitivity. The "Q" value for the standard-value inductor was also reduced from 100 to 60, to reflect achievable Q of SMT inductors:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2ffWVoG.png)
Note that R2,R3,R5 in this revised filter are equivalent loss resistance of the associated inductor, and are **not components to be added**. These increased losses added another few decibels to filter passband attenuation.
|
If you're a hobbyist, you might have a copy of Practical Electronics for Inventors. Chapter 9 (of the 4th edition) would likely have a lot of great information for guys like you.
|
13,342 |
I believe that there is a statement along the following lines (I would, of course, love to be corrected): a formal power series is the Taylor expansion of a rational function if and only if the coefficients eventually satisfy a linear relationship.
Let's suppose that I understand what "satisfy a linear relationship" means, because it's not the part I actually want to ask about (although clarifications are very welcome!). What I would like to know is what conditions on a rational function are equivalent to all the Taylor coefficients being nonnegative integers. For example, I happen to know that $1/(1-kx) = \sum (kx)^n$, and so any sum or product of such functions works. In particular, I can try playing around with partial-fraction decompositions to see if I can write a given rational function in this way. But I have no idea if this is all of them.
Put another way, there is a map $\mathbb R(x) \to \mathbb R[x^{-1},x]]$ (rational functions to Laurent series). I would like to understand the inverse image of $\mathbb N[x^{-1},x]]$.
(Oh, also, I have no idea how to tag this, and I think "general mathematics" is probably an inappropriate tag for MO. So please re-tag as you see fit.)
|
2010/01/29
|
[
"https://mathoverflow.net/questions/13342",
"https://mathoverflow.net",
"https://mathoverflow.net/users/78/"
] |
It is apparently «unknown whether the problem "$a\_n > 0$ for all $n$?" is decidable for linear recurrence sequences», according to [these notes](http://www.fam.tuwien.ac.at/~sgerhold/pub_files/talks/laufen_gerhold.pdf) by Stefan Gerhold.
|
By linear relationship, you mean a linear recurrence relation. Do it by writing down $$ P(z)/Q(z) = \sum\_n a\_nx^n $$, multiply by $Q(z)$ on both sides, regroup terms. You'll get something like $$ 0 = \sum\_n (c\_1a\_{n+k} + c\_2 a\_{n+k-1} + \dots + c\_ka\_n)x^n $$ so the coefficients do indeed satisfy a linear recurrence.
Furthermore, I think that a function, with radius of convergence 1, and positive integer coefficients, has to be either a rational function (in which case the coefficients satisfy a linear recurrence relation) or has natural boundary on the circle $|z| = 1$ (in which case the function could be taught off as rather complicated).
So in the end, your question is really a question about linear recurrences relations, rather than about rational functions. I think Narkiewicz did some work in the field, but I have no reference on top of my head.
|
13,342 |
I believe that there is a statement along the following lines (I would, of course, love to be corrected): a formal power series is the Taylor expansion of a rational function if and only if the coefficients eventually satisfy a linear relationship.
Let's suppose that I understand what "satisfy a linear relationship" means, because it's not the part I actually want to ask about (although clarifications are very welcome!). What I would like to know is what conditions on a rational function are equivalent to all the Taylor coefficients being nonnegative integers. For example, I happen to know that $1/(1-kx) = \sum (kx)^n$, and so any sum or product of such functions works. In particular, I can try playing around with partial-fraction decompositions to see if I can write a given rational function in this way. But I have no idea if this is all of them.
Put another way, there is a map $\mathbb R(x) \to \mathbb R[x^{-1},x]]$ (rational functions to Laurent series). I would like to understand the inverse image of $\mathbb N[x^{-1},x]]$.
(Oh, also, I have no idea how to tag this, and I think "general mathematics" is probably an inappropriate tag for MO. So please re-tag as you see fit.)
|
2010/01/29
|
[
"https://mathoverflow.net/questions/13342",
"https://mathoverflow.net",
"https://mathoverflow.net/users/78/"
] |
[This paper (?) of Gessel](http://people.brandeis.edu/~gessel/homepage/papers/nonneg.pdf) might help you out, although it is mostly about combinatorics. There are two natural ways to write down rational functions with non-negative integer coefficients in combinatorics, one coming from transfer matrices / finite automata and one coming from regular languages. The two give the same class of rational functions, but there exist rational functions with non-negative integer coefficients which provably don't arise in this way, so the situation seems complicated.
Your question seems to indicate you're not familiar with this class of rational functions, so here are two equivalent definitions: it is, on the one hand, the class of all non-negative linear combinations of entries of matrices of the form $(\mathbf{I} - \mathbf{A})^{-1}$ where $\mathbf{A}$ is a square matrix with entries in $x \mathbb{N}[x]$, and on the other hand the minimal class of rational functions containing $1, x$, and closed under addition, multiplication, and the operation $f \mapsto \frac{1}{1 - xf}$.
**Edit:** One reason there isn't likely to be a particularly nice classification is that one can start with any rational function with integer coefficients and add a polynomial and a term of the form $\frac{1}{1 - kx}$ for $k$ such that $\frac{1}{k}$ is smaller than the smallest pole.
|
By linear relationship, you mean a linear recurrence relation. Do it by writing down $$ P(z)/Q(z) = \sum\_n a\_nx^n $$, multiply by $Q(z)$ on both sides, regroup terms. You'll get something like $$ 0 = \sum\_n (c\_1a\_{n+k} + c\_2 a\_{n+k-1} + \dots + c\_ka\_n)x^n $$ so the coefficients do indeed satisfy a linear recurrence.
Furthermore, I think that a function, with radius of convergence 1, and positive integer coefficients, has to be either a rational function (in which case the coefficients satisfy a linear recurrence relation) or has natural boundary on the circle $|z| = 1$ (in which case the function could be taught off as rather complicated).
So in the end, your question is really a question about linear recurrences relations, rather than about rational functions. I think Narkiewicz did some work in the field, but I have no reference on top of my head.
|
61,531,309 |
I have a TabControl with a ContentTemplate defining a CheckBox. Outside the TabControl I want to bind to the CheckBox in the currently selected TabItem. How can I do that?
In the code below the CheckBox "Mirror" is bound to a CheckBox on the same level, which works. How can I make the Mirror-CheckBox to mirror tabCheckbox?
```
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TabControl Grid.Row="0">
<TabControl.ContentTemplate>
<DataTemplate>
<CheckBox
Name="tabCheckbox"
Content="Check me"
/>
</DataTemplate>
</TabControl.ContentTemplate>
<TabItem Header="Tab 1">
</TabItem>
</TabControl>
<CheckBox
x:Name="checkbox"
Grid.Row="1"
Content="Some CheckBox"
/>
<CheckBox
Grid.Row="2"
Content="Mirror"
IsChecked="{Binding ElementName=checkbox, Path=IsChecked}"
/>
</Grid>
```
|
2020/04/30
|
[
"https://Stackoverflow.com/questions/61531309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361283/"
] |
It is not too *complicated* to follow the examples on `scipy.optimize.curve_fit` [documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html).
Also, you won't get the same values as from the *commercial software* since your dataset is too small to be correctly fitted.
```py
import pandas as pd
from scipy.optimize import curve_fit
def func(x, k, m):
return k * (x**m)
dat = pd.DataFrame({'Y': [0.0455, 0.079, 0.059, 0.144], 'X': [0.055, 0.110, 0.165, 0.220]})
popt, pcov = curve_fit(func, dat.X.values, dat.Y.values)
print('k:', popt[0])
print('m:', popt[1])
```
```
k: 0.4813840693004318
m: 0.8935556114206501
```
|
You could linearize your data/model and use least squares:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dat = pd.DataFrame({'Y':[0.0455,0.079,0.059,0.144],'X':[0.055,0.110,0.165,0.220]})
def func(x, y):
Y = np.log(y)
X = np.log(x)
M = np.array((np.ones(len(X)), X)).T
lnk, m = np.linalg.solve(np.dot(M.T, M), np.dot(M.T, Y))
return np.exp(lnk), m
x = dat['X']
y = dat['Y']
k, m = func(x, y)
print('k: ', k)
print('m: ', m)
k: 0.2922891128901261
m: 0.6501306234660938
```
|
48,727,604 |
I am making a Discord bot in Python. I have some cool commands installed on my shell (like `cowsay`) that I want to be implemented into the bot, so I have this code near the end:
```
else:
for i in bash_cmds:
if digested.startswith(prefix + i):
cmd = digested.replace(prefix, '')
msg = os.popen(cmd).read()
msg = '```' + msg + '```'
await client.send_message(channel, msg)
```
So basically, if it starts with `!!` + any of the BASh commands I've added in an array `["cowsay", "cowthink", "fortune", "echo"]`, then execute the command in the shell. However, this brings up some security problems. For example, one could write `echo hackscript | bash` or `nc -l 1337` or `cat *` or `rm *` (you get the point).
I have started a list of commands that I don't want to occur in the command. However, I don't want an error to prevent the succesful part of the message not to be seen. (If someone put `cowsay foo && ls`, I still want the output of `cowsay foo` to appear.)
How would I be able to filter out possibly malicious commands and allow the unfiltered part of a message to succeed?
---
I thought that replacing things like `;`s and `&`s would work, but I want to leave some things like `$()` available so people can use `cowsay $(fortune)`, but then people would be able to do things like `echo $(ls)`... But I don't want to filter out commands either, because:
a. There could be ways around it and
b. I don't want `I eat 3 meals a day` to turn into `I eat three mea a day`...
|
2018/02/11
|
[
"https://Stackoverflow.com/questions/48727604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5910861/"
] |
Based on your result, your timestamp is in milliseconds, not seconds. You need to divide by 1000.
You also have the wrong `dateFormat`. You want to use `hh`, not `HH` for the hour. `H` is for 24-hour time which makes no sense when using `a` for AM/PM. You should also avoid using `dateFormat`. Use `dateStyle` and `timeStyle`. Let the formatter give you a date formatted best for the user's locale.
Your code also does a lot of needless conversion. You get your timestamp as a `Double` and store it as a `Double`. But then your function to convert the timestamp you expect your number of seconds as a `String` which you then convert back to a `Double`. Avoid the needless use of a `String`.
|
To get the ordinal day, you can use `Calendar` to extract the `day` from your `Date`.
```
let date = Date()
let calendar = Calendar.current
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)
```
From there, you'd just code your date format with a `DateFormatter` and drop in the ordinal date you extracted above, like so:
```
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM '\(String(describing: day!)),' yyyy h:mm a"
let dateString = "\(dateFormatter.string(from: date))"
print(dateString)
```
Additionally, the issue with your year probably stems from the number you're feeding it. [`timeIntervalSince1970`](https://developer.apple.com/documentation/foundation/nsdate) is expecting whole seconds, so make sure you're feeding it whole seconds.
>
> init(timeIntervalSince1970: TimeInterval) Returns a date object
> initialized relative to 00:00:00 UTC on 1 January 1970 by a given
> number of seconds.
>
>
>
Adapted from [this answer](https://stackoverflow.com/a/37539469/4475605). Additionally, you may find [this site](http://nsdateformatter.com) helpful for formatting dates.
|
24,043,234 |
I want to dynamically generate markup for a data structure using JavaScript, so that it can be sent to an arbitrary server via submit.
As I understand it, this is valid HTML:
```
<form method="POST" action="/submit_data">
<input type="checkbox" name="animal" value="Ape" />
<input type="checkbox" name="animal" value="Snake" />
<input type="submit" value="Send data">
</form>
```
But it seems that some servers (for example PHP based?) can deal better with a list when the name is followed by a pair of square brackets:
```
<form method="POST" action="/submit_data">
<input type="checkbox" name="animal[]" value="Ape" />
<input type="checkbox" name="animal[]" value="Snake" />
<input type="submit" value="Send data">
</form>
```
What is the difference, when this data is sent to servers (PHP based or not)?
|
2014/06/04
|
[
"https://Stackoverflow.com/questions/24043234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19166/"
] |
If you are using PHP, then yes you should append `[]` to the name when you expect these values to be part of a list, at least when using `$_GET` and `$_POST`.
Strictly speaking, however, `animal[]` is no different than `animal`. Both are keys, and square brackets are not special in the query string format. If you are using a different server backend it is possible to handle multiple values of `animal`. Both values are sent by the browser:
```
animal=Ape&animal=Snake
```
In PHP it is possible, however, to parse multiple values of `animal` in PHP as well. The `$_GET` and `$_POST` globals are for convenience. They follow the same rules as the [parse\_str](http://www.php.net/manual/en/function.parse-str.php) function, which has some quirks like periods `.` being converted to underscores `_`.
You can get the raw GET query with:
```
$_SERVER['QUERY_STRING']
```
And you can get the raw POST data with:
```
file_get_contents("php://input")
```
(See <http://www.php.net/manual/en/wrappers.php.php>)
The creation of `$_GET` and `$_POST` superglobals are regulated with the [variables\_order](http://us3.php.net/manual/en/ini.core.php#ini.variables-order) setting in php.ini. These are created only when you use them, as long as [auto\_globals\_jit](http://us3.php.net/manual/en/ini.core.php#ini.auto-globals-jit) is enabled (otherwise it always happens just before the script runs). As long as auto\_globals\_jit is enabled you can use the raw data without the extra overhead.
|
You should either use different names or use the square brackets (which will basically create an array of the values).
If you use the same name for multiple inputs, PHP will only be able to handle the last one.
Radio buttons are an exception as there you can only make one selection thus only one value will be needed.
|
24,043,234 |
I want to dynamically generate markup for a data structure using JavaScript, so that it can be sent to an arbitrary server via submit.
As I understand it, this is valid HTML:
```
<form method="POST" action="/submit_data">
<input type="checkbox" name="animal" value="Ape" />
<input type="checkbox" name="animal" value="Snake" />
<input type="submit" value="Send data">
</form>
```
But it seems that some servers (for example PHP based?) can deal better with a list when the name is followed by a pair of square brackets:
```
<form method="POST" action="/submit_data">
<input type="checkbox" name="animal[]" value="Ape" />
<input type="checkbox" name="animal[]" value="Snake" />
<input type="submit" value="Send data">
</form>
```
What is the difference, when this data is sent to servers (PHP based or not)?
|
2014/06/04
|
[
"https://Stackoverflow.com/questions/24043234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19166/"
] |
If you are using PHP, then yes you should append `[]` to the name when you expect these values to be part of a list, at least when using `$_GET` and `$_POST`.
Strictly speaking, however, `animal[]` is no different than `animal`. Both are keys, and square brackets are not special in the query string format. If you are using a different server backend it is possible to handle multiple values of `animal`. Both values are sent by the browser:
```
animal=Ape&animal=Snake
```
In PHP it is possible, however, to parse multiple values of `animal` in PHP as well. The `$_GET` and `$_POST` globals are for convenience. They follow the same rules as the [parse\_str](http://www.php.net/manual/en/function.parse-str.php) function, which has some quirks like periods `.` being converted to underscores `_`.
You can get the raw GET query with:
```
$_SERVER['QUERY_STRING']
```
And you can get the raw POST data with:
```
file_get_contents("php://input")
```
(See <http://www.php.net/manual/en/wrappers.php.php>)
The creation of `$_GET` and `$_POST` superglobals are regulated with the [variables\_order](http://us3.php.net/manual/en/ini.core.php#ini.variables-order) setting in php.ini. These are created only when you use them, as long as [auto\_globals\_jit](http://us3.php.net/manual/en/ini.core.php#ini.auto-globals-jit) is enabled (otherwise it always happens just before the script runs). As long as auto\_globals\_jit is enabled you can use the raw data without the extra overhead.
|
*Thanks to every one who commented or posted answers. Alas, most responses were targeted at PHP scenarios, which is not my main concern. @FelixKling added some helpful comments that I pick up here (Felix, if you choose to post an answer, I will remove mine and accept yours).*
From [W3C](http://www.w3.org/TR/html5/forms.html):
>
> Multiple controls can have the same name; for example, here we give all the checkboxes the same name, and the server distinguishes which checkbox was checked by seeing which values are submitted with that name — like the radio buttons, they are also given unique values with the value attribute.
>
>
>
So using `name="animal"` and `name="animal[]"` are both valid and will send multiple entries to the server: `animal=Ape&animal=Snake` or `animal[]=Ape&animal[]=Snake` respectively.
In general servers can process both variants.
**If, however** the server is implemented using PHP, the latter syntax (with trailing `[]`) is required, because otherwise PHP will discard all but the last entry.
So my conclusion is: use the plain syntax, unless you have a PHP backend (or if the backend has similar behavior).
|
149,086 |
A company that I do business with (e.g. Uber, Google) has requested scans of identity documents. How should I respond? For example:
* Should I provide the documents? What risks are associated with this? What steps (e.g. watermarking) can I take to reduce these risks?
* Should I refuse? If so, what are good ways to persuade the company to continue doing business with me?
Context: People in real life sometimes ask me for advice when they encounter this. I generally just advise to provide the documents and move on, but it would be good to have a detailed answer that I could refer to.
|
2017/01/22
|
[
"https://security.stackexchange.com/questions/149086",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/31625/"
] |
It is not uncommon for organisations you do business with to ask for some level of identification using scanned documents.
You need to do a realistic assessment of the information you are presenting and to whom. It is impossible for us to make a fundamental judgement on whether it is reasonable or not because it depends on the business you are doing, the value, risk (both to you and them) and so on.
Bearing in mind that much of the information you are being asked to share may well not be that sensitive. For example, if I copy my credit card, even the back with its CVV and send it, it is likely that the organisation would get that data anyway. Perhaps they ask for a company bill or bank statement as proof of you being a legitimate and financially secure business - in that case, they will get little more than they already know but with some extra such as someone you paid money to and how much was recently in your company bank account. Is that a great risk to you when you pass it to someone you are about to do some valuable (presumably) business with?
If there is a document you think carries an unacceptable risk, try and get them to accept an alternative.
|
I think it is critical to ask them either for their public PGP key and encrypt for them, or send them as encrypted zip, and in a separate email or better in a separate channel send them the password.
Just imagine what those billion Yahoo hacked emails can contain. People send their CC via email in plaintext.
|
149,086 |
A company that I do business with (e.g. Uber, Google) has requested scans of identity documents. How should I respond? For example:
* Should I provide the documents? What risks are associated with this? What steps (e.g. watermarking) can I take to reduce these risks?
* Should I refuse? If so, what are good ways to persuade the company to continue doing business with me?
Context: People in real life sometimes ask me for advice when they encounter this. I generally just advise to provide the documents and move on, but it would be good to have a detailed answer that I could refer to.
|
2017/01/22
|
[
"https://security.stackexchange.com/questions/149086",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/31625/"
] |
As per the same question that was directed on the meta: [X company has requested a scan of my passport](https://security.meta.stackexchange.com/questions/2616/x-company-has-requested-a-scan-of-my-passport?cb=1)
Handling various security documents frequently, these are some of the pointers I give to people:
* Most security features don't appear in a scanned image
* Send the scan in black in white
* Send a lower resolution, or compressed image (Medium/Low JPEG)
* Attach only one side of the document if possible
* Ask the company what their data retention policies are
* Get a bank or other notary public to notarize the scanned copies
* Do a search to see if there are any past data leaks at the company (e.g. Yahoo)
* See if you can arrange for a physical presentation of the document.
* Send the document with a link to a service that allows for retraction (Expiry)
* Ask about sending the images by Fax
* Ask if they require document numbers only (much more secure)
* If you are still concerned, apply a physical/digital watermark
**By not verifying an identity document in person can land companies in hot water, and is simply bad practice.** *There is no valid excuse* why one would not verify the true holder of the document, or if there is in fact a true document at all. Companies are unfortunately lazy in this regard.
There are plenty of scans of common documents on the internet, which include US/Canadian/UK passports and drivers licences. Many come as Photoshop templates with instructions on how to paste your own image in, change a few other personal features (name/date of birth), and how to attempt to pass it off as a real scan.
Once you have sent an image (or series of images) off, there is very little you can do to protect yourself. There is a whole area of study related to Data Loss Prevention when it comes to company secrets. Most of these can not be applied to the "Average Joe", as it requires an elaborate setup.
By refusing to send a scan of a document makes it look as if you are hiding something, which may or may not be true. When applying for a job, refusing to send identity documents by email could result in the loss of an opportunity. So unfortunately, you are between a rock and a hard place when it comes to this.
|
I think it is critical to ask them either for their public PGP key and encrypt for them, or send them as encrypted zip, and in a separate email or better in a separate channel send them the password.
Just imagine what those billion Yahoo hacked emails can contain. People send their CC via email in plaintext.
|
149,086 |
A company that I do business with (e.g. Uber, Google) has requested scans of identity documents. How should I respond? For example:
* Should I provide the documents? What risks are associated with this? What steps (e.g. watermarking) can I take to reduce these risks?
* Should I refuse? If so, what are good ways to persuade the company to continue doing business with me?
Context: People in real life sometimes ask me for advice when they encounter this. I generally just advise to provide the documents and move on, but it would be good to have a detailed answer that I could refer to.
|
2017/01/22
|
[
"https://security.stackexchange.com/questions/149086",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/31625/"
] |
I suggest removing the parts (by taping them before scanning) that are not necessary to match your picture with your name, i.e. the passport and serial numbers. Ask the party requesting the password scan about the purpose of this to figure out which parts are essential to them, why they would need them, how they would store the scan and when they would delete it from all their media. Maybe even the picture is not relevant to them or you can have a webcam session showing it to them.
In Germany, there is actually a law that forbids electronically scanning ID cards: the "Personalausweisgesetz" ([§ 20 PAuswG](https://www.gesetze-im-internet.de/pauswg/__20.html)). It is only allowed to use a copy machine (basically to "store it on paper"), but the company/person requesting a copy must inform you that you have the right to black out the serial numbers. The copy must be destroyed as soon as its purpose is fulfilled.
Find all guidelines summarized [here](https://datenschutz-agentur.de/das-einscannen-und-speichern-von-personalausweisen-ist-unzulaessig/).
But you have to know that Germany has the best data protection laws worldwide, so don't be surprised if other countries don't follow this example.
Note: first answered [here](https://security.meta.stackexchange.com/questions/2616/x-company-has-requested-a-scan-of-my-passport/2629?noredirect=1#comment6827_2629), didn't look for this question. Thanks @[paj28](https://security.meta.stackexchange.com/users/31625/paj28) for his remark.
|
I think it is critical to ask them either for their public PGP key and encrypt for them, or send them as encrypted zip, and in a separate email or better in a separate channel send them the password.
Just imagine what those billion Yahoo hacked emails can contain. People send their CC via email in plaintext.
|
149,086 |
A company that I do business with (e.g. Uber, Google) has requested scans of identity documents. How should I respond? For example:
* Should I provide the documents? What risks are associated with this? What steps (e.g. watermarking) can I take to reduce these risks?
* Should I refuse? If so, what are good ways to persuade the company to continue doing business with me?
Context: People in real life sometimes ask me for advice when they encounter this. I generally just advise to provide the documents and move on, but it would be good to have a detailed answer that I could refer to.
|
2017/01/22
|
[
"https://security.stackexchange.com/questions/149086",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/31625/"
] |
As per the same question that was directed on the meta: [X company has requested a scan of my passport](https://security.meta.stackexchange.com/questions/2616/x-company-has-requested-a-scan-of-my-passport?cb=1)
Handling various security documents frequently, these are some of the pointers I give to people:
* Most security features don't appear in a scanned image
* Send the scan in black in white
* Send a lower resolution, or compressed image (Medium/Low JPEG)
* Attach only one side of the document if possible
* Ask the company what their data retention policies are
* Get a bank or other notary public to notarize the scanned copies
* Do a search to see if there are any past data leaks at the company (e.g. Yahoo)
* See if you can arrange for a physical presentation of the document.
* Send the document with a link to a service that allows for retraction (Expiry)
* Ask about sending the images by Fax
* Ask if they require document numbers only (much more secure)
* If you are still concerned, apply a physical/digital watermark
**By not verifying an identity document in person can land companies in hot water, and is simply bad practice.** *There is no valid excuse* why one would not verify the true holder of the document, or if there is in fact a true document at all. Companies are unfortunately lazy in this regard.
There are plenty of scans of common documents on the internet, which include US/Canadian/UK passports and drivers licences. Many come as Photoshop templates with instructions on how to paste your own image in, change a few other personal features (name/date of birth), and how to attempt to pass it off as a real scan.
Once you have sent an image (or series of images) off, there is very little you can do to protect yourself. There is a whole area of study related to Data Loss Prevention when it comes to company secrets. Most of these can not be applied to the "Average Joe", as it requires an elaborate setup.
By refusing to send a scan of a document makes it look as if you are hiding something, which may or may not be true. When applying for a job, refusing to send identity documents by email could result in the loss of an opportunity. So unfortunately, you are between a rock and a hard place when it comes to this.
|
It is not uncommon for organisations you do business with to ask for some level of identification using scanned documents.
You need to do a realistic assessment of the information you are presenting and to whom. It is impossible for us to make a fundamental judgement on whether it is reasonable or not because it depends on the business you are doing, the value, risk (both to you and them) and so on.
Bearing in mind that much of the information you are being asked to share may well not be that sensitive. For example, if I copy my credit card, even the back with its CVV and send it, it is likely that the organisation would get that data anyway. Perhaps they ask for a company bill or bank statement as proof of you being a legitimate and financially secure business - in that case, they will get little more than they already know but with some extra such as someone you paid money to and how much was recently in your company bank account. Is that a great risk to you when you pass it to someone you are about to do some valuable (presumably) business with?
If there is a document you think carries an unacceptable risk, try and get them to accept an alternative.
|
149,086 |
A company that I do business with (e.g. Uber, Google) has requested scans of identity documents. How should I respond? For example:
* Should I provide the documents? What risks are associated with this? What steps (e.g. watermarking) can I take to reduce these risks?
* Should I refuse? If so, what are good ways to persuade the company to continue doing business with me?
Context: People in real life sometimes ask me for advice when they encounter this. I generally just advise to provide the documents and move on, but it would be good to have a detailed answer that I could refer to.
|
2017/01/22
|
[
"https://security.stackexchange.com/questions/149086",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/31625/"
] |
As per the same question that was directed on the meta: [X company has requested a scan of my passport](https://security.meta.stackexchange.com/questions/2616/x-company-has-requested-a-scan-of-my-passport?cb=1)
Handling various security documents frequently, these are some of the pointers I give to people:
* Most security features don't appear in a scanned image
* Send the scan in black in white
* Send a lower resolution, or compressed image (Medium/Low JPEG)
* Attach only one side of the document if possible
* Ask the company what their data retention policies are
* Get a bank or other notary public to notarize the scanned copies
* Do a search to see if there are any past data leaks at the company (e.g. Yahoo)
* See if you can arrange for a physical presentation of the document.
* Send the document with a link to a service that allows for retraction (Expiry)
* Ask about sending the images by Fax
* Ask if they require document numbers only (much more secure)
* If you are still concerned, apply a physical/digital watermark
**By not verifying an identity document in person can land companies in hot water, and is simply bad practice.** *There is no valid excuse* why one would not verify the true holder of the document, or if there is in fact a true document at all. Companies are unfortunately lazy in this regard.
There are plenty of scans of common documents on the internet, which include US/Canadian/UK passports and drivers licences. Many come as Photoshop templates with instructions on how to paste your own image in, change a few other personal features (name/date of birth), and how to attempt to pass it off as a real scan.
Once you have sent an image (or series of images) off, there is very little you can do to protect yourself. There is a whole area of study related to Data Loss Prevention when it comes to company secrets. Most of these can not be applied to the "Average Joe", as it requires an elaborate setup.
By refusing to send a scan of a document makes it look as if you are hiding something, which may or may not be true. When applying for a job, refusing to send identity documents by email could result in the loss of an opportunity. So unfortunately, you are between a rock and a hard place when it comes to this.
|
I suggest removing the parts (by taping them before scanning) that are not necessary to match your picture with your name, i.e. the passport and serial numbers. Ask the party requesting the password scan about the purpose of this to figure out which parts are essential to them, why they would need them, how they would store the scan and when they would delete it from all their media. Maybe even the picture is not relevant to them or you can have a webcam session showing it to them.
In Germany, there is actually a law that forbids electronically scanning ID cards: the "Personalausweisgesetz" ([§ 20 PAuswG](https://www.gesetze-im-internet.de/pauswg/__20.html)). It is only allowed to use a copy machine (basically to "store it on paper"), but the company/person requesting a copy must inform you that you have the right to black out the serial numbers. The copy must be destroyed as soon as its purpose is fulfilled.
Find all guidelines summarized [here](https://datenschutz-agentur.de/das-einscannen-und-speichern-von-personalausweisen-ist-unzulaessig/).
But you have to know that Germany has the best data protection laws worldwide, so don't be surprised if other countries don't follow this example.
Note: first answered [here](https://security.meta.stackexchange.com/questions/2616/x-company-has-requested-a-scan-of-my-passport/2629?noredirect=1#comment6827_2629), didn't look for this question. Thanks @[paj28](https://security.meta.stackexchange.com/users/31625/paj28) for his remark.
|
12,339,276 |
Is there a way, using the Interface Builder, in XCode to display a random image? So let's say I have three images and want a random one to display each time my app is loaded. I'm new to XCode, so I'm looking for the simplest way to do it and IB seems to be the route to take. Thanks!
|
2012/09/09
|
[
"https://Stackoverflow.com/questions/12339276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1506841/"
] |
After thinking about this for a few seconds, I realized the answer is of course you can, but it is such a pain, that I doubt that you would want to. I came up with a approach as an example of how to use IB in such a way.
First, subclass UIImageView, I will call it MyRandomImageView. The only member of MyRandomImageView is `@property (retain, nonatomic) NSString *randomImageJSON`.
Next, add a UIImageView to your view. In the Identity Inspector, change the Custom Class from UIImageView to MyRandomImageView. Then in the Identity Inspector, under User Defined Runtime Attributes, set randomImageJSON to something like `[ "image1.png", "image2.png", "image3.png" ]`.
The final part is where you have all the trouble. Create `-[MyRandomImageView setRandomImageJSON]`. It needs to set the `_randomImageJSON` iVar, use `NSJSONSerialization` to create the array of strings, randomly pick one of the strings, then set `self.image = [UIImage imageNamed:randomImage]`
This should do exactly and you wish, a random image from the Interface Builder. Hope that helps.
|
You have to do this programmatically. Haven't tested the code below, but I'm pretty sure it works.
```
int imageNumber = arc4random() % 3;
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%i", imageNumber]]];
```
You should first declare it in the implementation and link it to your UIImageView in the Interface Builder.
|
235,943 |
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in
time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be.
For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago.
While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
|
2022/09/22
|
[
"https://worldbuilding.stackexchange.com/questions/235943",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/57832/"
] |
**What paradox?**
All ships are 100% automatic (it doesn't matter if it they are or not, it's just easier for the explanation). The moment my ship detects the enemy ship, it fires the weapon. The very moment the circuits activate the weapon, my enemy is hit.
Ditto for my enemy, which did the same to me.
Where's the paradox? If my ship detected the enemy ship first, the enemy ship won't get a shot off. If the enemy ship detected my ship first, I won't get a shot off. If we detected each other simultaneously, neither of us will be around to argue about whether or not there was a paradox.
**But I want a rule!**
I literally can think of only one scenario where a paradox can occur. Your detonation can occur ***before*** the weapon is activated. In that case, the paradox of your ship destroying another ship, but you were destroyed before you activated your weapon, could occur.
**Rule:** don't do that. Regardless the range you wish to give your weapon, no detonation can occur before the weapon is activated. In other words, time travel in your universe is causal. No paradox can occur because no effect can occur without the cause that brought the effect about.
*And why do you want your rule? Because if you didn't then all it would take is one drunken sailor ordered to fire the weapon to look at his friend and say, "watch, this will be funny" and not push the button to rip all of space and time apart. You don't want that. Nobody wants that. Well, psychopaths might want that. But we're not psychopaths, right? RIGHT?*
|
**No real paradox free time travel**
Unless the time travelling component is required, you can get around this by making weapons fire their projectiles at very near light speed. You could say they somehow weaponized neutrinos or something similar. This would have very similar results in that the attacks are unable to be dodged, undetectable, and can only hit a target where they are currently at (unless they are extremely far away).
Another good way to deal with this is treating the shots as instantly teleporting the distance as Mileonen mentioned. While this does result in problems of FTL travel, those are a lot easier to ignore than time travel.
The paradox you proposed of not having a ship to shoot at so why shoot does happen anyway regardless of whether there are the two ships are firing at each other. If the ship is destroyed before you would have pushed the button to fire, then there would be no need to press it in the first place so you wouldn't have fired the shot that destroyed the enemy ship.
If the time travel is important I would follow what JBH recommended and make a rule where time travel is causal.
Another way around this might be that the weapon's computer and projectile exists in its current state across time eg any firing information and the fired projectile exists on it in the past present and future. With the time of the attack being part of the firing information the projectile will only meaningfully "exist" only for the moment it strikes the target. This, along with the firing information only meaningfully existing for the crew when the data is entered and after that, would remove the paradox (or at least make it feel like its not there, there is probably something I am overlooking). This is a lot more complicated though.
|
235,943 |
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in
time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be.
For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago.
While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
|
2022/09/22
|
[
"https://worldbuilding.stackexchange.com/questions/235943",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/57832/"
] |
**No real paradox free time travel**
Unless the time travelling component is required, you can get around this by making weapons fire their projectiles at very near light speed. You could say they somehow weaponized neutrinos or something similar. This would have very similar results in that the attacks are unable to be dodged, undetectable, and can only hit a target where they are currently at (unless they are extremely far away).
Another good way to deal with this is treating the shots as instantly teleporting the distance as Mileonen mentioned. While this does result in problems of FTL travel, those are a lot easier to ignore than time travel.
The paradox you proposed of not having a ship to shoot at so why shoot does happen anyway regardless of whether there are the two ships are firing at each other. If the ship is destroyed before you would have pushed the button to fire, then there would be no need to press it in the first place so you wouldn't have fired the shot that destroyed the enemy ship.
If the time travel is important I would follow what JBH recommended and make a rule where time travel is causal.
Another way around this might be that the weapon's computer and projectile exists in its current state across time eg any firing information and the fired projectile exists on it in the past present and future. With the time of the attack being part of the firing information the projectile will only meaningfully "exist" only for the moment it strikes the target. This, along with the firing information only meaningfully existing for the crew when the data is entered and after that, would remove the paradox (or at least make it feel like its not there, there is probably something I am overlooking). This is a lot more complicated though.
|
I think the paradox can be resolved by adding a necessary delay: mass prevents time travel. The mass of the firing ship means the weapon needs to travel a bit before it can start traveling backwards, and the mass of the target ship likewise causes the weapon to reenter normal time a short distance away. Just tune the effect so the arrival time is too small to allow a response and the weapon will largely function like you want. The mass of the weapon itself isn't relevant, as the whole thing will time travel. The relative masses of the two ships is also not important, as the departure delay for one ship;s weapon will equal the arrival delay for the other ship's weapon, so the total trip is functionally symmetrical in both directions (less massive ships would have a slight advantage in departure time, but an equal disadvantage in arrival time).
So simultaneous shots will both arrive, as the two shots will have time to travel before their source is destroyed. Near simultaneous shots will also result in both ships being destroyed, due to the delays.
Super massive ships (I'm thinking planetoid mass) would have enough arrival delay to respond with point weapons, but the cost to make, move, and maintain such a ship would be prohibitive. Likewise, the time travel feature of the weapon isn't usable too close to a planet, or more likely inside a solar system at all. Maybe outer reaches are low mass enough. Battle fields with asteroids or debris or whatever would require carefully aimed shots to avoid having the weapon knocked out of time travel too soon.
|
235,943 |
In space, normal weapons are so easy to dodge because by the time you see an enemy ship and fire at it, it's already moved out of the way. Now imagine a weapon that travels backwards in
time as it flies though space so that when it arrives at its target, it converges with the exact time and location that you saw the target when you fired. So, if an enemy ship is 5 light minutes away. Then your shot travels back in time 5 minutes as it closes the distance eliminating all guess work about where the ship will be.
For purposes of this question, assume this weapon can only travel back in time as fast as light can travel forward in time. So you can target a thing in the past exactly where you see it now, but you cant target something you saw 10 minutes ago.
While such a weapon would seem to work without any major paradoxes when you just have one ship shooting another, what would happen if 2 ships shot at each other with such a weapon. Since both ships could in theory be destroyed before either ship actually fires thier weapons does there need to be some rule that one event will take precedence over the other, or is there a logically consistent way for both ships to destroy each other in this manner since neither ship captain could see any future events that might cause him to change his course of action.
|
2022/09/22
|
[
"https://worldbuilding.stackexchange.com/questions/235943",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/57832/"
] |
I think the paradox can be resolved by adding a necessary delay: mass prevents time travel. The mass of the firing ship means the weapon needs to travel a bit before it can start traveling backwards, and the mass of the target ship likewise causes the weapon to reenter normal time a short distance away. Just tune the effect so the arrival time is too small to allow a response and the weapon will largely function like you want. The mass of the weapon itself isn't relevant, as the whole thing will time travel. The relative masses of the two ships is also not important, as the departure delay for one ship;s weapon will equal the arrival delay for the other ship's weapon, so the total trip is functionally symmetrical in both directions (less massive ships would have a slight advantage in departure time, but an equal disadvantage in arrival time).
So simultaneous shots will both arrive, as the two shots will have time to travel before their source is destroyed. Near simultaneous shots will also result in both ships being destroyed, due to the delays.
Super massive ships (I'm thinking planetoid mass) would have enough arrival delay to respond with point weapons, but the cost to make, move, and maintain such a ship would be prohibitive. Likewise, the time travel feature of the weapon isn't usable too close to a planet, or more likely inside a solar system at all. Maybe outer reaches are low mass enough. Battle fields with asteroids or debris or whatever would require carefully aimed shots to avoid having the weapon knocked out of time travel too soon.
|
Seems to ME that it's really contingent on the mechanic by which you decide time "actually" functions. Even Einstein and Hawking kinda "settled" into the whole infinite parallel universe thing for lack of better means to reconcile these sort of incongruities.
Fact is, for you to have cause and effect, action/reaction, determinism/consequence, there's ALWAYS a sequence of events. And there's one thing nearly all those theoretical physicists DO agree on: time is relative from the point of view of the observer.
So my suggestion would be reductionism: break the sequence of events down into smaller and smaller chunks and ultimately there's no paradox. Yes, it's possible one party is retroactively "deleted" from the timeline. Whereupon, for the frame of reference of their opponent, they never fired. They ceased before it could become a conflict. And since their opponent, too is submerged in the same stream of time, they, perforce, would be unable to perceive any sort of potential paradox.
Or, take the string theory approach and assuming every choice bifurcates into every possible choice, and obviate the potential for it entirely.
Personally, I think the mechanic by which the characters could have perceived an event taking place that was subsequently balefire'd out of existence *yet they still remember it* would/could/***should*** be harder to explain than the nitty gritty of the temporal torpedo... but maybe that's just me.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.