qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
4,966,564 | I m working on login module. In logout function i worte the code as below, first kill the session,then redirect it to home page. It is working fine but session is not destroying.
If anybody knows please help me
Here is my code snippet for login & logout:
```
function login()
{
if(!empty($this->data))
{
$user1= $this->User->validateLogin($this->data['User']);
if($user1== true)
{
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setflash('Login failed, Try again');
}
}
}
function logout()
{
$this->Session->delete('User');
$this->redirect('/users/index');
}
```
I got information that, I have to keep header information, below is my code snippet:
$this->header("Cache-Control: no-cache, no-store, must-revalidate"); $this->header("Expires: Mon, 1 Jan 1970 00:00:00 GMT");
But m not getting in which part of my controller i should paste this code? Please help me.... | 2011/02/11 | [
"https://Stackoverflow.com/questions/4966564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/606445/"
] | Try $this->Session->destroy();
The destroy method will delete the session cookie and all session data stored in the temporary file system. check this [link](http://book.cakephp.org/1.3/en/The-Manual/Core-Components/Sessions.html#destroy) | you dont want to kill the session. only to log the user out!
```
$this->Session->delete('Auth');
```
otherwise you destroy cookies and other user defined settings which would be pretty annoying (language, ...)
but the official cake way would be:
```
$this->redirect($this->Auth->logout());
``` |
41,905,301 | I am generating a line chart with d3. It works, but typescript code complain about a property not exists in vs.
>
> Property 'x' does not exist on type '[number, number]'
>
>
>
[](https://i.stack.imgur.com/rWbt2.png)
Looking at the error. It seems like the data point expected is an array with two numbers.
But I am passing in an object. D3 should support both I think.
Does anyone know how to get rid of this error without changing my data? | 2017/01/28 | [
"https://Stackoverflow.com/questions/41905301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4611304/"
] | its a typescript error.
i think there is no x property right now in your d. can you try this
```
return this.xScale(d?.x);
return this.xScale(d?.y);
```
or may be your d have data like this `["x_value","y_value"]` in number format.
in this case you should try
```
return this.xScale(d[0]);
return this.yScale(d[1]);
```
i hope this will help | .x((d:any) => this.xScale(d.x))
.y((d:any) => this.yScale(d.y)) |
49,500,309 | I'm using Spring JPA and I need to have a native query. With that query, I need to get only two fields from the table, so I'm trying to use [Projections](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections). It isn't working, this is the error I'm getting:
```
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.example.IdsOnly]
```
I tried to follow precisely the instructions of that page I linked, I tried to make my query non-native (do I actually need it to be native if I use projections, btw?), but I always get that error.
If I use an interface it works, but the results are proxies and I really need them to be "normal results" that I can turn into json.
So, here's my code. The Entity:
```
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@Entity
@Table(name = "TestTable")
public class TestTable {
@Id
@Basic(optional = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "Id")
private Integer id;
@Column(name = "OtherId")
private String otherId;
@Column(name = "CreationDate")
@Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
@Column(name = "Type")
private Integer type;
}
```
The class for the projection:
```
import lombok.Value;
@Value // This annotation fills in the "hashCode" and "equals" methods, plus the all-arguments constructor
public class IdsOnly {
private final Integer id;
private final String otherId;
}
```
The Repository:
```
public interface TestTableRepository extends JpaRepository<TestTable, Integer> {
@Query(value = "select Id, OtherId from TestTable where CreationDate > ?1 and Type in (?2)", nativeQuery = true)
public Collection<IdsOnly> findEntriesAfterDate(Date creationDate, List<Integer> types);
}
```
And the code that tries to get the data:
```
@Autowired
TestTableRepository ttRepo;
...
Date theDate = ...
List<Integer> theListOfTypes = ...
...
Collection<IdsOnly> results = ttRepo.findEntriesAfterDate(theDate, theListOfTypes);
```
Thanks for the help. I really don't understand what I'm doing wrong. | 2018/03/26 | [
"https://Stackoverflow.com/questions/49500309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3514976/"
] | The query should be using a [constructor expression](https://www.objectdb.com/java/jpa/query/jpql/select#Result_Classes_Constructor_Expressions_):
```
@Query("select new com.example.IdsOnly(t.id, t.otherId) from TestTable t where t.creationDate > ?1 and t.type in (?2)")
```
And i dont know Lombok, but make sure there is a constructor that takes the two IDs as parameters. | You can return list of Object Array (List) as return type of the native query method in repository class.
```
@Query(
value = "SELECT [type],sum([cost]),[currency] FROM [CostDetails] " +
"where product_id = ? group by [type],[currency] ",
nativeQuery = true
)
public List<Object[]> getCostDetailsByProduct(Long productId);
```
```
for(Object[] obj : objectList){
String type = (String) obj[0];
Double cost = (Double) obj[1];
String currency = (String) obj[2];
}
``` |
98,623 | I have a few apps, but this tablet is new and I want more apps. Every time I say download, it says I have insufficient space. Please help! | 2015/02/12 | [
"https://android.stackexchange.com/questions/98623",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/94118/"
] | Go to settings>storage and take a look at what you have for space. Some devices come with very little to start with (4gb) while others have buckets (64gb). Downloading a few movies or games (or loading a big music library) can push a 4gb device to its limit fairly quickly.
If you've checked settings and see that you have very little available space, doing some app housecleaning will obviously help. Some devices will accept an external microsd card, so you have a relatively inexpensive way put a bunch more room on your tablet.
If you've checked setting and there is a lot of available space left, then we need to explore other options. | I would suggest checking what it says in your storage settings to see what you have available for space, and what is taking up the most space. Your media files, downloads, or cached data may be taking up more space than you expect. |
8,621,141 | I am attempting to connect to my local MySQL server with the following code:
```
dbURL = "jdbc:mysql://localhost:3306:/" + dbname;
try{
Class.forName("com.mysql.jdbc.Driver");
try{
con = DriverManager.getConnection(dbURL, dbuser, dbpass);
} catch (SQLException ex){
System.out.println("ERROR: Could not connection to SQL DB");
con = null;
}
} catch (ClassNotFoundException e){
System.out.println("Error: ");
e.printStackTrace();
}
```
I then get
>
> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
>
>
>
I understand that Java cannot find the proper driver for connecting the Java environment to the MySQL database. This is being compiled on a Windows 7 system and ported over to an Ubuntu 11.04 system.
Is there a particular way I can run the Java program with a particular classpath such as:
```
java -cp /usr/share/java/mysql-connector-java.jar program.jar
```
That didn't work when I tried it. | 2011/12/23 | [
"https://Stackoverflow.com/questions/8621141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114045/"
] | In case of JARs, the `-cp` and `-classpath` arguments and the `%CLASSPATH%` environment variable are **ignored**. Instead, the classpath has to be specified in the `Class-Path` entry of JAR's own `/META-INF/MANIFEST.MF` file. It can be a path relative to the JAR itself. E.g. in the same folder or in a `/lib` subfolder.
The below example assumes the driver to be in the same folder as the JAR.
```none
Class-Path: mysql-connector-java.jar
```
*(make sure that the `MANIFEST.MF` file has a blank line at the end)*
### See also:
* [Using JAR files - The Basics - Understanding the MANIFEST.MF](https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html)
* [Eclipse: Package multiple projects into one JAR](https://stackoverflow.com/questions/7218506/eclipse-package-multiple-projects-into-one-jar/)
* [Java Manifest file's class path and how it determines relative dirs](https://stackoverflow.com/questions/3464205/java-manifest-files-class-path-and-how-it-determines-relative-dirs/) | Install MySQL connector for JAVA
```
sudo apt-get install libmysql-java
```
Set classpath
```
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java.jar
```
Source: <http://marksman.wordpress.com/2009/03/01/setting-up-mysqljdbc-driver-on-ubuntu/> |
28,665 | May be we can add a button to ask a previously asked question again to bring it to the top. May be some one else will be able to find it this time and anser. And it will be nice if a rule is put like a question can be "re-asked" only once in a week or so and a total of 5 times or so.. What you think? | 2009/11/05 | [
"https://meta.stackexchange.com/questions/28665",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/135920/"
] | We definitely won't be doing that.
Here's what I recommend:
[Getting attention for unanswered questions?](https://meta.stackexchange.com/questions/7046/how-to-get-attention-for-your-old-unanswered-questions) | How will this be beneficial to the community? It will lead to questions being reposted as exact duplicates, which will either be closed very quickly by the community (wasting the time of those who look at the question to answer it, then realise that it is a dupe), or the answers will be spread out too much rather than being collated in one place.
Instead, draw people's attention to your current question. There they will see answers already provided, which may give them a starting point (e.g. this kind of worked, this didn't work, etc.). For more information on how to draw attention to the post, see the link that Jeff and random have provided ([How to get attention for your old unanswered questions](https://meta.stackexchange.com/questions/7046/how-to-get-attention-for-your-old-unanswered-questions "Please search for dupes before asking your question!")). |
4,640 | It's well-known that we have a quality problem in the [kali-linux](https://unix.stackexchange.com/questions/tagged/kali-linux "show questions tagged 'kali-linux'") tag. Some statistics corroborate this perception (though not to the extent that I'd expected):
* 16.4% of the [kali-linux](https://unix.stackexchange.com/questions/tagged/kali-linux "show questions tagged 'kali-linux'") questions have a negative score, compared with 3% for the site as a whole.
* 39.6% of the [kali-linux](https://unix.stackexchange.com/questions/tagged/kali-linux "show questions tagged 'kali-linux'") questions have a score ≤ 0, compared with 27% for the site as a whole.
* 21.9% have no answer, compared with 15.8% for the site as a whole.
* 21.9% of non-closed question have no answer, compared with 15.6% for the site as a whole.
* 7% are closed (excluding duplicates), compared with 3.5% for the site as a whole.
* 2.4% are closed as duplicates, compared with 4.2% for the site as a whole.
There isn't a *flood* of Kali questions, mind you. About 1.3% of the recently asked questions are [kali-linux](https://unix.stackexchange.com/questions/tagged/kali-linux "show questions tagged 'kali-linux'") (that's the rate for 2017 as a whole as well as for August and for September, rounded to the nearest 0.1%), excluding deleted questions (can a mod please edit in figures that account for deleted questions?).
In chat, several regulars have said that they largely ignore Kali questions. (Personally, I don't ignore the tag, but I tend to skip the questions without reading them.) It seems that many Kali questions are a bad thing for answerers. And I suspect that they're also a bad thing for askers, because all too often, we aren't helping them.
What should we do about Kali questions? | 2017/10/22 | [
"https://unix.meta.stackexchange.com/questions/4640",
"https://unix.meta.stackexchange.com",
"https://unix.meta.stackexchange.com/users/885/"
] | We've often talked in the chat about having a “reference question” telling people not to use Kali Linux. Well, [here's my proposal](https://unix.stackexchange.com/questions/399626/why-is-kali-linux-so-hard-to-set-up-why-wont-people-help-me). Edits welcome, but please keep the gist unless we decide on meta that this isn't the advice we want to give as a community.
Note that I do not propose systematically closing Kali questions! Each question should be judged on its merit. But **when people are clearly in way over their head** and they've asked a question with the usual novice problems (unclear because they didn't explain what they were doing, they didn't copy-paste error messages, they didn't provide relevant information about their system, etc.), we could close it as a duplicate of this advice-giving question *rather than letting the question rot with zero answers and zero comments or closing it as unclear*. | Listening to my fellow networking security classmates from years back, when it was still called BackTrack Linux, I can fully understand this phenomenon. It's somewhat anecdotal, but Kali Linux is seen as the "Swiss army knife" of Linux, and if you haven't installed it yet you aren't cool.
Meanwhile I had been using Debian for years, and around that time was learning how to use Arch Linux. The types of people interested in it expect it to unlock the powers of jujitsu without any rigor of actually understanding Linux. It was like the secret to becoming a nerd quickly without all the fuss.
To that end it may not be particularly useful to tell such askers not to use Kali.. because they want to (say they) use Kali. We'd be better off making "Kali - Script Kiddies Edition" with a Ubuntu installer.
I think to some degree this is the nature of this userbase and simply put fewer of those questions will get answered. I do not think there should be any special response to questions that simply aren't researched or well written. Those should be handled like any other question that isn't well written.
On the other hand there's a special place in my heart for Linux noobs and those newly interested in Linux and I tend to pick up on questions that are simply misinformed rather than poorly written. I do believe that Kali is a vector for getting people interested in Linux as a whole. So that again argues for not telling all these users "your question is irrelevant you were wrong the moment you decided to use Kali Linux."
I think a three step filter should be applied:
1. If the question isn't well researched, close it.
2. If Kali isn't being used for its intended purpose, refer to Gilles
answer.
3. If the user is struggling because they are in over their head, then here we need to question the purpose of this site.
If this site is to help all users of Linux and Unix do what *they* want to, then we should just try our best to answer those questions. If we want to be more like teachers or guides then we should point such users away from Kali and toward a more suitable Linux distribution first. The latter might be hard considering that many Kali users use it because of the name alone.
(I'm new to this site and to Meta. But I figured I'd participate since I have somewhat unique knowledge on the subject.) |
466,197 | I'm running Ubuntu 14.04 LTS, and I have an HD 4600 integrated graphics chip.
```
lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor Integrated Graphics Controller (rev 06)
```
Intel just released the new version of their Graphics driver for Ubuntu 14.04.
<https://01.org/linuxgraphics/downloads/2014/intelr-graphics-installer-1.0.5-linux>
When I try to install it, I get stuck at:
```
Finished : E:GPG error: http://download.01.org trusty InRelease: Clearsigned file isn't valid, got 'NODATA' (does the network require authentication?) [ ] ◦
main-window.c/on_transaction_finished: Package transaction finished with an error
```
And it prevents `sudo apt-get update` from completing. I get the same error as before.
I went to **Software & Updates** and under **Other Software** tab I removed the bad repository: `http://download.01.org/gfx/ubuntu/14.04/main`, and then I could update my repositories. But I cannot install the Intel Graphics Driver!
I hope I'm making sense. This is the first day this is available, so I'm counting on Intel to fix this soon, if not, I hope someone can help find a work around. | 2014/05/15 | [
"https://askubuntu.com/questions/466197",
"https://askubuntu.com",
"https://askubuntu.com/users/277287/"
] | Here's the easier solution for those with problems:
1. Open Nautilus(file explorer), go to Edit -> Preferences -> Behavior, and make sure that under **Executable text files**, **Ask each time** is selected! (if not, select it)
2. Close the window
3. Open Nautilus (if not already open)
4. Right click **New document > Empty document**
5. Name it script.sh
6. Open it and enter this:
```bsh
#! /bin/bash
while [ 1 ]; do
sudo sed --in-place 's/http:/https:/g' /etc/apt/sources.list.d/intellinuxgraphics.list
sleep 1
done
```
7. Save it and close it
8. Right click on `script.sh` and select **Permissions**
9. Check **Allow executing this file as program**
10. Close the window
11. Double click it
12. Select **Run in terminal**
13. Enter password
14. **DO NOT** close the terminal
15. Begin installation, and everything should work
I also got **Failed to fetch download.01.org/gfx/ubuntu/14.04/main/pool/main/i/… Size mismatch** error and this fixed the problem. You can delete script file and close the terminal when the installation is finished.
Edit: There is simpler way:
1. Enter this in terminal:
```bsh
#! /bin/bash
while [ 1 ]; do
sudo sed --in-place 's/http:/https:/g' /etc/apt/sources.list.d/intellinuxgraphics.list
sleep 1
done
```
2. Enter password
3. Run the installer | Use gdebi to install the intel-linux-graphics-installer and you won't have the GPG problems. It should automatically install with the deb package. Use the following commands to do so:
```
sudo apt-get update && sudo apt-get install gdebi
cd && wget https://download.01.org/gfx/ubuntu/14.04/main/pool/main/i/intel-linux-graphics-installer/intel-linux-graphics-installer_1.0.6-0intel1_amd64.deb
sudo gdebi intel-linux-graphics-installer_1.0.6-0intel1_amd64.deb
intel-linux-graphics-installer
```
Follow the instructions displayed in the GUI to update your system. Save any unsaved work and reboot for the changes to take effect.
---
Furthermore, using
```
sudo apt-key adv
```
Is considered a security risk and is not recommended as you are *"undermining the whole security concept as this is not a secure way of recieving keys for various reasons (like: hkp is a plaintext protocol, short and even long keyids can be forged, …)"*. <http://ubuntuforums.org/showthread.php?t=2195579>
I believe the correct way is to first import the key
```
GET https://download.01.org/gfx/RPM-GPG-KEY-ilg | gpg --import
```
Check the fingerprint
```
gpg --check-sigs --fingerprint 75E52366
```
Get the key from the keyserver
```
gpg --keyserver pgpkeys.mit.edu --recv-key 7CB0FA13
```
Export the key to your keyring
```
gpg -a --export 75E52366 | sudo apt-key add -
```
Repeat for second key
```
GET https://download.01.org/gfx/RPM-GPG-KEY-ilg-2 | gpg --import
gpg --check-sigs --fingerprint 2F4AAA66
gpg --keyserver pgpkeys.mit.edu --recv-key 144BD458
gpg -a --export 2F4AAA66 | sudo apt-key add -
```
more info <http://www.debian.org/doc/manuals/securing-debian-howto/ch7.en.html#s-deb-pack-sign> |
35,541,978 | Using the [Refile](https://github.com/refile/refile) gem to handle file uploading in Rails, what is the best way to determine image height and width during / after it has been uploaded? There is no built in support for this AFAIK, and I can't figure out how to do it using MiniMagick. | 2016/02/21 | [
"https://Stackoverflow.com/questions/35541978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/496080/"
] | Refile attachments have a `to_io` method (see [Refile::File](http://www.rubydoc.info/gems/refile/Refile/File) docs) which returns an IO object that you can pass to MiniMagick.
Assuming you have an Image model with a `file` attachment (id stored in a `file_id` string column) and `width` and `height` columns you can use the following callback:
```
class Image < ActiveRecord::Base
attachment :file
before_save :set_dimensions, if: :file_id_changed?
def set_dimensions
image = MiniMagick::Image.open(file.to_io)
self.width = image.width
self.height = image.height
end
end
```
Hope that helps. | You can use MiniMagick to do this (but need to be using the latest version).
```
image = MiniMagick::Image.open('my_image.jpg')
image.height #=> 300
image.width #=> 1300
```
This is all pretty well documented in the README.md for the gem: <https://github.com/minimagick/minimagick> |
68,041 | Lets say that I have a smart contract C witch has a function setf(uint256). Also let's assume that there are many users(with different accounts) that want to call that function with argument 5 for example. As i understand each of them will make a logically same transaction to the same contract function with the same argument and each of them will pay the same gas. Is there any way to reject the rest of the pending transactions when the first one of them is mined and avoid the gas? If every user use the same account I could use the same nonce in all the transactions and only one would be mined. In the case of different accounts is there any way? | 2019/03/07 | [
"https://ethereum.stackexchange.com/questions/68041",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/50750/"
] | Just to add to @haxerl's good answer: you could use a proxy contract which does the logic for you. So the idea is the same but the proxy account would act as an intermediare which is only used for checking for duplicate transactions.
The benefit of this is that you can code the actual contract normally and then afterwards just include the proxy contract in-between to do the actual checking. The downside is that your "context" changes - for example `msg.sender` would be the proxy account instead of the actual sender (unless you do some ugly `delegatecall` magic). | A very simple solution: you can have a nonce in your contract storage.
```
uint256 contractNonce;
uint256 f;
function setF(uint256 newF, uint256 providedNonce) public {
revert(providedNonce <= contractNonce);
f = newF;
contractNonce++;
}
``` |
24,349,504 | How can I handle very long strings in Play's application.conf? Suppose I have:
```
my.value.param = "Very very very very long line"
```
and I want to split long line like
```
my.value.param = "Very very very "
+ "very long line"
```
How can I do this using HOCON format? Thanks | 2014/06/22 | [
"https://Stackoverflow.com/questions/24349504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/511964/"
] | From the [documentation](https://github.com/typesafehub/config/blob/master/HOCON.md#multi-line-strings) it appears to not be possible in that way. You could work around it slightly, like this:
```
my.value.param = ${my.value.param1} ${my.value.param2}
my.value.param1="Very very very"
my.value.param2="very long line"
```
But this is very ugly, of course. I don't think it was ever the intention to have long strings stored in the configuration. | ```
build.path = ${PATH}
build.path = ${build.path}":/opt/groovy-2.4.5/bin"
build.path = ${build.path}":/opt/gradle-2.9/bin"
build.path = ${build.path}":/opt/scala-2.11.7/bin"
build.path = ${build.path}":/opt/sbt-0.13.9/bin"
``` |
4,242,437 | I am trying to create a small applescript which will launch the DVD Player application and then resize it to its Actual Size. The code is listed below. When I run the code the DVD Player launches but it does not resize the window. What am I missing to get this to work?
Thanks,
Rob
```
do_menu("DVD Player", "View", "Actual Size")
on do_menu(app_name, menu_name, menu_item)
try
-- bring the target application to the front
tell application app_name
activate
end tell
delay 3
tell application "System Events"
tell process app_name
tell menu bar 1
tell menu bar item menu_name
tell menu menu_name
click menu item menu_item
end tell
end tell
end tell
end tell
end tell
return true
on error error_message
return false
end try
end do_menu
``` | 2010/11/22 | [
"https://Stackoverflow.com/questions/4242437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/434446/"
] | Have you looked at the dictionary for DVD Player?
There are properties for adjusting the size.
This will open it and go full screen:
```
tell application "DVD Player"
open
delay 2
set viewer full screen to true
end tell
```
Or there is the viewer size property which states:
viewer size (half/normal/double/max) : To set the the viewer size
So you could use this to go to Actual Size:
```
tell application "DVD Player"
open
delay 2
set viewer size to normal
end tell
```
Is that what you wanted to do? | I'm not in front of a Mac so I can't really test your code, but my suggestion is to try an existing and proven implementation of the same functionality, which uses recursion rather than nesting:
<http://hints.macworld.com/article.php?story=20060921045743404>
It's also possible that your `delay 3` is not long enough for the DVD Player application to completely load before you start trying to script menu events. You could try debugging this by running two separate scripts and see if your menu-activation code works once the DVD Player app is loaded. |
10,478,234 | farmville/frontierville/etc
How do I figure out how many "likes" these apps have?
The graph API does not work with apps. | 2012/05/07 | [
"https://Stackoverflow.com/questions/10478234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179736/"
] | Call
```
https://graph.facebook.com/APP_ID
```
Try this example call in [Graph Explorer](https://developers.facebook.com/tools/explorer):
```
https://graph.facebook.com/farmville
```
which will return a JSON reponse with id, name, picture, link and then likes as 5th value. | You can get the number of likes from Graph API by querying by Application `id` or Application `namespace`.
```
https://graph.facebook.com/APP_ID_OR_NAMESPACE
```
You can also limit results to be only constructed from `id` of an application and `likes` by using `fields` argument in URL:
```
https://graph.facebook.com/APP_ID_OR_NAMESPACE?fields=likes
```
Beware that not every application have a `namespace` defined and because name of application is not unique, it's better to use `id` of application to retrieve details from Graph API |
2,807,390 | Given function
$$F(x,y)=\frac{(x+y-2)(x+y-1)}{2}+y$$ is bijective or not.
Attempt:
I check $F(x\_1,y\_1)$ and $F(x\_2,y\_2)$
and ends up in
$$(x\_1+y\_1)^2-3x\_1-y\_1=(x\_2+y\_2)^2-3x\_2-y\_2$$
Now how to show $(x\_1,y\_1)=(x\_2,y\_2)$?
How one can show it is surjective? | 2018/06/04 | [
"https://math.stackexchange.com/questions/2807390",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/317044/"
] | Write it as
$(x\_1+y\_1)^2-(x\_2+y\_2)^2+3(x\_2-x\_1)+(y\_2-y\_1)=0$
Now suppose, $x\_1 \neq x\_2$ and $y\_1 \neq y\_2$.
What can you say about the expression i.e., can it be $0$?
Remember $x\_1,x\_2,y\_1,y\_2 \in \mathbb{N}$. | Its not even injective, since $F(2,0) = 0 = F(1,0)$ |
4,623 | In [this thread about cooking for people with allergies](https://cooking.stackexchange.com/questions/4621/tips-on-cooking-for-people-with-different-allergies) the first commenter (rightly, IMHO) suggests splitting up that general effort into more allergy-specific tips. The overall effort might still be worthwile, but as I suffer from the 'fruit/nut' allergy myself, I would like to start this question & answer.
My question: which foods trigger the fruit/nut allergy, rated by severity, and what techniques can you use to reduce the effect? I will be answering my own question as well (in the hope of offering some help), but would prefer answers that I don't know already.
For those that aren't aware of the allergy for nuts and fruits and wondering whether they may have it, here are links to [wikipedia on oral allergy syndrome](http://en.wikipedia.org/wiki/Oral_allergy_syndrome) and the [Calgary Allergy network](http://www.calgaryallergy.ca/Articles/English/Oral_Food_Allergy.htm) (as I find their site useful and will be using it, and my own experience, as a departure point. Note that the allergy may start later in life. | 2010/08/09 | [
"https://cooking.stackexchange.com/questions/4623",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/8457/"
] | Well, if you're having friends over for dinner, you're probably willing to put in some extra effort anyway. That may sounds like throwaway advice, but it's not meant that way: for instance when my vegetarian friends come over, I make sure to have vegetarian food (duh), or I go buffet-style: as longs as there are enough vegetarian dishes, not all of them need to be that way.
The same thing (buffet) could work for multiple allergies.
Some times, however, sure, you're tired, rushed, or you just don't want to 'rise to the occasion'. I get that. Apparently there are commercial products out there that may help you ([one such example offering](http://www.intolerablefood.com/products.html)), and amazon has a TON of cookbooks on this issue as well. ([One example](http://rads.stackoverflow.com/amzn/click/0722540272), and [one more](http://rads.stackoverflow.com/amzn/click/0595515266)) (Also note the 'Customers Who Bought This Item Also Bought' section).
Good luck! | I'd begin by coming up with a couple of dishes for each course that are allergen-free, as this dietary requirement affects the health and well-being of the people. Once you are certain that there are no ingredients that are harmful to health, take the next step regarding omitting other offending ingredients. I think this method would make it easier and clearer for you and will cover two meals to start off with. If you can, always use unprocessed ingredients, if you can't, then check each ingredient list for allergens first, then other problem items. Keep documents for each recipe and a list of foodstuffs that comply with your requirements. You could complicate the matter here and have recipes and food lists in sections for the different dietary requirements for when you want more choice and you only have guests with one special dietary requirement. As another poster mentioned, be aware of cross-contamination of residues. |
24,414,315 | I am using the FOSUserBundle to register users. The errors are appearing in an odd place though.
They are appearing within the Password field row, not the username or email

As you can see the errors are rendered next to Password and not Username nor Email. The HTML shows that the errors are within the Password row and not just at the bottom of the Username row.
Why is this?
I have used `fields.html.twig` and added this;
```
{% block form_row %}
{% spaceless %}
<div class="form-group">
{{ form_errors(form) }}
{{ form_label(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
```
This works but the errors are all appearing within the password `form-group` div.
The view file looks like this within `Resources/views/Registration/register_content.html.twig`
```
<form role="form" action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="form-horizontal fos_user_registration_register">
{{ form_widget(form) }}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-info" value="{{ 'registration.submit'|trans }}" />
</div>
</div>
</form>
```
How can I move them into their respective divs or move them to the start of the form?
I also have this validation.yml file, which might be note worthy
```
FOS\UserBundle\Model\User:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: {fields: username, message: "This username is taken" }
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: {fields: email, message: "This email is taken" }
``` | 2014/06/25 | [
"https://Stackoverflow.com/questions/24414315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/119737/"
] | Assuming (since you won't show it) that `{word}` is expanded to `hello there`, your code becomes:
```
var hello there = 'hello there';
if(
hello there == 'hellothere' ||
hello there == 'hello there' ||
hello there == 'hello-there'
){
document.write('blah blah');
}
else {
document.write('');
}
```
As several of the commenters have pointed out, variables can't have spaces in their names.
Why do you need to name the variable after its contents? This version would work fine:
```
var myword = '{word}';
if(
myword == 'hellothere' ||
myword == 'hello there' ||
myword == 'hello-there'
){
```
You could then rewrite your `if` to take spaces and dashes into account:
```
if (myword.match(/^hello[ \-]*there$/i)) {
``` | I think you're looking for
```
if ({word}.replace(/-| /g, "") == 'hellothere') { … }
```
(despite the obvious syntax issue). It just removes all hyphens and spaces from the `{word}` before comparing it. If you want to make it case-insensitive, add `.toLowerCase()`. |
5,994,040 | Sup guys !
I'm currently have some problems about the synchronization with JavaScript. It's about a refresh. When it reach 10 second i refresh an array.
```
var curD = new Date();
if((curD.getTime() / 1000) - dMList[i].startTime > dMList[i].refreshTime)
{
dMList[i].elem = new Array();
RSSDropMenuConstructor(dMList[i]);
dMList[i].startTime = curD.getTime() / 1000;
}
sendResponse({ getdropMenuFields: dMList[i] }); // Send the appropiate dropMenu
```
Function RSS
```
function RSSDropMenuConstructor(dMObject)
{
jQuery.getFeed({
url: dMObject.rssLink,
success: function(feed) {
for(var i = 0; i < feed.items.length && i < dMObject.maxItem; i++) {
var item = feed.items[i];
field = new Object();
field.name = 'text';
field.value = item.title;
dMObject.elem.push(field);
field = new Object();
field.name = 'weblink';
field.value = item.link;
dMObject.elem.push(field);
field = new Object();
field.name = 'icon';
field.value = 'http://mediacdn.disqus.com/1305270873/images/embed/bullet-feed.png';
dMObject.elem.push(field);
}
dMList.push(dMObject);
}
});
```
So the RSSDropMenuConstructor will construct the dMList[i].elem, but the problem is that then "SendReponse" don't wait the end of the function.
So what it happend, when it refresh i received an empty array because the array is not yet initialized... Somebody have an idea how i can synchronize this ? | 2011/05/13 | [
"https://Stackoverflow.com/questions/5994040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/632950/"
] | You need to wait for the feed to come back from the server before calling sendResponse(). Place the call to sendResponse() in the callback function (that is, function(feed){...}).
Because AJAX is asynchronous, Javascript will continue to execute your code, even while a request to the server is pending. The callback, on the other hand, does not execute until the server responds. | Put the sendReponse() function inside the if statement. That way it will execute when the rest of the code inside that block is executing. |
2,800,013 | I'm learning math.
I've recently thought more about the proof by contradiction technique, and I have a question that I would like cleared up. Let me set the stage.
Suppose I am trying to prove a theorem.
Theorem: If A and $\neg$B, then $\neg$C.
Proof (contradiction): Let us suppose that A is true and $\neg$B is true. Let us assume that C is true ($\neg$C is false).
[blah blah blah]
From this, we arrive at a contradiction because we see that B is true ($\neg$B is false), but we know that $\neg$B is true (because we assumed it to be true). Thus, since assuming that C is true lead us to a contradiction, it must be the case that C is false ($\neg$C is true). QED.
**My issue with this**: why is it that C leading to a contradiction must mean that $\neg$C is true? What if $\neg$C also leads to a contradiction? In that case, doesn't a proof by contradiction not prove anything? *Why can we be sure that C leading to a contradiction must mean that $\neg$C doesn't lead to a contradiction?*
I'm sorry if this question has already been asked. I searched for a bit before asking to see if anyone had this same specific question, but most results just asked why a proof by contradiction works in general without any clear question. | 2018/05/29 | [
"https://math.stackexchange.com/questions/2800013",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/565705/"
] | Similar to what Wofsey commented, a statement must be either true or false. You might wonder what happens if we have conflicting axioms. That is, what if we assume A and not A? It turns out that you can then prove any statement with these assumptions. | If assuming that C is true leads to a contradiction, and assuming that C is false also leads to a contradiction, then the universe collapses in on itself and time comes to an end.
Seriously, either you have made an error in your proofs, or your axioms are mutually contradictory.
Do you actually have an example of this? It should be impossible. And asking, "What would happen if this impossible hypothetical situation actually happened?" is generally non-productive. It's like asking, "What if someone could prove that 2+2=5?" Well, in that case I guess a lot of mathematics would turn out to be a giant mistake. |
457,026 | I was wondering that the density of electric field lines determine the strength of the electric field .Now let's say you have an isolated charge ; you know the flux through a closed surface which I take to be a unit sphere suddenly limited by the Gauss law. If the flux is limited then it's bound to be the field lines should be also Limited as if its Infinite if then you know that $\int \int E.ds$ is infinite and the flux becomes infinite as well. Given that the electric field lines are not infinite and they indicate where a unit point charge goes if kept at that point now it create some empty spaces where there are no field lines; so does it suggest that if I put a point charge in those empty spaces for there are no field lines that it would not interact with the field or feel a force outward or inward depending on the charge? Please show that where am I misunderstanding? | 2019/01/27 | [
"https://physics.stackexchange.com/questions/457026",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/187604/"
] | ***I was wondering that the density of electric field lines determine the strength of the electric field***
First we need to realize that electric field lines are used to visualize and analyze electric fields and therefore should be considered as a pictorial tool as opposed to a physical entity. For example, one cannot think of the space between the field lines in the picture, which gets larger and larger the further away we go from the point charge producing the field, to be “devoid” of an electric field.
***Now let's say you have an isolated charge ; you know the flux through a closed surface which I take to be a unit sphere suddenly limited by the Gauss law.***
Not quite sure what you mean here, but the total flux is the same for any spherical closed surface surrounding the charge, no mater how large the sphere. Since the flux is the product of field strength and area perpendicular to the field, as the surface area increases with increasing radius, the electric field strength decreases proportionally so that ExA is a constant.
***If the flux is limited then it's bound to be the field lines should be also Limited as if its Infinite if then you know that the double integral of E.dS is infinite and the flux becomes infinite as well.***
As said previously, pictorially the number of field lines is the same, but their density decreases with increasing area, so that the total flux bounded by any sized closed surface remains the same.
***Given that the electric field lines are not infinite and they indicate where a unit point charge goes if kept at that point now it create some empty spaces where there are no field lines; so does it suggest that if I put a point charge in those empty spaces for there are no field lines that it would not interact with the field or feel a force outward or inward depending on the charge? Please show that where am I misunderstanding?***
As previously said, field lines are a pictorial tool. You cannot think of the space between lines as having no field. A charge placed anywhere will experience the field, albeit weakly the further out you go. Instead of thinking of individual, discrete field lines, think of the electric field as a continuum or smear of field lines each line getting thinner and thinner to represent lessening strength. This would be much harder to show in a picture, thus we use the discrete field lines representation.
Hope this helps. | It is **not** true that if $E \rightarrow \infty$ then it should be the case that $\Phi\_E \rightarrow \infty$.
Notice that in your example, the surface area of your sphere tends to zero $A \rightarrow 0$ as the sphere gets smaller. Since you're computing $\Phi\_E = EA$, you're trying to multiply a quantity that tends to infinity by a quantity that vanishes. It turns out that $E$ grows exactly in a way to cancel out $A$ shrinking and the product $EA$ remains at a constant value of $q / \epsilon\_0$.
If you're not convined that the product $EA$ could feasibly remain constant, consider the functions $f(x) = 1/x$ and $g(x) = x$. As $x \rightarrow 0$, we have $f \rightarrow \infty$ and $g \rightarrow 0$. However, if we consider their product $f(x) g(x)$, you'll probably agree that it remains at a constant value, even as $x \rightarrow 0$. |
50,180,241 | I am trying to connect to an AWS RDS MySQL instance from Google Dataflow. I created a java program to create the pipeline. The job creates successfully but the MySQL connection always fails with the following error:
```
java.lang.RuntimeException: org.apache.beam.sdk.util.UserCodeException: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.google.cloud.dataflow.worker.MapTaskExecutorFactory$3.typedApply(MapTaskExecutorFactory.java:338)
at com.google.cloud.dataflow.worker.MapTaskExecutorFactory$3.typedApply(MapTaskExecutorFactory.java:308)
at com.google.cloud.dataflow.worker.graph.Networks$TypeSafeNodeFunction.apply(Networks.java:63)
at com.google.cloud.dataflow.worker.graph.Networks$TypeSafeNodeFunction.apply(Networks.java:50)
at com.google.cloud.dataflow.worker.graph.Networks.replaceDirectedNetworkNodes(Networks.java:87)
at com.google.cloud.dataflow.worker.MapTaskExecutorFactory.create(MapTaskExecutorFactory.java:154)
at com.google.cloud.dataflow.worker.DataflowWorker.doWork(DataflowWorker.java:308)
at com.google.cloud.dataflow.worker.DataflowWorker.getAndPerformWork(DataflowWorker.java:264)
at com.google.cloud.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork(DataflowBatchWorkerHarness.java:133)
at com.google.cloud.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:113)
at com.google.cloud.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:100)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.beam.sdk.util.UserCodeException: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at org.apache.beam.sdk.util.UserCodeException.wrap(UserCodeException.java:36)
at org.apache.beam.sdk.io.jdbc.JdbcIO$ReadFn$DoFnInvoker.invokeSetup(Unknown Source)
at com.google.cloud.dataflow.worker.DoFnInstanceManagers$ConcurrentQueueInstanceManager.deserializeCopy(DoFnInstanceManagers.java:63)
at com.google.cloud.dataflow.worker.DoFnInstanceManagers$ConcurrentQueueInstanceManager.peek(DoFnInstanceManagers.java:45)
at com.google.cloud.dataflow.worker.UserParDoFnFactory.create(UserParDoFnFactory.java:94)
at com.google.cloud.dataflow.worker.DefaultParDoFnFactory.create(DefaultParDoFnFactory.java:74)
at com.google.cloud.dataflow.worker.MapTaskExecutorFactory.createParDoOperation(MapTaskExecutorFactory.java:415)
at com.google.cloud.dataflow.worker.MapTaskExecutorFactory$3.typedApply(MapTaskExecutorFactory.java:326)
... 14 more
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException:
Communications link failure
Caused by: java.net.SocketTimeoutException: connect timed out
```
The JAVA source code is below:
```
public class MySQLToBQ {
public static void main(String[] args) throws Exception {
DataflowPipelineOptions options = PipelineOptionsFactory.as(DataflowPipelineOptions.class);
options.setProject("project_name");
options.setStagingLocation("gs://staging");
options.setTempLocation("gs://temp");
options.setRunner(DataflowRunner.class);
options.setJobName("MySQL-To-BQ-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()));
System.out.println("Job Name " + options.getJobName());
Pipeline p = Pipeline.create(options);
DataSourceConfiguration mysqlConfig = JdbcIO.DataSourceConfiguration.create(
"com.mysql.cj.jdbc.Driver", "jdbc:mysql://mysql_host:3306/mysql_database")
.withUsername("user")
.withPassword("password");
p.apply("mysql_source", JdbcIO.<SourceRow>read()
.withDataSourceConfiguration(mysqlConfig)
.withQuery("query")
.withCoder(SerializableCoder.of(SourceRow.class))
.withRowMapper(new JdbcIO.RowMapper<SourceRow>() {
@Override
public SourceRow mapRow(ResultSet resultSet) throws Exception {
SourceRow datarow = new SourceRow();
ResultSetMetaData rsmd = resultSet.getMetaData();
for(int i = 1; i <= rsmd.getColumnCount(); i++) {
datarow.add(rsmd.getColumnName(i), resultSet.getString(i));
}
return datarow;
}
}
)
)
.apply(table + "_transform", ParDo.of(new TransformToTableRow()))
.apply(table + "_destination", BigQueryIO.writeTableRows()
.to("table_name")
.withSchema(getSchema())
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)
);
p.run();
}
}
```
I was able to create a Compute Engine VM instance and successfully connect to the MySQL database from there. | 2018/05/04 | [
"https://Stackoverflow.com/questions/50180241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9742590/"
] | ```
> number <- 1059
> x <- strsplit(as.character(number), "")[[1]]
> y <- seq_len(nchar(number))
> as.numeric(as.numeric(x) %*% y)
[1] 52
``` | ```
weighted.digit <- function(str) {
splitted.nums <- as.numeric(strsplit(str, '')[[1]])
return(sum(splitted.nums * 1:length(splitted.nums)))
}
weighted.digit('1059')
[1] 52
```
One could modify this to accept a numeric input, and then simply convert that to character as a first step. |
34,428,972 | So I created my first label without story board today and I am wondering how to change the text of the label when I click a button. The action for the button works just fine. I did create an outlet for the label so I could refer to it out of the method I initially called it in but when I click the button the app crashes.
Here is my code:
```
import UIKit
import Foundation
class ThirdViewController: UIViewController {
@IBOutlet weak var label1: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addBackground()
//label one
var label1 = UILabel(frame: CGRectMake(0, 0, view.bounds.width - 80, 30))
label1.center = CGPointMake(view.bounds.width/2, 20)
label1.textAlignment = NSTextAlignment.Center
label1.text = "Pick the largest number"
label1.font = UIFont(name: font, size: 25)
self.view.addSubview(label1)
//number one
var num1 = UIButton(frame: CGRectMake(0, 0, 100, 100))
num1.center = CGPointMake(view.bounds.width/4, view.bounds.height/4)
num1.setTitle("37", forState: UIControlState.Normal)
num1.addTarget(self, action: "num1Tapped", forControlEvents: UIControlEvents.TouchUpInside)
num1.titleLabel!.font = UIFont(name: font, size: 70)
self.view.addSubview(num1)
}
func num1Tapped(UIButton!){
label1.text = "test"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
``` | 2015/12/23 | [
"https://Stackoverflow.com/questions/34428972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5709705/"
] | Dave's answer is pretty good. Look there for an explanation.
If you are still having trouble I'll simplify it.
**Case 1:**
```
if(a && b || c || d || e)
```
In this case you can simplify it by saying `z = a && b`
This means that the expression becomes
```
if(z || c || d || e)
```
This is the same as the expression above. `z` is only true if `a` and `b` are true.
**Case 2:**
```
((a && b) || a && c || a && d || a && e))
```
As Arc676 commented, you can simplify it as
```
a && (b || c || d || e)
```
Here you can use the same technique as in case 1 to further simplify it.
If you take `y = b || c || d || e`. Meaning `y` is true if any of `b`, `c`, `d` or `e` are true. Then you can simplify the expression as
```
a && y
```
I'm not saying you should always simplify this but using this technique can make long boolean statements more readable. | `if(a && b || c || d || e)` stands for:
If `a` is `true` and `b` or `c` or `d` or `e` is true then it will go `inside`. That's it.
So, if `a` is `true` and at least any rest other variables(`b` or `c` or `d` or `e`) then it will go inside. Otherwise it won't. |
36,208,630 | I use some of Xcode's source control features, specifically the blame feature in the main editor, but use git on the command line for all of my actual version control. This means that, fairly often, git commands on the command line fail with the message:
```
fatal: Unable to create '/path/to/repo/.git/index.lock': File exists.
```
Xcode is creating this file to lock the repo as it runs its own git commands. I've already turned off all the unnecessary source control options in Preferences (Refresh local status automatically, Refresh server status automatically, and Add and remove files automatically.)
My current strategy is just to retry the command until it works, which rarely takes more than one attempt.
Is there a way to make Xcode any less aggressive with how often it creates `index.lock`?
Or, is there a way I can make git automatically retry commands until they succeed if they fail in this way? | 2016/03/24 | [
"https://Stackoverflow.com/questions/36208630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378418/"
] | Here's my hacky patchy for this: a few lines of bash which waits till the lock file disappears and then runs your git commands. Race conditions are certainly possible, this isn't bullet proof but would work *most of the time*.
```
function retry {
while [ 1 == 1 ]; do
if test -f /path/to/repo/.git/index.lock; then
echo -n ".";
sleep 0.5;
else
"$@";
return;
fi
done
}
```
You could throw this into your ~/.bashrc for example then to use it:
```
retry git commit -m "ohhh yeaaaa"
```
Cheers! | I used to use Xcode's git client, and it was consistently causing errors including this one, so I've stopped using Xcode to setup my workspaces or make commits. To enable this setup, I installed the git support from the Command Line Tools for Xcode X.x, and refer to an external git GUI for any commands that result in a change to my local or remote copy, including switching branches.
**Since I've started using an external client, I've had no problems with an index.lock file.** When performing rare operations, like resetting a remote branch, or renaming a branch, I use the terminal. There are a few high-quality git clients out there that are free, including SourceTree.
If you want to use an external git client with a new project in Xcode, simply do not opt-in to the git workspace option, if it is displayed. Instead, use your external git client to 'Add' an additional git workspace, and choose the root directory of the Xcode project.
As a side note, when I do this, I usually have a root directory for a lot of related miscellaneous files, and that is also the home of my Xcode project directory which is the root of my git workspace. This allows me to have notes, and other files that I don't want to be version-controlled.
Here's a typical setup:
```
+ Project Directory
---+ Xcode project directory (git root)
---- Other project files (not under source control)
```
Hope that helps! |
39,016,923 | I am trying to benchmark CPU calculation power with a simple function, without adding huge frameworks with thousands of lines and some MB's to my project.
I developed this sample code. It is a for wich does 100 times a huge task. This huge task (benchmark() function) consists in a while which will do a math complex calc and increasing a counter in a period of 100ms. Each 100ms it is printed in log the number of times that the benchmark() function has completed the complex math calculation.
OK, so, I have 100 times printed on screen that calculation.
The first times I execute the benchmark I get correct results, more or less the same log results for each one of the 100 iterations of the benchmark:
```
08-18 13:09:52.806 26543-27748/com.mytestapp D/XXXX: Iteration: 0 Result: 118200
08-18 13:09:52.906 26543-27748/com.mytestapp D/XXXX: Iteration: 1 Result: 171580
08-18 13:09:53.006 26543-27748/com.mytestapp D/XXXX: Iteration: 2 Result: 170654
08-18 13:09:53.106 26543-27748/com.mytestapp D/XXXX: Iteration: 3 Result: 168676
08-18 13:09:53.206 26543-27748/com.mytestapp D/XXXX: Iteration: 4 Result: 168372
08-18 13:09:53.306 26543-27748/com.mytestapp D/XXXX: Iteration: 5 Result: 165558
08-18 13:09:53.406 26543-27748/com.mytestapp D/XXXX: Iteration: 6 Result: 171368
08-18 13:09:53.506 26543-27748/com.mytestapp D/XXXX: Iteration: 7 Result: 171680
08-18 13:09:53.606 26543-27748/com.mytestapp D/XXXX: Iteration: 8 Result: 171516
08-18 13:09:53.706 26543-27748/com.mytestapp D/XXXX: Iteration: 9 Result: 171598
```
But after some executions the number starts decreasing, and I dont understand why:
```
08-18 13:10:20.850 26543-28161/com.mytestapp D/XXXX: Iteration: 1 Result: 94320
08-18 13:10:20.951 26543-28161/com.mytestapp D/XXXX: Iteration: 2 Result: 90364
08-18 13:10:21.051 26543-28161/com.mytestapp D/XXXX: Iteration: 3 Result: 94240
08-18 13:10:21.152 26543-28161/com.mytestapp D/XXXX: Iteration: 4 Result: 93676
08-18 13:10:21.252 26543-28161/com.mytestapp D/XXXX: Iteration: 5 Result: 91554
08-18 13:10:21.352 26543-28161/com.mytestapp D/XXXX: Iteration: 6 Result: 94358
08-18 13:10:21.452 26543-28161/com.mytestapp D/XXXX: Iteration: 7 Result: 90954
08-18 13:10:21.552 26543-28161/com.mytestapp D/XXXX: Iteration: 8 Result: 94874
08-18 13:10:21.652 26543-28161/com.mytestapp D/XXXX: Iteration: 9 Result: 94464
```
If i wait some minutes and try again, the results increases again to its normal values.
Why this behaviour? How to avoid it and get always correct benchmark results?
This is my sample code:
```
public void benchmarkIterator(){
int result = 0;
int iterations = 100;
for (int i=0; i<iterations; i++){
result = benchmark();
Log.d("XXXX", "Iteration: "+i+" Result: "+result);
}
}
```
....
```
public int benchmark(){
long startTime = System.currentTimeMillis();
int count=0;
double aux=0;
while((System.currentTimeMillis()-startTime)<100){
count++;
double d = 7777777777d;
aux = 0;
aux=aux+(int)(aux+Math.sin(d)*Math.cos(d));
}
return count;
}
``` | 2016/08/18 | [
"https://Stackoverflow.com/questions/39016923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479886/"
] | Overheating? No. I doubt that this calculation can make your CPU break a sweat.
I think the change over time has to do with the JVM and statistics. The HotSpot compiler uses them to optimize code branching based on what your code is doing.
<http://blog.takipi.com/jvm-performance-magic-tricks/>
<https://wiki.openjdk.java.net/display/HotSpot/PerformanceTechniques>
The only way you can know what's happening is to use a profiler. You need to look at garbage collection, memory, and where the time is being spent. Your simple benchmark won't give you that kind of insight. | If I understand correctly, the two log snippet are for different execution made with different JVM launches?
In this case, the difference between the two cannot be caused by the JVM (as it has been restarted).
So, the difference can be caused by a lot of stuff: OS file cache (there is already some file stuff going on), CPU power management (CPU frequency going down when not in used can take some times to go back to it's max frequency), something else running on the host (if it's a VM ... a lot of stuff can going on), CPU optimization (like branch prediction of prefetching), ...
Anyway, you don't have an issue, it's just the way computer/jvm/cpu works these days ... |
15,300 | My cat has a problem with eating houseplants.
He ate an entire succulent over a month time period while I was at work even with lemons near or aluminum foil on the windowsill.
I was thinking about going the pet grass option but he has another problem. He also likes to knock over plants and scatter the dirt around.
I had a small cactus with a red bulb on the end and he batted it around until I lost it (it is somewhere in or around my living room furniture) and spilled the dirt everywhere.
He also knocked over my other succulent (I had a nice desert plant arrangement too).
I believe this will be a problem when I go the pet grass route.
My question is, how would I keep him from playing with the pet grass dirt and spreading the dirt around my apartment? | 2016/09/16 | [
"https://pets.stackexchange.com/questions/15300",
"https://pets.stackexchange.com",
"https://pets.stackexchange.com/users/6901/"
] | I think it is important to offer cat grass (in austria it is even mentioned in the law as minimum requirement for having a cat indoors). I feel like my cats are a lot less interested in my plants since they have cat grass (that they got calmer after turning 3 helped as well). I placed it somewhere high where they can sit comfortable and placed my other plants somewhere high where it is uncomfortable for them.
Big stones in the pots on the earth were already mentioned.
If you use big pots then they cannot knock it over.
Maybe you have the opportunity to span a net over the most parts of the earth.
If your cat is bored it might help to offer different activities which can distract him from the plants. For example a box filled with crumpled papers or a rail cat toy. | The easiest, safest and best way is simple; don't let them get near it.
You can't teach a cat not to do something, you can only teach them to not do something while you are nearby.
Small example, our cats never walk on the dinner table when we are home, but if we happen to be outside in the garden or come home when they don't expect it, we might find them sitting or walking on the table.
As for plants, years of personal experience has taught me that plants and cats inside do not mix.
Cats like to chew on plants and they will continue to do this. Cats also love to play with small moving objects (bugs) and there will be small tiny bugs on/in your plant eventually that will draw their attention.
Either place the plants where they cannot reach them or put large pointy stones in the pot. This might help prevent them from scratching out the dirt everywhere.
Keyword is "Might". |
23,281,399 | Hi I am trying to find the depth of the binary tree. I was trying a different method than the conventional way to do it. My logic is trying to find max of the levels while doing a depth traversal. Following is the code. This approach is not working as the max value is always zero once it reaches the else part. I am not understanding why.
```
public class BinaryTree {
public static void main(String args[])
{
Node root = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
Node six = new Node(6);
Node seven = new Node(7);
Node eight = new Node(8);
root.left = two;
root.right = three;
two.left = four;
two.right = five;
three.left = six;
three.right = seven;
five.left = eight;
findDepth(root,0,0);
}
public static void findDepth(Node root,int level, int max)
{
if(root==null)
return ;
else{
if(root.left==null && root.right==null)
{
if(max<level)
{
max=level;
}
level=level-1;
}
findDepth(root.left,level+1,max);
findDepth(root.right,level+1,max);
}
}
}
// The Node class
public class Node {
int data;
Node left;
Node right;
public Node(int i) {
this.data = i;
}
}
```
I did this and it worked perfectly
```
public static int findDepth(Node root,int level, int max1, String str)
{
if(root==null)
return 0;
if(max<level)
{
max=level;
}
findDepth(root.left,level+1,max,"left");
findDepth(root.right,level+1,max,"right");
return max;
}
```
Here max is static member of the class. But i want to point out to another article in stack overflow where they said the value will propagate down to the next recursive call.
[Print all paths from root to leaf in a Binary tree](https://stackoverflow.com/questions/18854264/print-all-paths-from-root-to-leaf-in-a-binary-tree)
Here the old value of list is getting propagated to all recursive calls | 2014/04/24 | [
"https://Stackoverflow.com/questions/23281399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246489/"
] | Your analysis is correct. Unrelated `JOIN` create cartesian products.
You have to do the sums separately and then do a final addition. This is doable in one query and you have several options for that:
* Sub-requests in your SELECT: `SELECT a.id, (SELECT SUM(b.debit) FROM b WHERE b.a_id = a.id) + ...`
* `CROSS APPLY` with a similar query as the first bullet then `SELECT a.id, b_sum + c_sum + d_sum`
* `UNION ALL` as you suggested with an outer `SUM` and `GROUP BY` on top of that.
* `LEFT JOIN` to similar subqueries as above.
And probably more... The performance of the various solutions might be slightly different depending on how many rows in `A` you want to select. | Can also be done with correlated subqueries:
```
SELECT a.id
, (SELECT SUM(debit) FROM b WHERE a.id = b.a_id)
, (SELECT SUM(credit) FROM c WHERE a.id = c.a_id)
, (SELECT SUM(other) FROM d WHERE a.id = d.a_id)
FROM a
``` |
37,100,825 | I'm looking to escape some character `(` and `)`, their respective escape codes are `(40)` and `(41)`.
```
echo 'Hello (world)' | sed 's/(/(40)/g;s/)/(41)/g'
```
This code fails with `Hello (40(41)world(41)` because it will also process the output from the first replacement. Is there any way I can skip the replacement characters or do conditional branches here. I don't want to use a temporary (as the input sequence could contain anything). | 2016/05/08 | [
"https://Stackoverflow.com/questions/37100825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2108150/"
] | All you need is:
```
$ echo 'Hello (world)' | sed 's/(/(40\n/g; s/)/(41)/g; s/\n/)/g'
Hello (40)world(41)
```
The above is safe because `\n` can't be present in the input since sed reads one line at a time. With some seds you might need to use a backslash followed by a literal newline or `$'\n'` instead of just `\n`.
Given [the answer you posted](https://stackoverflow.com/a/37103168/1745001), though, this may be what you really want (uses GNU awk for [ord()](http://www.gnu.org/software/gawk/manual/gawk.html#Extension-Sample-Ord), multi-char `RS`, and `RT`):
```
$ cat tst.awk
@load "ordchr"
BEGIN { RS = "[][(){}]"; ORS="" }
{ print $0 ( RT=="" ? "" : "(" ord(RT) ")" ) }
$ echo 'Hello (world) foo [bar] other {stuff} etc.' | awk -f tst.awk
Hello (40)world(41) foo (91)bar(93) other (123)stuff(125) etc.
```
If you have an older gawk that doesn't support `@load` than get a new one but if that's impossible for some reason then just create an array of the values, e.g.:
```
$ cat tst.awk
BEGIN {
RS = "[][(){}]"
ORS = ""
for (i=0;i<=255;i++) {
char = sprintf("%c",i)
map[char] = "(" i ")"
}
}
{ print $0 ( RT=="" ? "" : map[RT] ) }
$ echo 'Hello (world) foo [bar] other {stuff} etc.' | awk -f tst.awk
Hello (40)world(41) foo (91)bar(93) other (123)stuff(125) etc.
```
**EDIT: timing data**
Given a file that has these 10 lines:
```
$ head -10 file1m
When (chapman) billies leave [the] street, And drouthy {neibors}, neibors, meet;
As market days are wearing late, And folk begin to [tak] the gate,
While (we) sit bousing {at} the nappy, An' getting [fou] and unco happy,
We think na on the [lang] Scots (miles), The mosses, {waters}, slaps and stiles,
That lie between us and our hame, Where sits our sulky, sullen dame,
Gathering her [brows] like gathering storm, (Nursing) her wrath to keep it warm.
This truth fand honest Tam o' Shanter,
As he frae Ayr ae night did canter:
(Auld Ayr, wham ne'er a town surpasses,
For honest men and bonie lasses).
```
repeating to a total of 1 million lines, 10.5 million characters, 60.4 million bytes:
```
$ wc file1m
1000000 10500000 60400000 file1m
```
the 3rd-run timing stats for the sed script and both awk scripts above are:
```
$ time sed 's/(/(40\n/g; s/)/(41)/g; s/\n/)/g; s/\[/(91)/g; s/\]/(93)/g; s/{/(123)/g; s/}/(125)/g;' file1m > sed.out
real 0m7.488s
user 0m7.378s
sys 0m0.093s
$ cat function.awk
@load "ordchr"
BEGIN { RS = "[][(){}]"; ORS="" }
{ print $0 ( RT=="" ? "" : "(" ord(RT) ")" ) }
$ time awk -f function.awk file1m > awk_function.out
real 0m7.426s
user 0m7.269s
sys 0m0.155s
$ cat array.awk
BEGIN {
RS = "[][(){}]"
ORS = ""
for (i=0;i<=255;i++) {
char = sprintf("%c",i)
map[char] = "(" i ")"
}
}
{ print $0 ( RT=="" ? "" : map[RT] ) }
$ time awk -f array.awk file1m > awk_array.out
real 0m4.758s
user 0m4.648s
sys 0m0.092s
```
I verified that all 3 scripts produce the same, successfully modified output:
```
$ head -10 sed.out
When (40)chapman(41) billies leave (91)the(93) street, And drouthy (123)neibors(125), neibors, meet;
As market days are wearing late, And folk begin to (91)tak(93) the gate,
While (40)we(41) sit bousing (123)at(125) the nappy, An' getting (91)fou(93) and unco happy,
We think na on the (91)lang(93) Scots (40)miles(41), The mosses, (123)waters(125), slaps and stiles,
That lie between us and our hame, Where sits our sulky, sullen dame,
Gathering her (91)brows(93) like gathering storm, (40)Nursing(41) her wrath to keep it warm.
This truth fand honest Tam o' Shanter,
As he frae Ayr ae night did canter:
(40)Auld Ayr, wham ne'er a town surpasses,
For honest men and bonie lasses(41).
$ wc sed.out
1000000 10500000 68800000 sed.out
$ diff sed.out awk_function.out
$ diff sed.out awk_array.out
$
``` | The problem is solved by creating an ord function in awk. It doesn't appear sed has this functionality.
```
#! /bin/sh
awk '
BEGIN { _ord_init() }
function _ord_init(low, high, i, t) {
low = sprintf("%c", 7) # BEL is ascii 7
if (low == "\a") {
low = 0;
high = 127;
} else if (sprintf("%c", 128 + 7) == "\a") {
low = 128;
high = 255;
} else {
low = 0;
high = 255;
}
for (i = low; i <= high; i++) {
t = sprintf("%c", i);
_ord_[t] = i;
}
}
function ord(str, c) {
c = substr(str, 1, 1)
return _ord_[c]
}
// {
split($0, array, "\\[|\\]|\\(|\\)|\\{|\\}", separators);
len = length(array);
seplen = length(separators);
for (i = 1; i < len; ++i) {
printf "%s(%s)", array[i], ord(separators[i]);
}
printf "%s", array[len];
}
'
``` |
624,354 | I want to rescale this table because I want it to fit in one page but for some reason it won't and it gives me errors. I tried using `\scalebox{0.5}` that I used for another table but it doesn't work.
```
\begin{table}[h]
\centering
\caption{Panel A}
\begin{tabular}{l*{2}{c}}
\hline\hline
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}\\
\hline
Highest schooling attained& -0.00577 & -0.00835 \\
& (0.0109) & (0.0108) \\
Husband's highest schooling attained (reported by wife)& 0.0151 & 0.0167 \\
& (0.0145) & (0.0145) \\
Ideal number of children& 0.00757 & 0.00803 \\
& (0.0292) & (0.0292) \\
Age & 0.00192 & 0.00132 \\
& (0.0110) & (0.0110) \\
Husband's age (reported by wife)& 0.00393 & 0.00467 \\
& (0.0120) & (0.0120) \\
Husband's ideal number of children (reported by wife)& -0.0225 & -0.0220 \\
& (0.0203) & (0.0203) \\
Has ever used a modern contraceptive method& -0.0181 & 0.00141 \\
& (0.102) & (0.101) \\
Wife has monthly income& -0.0735 & -0.0748 \\
& (0.129) & (0.129) \\
Wife knows when she is most fertile& 0.0917 & 0.0965 \\
& (0.0817) & (0.0816) \\
Wife wants to become pregnant in following 2 years& 0.00457 & -0.00293 \\
& (0.0664) & (0.0657) \\
Age wife married& 0.00758 & 0.00787 \\
& (0.00948) & (0.00947) \\
Catholic & -0.00748 & -0.00580 \\
& (0.0658) & (0.0657) \\
Comparison of happiness with other women in region\\(1=very unhappy, 5=very happy)& 0.00915 & 0.0119 \\
& (0.0353) & (0.0352) \\
Comparison of health with other women in region\\(1=very poor, 5=excellent)& 0.00229 & -0.00611 \\
& (0.0406) & (0.0403) \\
Number of years respondent lived in Lusaka& 0.000733 & 0.000546 \\
& (0.00256) & (0.00255) \\
Couple has electricity& 0.00826 & 0.00748 \\
& (0.0574) & (0.0569) \\
Formally married& 0.0388 & 0.0233 \\
& (0.0930) & (0.0916) \\
Number of days in past 7 days couple has sex& 0.0194 & 0.0174 \\
& (0.0256) & (0.0256) \\
Number of days in past month couple has sex& -0.00292 & -0.00287 \\
& (0.00786) & (0.00785) \\
Number of children husband has with other women& -0.00612 & -0.000674 \\
& (0.0676) & (0.0674) \\
Frequency at which couple has talked about contraception in last year& 0.0137 & 0.0112 \\
& (0.0267) & (0.0266) \\
Couple has ever disagreed on number of children& 0.0559 & 0.0559 \\
& (0.0824) & (0.0824) \\
Couple has ever disagreed on contraception use& -0.0699 & -0.0682 \\
& (0.0909) & (0.0908) \\
Have used contraceptive method without husband's knowledge& 0.00117 & -0.00202 \\
& (0.0875) & (0.0874) \\
Husband drinks at least 2 to 3 times a week& -0.00806 & -0.00576 \\
& (0.0553) & (0.0552) \\
f29 & -0.0802 & -0.0819 \\
& (0.0580) & (0.0579) \\
Wife ever pressured to have sex& 0.0549 & 0.0560 \\
& (0.0623) & (0.0621) \\
Husband does budgeting& 0.0193 & 0.0141 \\
& (0.0818) & (0.0817) \\
Husband decides major purchases& 0.0404 & 0.0421 \\
& (0.0632) & (0.0631) \\
cons & 0.286 & 0.303 \\
& (0.321) & (0.321) \\
\hline
\(N\) & 423 & 426 \\
\hline\hline
\multicolumn{2}{l}{\footnotesize Standard errors in parentheses}\\
\multicolumn{2}{l}{\footnotesize * \(p<0.05\), ** \(p<0.01\), *** \(p<0.001\)}\\
\end{tabular}
\end{table}
```
This is what I used for the other
```
\begin{table}[htbp]
\centering
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{Summary Statistics for Final Sample \label{tab:tab2}} \scalebox{0.5}{\begin{tabular}{l c*{6}{c}} \hline
&\multicolumn{3}{c}{Individual Treatment} &\multicolumn{2}{c}\\\cmidrule(lr){2-4}
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}\\
\toprule \multicolumn{6}{l}{\textbf{Panel B}} \\ \midrule
Using any method at baseline& -0.0613 & -0.0444 \\
& (0.0820) & (0.0810) \\
Number of living children& 0.0143 & 0.0133 \\
& (0.0276) & (0.0276) \\
Using injectable at baseline& -0.151 & -0.153 \\
& (0.384) & (0.384) \\
\hline\hline
\multicolumn{11}{l}{\footnotesize Standard errors in parentheses}\\
\multicolumn{11}{l}{\footnotesize \sym{*} \(p<0.05\), \sym{**} \(p<0.01\), \sym{***} \(p<0.001\)}\\
\end{tabular}}
\end{table}
``` | 2021/11/29 | [
"https://tex.stackexchange.com/questions/624354",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/239891/"
] | After half of year (I didn't notice this question before) ...
Your first table in its current format is too long to fit on a page. If you willing to write standard errors in separate columns and round number of decimals to (reasonable) three, than is possible to fit it on one page at using normal font size.
By use of the `tabularray` package with libraries `booktabs` and `siunitx` (which load packages of the same names) the MWE with your table can be as follows:
```
\documentclass{article}
\usepackage[margin=25mm]{geometry}
\usepackage{tabularray}
\UseTblrLibrary{siunitx,booktabs}
\ExplSyntaxOn
\NewChildSelector {eachfour}
{
\int_step_inline:nnnn {2} {4} { \l_tblr_childs_total_tl }
{ \clist_put_right:Nn \l_tblr_childs_clist {##1} }
}
\ExplSyntaxOff
\usepackage{lipsum}
\begin{document}
%\lipsum[55]
\begin{table}
\sisetup{
input-open-uncertainty={},
input-close-uncertainty={},
table-align-text-before=false,
table-align-text-after=false,
round-mode=places,
round-precision=3,
table-format={(}-1.3{)}
}
\begin{talltblr}[
caption = {Panel A},
label = {tab:???},
note{} = {Standard errors in parentheses:\newline
*: \(p<0.10\),\quad
**: \(p<0.05\),\quad
***: \(p<0.01\).
}
]{
colsep = 3pt,
colspec = { X[2.8,l,m, font=\linespread{0.84}\selectfont]
*{4}{X[0.8, c, si]}
},
row{1} = {font=\small\bfseries},
hline{eachfour} = {1-5}{0.2pt,dashed},
}
\toprule
&\SetCell[c=2]{c} {{{(1)}}}
& &\SetCell[c=2]{c} {{{(2)}}}
& \\
\cmidrule[r]{1-1}
\cmidrule[l]{2-3}
\cmidrule[l]{4-5}
Highest schooling attained
& -0.00577 & (0.0109) & -0.00835 & (0.0108) \\
Husband's highest schooling attained (reported by wife)
& 0.0151 & (0.0145) & 0.0167 & (0.0145) \\
Ideal number of children
& 0.00757 & (0.0292) & 0.00803 & (0.0292) \\
Age & 0.00192 & (0.0110) & 0.00132 & (0.0110) \\
Husband's age (reported by wife)
& 0.00393 & (0.0120) & 0.00467 & (0.0120) \\
Husband's ideal number of children (reported by wife)
& -0.0225 & (0.0203) & -0.0220 & (0.0203) \\
Has ever used a modern contraceptive method
& -0.0181 & (0.102) & 0.00141 & (0.101) \\
Wife has monthly income
& -0.0735 & (0.129) & -0.0748 & (0.129) \\
Wife knows when she is most fertile
& 0.0917 & (0.0817) & 0.0965 & (0.0816) \\
Wife wants to become pregnant in following 2 years
& 0.00457 & (0.0664) & -0.00293 & (0.0657) \\
Age wife married
& 0.00758 & (0.00948) & 0.00787 & (0.00947) \\
Catholic
& -0.00748 & (0.0658) & -0.00580 & (0.0657) \\
Comparison of happiness with other women in region (1=very unhappy, 5=very happy)
& 0.00915 & (0.0353) & 0.0119 & (0.0352) \\
Comparison of health with other women in region (1=very poor, 5=excellent)
& 0.00229 & (0.0406) & -0.00611 & (0.0403) \\
Number of years respondent lived in Lusaka
& 0.000733 & (0.00256) & 0.000546 & (0.00255) \\
Couple has electricity
& 0.00826 & (0.0574) & 0.00748 & (0.0569) \\
Formally married
& 0.0388 & (0.0930) & 0.0233 & (0.0916) \\
Number of days in past 7 days couple has sex
& 0.0194 & (0.0256) & 0.0174 & (0.0256) \\
Number of days in past month couple has sex
& -0.00292 & (0.00786) & -0.00287 & (0.00785) \\
Number of children husband has with other women
& -0.00612 & (0.0676) & -0.000674 & (0.0674) \\
Frequency at which couple has talked about contraception in last year
& 0.0137 & (0.0267) & 0.0112 & (0.0266) \\
Couple has ever disagreed on number of children
& 0.0559 & (0.0824) & 0.0559 & (0.0824) \\
Couple has ever disagreed on contraception use
& -0.0699 & (0.0909) & -0.0682 & (0.0908) \\
Have used contraceptive method without husband's knowledge
& 0.00117 & (0.0875) & -0.00202 & (0.0874) \\
Husband drinks at least 2 to 3 times a week
& -0.00806 & (0.0553) & -0.00576 & (0.0552) \\
f29 & -0.0802 & (0.0580) & -0.0819 & (0.0579) \\
Wife ever pressured to have sex
& 0.0549 & (0.0623) & 0.0560 & (0.0621) \\
Husband does budgeting
& 0.0193 & (0.0818) & 0.0141 & (0.0817) \\
Husband decides major purchases
& 0.0404 & (0.0632) & 0.0421 & (0.0631) \\
cons
& 0.286 & (0.321) & 0.303 & (0.321) \\
\midrule
\(N\)
& {423} & & {426} & \\
\bottomrule
\end{talltblr}
\end{table}
\end{document}
```
[](https://i.stack.imgur.com/Nmy8p.png)
Meanwhile the structure of the first table and its content is clear, the second table is unclear at all. Therefore the suggestion for it is based on guessing (and may be completely wrong). Anyway, given is skeleton in which can be (hopefuly) easy insert correct content:
```
\documentclass{article}
\usepackage[margin=25mm]{geometry}
\usepackage{tabularray}
\UseTblrLibrary{siunitx,booktabs}
\begin{document}
\begin{table}[htbp]
\sisetup{
input-open-uncertainty={},
input-close-uncertainty={},
table-align-text-before=false,
table-align-text-after=false,
round-mode=places,
round-precision=3,
table-format={(}-1.3{)}
}
\begin{talltblr}[
caption = {Panel B},
label = {tab:?},
note{} = {Standard errors in parentheses:\newline
*: \(p<0.10\),\quad
**: \(p<0.05\),\quad
***: \(p<0.01\).
}
]{
colsep = 3pt,
colspec = { X[2.8,l,m, font=\linespread{0.84}\selectfont]
*{6}{X[0.8, c, si]}
},
row{1} = {font=\small\bfseries},
}
\toprule
&\SetCell[c=4]{c} {{{Individual Treatment}}}
& & & &\SetCell[c=2]{c} {{{missing}}}
& \\
\cmidrule[r]{2-5}
\cmidrule[l]{6-7}
&\SetCell[c=2]{c} {{{(1)}}}
& &\SetCell[c=2]{c} {{{(2)}}}
& & {{{?}}}
& {{{?}}} \\
\cmidrule[r]{1-1}
\cmidrule[l]{2-3}
\cmidrule[l]{4-5}
\cmidrule[l]{6-7}
Using any method at baseline
& -0.0613 & (0.0820) & -0.0444 & (0.0810) & & \\
Number of living children
& 0.0143 & (0.0276) & 0.0133 & (0.0276) & & \\
Using injectable at baseline
& -0.151 & (0.384) & -0.153 & (0.384) & & \\
\bottomrule
\end{talltblr}
\end{table}
\end{document}
```
[](https://i.stack.imgur.com/5G5bS.png)
**Note:** both MWEs have been tested with the 2022A tabularray version. In a few days, a new version of the 2022B will be available with new features that will, among other things, allow you to write even simpler code for column headers.
The package version 2022A (unfortunately) are still not available on Overleaf. | I have no problems to scale your first example:
```
\begin{table}[h]
\centering
\caption{Panel A}
\scalebox{0.5}{\begin{tabular}{l*{2}{c}}
\hline\hline
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}\\
\hline
Highest schooling attained& -0.00577 & -0.00835 \\
& (0.0109) & (0.0108) \\
Husband's highest schooling attained (reported by wife)& 0.0151 & 0.0167 \\
& (0.0145) & (0.0145) \\
Ideal number of children& 0.00757 & 0.00803 \\
& (0.0292) & (0.0292) \\
Age & 0.00192 & 0.00132 \\
& (0.0110) & (0.0110) \\
Husband's age (reported by wife)& 0.00393 & 0.00467 \\
& (0.0120) & (0.0120) \\
Husband's ideal number of children (reported by wife)& -0.0225 & -0.0220 \\
& (0.0203) & (0.0203) \\
Has ever used a modern contraceptive method& -0.0181 & 0.00141 \\
& (0.102) & (0.101) \\
Wife has monthly income& -0.0735 & -0.0748 \\
& (0.129) & (0.129) \\
Wife knows when she is most fertile& 0.0917 & 0.0965 \\
& (0.0817) & (0.0816) \\
Wife wants to become pregnant in following 2 years& 0.00457 & -0.00293 \\
& (0.0664) & (0.0657) \\
Age wife married& 0.00758 & 0.00787 \\
& (0.00948) & (0.00947) \\
Catholic & -0.00748 & -0.00580 \\
& (0.0658) & (0.0657) \\
Comparison of happiness with other women in region\\(1=very unhappy, 5=very happy)& 0.00915 & 0.0119 \\
& (0.0353) & (0.0352) \\
Comparison of health with other women in region\\(1=very poor, 5=excellent)& 0.00229 & -0.00611 \\
& (0.0406) & (0.0403) \\
Number of years respondent lived in Lusaka& 0.000733 & 0.000546 \\
& (0.00256) & (0.00255) \\
Couple has electricity& 0.00826 & 0.00748 \\
& (0.0574) & (0.0569) \\
Formally married& 0.0388 & 0.0233 \\
& (0.0930) & (0.0916) \\
Number of days in past 7 days couple has sex& 0.0194 & 0.0174 \\
& (0.0256) & (0.0256) \\
Number of days in past month couple has sex& -0.00292 & -0.00287 \\
& (0.00786) & (0.00785) \\
Number of children husband has with other women& -0.00612 & -0.000674 \\
& (0.0676) & (0.0674) \\
Frequency at which couple has talked about contraception in last year& 0.0137 & 0.0112 \\
& (0.0267) & (0.0266) \\
Couple has ever disagreed on number of children& 0.0559 & 0.0559 \\
& (0.0824) & (0.0824) \\
Couple has ever disagreed on contraception use& -0.0699 & -0.0682 \\
& (0.0909) & (0.0908) \\
Have used contraceptive method without husband's knowledge& 0.00117 & -0.00202 \\
& (0.0875) & (0.0874) \\
Husband drinks at least 2 to 3 times a week& -0.00806 & -0.00576 \\
& (0.0553) & (0.0552) \\
f29 & -0.0802 & -0.0819 \\
& (0.0580) & (0.0579) \\
Wife ever pressured to have sex& 0.0549 & 0.0560 \\
& (0.0623) & (0.0621) \\
Husband does budgeting& 0.0193 & 0.0141 \\
& (0.0818) & (0.0817) \\
Husband decides major purchases& 0.0404 & 0.0421 \\
& (0.0632) & (0.0631) \\
cons & 0.286 & 0.303 \\
& (0.321) & (0.321) \\
\hline
\(N\) & 423 & 426 \\
\hline\hline
\multicolumn{2}{l}{\footnotesize Standard errors in parentheses}\\
\multicolumn{2}{l}{\footnotesize * \(p<0.05\), ** \(p<0.01\), *** \(p<0.001\)}\\
\end{tabular}
}
\end{table}
```
There are 3 errors in the second table:
1. In the second \multicolumn command the third argument is missing.
2. and 3. In the last 2 \multicolumn comands you write 11, but you defined only 8 columns.
That works for me:
```
\begin{table}[htbp]
\centering
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{Summary Statistics for Final Sample \label{tab:tab2}} \scalebox{0.5}{\begin{tabular}{l c*{6}{c}} \hline
&\multicolumn{3}{c}{Individual Treatment} &\multicolumn{2}{c}{missing}\\\cmidrule(lr){2-4}
&\multicolumn{1}{c}{(1)}&\multicolumn{1}{c}{(2)}\\
\toprule \multicolumn{6}{l}{\textbf{Panel B}} \\ \midrule
Using any method at baseline& -0.0613 & -0.0444 \\
& (0.0820) & (0.0810) \\
Number of living children& 0.0143 & 0.0133 \\
& (0.0276) & (0.0276) \\
Using injectable at baseline& -0.151 & -0.153 \\
& (0.384) & (0.384) \\
\hline\hline
\multicolumn{8}{l}{\footnotesize Standard errors in parentheses}\\ % changed to 8 columns
\multicolumn{8}{l}{\footnotesize \sym{*} \(p<0.05\), \sym{**} \(p<0.01\), \sym{***} \(p<0.001\)}\\ % changed to 8 columns
\end{tabular}}
\end{table}
``` |
39,411,200 | I heard that the computer only understands numbers in base two (binary) for years.
Recently, I wanted to understand in depth how my machine was working by stopping high level scripting languages and read few Assembly.
I understood that the goal of this language was for the CPU to be fast: simple for it, the CPU can easily decode assembly instructions.
Sorry if my question is not clear, I will try to clear the doubts:
How does the CPU converts assembly to binary ?
My question may be senseless, because the computer also plays with electricity, in this case, my question would be:
What does it mean: "The computer only understands binary" ? | 2016/09/09 | [
"https://Stackoverflow.com/questions/39411200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6813446/"
] | "The computer only understands binary" is an oversimplification of reality. The CPU (lets limit it to just the CPU for now), is a very complicated piece of hardware. It consists of modules like the arithmetic and logic unit (ALU) and the control unit (CU).
Now a program which the CPU can "understand" is only in binary, now to understand what this means one needs to understand how memory works fundamentally. Memory is constructed using transistors which are used to create logic gates (more complication hidden here). The way memory works is like it's in a constant loop. If you feed current through it (set its value to 1), then it will keep feeding it back to itself as long as there's power. When this happens we say that that piece of memory is holding a value of 1 (because there's current). If there's no current then the memory location has a value of 0 (no current).
Now "running" a program means feeding the memory contents of a block of memory (containing the program) into the CPU. There's an entry point for the program and from that blocks of pulses of power/no power (0s and 1s) start flowing into the CPU based on memory contents. Based on what the CPU is getting in the input, and the CPU architecture internally, the current will follow a different path and on the output of the CPU the result will vary depending on what the input is. How each CPU does this is very long and complicated (<https://en.wikipedia.org/wiki/Processor_design> for how CPUs look like internally).
Now if you write something in assembly, it goes through a specialised program which translates what you wrote in an equivalent binary representation.
For example if you write something like `ADD 2, 3` then the assembler will translate that into the stream of 0s and 1s which when passed through the CPU will result in a 5 (or the binary representation of a 5) | I will try to focus on the question that what do we mean when we say computer only understands binary
First let's take this example
Say you have to store a letter 'g' in the machine
First we convert it to it's ASCII value that is 103
Now binary equivalent of 103 is 1100111
Now we don't have any mechanism to store this number in a machine.
We figured a way out to remember this using machine or in other words collection of electric wires
We placed 7 parallel wires and let the current flow from the wires where we see 1 and leave other wires with no current specifically in the order of occurrence of bits i.e 0 or 1
Now every time I see this pattern I know this is the English letter g.
Now we can assume our storage devices or processors to be a huge network of such wires that are synergistically arranged to make our logics work
Please note that I have taken a oversimplified approach just it make it more shuttle and clear actual implementation is obviously much more complex as explained in other answers but the base line remains the same
Hope this helps |
22,305,141 | I am fairly new to java. I want to count the occurrences of words in a particular line. So far i can only count the words but no idea how to count occurrences.
Is there a simple way to do this?
```
Scanner file = new Scanner(new FileInputStream("/../output.txt"));
int count = 0;
while (file.hasNextLine()) {
String s = file.nextLine();
count++;
if(s.contains("#AVFC")){
System.out.printf("There are %d words on this line ", s.split("\\s").length-1);
System.out.println(count);
}
}
file.close();
```
Output:
```
There are 4 words on this line 1
There are 8 words on this line 13
There are 3 words on this line 16
``` | 2014/03/10 | [
"https://Stackoverflow.com/questions/22305141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3375627/"
] | Check Guava's [Multiset](http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset). Their description starts with `'The traditional Java idiom for e.g. counting how many times a word occurs in a document is something like:'`. You find some code snippets how to do that without a MultiSet.
BTW: If you only wanted to count the number of words in your string, why not just count the spaces? You could use [StringUtils](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html) from the apache commons. It's much better than creating an array of the split parts. Also have a look at [their implementation](http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html).
```
int count = StringUtils.countMatches(string, " ");
``` | In a given `String`, occurrences of a given `String` can be counted using `String#indexOf(String, int)` and through a loop
```
String haystack = "This is a string";
String needle = "i";
int index = 0;
while (index != -1) {
index = haystack.indexOf(needle, index + 1);
if (index != -1) {
System.out.println(String.format("Found %s in %s at index %s.", needle, haystack, index));
}
}
``` |
57,601 | Write a program or function that transforms an input string into [Zalgo](https://stackoverflow.com/questions/6579844/how-does-zalgo-text-work) text.
For example, for an input string `Zalgo`, a possible output might look like:
>
> Z̗̄̀ȧ̛̛̭̣̖̇̀̚l̡̯̮̠̗̩̩̥̭̋̒̄̉̏̂̍̄̌ģ̨̭̭̪̯̫̒̇̌̂o̢̟̬̪̬̙̝̫̍̈̓̅̉̇
>
>
>
Zalgoification specs
--------------------
* Each letter (upper or lower case) must be zalgoified, and nothing else (spaces, punctuation).
* The [combining characters](https://en.wikipedia.org/wiki/Combining_character) that can be placed on letters here are all those between U+0300 ̀ and U+032F ̯
* Each letter must have a total number of combining characters on it (above and under combined) which is randomly chosen according to a normal distribution of mean 10 and standard deviation 5 (If a negative number is chosen, 0 combining characters must be added).
* Each combining character placed on a letter is chosen uniformly at random between the 48 possible combining characters (see 2nd item).
Inputs, Outputs
---------------
* Input is a single line string that contains only characters between ASCII 32 (space) and ASCII 126 (tilde). No line breaks. You may assume there is at least one letter in the string. The input can be taken as command line argument, function parameter, or STDIN.
* Output is the Zalgoified string. It can be written to a file, or printed to STDOUT, or returned from a function. A trailing line feed is fine. **The output doesn't have to display properly in your interpreter/whatever, as long as when you copy it to a Stack Exchange answer it displays properly like here**.
Test cases
----------
* The Zalgo example above.
* Input: `Programming Puzzles & Code Golf`
Possible output:
>
> P̢̭̟̟̮̍̅̏̍̀̊̕̚̚r̢̫̝̟̩̎̔̅̈̑o̡̠̣̪̠̍̈̐̏̌̆g̡̬̯̟̠̩̎̐́̅̚ȑ̢̨̩̠̙̭̤̩̟̔̕ą̟̟̯̠̪̜́̉̒̎̂̍̃́̚̚̚m̪̈̅̈m̨̛̛̪̤̟̔̍̓i̢̛̬̠̠̇̈̂̓̒̀̋̔̚̚n̛̝̩̜̓̐̑̅̅g̨̩̪̊ P̨̧̢̟̙̮̋̆ų̨̙̞̙̫̤̫̭̊̓̒̃̒̚z̜̤̮̪̫̄̌̃̈̉̑̋́̕z̡̥̯̠̬̜̥̑̌̓̌̋́̅ľ̫̙̟̪̖̉ė̢̨̘̦̘̖s̛̜̙̘̚ & C̨̠̟̯̟̙̠̉̄̄́̄̑̈̔̆̀ö̭̟̗̯̥̏̐̄̏̌d̞̬̀̆́̀é̟̙̩̗̙̣̋̎̌̌̋ Ğ̨̡̧̡̣̪̝̝̘̩̮̉̋̀̉̉̕̕ọ̠̠̘̟̑̇́̀̃̎̓̋̚ḽ̡̢̟̪̥̍̍̅̀́̎̆̕f̧̢̪̠̠̀̉̒̍̍̊́
>
>
>
* Input: `Golf is a club and ball sport in which players use various clubs to hit balls into a series of holes on a course in as few strokes as possible.`
Possible output:
>
> Ǧ̡̧̄̐̊ò̡̞̟̖̌́̄́̆̈̒l̡̬̣̜̫̞̘̪̇̈̏̊̆̃̑̉̓̒f̙̐̍̇́̐̍̉ į̦̘̝̣̊̒̎̚s à̡̛̠̜̙̣̙̞̣̗̯̝̘̩̅̊̓̄̒̃ ć̬̗̫̯̫̎́̚l̒̎̋ű̯̜̑̎b̯̣̮̭̤̃̊́ a̡̨̟̘̭̣̍̈̀̃̎́̐̋̆̂ń̨̖̭̝̬̘̦̣̓̇̚̕d̨̤̣̙̜̪̖̪̍̓̔̍̔̃̒̍̆̏̚̚̕̚ ḃ̬̪̇̕a̡̟̖̬̬̖̬̋́̎̎̔̄̏̒̑̚l̨̖̜̬̠̭̭̇l̡̡̛̛̬̤̆̔̑̍ s̠̙̣̠̖̜̜̅p̤̖̃́̅̕̕ǫ̢̥̬̠̞̭̭̘̟̞̋̊̌r̡̛̞̬̈̇̑̎̄̚t̟̩̏̀ ï̡̧̢̨̜̜̝̝̜̜̫̔̇̂̔̐n̞̖̫̪̟̤̦̫̂̓̍̑̆̒̚ w̨̧̟̠̯̜̙̘̏̎̈̆̂̅̔hi̧̝̖̗̖̒̆̆̈̚ć̪̜̫̖̠̣̞̋̈́̀̌̋h̢̢̨̥̮ p̜̣̋̔̆l̨̧̛̘̫̝̙̠̯̂̑̌̈̒̐ā̩̗̟̐ẏ̢̛̫̠̦̤̫̞̦̯̥̜̀̀̈̅̉̈̄ẹ̡̑̔̄̉̀̎̒̑r̛̫̭̤̋̄̓̀̅̓ș̜̯̆̋̒̍̔ ų̛̘̭̜̝̈̃̂̅̌̍̆̚s̡̡̡̨̫̥̪̋̈̀̀̆ê̢̡̡̥̖̮̞̫̪̥̘̥̯̎́ v̡̢̢̟̠̞̬̥̩̣̫̫̦̞̂̐̓̇ặ̢̧̙̝̥̪̗̆̎̓ŗ̦̙̩̑̒̕í̫̣̊̚ō̡̧̤̘̟̩̠̫̗̃̍̉̊̕ụ̡̪̠̈̈́̊̅s̢̢̘̤̝̪̀̎̅ c̡̢̛̖̫̗̑̒̆́̎̚l̥̥̖̘̉̎̓̔̀̔ų̘̘̣̟̃̆̓̉̏̅̓̂́̇b̡̝̗̙̗̮̖̩̗̦̏̌̏š̛̮̣̮̜̒̓̌ ṭ̣̫̗̮̙̈̔̅̂̎̃̌̈ò̮̘̍̅̃̃̅̚̕ ḩ̜̞̮̠̇i̮t̝̗̦̖̮̞̗̩̞̤̎̍̒̐ bȁ̢̮̩̝̣̉ļ̛̮̘̏ĺ̨̖̮̑s̢̬̪̗̬̖̟̅̀ i̢̗̖̊̃ń̨̧̛̫̮̞̎t̡̗̞̩̙̑̐̏̔̏ơ̧̯̮̦̖̇̆̔ ạ̧̉̍̚ s̤̬̫̠̉e̎̃r̟̪̥̗̜̥̍̆̍̇̕̕i̧̧̭̝̫̪̯̖̞̪̅̇̎̈̐̅̍ȇ̟̬́̄̃̐̊̕s̢̢̛̝̤̙̭̘̩̩̍̑̂̈̀̀̍̄̔̒̒ o̡̢̘̩̣̅̐̆̌̂̉̇̆̋̕f̡̯̜̝̘̮̠̖̐̂̒̃̚̕ h̪̘̫̪́ǫ̭̦̔̋̆̚̕l̢̡̧̨̙̯̤̔̅̓̆̑̍́ȅ̪̬̝̙̅̋̍s̪̖̭̫̪̟̖̐̀̕ ǫ̦̠̫̍̊̉̄̚n̐̎̂̀ ą̡̛̛̤̦̪̣̭̈̐̂̎ c̪̩̠̗̟̜̘̐̂̈̐̑̏̈ọ̡̡̙̫̞̜̐̇̄̓̏u̥̖̙̝̔̂̎̅̚̚r̙̜̬̭̠̮̙̙̪̫̝̙̬̥̥̯̐́̈́̊̈̍̍ș̀́e̞̜̒̌̚ ĩ̧̦̝̪̆n̛̞̞̆̆̀ a̟̅̐̈̍̉̚̚̕ş̫̭̍̐̚ f̘̝̠̪̦̜́̌̍̇̀̕e̩̫̣̊̎̇̚w̪ ŝ̨̨̠̠̝̦̣̜̦̗̮̞̞̥̥̅̄̄̕t̢̡̢̙̞̟̩̭̤̅̎̌̒̃̇̕r̞̤̙̄̊̃̇̅̈̏̈̌ǫ̝̬̀̋̏̐̌̈k̡̢̧̪̭̝̙̆̈̒̀ȩ̛̙̣̠̗̞̮̅̅s̙̣̒̉̎́̂̅ à̧̛̖̘̞̫̘̎̃̀̑̎̕̕s̢̟̟̭̩̈̏̇ p̣̟̭̗̪̜̫̦̝̣̎̋̎̀̐̏o̧̢̪̮̤̦̎́̐̒̀̚̕s̛̯̦̗̬̬̊̊̄̓̐̉̏́̚s̢̠̣̬̥̬̔̅̕̕i̡̠̣̣̫̞̣̮̥̟̅̎̇̄̋̌̌̇b̡̧̡̖̖̃̄̋̈̋l̢̢̙̪̣̉̉̐̑̆ẹ̢̒̎.
>
>
>
Scoring
-------
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes ẁ̨̛̭̙̥̖̏̏̐̐̉̃̅̚i̜̟̭̤̞̘̗̐̐̔̈̍̋̏̚n̘̯̥̩̗̯̠̘̮̋̈̃̀̊̉̎̈̕s̛̬̦̙̮̩̜̄̑̐́̎̆̚. | 2015/09/11 | [
"https://codegolf.stackexchange.com/questions/57601",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/41723/"
] | MATLAB, 106 bytes
=================
I thought I'd submit another answer from a language which actually has a built in normal distribution function. I don't think I've ever tried MATLAB before so this may not be the most golfed it can be.
```
function o=z(a)
o=[]
for c=a
o=[o c floor(rand(1,floor(normrnd(5,10)*isstrprop(c,'alpha'))).*48.+768)]
end
``` | Perl, 73 bytes
--------------
```perl
s!\w\K!$x=-140;$x+=rand for 1..300;(x x $x) =~ s/x/chr 768+rand 48/ger!ge
```
Input is taken as newline-separated strings.
If you want to ignore the warnings printed to STDERR, use the `-C7` command-line flag.
This uses the same approximation for a normal distribution as the Moonscript solution. |
2,469,767 | We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time? | 2010/03/18 | [
"https://Stackoverflow.com/questions/2469767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296495/"
] | Your are right - calls to overloaded methods are realized at compile time. That's why it is *static*.
Calls to overridden methods are realized at run-time, based on the type on which the method is invoked.
[On virtual methods wikipedia says:](http://en.wikipedia.org/wiki/Virtual_function#Java)
>
> In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final are non-virtual.
>
>
>
`final` methods cannot be overridden, so they are realized statically.
Imagine the method:
```
public String analyze(Interface i) {
i.analyze();
return i.getAnalysisDetails();
}
```
The compiler can't overload this method for all implementations of `Interface` that can possibly be passed to it. | First, I want to discuss Run-time/Dynamic polymorphism and Compile-time/static polymorphism.
Compile-time/static polymorphism:- as its name suggests that it bind the function call to its appropriate Function at compile time. That means the compiler exactly know which function call associated to which function. Function overloading is an example of compile time polymorphism.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Run-time/Dynamic polymorphism:-In this type of polymorphism compiler don't know which functions call associates to which function until the run of the program. Eg. function overriding.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NOW, what are the function overriding and function overloading???
Function Overloading:- same function name but different function signature/parameter.
```
eg. Area(no. of parameter)
{ -------------
----------------
return area;}
area of square requires only one parameter
area of rectangle requires two parameters(Length and breadth)
```
function overriding:- alter the work of a function which is present in both the Superclass and Child class.
eg. name() in superclass prints "hello Rahul" but after overring in child class it prints "hello Akshit" |
2,430,350 | I am trying to set and catch the URL variable
It begins with a form which has the standard action set to "/autorisation/logout"
Then a button with an inline JavaScript function
```
function tbPayout()
{
parent.location = "/autorisation/logout?rcgo=payout";
return true;
}
<input src="/images/go02.gif" type=image border=0 name="go1" onClick="return tbPayout();">
```
In the authorization controller I try to catch it
```
if ( isset($_GET['rcgo']) ) {
```
but it doesn't work and I can't see the variable in the URL and therefore the
default forms action is performed?
I also have another redirect page with:
```
content="3; url=http://www.domain.nl/index/index?rcgo=logout" />
```
and that works fine.
How can I get the JavaScript to work because I have three submit buttons that I need to control by using different URL variables that I need to read in the controller function.
Which is logout() in this case.
It is worth mentioning that is has got something to do with the fact that it can not interpret the variable in the URI because it defaults to the index function off that controller which is the standard behavior if it can't find the second part.
Without the variable attached, it redirects ok.
Is there a solution? | 2010/03/12 | [
"https://Stackoverflow.com/questions/2430350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133418/"
] | **Since php 5.3:**
Use `static::MY_CONST`
---
**More details on `static`**
In this case [the keyword `static`](http://php.net/manual/en/language.oop5.late-static-bindings.php#language.oop5.late-static-bindings.usage) is a reference to the actually called class.
This illustrates the difference between `static $var`, `static::$var` and `self::$var`:
```
class Base {
const VALUE = 'base';
static function testSelf() {
// Output is always 'base', because `self::` is always class Base
return self::VALUE;
}
static function testStatic() {
// Output is variable: `static::` is a reference to the called class.
return static::VALUE;
}
}
class Child extends Base {
const VALUE = 'child';
}
echo Base::testStatic(); // output: base
echo Base::testSelf(); // output: base
echo Child::testStatic(); // output: child
echo Child::testSelf(); // output: base
```
Also note that the keyword `static` has 2 quite different meanings:
```
class StaticDemo {
static function demo() {
// Type 1: `static` defines a static variable.
static $Var = 'bar';
// Type 2: `static::` is a reference to the called class.
return static::VALUE;
}
}
``` | I couldn't get it to work with const as it prints "yonderyonder" (that's the thing about constants, they don't change), but it works fine with var:
```
<?php
class MyClass {
var $MY_CONST = "yonder";
public function __construct() {
echo $this->MY_CONST;
}
}
class ChildClass extends MyClass {
var $MY_CONST = "bar";
}
$x = new ChildClass(); // prints 'bar'
$y = new MyClass(); // prints 'yonder'
?>
``` |
1,231,288 | I have an object that has several properties. If I have a pointer to one of those properties, is it possible to get a pointer to the class instance to which that ivar belongs?
for example: foo.bar, where I know the address of bar, can the address of foo be found?
This seems related to: [run time references](http://developer.apple.com/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/ivar_getOffset) but I didn't see any references that were quite what I'm looking for.
Thanks for your help! | 2009/08/05 | [
"https://Stackoverflow.com/questions/1231288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | First, you need to adjust your terminology a bit. You cannot have a pointer to a property, because a property is an interface to an object, specifying the format of the getter and setter methods.
If you had a pointer to the getter, a method (IMP) at best you could get back would be a pointer to the class, certainly you could not get back to an instance.
If you had a pointer to an ivar, I don't believe there is any way to get back to the containing object instance. If you had an array of all posible foos, it might be possible to ask each of them for a list of ivars, and get the address of each ivar and eventuallty find the instance in question that way.
The best solution is for bar to contain a parent reference to foo, so that foo.bar.foo will give you the answer you want. But it depends on what exactly you are trying to do. The normal Cocoa way for a lot of these things is to pass foo as well, as is done for many delegates. For example:
```
[obj foo:foo doSomethingWithBar:foo.bar];
``` | Unless the object has a pointer back to it's "parent" or you explicitly track it yourself, I don't believe there's a way to resolve that. You'd really have to trace through memory to find what basically amounts to "who points to me". It's essentially the same problem as finding the previous node in a singly-linked list — you have to start from the beginning and stop when you reach the node that points to the node of interest.
The problem with trying to track down `foo` from the address to `bar` is that `foo.bar` is a pointer that contains the address of an object, and only `foo` calls it "bar". For simplicity's sake, imagine that `foo` is at address 0x1000, and `foo.bar` is at 0x1008 and points to another object at 0x2000. Now, if you have the address 0x2000, there's no easy way to know that 0x1008 points to it.
It's even more complicated if you imagine that N other addresses might also point to 0x2000, so even if you did scan memory, you wouldn't know whether the pointer belonged to an object, struct, local variable, or even was just a random pattern that happened to match the address you're looking for. |
136,302 | I’m in talks with an early age startup (would be joining as employee number 2). I do realise that working in a startup is not a classic 9-5. I understand that there might often be deadlines which will require me to put in more work than that. I understand that and am ok with this arrangement - obviously I will *want* to put in those hours because once on board I will *want* the product to succeed.
But I also understand that in a startup there is potentially unbounded amount of week-to-week work which means how much one works is largely determined by what the company founders expect. I value having time off, not only because of hobbies, social life etc, but also for mental health’s sake. And so if they expect that I should have no life and spend 100 hours a week on this project like they might do, then it’s easier to know that before getting on board rather than finding out later, quitting and wasting everyone’s time.
So, how do I find out what is the average normal time committment expected of me, roughly, while also not making it seem like I expect to be simply clocking in and out? | 2019/05/09 | [
"https://workplace.stackexchange.com/questions/136302",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/-1/"
] | Here's the thing: I *do* want to work eight hours a day and no more. And I do a good job in eight hours. I know I wouldn't do any more work in ten hours, so that would be pointless.
Now whether the startup thinks spending time in the office is necessary to prove your dedicated, or whether they just think they want someone to do the job reliably, that's up to them. | Read "Slicing Pie" about wages vs equity in a startup. If you're getting paid 100% of your market wage, you get no equity; if you work for free, you get your wage equivalent in equity, and everything in between.
The important thing is, this should be laid out before you start. This approach accounts for the different needs and expectations of a startup's employees. |
27,712,915 | We're working on a website makeover and have the look that we would like but are trying to figure out how to get it to be functional. The page is linked below for reference.
<http://centraliowaaccountant.com/newhomepage.html>
Basically what we're looking for is the entire area when you hover on "Tax Preparation" to be linked to "tax\_preparation.html" instead of just the text if you use an href. Is this something which can be done with just html/css? | 2014/12/30 | [
"https://Stackoverflow.com/questions/27712915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406686/"
] | This example is taken from <http://api.jquery.com/animate/>
```
$( "#book" ).animate({
opacity: 0.25,
left: "+=50",
height: "toggle"
}, 5000, function() {
// Animation complete.
});
```
Basically instead of setting the height directly you pass the animate function the value it should be. The animate function will then internally call the requestAnimationFrame function in order to change the value over time. <https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame>
The second parameter given (5000) is the amount of time it will animate in milliseconds. So 5000 will last 5 seconds. This parameter is optional.
You can tell the animate function to animate differently by giving it an easing string. Not all easings are supported in jQuery but you can try a few listed here: <http://api.jqueryui.com/easings/>
Lastly, the empty function in the example is a function that will be called when the animation finishes. This parameter is also optional. | In my opinion, a "setInterval" it's a little heavier, because it's always checking something.
Did you try with css?... What if you put a transition to the .flexht class?
```
.flexht{
-moz-transition:all 1s;
-webkit-transition:all 1s;
transition:all 1s;
}
```
Sorry, I don't know how your HTML looks like. But in my experience, this works. |
20,296 | Suppose I build a neural network for classification. The last layer is a dense layer with Softmax activation. I have five different classes to classify. Suppose for a single training example, the `true label` is `[1 0 0 0 0]` while the predictions be `[0.1 0.5 0.1 0.1 0.2]`. How would I calculate the cross entropy loss for this example? | 2017/07/10 | [
"https://datascience.stackexchange.com/questions/20296",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/15412/"
] | Let's start with understanding entropy in information theory: Suppose you want to communicate a string of alphabets "aaaaaaaa". You could easily do that as 8\*"a". Now take another string "jteikfqa". Is there a compressed way of communicating this string? There isn't is there. We can say that the entropy of the 2nd string is more as, to communicate it, we need more "bits" of information.
This analogy applies to probabilities as well. If you have a set of items, fruits for example, the binary encoding of those fruits would be $log\_2(n)$ where n is the number of fruits. For 8 fruits you need 3 bits, and so on. Another way of looking at this is that given the probability of someone selecting a fruit at random is 1/8, the uncertainty reduction if a fruit is selected is $-\log\_{2}(1/8)$ which is 3. More specifically,
$$-\sum\_{i=1}^{8}\frac{1}{8}\log\_{2}(\frac{1}{8}) = 3$$
This entropy tells us about the uncertainty involved with certain probability distributions; the more uncertainty/variation in a probability distribution, the larger is the entropy (e.g. for 1024 fruits, it would be 10).
In "cross"-entropy, as the name suggests, we focus on the number of bits required to explain the difference in two different probability distributions. The best case scenario is that both distributions are identical, in which case the least amount of bits are required i.e. simple entropy. In mathematical terms,
$$H(\bf{y},\bf{\hat{y}}) = -\sum\_{i}\bf{y}\_i\log\_{e}(\bf{\hat{y}}\_i)$$
Where $\bf{\hat{y}}$ is the predicted probability vector (Softmax output), and $\bf{y}$ is the ground-truth vector( e.g. one-hot). The reason we use natural log is because it is easy to differentiate (ref. calculating gradients) and the reason we do not take log of ground truth vector is because it contains a lot of 0's which simplify the summation.
Bottom line: In layman terms, one could think of cross-entropy as the distance between two probability distributions in terms of the amount of information (bits) needed to explain that distance. It is a neat way of defining a loss which goes down as the probability vectors get closer to one another. | The problem is that the probabilities are coming from a 'complicated' function that incorporates the other outputs into the given value. The outcomes are inter-connected, so this way we are not deriving regarding to the actual outcome, but by all the inputs of the last activation function (softmax), for each and every outcome.
I have found a very nice description [here](https://deepnotes.io/softmax-crossentropy) where the author shows that the actual derivative is $p\_i - y\_i$.
Other neat description can be found [here](https://gombru.github.io/2018/05/23/cross_entropy_loss).
I think that using a simple sigmoid as a last activation layer would lead to the approved answer, but using softmax indicates different answer. |
27,236,947 | I am trying to use MailKit (<http://jstedfast.github.io/MailKit/docs/index.html>) to log into Gmail using oAuth. I am able to log into Google API using a refreshed AuthToken, but when I try to use the refreshed token in MailKit, I get an error "Invalid Credentials"
Any clues??
Thanks,
Jeff
Here is my code:
```cs
var secrets = new ClientSecrets()
{
ClientId = "xxx-yyy.apps.googleusercontent.com",
ClientSecret = "xyzSecret"
};
IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = new string[] { GmailService.Scope.GmailReadonly }
});
var tokenResponse = flow.RefreshTokenAsync("", connection.RefreshToken, CancellationToken.None).Result;
using (var client = new MailKit.Net.Imap.ImapClient())
{
var credentials = new NetworkCredential("emailtoconnect@gmail.com", tokenResponse.AccessToken);
client.Connect("imap.gmail.com", 993, true, CancellationToken.None);
try
{
client.Authenticate(credentials, CancellationToken.None);
}
catch (Exception ex)
{
throw;
}
}
``` | 2014/12/01 | [
"https://Stackoverflow.com/questions/27236947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797825/"
] | a clearer answer is that the scope was incorrect in the original code
```cs
Scopes = new string[] { GmailService.Scope.GmailReadonly }
```
needs to be
```cs
Scopes = new string[] { GmailService.Scope.MailGoogleCom }
```
in order to authenticate with imapi using a access token. | ```cs
using (var client = new ImapClient())
{
client.Connect("imap.gmail.com", 993, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(EmailId, Password);
}
```
The above piece of code is used to log in to gmail using imap and MailKit tool. But before this, you have to log in to gmail manually and check "Enable Imap" option in Settings. This will surely work. |
17,128,999 | I have decided to give bluestack a try for debugging and testing my android dev games. However I have discover that the tilt doesn't seem to work.
There seem to be a few config files in the app folder, but they are for specfic game and have a classpath associated with them. eg.. com.halfbrick.jetpack.input.cfg
```
#
# Jetpack Joyride
#
[Origin]
Author = David Reese
Rating = 5.0
[Keys]
Space = Tap
[Guidance]
Space = SBoost
[GamePad]
Hat_Up = Space
LeftStick_Up = Space
A = Space
[OpenSensor]
Mode = TapA
A = Space SBoost
[Strings]
SBoost = Boost
[Strings.nb_NO]
SBoost = Gå
```
I would like to be able to test my application fully with tilt etc, but im not sure what the process is for creating one of these input files.
So my question is:
>
> How can I use tilt in Bluestack for Mac, for debugging and testing
> with eclipse?
>
>
>
Or
>
> How do I create a input CFG file in bluestack for development games
>
>
>
. | 2013/06/15 | [
"https://Stackoverflow.com/questions/17128999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/830439/"
] | In this case, it is advised that you declare it in only one place. It will be more readable and spare some lines of code.
Renaming would also be good, maybe something that suggests that is the final result of your method (like `returnArray`, `resultArray`).
In other circumstances, when that list would mean several different things, it would be really better to declare it, in that case, you would have different names too. | There's nothing wrong with declaring it multiple times, but you have a lot of repeated code: you can significantly improve your code by refactoring.
In your case, the JDK provides a convenience utility method to create ArrayLists in-line:
Instead of:
```
ArrayList<E> arr = new ArrayList<E>();
arr.add(slow.element);
arr.add(slow.next.element);
return arr;
```
Code this:
```
return Arrays.asList(slow.element, slow.next.element);
```
And so forth.
---
Note that the list returned from `asList()` is not modifiable. If you need a modifiable list, pass it to [`ArrayList`'s copy constructor](http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29):
```
return new ArrayList(Arrays.<E>asList(slow.element, slow.next.element));
``` |
14,064,111 | I have a Java program which uses javax.mail to send an SMTP message. This program works fine on a Linux box, I want to emphasize that beforehand. When I try this same code on my Windows 7 x64 box, I get this error:
```
send failed, exception: javax.mail.MessagingException: Could not connect to SMTP host: smtp.west.cox.net, port: 25;
nested exception is: java.net.SocketException: Network is unreachable: connect
```
Here is the code:
```
Session session = Session.getInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, props.getProperty("mail.to", "me@mine.com"));
msg.setSubject(mySubject);
msg.setSentDate(new Date());
msg.setContent(sBuf.toString(), "text/html");
Transport.send(msg);
```
This program pretty much uses defaults for everything. It works fine on another box on the same network. It uses the same settings that I use for my regular mail client, which works fine. There is something on THIS Windows box that is blocking SMTP, but only for Java.
I have Symantec (Norton) 360 installed. Turning it off makes no difference, but rebooting into Safe Mode (which disables almost everything) allows the program to work and send mail just fine.
So, to recap:
1. The program code works.
2. The settings are correct.
3. SMTP works for Windows Mail and is only blocked for Java on this Windows machine.
Before I spend another day tearing things apart and uninstalling / reinstalling, I wondered if anyone had any advice on fixing this? | 2012/12/28 | [
"https://Stackoverflow.com/questions/14064111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071914/"
] | I was also facing the same issue , basically it was a Java 7 issue, Just passing in JVM argument "-Djava.net.preferIPv4Stack=true", i got rid from issue . | I had similar issue but strangely everything was working fine with jdk 1.6 once I install jdk 1.7 I got the exception. I wonder what could be the reason for this!
After adding IPV4 argument it is working fine..Thank you so much. |
57,865,772 | I have a script in php that is calling a python one, which is a neural network being trained and it takes about 80 seconds to finish, but my php script finishes fast.
I tried just creating a csv file in python which is a quick process, and it worked, so its really a question of time.
I've already tried using the following code, and it didn't worked.
```
var_dump(time_sleep_until(microtime(true)+100));
``` | 2019/09/10 | [
"https://Stackoverflow.com/questions/57865772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10807658/"
] | Just use the Symphony Process component -> <https://symfony.com/doc/current/components/process.html>
It allows you to run processes asynchronously and check whether they are still running: <https://symfony.com/doc/current/components/process.html#running-processes-asynchronously>
Cheers. | Straight from the manual
<https://www.php.net/manual/en/function.sleep.php>
```
sleep ( int $seconds ) : int
```
Delays the program execution for the given number of seconds.
**Parameters ¶**
seconds
Halt time in seconds.
**Return Values ¶**
Returns zero on success, or FALSE on error.
If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT\_IO\_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.
**Errors/Exceptions ¶**
If the specified number of seconds is negative, this function will generate a E\_WARNING. |
838 | I recently came across this picture of the Boeing 787 series aircraft's incredible wingflex:

I suppose this is a consequence of using very light CFRP wings, but how does the wingflex itself improve the 787's flight performance? Do the benefits/drawbacks also apply to the 747-8 (which IIRC also uses CFRP wings)? | 2014/01/10 | [
"https://aviation.stackexchange.com/questions/838",
"https://aviation.stackexchange.com",
"https://aviation.stackexchange.com/users/504/"
] | The wings of the Boeing 787 are so flexible because its carbon fiber material can be stretched more, and the high aspect ratio of 11 will magnify this effect. In flight, all you will feel is less shaking due to gusts, because the wing will dampen load changes more effectively. On the ground, the wing might have less tip clearance, because less in-built dihedral is needed - the rest is supplied by the wing's elasticity in flight.
The influence on performance is slightly negative, but this is a very weak effect. It can be compared to the rolling resistance of a stiff bicycle versus one with a spring-loaded frame.
The amount of bending for a given bending moment depends on three factors:
1. Wing span: A given curvature of the wing due to bending at the wing root will cause a tip displacement which is proportional to the distance of that tip from the root.
2. Spar heigt: This curvature grows with the inverse of the square of the spar height. A lower relative thickness of the wing will produce more bending.
3. Spar material: The [Young's modulus](http://en.wikipedia.org/wiki/Young's_modulus) of the material describes how much it stretches for a given stress. More important, however, is the elastic elongation at yield stress. Carbon fiber has a higher Young's modulus than aluminium, but is elastic until rupture, so it can be stretched more and produces more bending at yield stress.
The numbers: The Young's modulus of aluminium is fairly constant for a wide range of alloys and normally 70,000 MPa or N/mm². The modulus of graphite fibers depends on their manufacturing process and varies between 200,000 and 700,000 MPa or N/mm². However, this value cannot be compared directly to that of aluminium. The final modulus of the composite depends on fiber orientation and resin content.
It is safe to assume that Boeing (or more precisely, Mitsubishi Heavy Industries) uses a modern, high-strength fiber like [IM7 (pdf)](http://www.hexcel.com/resources/datasheets/carbon-fiber-data-sheets/im7.pdf) (IM stands for intermediate modulus), which has a modulus of 276,000 MPa. It is also safe to assume that most of the fibers are oriented in span direction, so they can contribute fully to taking the bending loads. If we assume a conservative fiber content of 60%, the resulting modulus of the spar material should be 164,000 MPa. However, the spar is not a discrete component, but part of the wing box which also has to take torsion loads. While Aluminium is an [isotropic](http://en.wikipedia.org/wiki/Isotropy) material (it has the same properties in all directions), CFRP is highly anisotropic, and adding torsional strength will require additional fibers in other directions. Consequence: The effective modulus of the wing box in bending direction might be as low as 110,000 MPa.
In the end, what counts is how much material is there to carry the bending loads. Here the yield stress of the material comes into play: The more stress a material can tolerate before it shows plastic deformation, the less of it is needed to carry a given bending moment. To arrive directly at the maximum deformation, it is enough to look at the maximum elastic strain. With IM7, this is 1.9%, and with high-strength [7068 aluminium (pdf)](http://www.kaiseraluminum.com/wp-content/themes/kac/files/alloy-7068-brochure.pdf), it is less than 1% before the material suffers permanent elongation. This means that, even though CFRP is stiffer than aluminium, it can be loaded more and will stretch more before it reaches its limits. | Not only the 787 with CFRP has this, all wings flex a lot as shown by the lower part of this image.
[](https://i.stack.imgur.com/igVdz.jpg)
Source: [Introduction to Transonic Aerodynamics](https://books.google.nl/books?id=KG3xCAAAQBAJ&pg=PA479&lpg=PA479&dq=rigid%20wing%20jig%20shape&source=bl&ots=54tuX6YSa5&sig=SffFn609gMWysb_gXRltY9-Bf28&hl=nl&sa=X&ved=0CDoQ6AEwA2oVChMIkIjYssS3xwIVTLwaCh1zwA9_#v=onepage&q=rigid%20wing%20jig%20shape&f=false) by R. Vos and S. Farokhi
These days, designers incorporate the flexing into the design, making sure that the shape in cruise is exactly as they want it.
But the two graphs above show some interesting facts. On het left you can see the pressure distribution on different locations on a flexible wing, and on the right the same, but then for a rigid wing (thus, not deformed)
You can see that on the right image (around x/c=0.3), there are sharp jumps in the graphs, these indicate shocks, and lead to wave drag. On the flexible side, the gradients are less steep, meaning the shock wave is less strong. As a consequence the wave drag will be less.
Thus, based on these graphs, we can conclude that the flexible wing will have less wave drag, than the same wing that would not deform. |
6,057,074 | I've a table we have userids of people and the langauges they can speak. just two columns, userid and language.
I want to find all those users who can speak hindi AND english AND german AND french.
How should I write this query ? I cannot use Inner Join 4 times. Problem being the check for number of languages might increase, I might want to check for more languages.
userid | language
1 | english
4 | english
1 | french
1 | german
................. | 2011/05/19 | [
"https://Stackoverflow.com/questions/6057074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422028/"
] | If using MySQL, you could do something like (to be debugged, not tested):
```
SELECT userid FROM (
SELECT userid, GROUP_CONCAT(language SEPARATOR ',') AS languages
FROM UserLanguage
ORDER BY userid ASC, language ASC
GROUP BY userid)
WHERE languages LIKE '%english%french%german%hindi%';
```
(the languages in the LIKE clause have to be sorted)
[How to use GROUP BY to concatenate strings in MySQL?](https://stackoverflow.com/questions/149772/how-to-use-group-by-to-concatenate-strings-in-mysql)
---
Or maybe faster:
```
SELECT userid
FROM UserLanguage
WHERE language IN ('fr', 'en, 'de', 'hi')
GROUP BY userid
HAVING COUNT(DISTINCT(language)) >= 4
``` | You could use a [correlated subquery](http://msdn.microsoft.com/en-us/library/ms187638.aspx), like this:
```
SELECT UserId
FROM UserLanguage UL1
WHERE
EXISTS (SELECT * FROM UserLanguage UL2 WHERE UL2.UserId = UL1.UserId
AND UL2.Language = 'english') AND
EXISTS (SELECT * FROM UserLanguage UL2 WHERE UL2.UserId = UL1.UserId
AND UL2.Language = 'hindi') AND
EXISTS (SELECT * FROM UserLanguage UL2 WHERE UL2.UserId = UL1.UserId
AND UL2.Language = 'german') AND
EXISTS (SELECT * FROM UserLanguage UL2 WHERE UL2.UserId = UL1.UserId
AND UL2.Language = 'french')
``` |
37,144,094 | how to update ReyclerView adapter without make OnCreateViewHolder(...) being called?
Because when i do
`mRecyclerView.getAdapter().notifiItemChanged(position)`
it goes inside `OnCreateViewHolder(...)` what i don't want to. The reason why i don't want is because I have expanded item view and `onCreateViewHolder(...)` will reinflate it so make collapsed. I only want to `OnBindViewHolder(...)` being called
Have anyone faced with it?
**UPD:**
Just found that `OnCreateViewHolder(...)` is called only one first time, in all next times it's not being called. What is the reason?
t | 2016/05/10 | [
"https://Stackoverflow.com/questions/37144094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4543133/"
] | you have several options
**1)** Include the path to the folder test to `sys.path`
you can do hardcoded
b.py
```
import sys
sys.path.append("path/to/test")
import test.a.a
```
but in this case you have to change it manually if later you change the test folder to another place
you can also do automatic with
b.py
```
import os, sys
path = os.path.dirname( os.path.dirname( os.path.dirname(__file__) ) )
# folder_of_test/ test / b
sys.path.append(path)
import test.a.a
```
in this one, if you are using python 2 you need to call `os.path.abspath` on `__file__` first
**2)** Add the `test`'s parent folder to your [PYTHONPATH](https://docs.python.org/3/using/cmdline.html?highlight=pythonpath#envvar-PYTHONPATH) environment variable, or put the `test` folder in a folder in your PYTHONPATH or PATH environment variable.
to do this do
```
$> export PYTHONPATH="/path/to/parent/folder/of/test:$PYTHONPATH"
```
but most likely will only be temporal, to do in a permanent way go to the file `.profile` or `.bashrc` in your home folder and put the above instruction in there at the end in your favorite [way](https://unix.stackexchange.com/questions/117467/how-to-permanently-set-environmental-variables) (I modify .profile to set my pythonpath)
**3)** Call your code as `python -m test.b.b` from the folder that contain `test`
in any case you have to make sure that you don't other library that have the same name, for example I have anaconda installed and that come with a test package, and in that case you should change the name to avoid confusion | The module `test` is part of the standard library. So when you `import test.a`, it tries to import the `a` module in it.
So, even if you find a solution, it is better you don't use that name for your package. |
3,818,956 | When we solve the equation
$$x^{12}+x^6+1=0$$ we obtain $2$ solutions that also satisfy $$x^2+x+1=0$$
namely $-\frac{1}{2}\pm i\frac{\sqrt3}{2}$.
Shouldn't this imply that $x^2+x+1$ is a factor of $x^{12}+x^6+1$? However, the fully factorsied form of
$x^{12}+x^6+1$ is $$(x^6-x^3+1)(x^6+x^3+1)$$
The reason I think that it should be a factor is that when we have, for a function $f(x)$, (here a polynomial,) $f(a)=0$ then we know that $(x-a)$ is a factor of $f(x)$.
If we multiply $(x-(-\frac{1}{2}+ i\frac{\sqrt3}{2}))$ by $(x-(-\frac{1}{2}- i\frac{\sqrt3}{2}))$ which are both factors of $x^{12}+x^6+1$ we get $x^2+x+1$. It seems to me that this should apply to the polynomials above. I have a feeling that my logic is specious, but I'm not entirely certain why; I think the answer to my problem may be that $x^2+x+1$ is factor of $x^{12}+x^6+1$, but only if the other factor has complex coefficients, but I'm not sure. Thank you for your help.
**EDIT**
Oh wow, I'm so sorry for making such a stupid mistake everyone, thanks for correcting me (see numerous comments and answers). I was looking at a few polynomials simultaneously and got mixed up. Thanks for your help. | 2020/09/08 | [
"https://math.stackexchange.com/questions/3818956",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/764058/"
] | You are correct that if all of the roots of a polynomial $f(x)$ are roots of a polynomial $g(x)$, then $f(x)$ is a factor of $g(x)$.
However $x^2 + x + 1$ is not a factor of $x^{12} + x^6 + 1$. The reason is because $- \frac{1}{2} \pm i \frac{\sqrt{3}}{2}$ are not roots of that polynomial. This is because
$$ \left( - \frac{1}{2} \pm i \frac{\sqrt{3}}{2} \right)^3 = 1,$$
so plugging it into $x^{12} + x^6 + 1$ gives $(x^3)^4 + (x^3)^2 + 1 = 1 + 1 + 1 = 3 \neq 0$. | Another issue besides that mentioned by several posters in both answers and comments is this: You say the "the fully factorsied form" is a certain product of two cubic polynomials with integer coefficients. But if that is "the fully factorsied form", that would mean that's as much factoring as can be done with integer coefficients. With complex coefficients, a cubic can be factored further. |
895,276 | I extracted a `.zip` file compressed on a Mac and discovered that the compression included all the `.DS_STORE` meta-directory files (I think used to speed up spotlight search, but besides the point?).
Is there a one-liner I can execute from a Windows PowerShell or simple python script to clean up this folder by recursively deleting these files?
I get the error: `FIND: Parameter format not correct` when using:
```
find . -name '*.DS_Store' -type f -delete
``` | 2015/03/29 | [
"https://superuser.com/questions/895276",
"https://superuser.com",
"https://superuser.com/users/155701/"
] | In PowerShell do this:
```
cd MyFolder
Get-ChildItem -recurse -filter .DS_STORE | Remove-Item -WhatIf
```
When you specify `-WhatIf`, then PowerShell won't make any changes. It will instead tell you what it would have done. When you are happy with what it will do, then you can remove the `-WhatIf`. (It always pays to be careful when doing a recursive delete. You don't want to delete the wrong things.) | That [`find`](http://linux.die.net/man/1/find) syntax you are using in your example seems to me to be more appropriate for Mac OS X or Linux/Unix setups than a Windows setup. Instead, perhaps use the [`del`](https://technet.microsoft.com/en-us/library/cc771049.aspx) command like this in Windows [as explained here](http://awesometoast.com/delete-all-instances-of-ds_store-in-windows/):
```
del /s /q /f /a:h .DS_STORE
``` |
56,443,904 | I have a JSON object that I pass to an API endpoint:
```
{
"ID": 12312,
"location": "London",
"friends": 1231,
"Name": "dsd",
"verified": true
}
```
I have an endpoint `UserController`:
```
@PostMapping("saveUser")
public String Save(@RequestBody(required = true) User newUser){
//TODO: User needs to have ID and all other necessary params
//TODO: RequestBody is not working. Why not?
userservice.saveNewUser(newUser);
return "True";
}
```
and I have a `User` class:
```
@NodeEntity
public class User {
@Id
private long ID;
private String Name;
private String location;
private int friends;
private boolean verified;
private int followers;
.... getters and setters
```
My problem: when I insert a user, the database registers the correct friends and location filed, but the ID and followers field and name are incorrect. Does anyone know why?[](https://i.stack.imgur.com/gJ2sd.png) | 2019/06/04 | [
"https://Stackoverflow.com/questions/56443904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10840790/"
] | camelCase. Try changing ID to id and Name to name. Frameworks assumes getID would have been declared as iD. | `@JsonProperty("ID"); private long ID;`
use the @JsonProperty to tell the mapper object the property of the request body object to read from and the response body. |
44,658,044 | I have a Java class that has a private constructor:
```
public class MyClass {
private static final MyClass myClass = new MyClass();
private MyClass() {}
public static MyClass getInstance() {
return myClass;
}
}
```
This class is being used in the application like this:
```
MyClass myClass = MyClass.getInstance();
```
The whole application is also exported as a JAR and used in another application.
When I try to do the same in another application (Where its being invoked from a JAR) I get the following error:
```
java.lang.NoClassDefFoundError: Could not initialize class com.example.MyClass
```
I am not sure if this is the required behavior for a class with a ***private constructor***, or is there something else wrong with it?
Thanks! | 2017/06/20 | [
"https://Stackoverflow.com/questions/44658044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3518066/"
] | Your error has nothing to do with static-ness or your constructor. From the [javadocs](https://docs.oracle.com/javase/8/docs/api/):
>
> Thrown if the Java Virtual Machine or a ClassLoader instance tries to
> load in the definition of a class (as part of a normal method call or
> as part of creating a new instance using the new expression) and no
> definition of the class could be found. The searched-for class
> definition existed when the currently executing class was compiled,
> but the definition can no longer be found.
>
>
>
NoClassDefFoundError means the class definition is unavailable when you're trying to run your program. This is some kind of path error - either this class is not in the exported jar or it's not being included on the classpath when it's being run. | **NoClassDefFoundError** Occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the new keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error. |
9,262,535 | I am new to iOS5 development and using objective-c. I have trouble understanding the difference between **strong** and **weak** storage. I have read the documentation and other SO questions, but they all sound identical to me with no further insight.
I read [the documentation: Transitioning To ARC](https://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html) - it references to iOS4 terms of retain, assign, and release; which confuses me. Then I look into Open U CS193p, where it differentiates strong and weak:
>
> **Strong**: "keep this in the heap until I don't point to it anymore"
>
> **Weak**: "keep this as long as someone else points to it strongly"
>
>
>
Aren't the two definition identical = if pointer no longer pointing to an object, then free the memory holding the object? I understand the concept of pointers, heap, allocation or deallocation of memory - but what's the difference between strong and weak? | 2012/02/13 | [
"https://Stackoverflow.com/questions/9262535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529310/"
] | >
> Aren't the two definition identical.
>
>
>
Absolutely not. The key difference in the two definitions that you've pointed out is the "as long as someone else". It's the "someone else" that is important.
Consider the following:
```
__strong id strongObject = <some_object>;
__weak id weakObject = strongObject;
```
Now we've got a two pointers to `<some_object>`, one strong and one weak. If we set `strongObject` to `nil` like so:
```
strongObject = nil;
```
Then if you go through the rules you outlined then you'll ask yourself these questions:
1. Strong: "keep this in the heap until I don't point to it anymore"
`strongObject` doesn't point to `<some_object>` any more. So we don't need to keep it.
2. Weak: "keep this as long as someone else points to it strongly"
`weakObject` still points to `<some_object>`. But since nobody *else* points to it, this rule also means that we don't need to keep it.
The result is that `<some_object>` is deallocated and if your runtime supports it (Lion and iOS 5 upwards) then `weakObject` will automatically be set to `nil`.
Now consider what happens if we set `weakObject` to `nil` like so:
```
weakObject = nil;
```
Then if you go through the rules you outlined then you'll ask yourself these questions:
1. Strong: "keep this in the heap until I don't point to it anymore"
`strongObject` does point to `<some_object>`. So we do need to keep it.
2. Weak: "keep this as long as someone else points to it strongly"
`weakObject` doesn't point to `<some_object>`.
The result is that `<some_object>` is *not* deallocated, but `weakObject` will be the `nil` pointer.
[Note that all that is assuming `<some_object>` is not pointed to by another strong reference somewhere else / some other means of being "held"] | I know I'm rather late to this party, but I think it's important to confuse the issue by pointing out that the meaning of "strong and weak memory models" depends on whether you are talking about software or hardware.
For hardware, weak or strong indicates whether there is support for sequential consistency.
>
> [SC means that]...the result of any execution is the same as if the operations of all
> the processors were executed in some sequential order, and the
> operations of each individual processor appear in this sequence in the
> order specified by its program. - [Lamport, 1979](https://doi.org/10.1109%2FTC.1979.1675439)
>
>
>
WTF does that have to do with memory? It implies that writes to variables by different processors have to be seen in the same order by all processors. In hardware with a strong model this is guaranteed. On hardware with a weak model, it isn't.
Existing answers interpret the question only in terms of software memory models. Hardware is not irrelevant to programming. This very question mentions iOS, which typically runs on Arm7 processors. Arm7 has a weak memory model. For programmers accustomed to processors with a strong model - which is all of us because x86 and x64 have a strong model - this is a terrible trap. Using a bool to signal another thread to exit works fine in a strong model. The same code on Arm doesn't work at all unless you mark the flag volatile, and even then it's erratic.
While it is true that Arm8+ changes this utterly with explicit support for acquire/release, legacy software doesn't use this support. Legacy software includes all three phone OSs and everything that runs on them, as well as compilers and libraries until they are updated.
For an extended examination of this topic I refer you to the inimitable [Herb Sutter](https://herbsutter.com/2012/08/02/strong-and-weak-hardware-memory-models/). |
58,422,224 | I am trying to get from My Starting DataFrame

to My Desired Results
.
I am trying to do a groupby on two columns (Name, Month) and I have a column (Category) that has either the value 'Score1' or 'Score2'. I want to create two columns with the name of values from the Category column and set their values to a value determined from another column.
```
pd.crosstab([df.Name, df.Month], df.Category)
```
is the closest I've got to create the desire data frame however I can't figure out how to get the values from my "Value" column to populate the dataframe.
Results from crosstab

The Dataframe in code form
```
df = pd.DataFrame(columns=['Name', 'Month', 'Category', 'Value'])
df['Name'] = ['Jack','Jack','Sarah','Sarah','Zack']
df['Month'] = ['Jan.','Jan.','Feb.','Feb.','Feb.']
df['Category'] = ['Score1','Score2','Score1','Score2','Score1']
df['Value'] = [1,2,3,4,5]
```
Thanks! | 2019/10/16 | [
"https://Stackoverflow.com/questions/58422224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12229134/"
] | You can use [Pivot Table](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.pivot_table.html)
```
df.pivot_table(index=['Name', 'Month'],values='Value', columns='Category').rename_axis(None, axis=1).reset_index()
Out[1]:
Name Month Score1 Score2
0 Jack Jan. 1.0 2.0
1 Sarah Feb. 3.0 4.0
2 Zack Feb. 5.0 NaN
``` | one way is with `groupby` and `unstack`
```
new_df = (df.groupby(['Name','Month','Category'])
['Value'].first().unstack().reset_index())
print(new_df)
Category Name Month Score1 Score2
0 Jack Jan. 1.0 2.0
1 Sarah Feb. 3.0 4.0
2 Zack Feb. 5.0 NaN
``` |
7,807,512 | I have created a sample application in Silverlight with RIA services. I am using entity framework for CRUD operation but it does not work for INSERT Operation with following Exception, **"Submit operation failed validation. Please inspect Entity.ValidationErrors for each entity in EntitiesInError for more information."** I have not apply any validation but don't know how the error occurs.
I have tested that when I create an object of DB entity and assign values to it and then save by calling object.SaveChages(), it works fine. But its default method does not work. Any help is appreciated.
Thanks | 2011/10/18 | [
"https://Stackoverflow.com/questions/7807512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/748021/"
] | The SubmitOperation callback has an `EntitiesInError` property which you can use to iterate thru the entities. That's the way of getting the "real" error.
Here's the method I have to show the user what went wrong...
```
public static bool WasSubmittedOK(SubmitOperation so, string errorMessageHeader, out string errorMessage)
{
errorMessage = string.Empty;
if (!so.HasError)
return true;
so.MarkErrorAsHandled();
errorMessage = "An unknown error has occurred";
if (so.EntitiesInError.Count() > 0)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}\r\n", errorMessageHeader);
foreach (Entity item in so.EntitiesInError)
{
#if DEBUG
builder.AppendFormat("\r\nFor {0}", item.GetType());
#endif
foreach (ValidationResult error in item.ValidationErrors)
{
builder.AppendFormat("\r\n- {0}", error.ErrorMessage);
Debug.WriteLine(string.Format("Error in {0}:'{1}'", string.Join(",", error.MemberNames.ToArray()), error.ErrorMessage));
}
}
errorMessage = builder.ToString();
}
else if (so.Error != null) { errorMessage = so.Error.Message; }
return false;
}
``` | Are you able to drill into the validation errors? I actually have an article about this coming in December MSDN Magazine Data Points but I bet you don't want to wait, right? :)
Even if you haven't applied any specific validations, there are things like foreign key contsraints that EF will still check. If you can see what the error is that will be ultimately useful in solving your problem. Debug into the exception. See if there is a DbEntityValidationException available...maybe it's in an innerexceptoin. DbEntityValidationException will have one or more EntityValidationErrors. Each of *those* contains a list of all of the errors found for one instance. That means expanding the EntityValidationErrors items one at a time and looking at the ValidationError items contained within. |
13,077,010 | I would like to modify the default behavior of a regular WinForms C# textbox control so that pressing `backspace` deletes **whole words** instead of just a single character.
Ideally I would like to have this special behavior **only** when the caret position is in-front of a white-space character. For example; pressing `backspace` one time when the caret is at "hello world|" should still only remove one character resulting in "hello worl|" - but if the caret is at "hello world |" when I press `backspace`, then the result should be "hello |" | 2012/10/25 | [
"https://Stackoverflow.com/questions/13077010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/805220/"
] | Take a look at the keypress/keydown events. | Its a psuedo code, I hope you will find it helpful:
```
// check backspace is pressed
if keycode==keycode(backspace) then
// testing cursor is just after space(113) character
if string[string length] == keycode(space) then
// loop through string in reverse order
loop each character in reverse
// start removing each character
remove the characters
till find 2nd space
end if
end if
``` |
2,041,782 | In the application I'm developing at the moment I'm using a datagridview to display data. To fill it, I've to press a button and a backgroundworker will start running, it will fill a datatable and when it's finished running it will use the datatable as the datasource for the datagrid. This works fine, the UI stays responsive et cetera.
But now I've implemented coloring to the rows, depending on their values (Im still playing around with it, so any suggestions are welcome):
```
private void ApplyColoring()
{
if (dataGridView1.DataSource != null)
{
foreach (DataGridViewRow dataGridRow in dataGridView1.Rows)
{
// hardmap a color to a column
IDictionary<Int32, Color> colorDictionary = new Dictionary<Int32, Color>();
colorDictionary.Add( 7, Color.FromArgb(194, 235, 211));
colorDictionary.Add( 8, Color.Salmon);
colorDictionary.Add( 9, Color.LightBlue);
colorDictionary.Add(10, Color.LightYellow);
colorDictionary.Add(11, Color.LightGreen);
colorDictionary.Add(12, Color.LightCoral);
colorDictionary.Add(13, Color.Blue);
colorDictionary.Add(14, Color.Yellow);
colorDictionary.Add(15, Color.Green);
colorDictionary.Add(16, Color.White);
foreach (DataGridViewRow gridRow in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in gridRow.Cells)
{
if (colorDictionary.Keys.Contains(cell.ColumnIndex))
{
// standard background
cell.Style.BackColor = Color.FromArgb(194, 235, 211);
}
}
}
IList<String> checkedValues = new List<String>();
// first we loop through all the rows
foreach (DataGridViewRow gridRow in dataGridView1.Rows)
{
IDictionary<String, Int32> checkedVal = new Dictionary<String, Int32>();
// then we loop through all the data columns
int maxCol = dnsList.Count + 7;
for (int columnLoop = 7; columnLoop < maxCol; columnLoop++)
{
string current = gridRow.Cells[columnLoop].Value.ToString();
for (int checkLoop = 7; checkLoop < maxCol; checkLoop++)
{
string check = gridRow.Cells[checkLoop].Value.ToString();
if (!current.Equals(check))
{
if (checkedVal.Keys.Contains(current))
{
gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[checkedVal[current]];
}
else
{
gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[columnLoop];
checkedVal.Add(current, columnLoop);
}
}
}
}
}
}
}
}
```
This is giving me problems. Not because the coloring doesn't work, it does. But because it makes it hella slow. The first time it runs fine, but when i press the button again, it's slow as hell and the datagrid is flickering.
I want this run as postprocess, so it's (or rather should) be run after the backgroundworker is completed.
But when i call applycoloring from the RunWorkerCompleted event its just slow. What should I do to prvent this? How can I make sure the UI doesnt flicker while its executing a new query (while NOT LOSING the current data in the grid). | 2010/01/11 | [
"https://Stackoverflow.com/questions/2041782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65002/"
] | I found another way to do the reflection double buffering for slow datagrids:
Create an extension method with some reflection to set double buffering on the datagrid:
```
public static class DataGridViewExtensioncs
{
public static void DoubleBuffered(this DataGridView dgv, bool setting)
{
var dgvType = dgv.GetType();
var pi = dgvType.GetProperty("DoubleBuffered",
BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(dgv, setting, null);
}
}
```
Then in the form initializer do:
```
this.dataGrid.DoubleBuffered(true);
```
This is very similar to Evolved's answer and credits go to Shweta Lodha:
<http://www.codeproject.com/Tips/390496/Reducing-flicker-blinking-in-DataGridView> | Turn on double buffering
List of namespaces required for the function to compile is:
```
using System;
using System.Reflection;
using System.Windows.Forms;
public static class ExtensionMethods
{
public static void DoubleBuffered(this DataGridView dgv, bool setting)
{
Type dgvType = dgv.GetType();
PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(dgv, setting, null);
}
}
```
then initialize datagridview
```
dataGridView1.DoubleBuffered(true);
``` |
49,142,045 | I'm relatively new to Laravel. I'm confused on what is the proper way to deploy a Laravel 5.5 app to a Godaddy cPanel shared hosting. I've read multiple posts on the subject and they give conflicting advice.
Part of what I'm not clear on is do I copy all my files to the server and then run the following composer commands?:
>
> `composer install --optimize-autoloader` and `php artisan config:cache`
>
>
>
I get the part where I should create a folder on the server outside of the public\_html folder, placing all of the app files there except what is in the app's public subfolder.
>
> If I want to run the app from a subfolder how would I do that? For
> example, www.mysite.com/laravelapp
>
>
>
The examples I found where for only running it from the public\_html folder itself. Would it just involve changing the file paths in the www/index.php? | 2018/03/07 | [
"https://Stackoverflow.com/questions/49142045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2026659/"
] | I figured out how to deploy Laravel on a Godaddy shared hosting plan after reading more posts about the subject. Here are the steps I took:
1. Created a new folder outside the public\_html folder and uploaded all of the app files to that folder except the vendor folder.
2. Using SSH access, I ran the command `curl -sS https://getcomposer.org/installer | php` in the newly created app folder on the server.
3. I removed the public folder from the Laravel app folder, placed it inside the public\_html folder and renamed it to the name of my project.
4. I modified the file paths in the index.php in the project folder so they pointed to the laravel app folder like so:
`require __DIR__.'/../../laravel/bootstrap/autoload.php';`
`$app = require_once __DIR__.'/../../laravel/bootstrap/app.php';`
5. I installed the dependencies by running the command in SSH: `php composer.phar install`, then adding the necessary cache by running: `php artisan config:cache`
That was it. I did it using Godaddy cPanel shared hosting. Before attempting this make sure the PHP version is set to 7.1. I wanted to post my steps because I found some of the tutorials on this subject either were confusing, gave conflicting advice or didn't provide all the necessary steps. | ~~The biggest problem you have is that GoDaddy's latest supported version of PHP is v5.6. Laravel v5.5 and later all require PHP v7.0 or higher.~~ Apparently, they added PHP 7 support in late 2017.
I'd **still** highly recommend shifting to a much more reputable host like (closest comparison) BlueHost.com or DigitalOcean.com.
---
The second biggest problem you have is that GoDaddy won't let you actually run the `artisan` command, which Laravel really needs. It means 1. needing to apply database creation and migrations manually and 2. running all the artisan commands locally and uploading the entire project, in situ.
The third biggest problem is that [`composer` doesn't run on GoDaddy](https://stackoverflow.com/questions/47596115/how-to-install-composer-on-godaddy-shared-hosting), meaning you'll need to upload all the `vendor` directories, too.
---
Addendum: Here is a guide for how to deploy Laravel on shared hosts: <https://www.youtube.com/watch?v=6g8G3YQtQt4> |
148,733 | This may or may not be off-topic; feel free to point me to a better place to ask this.
My father brought home a cell phone he found in the woods, and I thought I'd charge it and turn it on to see if I can find out anything about the owner. (Needless to say I got no further than the lock screen.)
The phone is now turned off and plugged in via USB (not connected to the computer, but directly to the electrical outlet). However, the screen now reads "*Firmware Update - do not unplug the USB connection until the process is complete*", with a progress bar stuck at zero. It also refuses to be turned on again.
What's the best course of action? That is, can I safely unplug the device? I would assume so since it's only connected to the electrical outlet, but who knows what's going on behind the scenes, and unplugging it may leave it in an inconsistent state. I'd also like to avoid connecting it directly to my computer.
I'm probably being overly cautious, but I have no experience with LG devices and it's someone else's to boot, so I'd like to make sure I'm not making any of the stupid mistakes I'm prone to making. Better safe than sorry.
I can post a picture of the phone if needed — from the looks of it, it's some kind of LG G Flex. | 2016/06/19 | [
"https://android.stackexchange.com/questions/148733",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/172233/"
] | Take out the battery while it is plugged into a laptop, computer, or maybe the wall, then leave it out for a few seconds. A battery with a red exclamation point should show up and that is when you insert the battery and turn it back on. | Had the same **problem with** **LG flex2 frozen firmware screen**:
"*Firmware Update - do not unplug the USB connection until the process is complete*", stuck on 0% while plugged into charger all night long without any progress, no response from any button or button combination; not even 2 minutes of holding down the power button. I have no idea how it got to that state. I think it happened at low battery level.
**What worked for me** :
Remove plastic snap on back cover. Remove the tiny screws and remove the plastic part to get to the battery. The battery didnt appeared to be removable, but at the top left a flat short cable pops out of the battery and its terminal can be unplugged. Just slide your fingernail under and the tiny plug detaches without lots of pulling force. I waited some 10seconds and plugged the battery back in. Et voila the phone screen went straight into normal startup. The battery level at that stage were 11% (so not flat at all) |
3,994,288 | I have enum say ErrorCodes that
```
public enum ErrorCodes {
INVALID_LOGIN(100),
INVALID_PASSWORD(101),
SESSION_EXPIRED(102) ...;
private int errorCode;
private ErrorCodes(int error){
this.errorCode = error;
} //setter and getter and other codes
}
```
now I check my exception error codes with this error codes. I don't want to write if this do this, if this do this. How I can solve this problem (writing 10+ if blocks)
Is there any design patter to that situation ?
Thanks | 2010/10/22 | [
"https://Stackoverflow.com/questions/3994288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Either you do it with a if-statement or a switch, or you just implement the logic in question into the ErrorCode somehow.
In an OO fashion it all depends on how you want the application or system react to the error code. Lets say you just want it to output somekind of dialog:
```
public doSomethingWithError() {
ErrorCodes e = getError();
// the source of error, or originator, returns the enum
switch(e) {
case ErrorCodes.INVALID_LOGIN:
prompt('Invalid Login');
case ErrorCodes.INVALID_PASSWORD:
prompt('Invalid password');
// and so on
}
}
```
We could instead create an ErrorHandler class that does this instead:
```
// We'll implement this using OO instead
public doSomethingWithError() {
ErrorHandler e = getError();
// the originator now returns an ErrorHandler object instead
e.handleMessage();
}
// We will need the following abstract class:
public abstract class ErrorHandler {
// Lets say we have a prompter class that prompts the message
private Prompter prompter = new Prompter();
public final void handleMessage() {
String message = this.getMessage();
prompter.prompt(message);
}
// This needs to be implemented in subclasses because
// handleMessage() method is using it.
public abstract String getMessage();
}
// And you'll have the following implementations, e.g.
// for invalid logins:
public final class InvalidLoginHandler() {
public final String getMessage() {
return "Invalid login";
}
}
// E.g. for invalid password:
public final class InvalidPasswordHandler() {
public final String getMessage() {
return "Invalid password";
}
}
```
The former solution is easy to implement, but becomes difficult to maintain as the code grows larger. The latter solution is more complex, (aka. [Template Method pattern](http://en.wikipedia.org/wiki/Template_method_pattern) following the [Open-Closed Principle](http://en.wikipedia.org/wiki/Open/closed_principle)) but enables you to add more methods into the `ErrorHandler` when you need it (such as restoring resources or whatever). You can also implement this with the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern).
You won't get away completely with the conditional statements, but in the latter the conditional is pushed to the part of the code where the error is originated. That way you won't have double maintenance on conditional statements both at the originator and the error handling code.
EDIT:
See [this answer by Michael Borgwardt](https://stackoverflow.com/questions/3994288/if-statement-vs-oo-design/3994710#3994710) and [this answer by oksayt](https://stackoverflow.com/questions/3994288/if-statement-vs-oo-design/3994458#3994458) for how to implement methods on Java Enums if you want to do that instead. | You can create a map of error codes(Integer) against enum types
**Edit**
In this solution, once the map is prepared, you can look up an error code in the map and thus will not require if..else look ups.
E.g.
```
Map<Integer, ErrorCodes> errorMap = new HashMap<Integer, ErrorCodes>();
for (ErrorCodes error : ErrorCodes.values()) {
errorMap.put(error.getCode(), error);
}
```
Now when you want to check an error code coming from your aplpication, all you need to do is,
```
ErrorCodes error = errorMap.get(erro_code_from_application);
```
Thus removing the need for all the if..else.
You just need to set up the map in a way that adding error codes doesn't require changes in other code. Preparation of the map is one time activity and can be linked to a database, property file etc during the initialization of your application |
61,173,695 | I have been trying to automate my firefox browser in Kali linux. I installed selenium and geckdriver and running this simple script:
```
from selenium import webdriver
browser = webdriver.Firefox('/usr/bin/')
browser.get('www.duckduckgo.com')
#I saw a video where the guy mentioned that we do not have to use the path of the browser (doesn't work for me)
```
After running this simple script in python as
`python3 script.py`
the terminal freezes at:
```
script.py:4: DeprecationWarning: firefox_profile has been deprecated, please pass in a Service object
```
After Interrupting the process, it delivers the following error:
```
browser = webdriver.Firefox('/usr/bin/')
^CTraceback (most recent call last):
File "script.py", line 4, in <module>
browser = webdriver.Firefox('/usr/bin/')
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/webdriver.py", line 155, in __init__
firefox_profile = FirefoxProfile(firefox_profile)
File "/usr/lib/python3/dist-packages/selenium/webdriver/firefox/firefox_profile.py", line 78, in __init__
ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock"))
File "/usr/lib/python3.7/shutil.py", line 354, in copytree
copy_function(srcname, dstname)
File "/usr/lib/python3.7/shutil.py", line 266, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/usr/lib/python3.7/shutil.py", line 122, in copyfile
copyfileobj(fsrc, fdst)
File "/usr/lib/python3.7/shutil.py", line 79, in copyfileobj
buf = fsrc.read(length)
KeyboardInterrupt
```
I really do not understand what does it mean. Can you please help me fix it? Thanks in advance.
PS: I also installed `geckodriver v0.26` and put in the same directory as the `script.py` file. | 2020/04/12 | [
"https://Stackoverflow.com/questions/61173695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13288913/"
] | Just another option is to `try_convert()` into a `date`
Note: the format() is optional
**Example**
```
Declare @YourTable Table ([Period_Name] varchar(50)) Insert Into @YourTable Values
('Jan-19')
,('Feb-19')
Select *
,NewVal = format(try_convert(date,'01-'+Period_Name),'MM')
from @YourTable
```
**Returns**
```
Period_Name NewVal
Jan-19 01
Feb-19 02
``` | A simply approach:
```
select right(t.period_name, 2) year, m.period, m.name
from
(select '01' period, 'Jan' name
union
select '02', 'Feb'
...
union
select '12', 'Dec') m
inner join table1 t
on Left(t.period_name,3) = m.name
order by right(t.period_name, 2), m.period
```
Return:
```
year -- period -- name
19 ----- 01 -------- Jan
19 ----- 02 -------- Feb
19 ----- 03 -------- Mar
...
19 ----- 12 -------- Dec
20 ----- 01 -------- Jan
20 ----- 02 -------- Feb
20 ----- 03 -------- Mar
...
20 ----- 12 -------- Dec
...
``` |
5,119,070 | I am writing a very simple RSS reader - all it needs to do is get the xml doc, and print to the console the title and publish date of every item. I got started using these two questions:
[How can I get started making a C# RSS Reader?](https://stackoverflow.com/questions/576267/c-rss-reader)
[Reading the Stack Overflow RSS feed](https://stackoverflow.com/questions/501643/reading-the-stackoverflow-rss-feed)
I'm trying to figure out how to subscribe, and as far as I can figure you do it one of two ways. Send an HTTP request to the feed site so it pushes you updates as they come, or poll the site every X seconds and simply print the new ones.
I find it difficult the believe that there is no way to subscribe due to the millions of RSS readers running at any given moment, popular RSS sites like facebook, twitter, or myspace would be hit hundreds of millions of times per second due to all the RSS readers "subscribed" to it and look like a DOS attack.
So what is the "standard" way to subscribe to an RSS feed, if such a standard truely exists? | 2011/02/25 | [
"https://Stackoverflow.com/questions/5119070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265640/"
] | The standard way is to poll. Not every x seconds but every x minutes or x hours.
The reasoning behind RSS is to keep the feed extremely simple. Small download and the same file can be served to all subscribers (easy to cache in memory and no processing overhead to find out exactly what and when to send to each client). | Not sure you quite understand the concept of *RSS feeds*.
It is simple:
1. You application (RSS reader) sends an `HTTP GET` request to given RSS feed url.
2. You get `XML` in return.
3. You parse that `XML` and show that data on your `UI`.
And generally, the websites you mentioned are smart enough to identify DOS attacks (for example, frequent requests from same IP in very short time). So, you don't have to worry about that.
Also, while creating an RSS reader, every time you get new `XML` from feed url, you have to identify new posts from old ones (that you already have on your UI). Timestamps are generally used to identify posts, but, there no standard way of doing that. |
36,579,184 | I want to change the `border-radius` of a circle when I scale the object (`if scaleX/scaleY>1`)...
**This is my circle object in fabricJS:**
```
function makeStation(left, top, stationID) {
var c = new fabric.Circle({
radius: 2,
fill: '#5afffa',
stroke: '#666',
selectable: true,
hasRotatingPoint: false,
borderColor: 'black',
cornerColor: 'black',
});
c.left1 = left;
c.top1 = top;
c.hasControls = c.hasBorders= true;
c.stationID = stationID;
c.stationName = stations[stationID].name;
c.description = stations[stationID].desc;
c.image = stations[stationID].image;
return c;
}
```
How can I change the `border radius`? | 2016/04/12 | [
"https://Stackoverflow.com/questions/36579184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5740092/"
] | You need to define 'ng2-highchart' within your SystemJS configuration:
```
<script>
System.config({
map: {
'ng2-highchart': 'node_modules/ng2-highchart'
},
(...)
});
</script>
```
See this question for more details:
* [How to use highcharts with angular 2?](https://stackoverflow.com/questions/35719921/how-to-use-highcharts-with-angular-2/35719957#35719957) | Remove format: 'register' from you packages. This will help it detect the right format. Or you can add the format as follows:
```
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
},
"node_modules/ng2-highcharts": {
format: 'cjs',
defaultExtension: 'js'
}
},
map: {
"ng2-highcharts/ng2-highcharts" : "node_modules/ng2-highcharts/ng2-highcharts"
},
paths: {
"ng2-highcharts/ng2-highcharts" : "node_modules/ng2-highcharts/ng2-highcharts"
}
});
``` |
238,460 | I just came to the conclusion that simply pressing someone else claim does not make them a vassal of you but grands them independence, which has been "too" nice of me. So what could I have done to avoid this?
After doing some reading I came to the conclusion that if I had the guy I pressed the claim for already had as a vassal he would remain a vassal of me. So I just had to give him one of my titles? I have several other weak claims from people in my court but I want to make sure I do not lose the title I give to them once I press there claim.
Is this true and are there any other ways to have them become my vassal? | 2015/10/02 | [
"https://gaming.stackexchange.com/questions/238460",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/48810/"
] | Bungie did not give much information about Three of Coins, besides a paragraph in the [Bungie Weekly Update on 9/17/15](https://www.bungie.net/7_Bungie-Weekly-Update---09172015/en/News/News?aid=13575):
>
> Xûr will also sell a new consumable, the Three of Coins, which gives bosses a chance to drop Exotic Engrams, including Weapon Engrams. These consumables have a cumulative luck effect, so even if one doesn’t net you a drop, the next one has a higher chance to do so.
>
>
>
So as we know it, this is how the buff works:
1) You must use a Three of Coins (3oC) to gain the buff.
2) Killing an Ultra (most strike bosses, most raid bosses, Taken champions in patrol, the Ultra Knight on the Dreadnought) removes the buff. On the kill you either get an exotic engram drop, or you don't.
3a) If you got an exotic engram, your increased exotic engram drop rate from 3oC is reset.
3b) If you did not get an exotic engram drop, the next time you pop a 3oC you have a better chance at getting an exotic.
Notes:
* As of the recent hotfix, 3oC can't be used as effectively to farm. There is some hidden timer between popping them that affects their effectiveness as of the [9/24/15 Hotfix](https://www.bungie.net/7_Destiny-Hot-Fix---09242015/en/News/News?aid=13601):
"Three of Coins now provides a smaller increase in Exotic Engram drop chance when rapidly killing Ultras"
* It is generally observed that the exotic engram drop rate to 3oC use is approximately 1:5, but YMMV. This is purely speculation based on accounts and sampling from friends, the Destiny subreddit, and the Bungie forums.
* There are no known statistics, including the "cooldown time" alluded to in the first note, what percentage each coin raises your chance by, or anything like that. Bungie tends to be cryptic about these sorts of things.
* It is also possible for most strike bosses to drop an exotic engram without a 3oC. This can be observed in cases of people getting [two exotic drops](https://www.youtube.com/watch?v=WrP4HEOE5wI&t=42) from one boss. This hints, in my opinion, that the 3oC buff is a separate roll that occurs when you take down an ultra. | it used to be that the Three of Coins worked as a method of exotic farming. after the recent patch however, it has been dramatically nerfed. it is designed to be used for the end boos on strikes and story missions, so it now has a hidden cooldown. you now only get the 'chance' of getting anything by using them every 10 minutes, instead of every minute. every time you don't receive anything, the chance that you will get something next time is increased, until you get something. so, basically, just use them at the end for strike bosses and you will get goodies. i recommend using them once a day, therefore you will make them last until next Xur's day |
52,677,194 | I am Trying to Using Observer for Deleting With Relationship But Problem Is When i DD in Created Function Its Working Fine But When i DD In Deleted Function It Shows Nothing (POSTMAN) Means Neither Working Nor Error With Same Everything
Here Is Api:
```
$api->post('store','App\Http\Controllers\CustomerController@store');
$api->delete('delete/{id}','App\Http\Controllers\CustomerController@destroy');
```
Here Is Observer file made by artisan
```
namespace App\Observers;
use App\Customer;
class CustomerObserver
{
public function created(Customer $customer)
{
dd($customer);
}
public function deleted(Customer $customer)
{
dd($customer);
}
}
```
Here is Customer Controller
```
class CustomerController extends Controller
{
public function store(Request $request)
{
return Customer::store($request->person);
}
public function destroy($id)
{
$delete = Customer::where('person_id',$id);
$delete->delete();
}
}
```
Here Is Customer Model File.
```
class Customer extends Model
{
//Relationship Start From Here
public function person()
{
return $this->belongsTo(Person::class);
}
//End Here
public static function store($request)
{
//Call to Person Model And Save User
$user = Person::store($request);
//Create object of Customer Model
$customer = new Customer();
$customer->fill($request['customers']);
$customer->person()->associate($user)->save();
//return customer
return $customer;
}
}
``` | 2018/10/06 | [
"https://Stackoverflow.com/questions/52677194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10033986/"
] | can you do all things
1 add line in `Customer::observe(CustomerObserver::class);` in CustomerServiceProvider in `boot` method
2. add `CustomerServiceProvider` in app.php file in provider array
3. `composer dump-autoload`
4. `php artisan config:cache` | Only these Methods Works
```
$customer=Customer::where('id',$id)->first();
if($customer){
$customer->delete();
}
Or
$customer=Customer::find($id)->delete();
``` |
24,043 | [Murder Investigation](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Murder%20Investigation) reads:
>
> When enchanted creature dies, put X 1/1 white Soldier creature tokens onto the battlefield, where X is its power.
>
>
>
[Flowstone Slide](https://gatherer.wizards.com/Pages/Card/Details.aspx?name=Flowstone%20Slide) reads:
>
> All creatures get +X/-X until end of turn.
>
>
>
Suppose I enchant my 1/1 white Soldier creature token with Murder Investigation and then cast Flowstone Slide with X = 3. The poor token dies for sure, but would I get 4 white Soldier creature tokens because he was a 4/-2 at the time he was destroyed, or would I get 1 white Soldier creature token because that is the *power of the enchanted creature as it last existed on the battlefield*? | 2015/05/06 | [
"https://boardgames.stackexchange.com/questions/24043",
"https://boardgames.stackexchange.com",
"https://boardgames.stackexchange.com/users/12554/"
] | Any.
Your graveyard is a graveyard.
Your opponent's graveyard is a graveyard.
Cards in either graveyards are cards in a graveyard.
It would say ["your graveyard"](http://magiccards.info/mma/en/219.html) or ["an opponent's graveyard"](http://magiccards.info/wwk/en/48.html) otherwise. | It means you pick the graveyard. So, it could be your graveyard or one belonging to an opponent; i.e. any graveyard. If it were supposed to only apply to your or an opponent's graveyard, the card would say so. |
96,105 | I added this condition to my collection for adding the or condition:
```
$collection->addFieldToFilter(
array('city','mobile_badge'),
array(array('eq' => $arealist),
'1'));
```
But it returns the wrong result.
This `$collection->getAllIds();` also returns the correct ids.
But when I execute
```
$collection->getSelect();
```
it's gives me correct values. | 2016/01/06 | [
"https://magento.stackexchange.com/questions/96105",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/24541/"
] | There is no way to deploy static files in 2.0.\* only for your theme. You need to upgrade to 2.1.1 if you want to deploy specific theme only.
From version 2.1.1 there is `--theme` option for `setup:static-content:deploy` command.
```
php bin/magento setup:static-content:deploy --theme Vendor/mytheme
```
There is also options for excluding themes or deploy/exclude arias such as adminhtml or frontend.
[Check official documentation here](http://devdocs.magento.com/guides/v2.1/config-guide/cli/config-cli-subcommands-static-view.html) | You can try delete your theme static content in pub/static/frontend/YOURTHEME, and clear cache - refresh site to view change. |
13,946,384 | I have
```
var a = 5;
var b = 5;
var c = 5;
var d = 5;
```
What could be robust and quick way to compare if they hold same value in plain JavaScript then return true else false.
```
function compare(){
var
}
``` | 2012/12/19 | [
"https://Stackoverflow.com/questions/13946384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569403/"
] | A quick comparison would be `a === (b&c&d)`
A generic comparison function could be:
```
function allEqual(){
if (arguments.length<2){
return true;
}
var args = [].slice.call(arguments);
return args.filter(
function(a,i){return a === this[i ? i-1 : 0]},args)
.length === args.length;
}
//usage
allEqual(7,6,5,4); //=> false
allEqual(5,5,5,5); //=> true
allEqual(1,1,1,1,1,1,1,1,1,1,1,1); //=> true
allEqual(1,1,1,1,1,1,2,1,1,1,1,1); //=> false
``` | I think the javascript equality test is
If a==b then
something; |
1,334,221 | I'm trying to return a JSON response from a Django view call via an ajax call like below:
```
var tab = 'test';
var response = $.ajax({
url: "/" + tab + "/"
}).responseText;
alert(response);
```
Here is my Django view:
```
if request.is_ajax() == True:
req = {}
req['html'] = '<b>This is a test</b>'
response = simplejson.dumps(req)
print response
return HttpResponse(response, mimetype="application/json")
else:
return render_to_response("ajax/pingpong.html", {'ajax': ajax})
```
For some odd reason, the alert box is blank (though it does not say undefined in it). Interestingly enough, $.post and $.getJSON work fine on the exact same URL. I also see the expected JSON output on my console. Any help would be appreciated! | 2009/08/26 | [
"https://Stackoverflow.com/questions/1334221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48796/"
] | Unless I am mistaken, `responseText` isn't an attribute on whatever `$.ajax()` returns. I think you have to do something like this:
```
$.ajax({
url: "/test",
dataType: "json",
success: function(data) {
// use data
}
});
```
Because of the `dataType` parameter, the data yielded to the success callback is a normal JS object. If you don't specify the `dataType`, you'll get the string with the raw content the server returns. | I'm having the same issue but only under a specific environment. I'm wondering if your issue is the same. My environment:
1. Running Django's internal webserver (./manage.py runserver 0.0.0.0:8080)
2. Viewing my website in Google Chrome (v4.1.249.1025).
Under those circumstances, the following jQuery code leads to data = null, status = "success" around half the time. The other half the time it returns a valid Object for data.
```
$.ajax({
type:"POST",
url:"response/"+q.id+"/",
cache:false,
dataType:"json",
data:{response:$(this).val()},
success:function(data, status) {
alert(data+","+status);
},
error:function() {
$(".main_container").text("Error. Please check your internet connection.");
}
});
``` |
37,724,495 | I am trying to delete any five rows from my *users* table. I used following code for that.
```
DB::table('users')->take(5)->delete();
```
But it deletes all rows in that table. How will I overcome this problem? | 2016/06/09 | [
"https://Stackoverflow.com/questions/37724495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3659972/"
] | You said you want to delete 5 rows **randomly**, in this case this will work, I've tested it:
```
DB::table('users')->whereIn('id', DB::table('users')->orderBy(DB::raw("RAND()"))->take(5)->lists('id'))->delete();
```
It will take 5 random IDs and then will delete rows with these IDs with just two queries:
```
select `id` from `users` order by RAND() asc limit 5
delete from `users` where `id` in ('786', '186', '82', '578', '232')
``` | You can use `foreach`
```
$users = DB::table("users")->orderBy(DB::raw("RAND()"))->take(5)->get();
foreach($users as $user){
DB::table("users")->where("id", $user->id)->delete();
}
``` |
8,790,926 | I'm trying to compile code such as the below using JDK1.5.0\_u22. I get two compile errors (further below). It works fine with JDK1.6.0u30, but my project is restricted to Java 5. It also works fine if I repleace float with the wrapper class Float. Does anyone know what's going on here? A simple bug or some general restriction on the use of primitive array types in generic situations?
```
import java.util.*;
public class A {
public static void main(String[] args) {
List<float[]> list = Arrays.asList(new float[1], new float[3]);
float[] key = new float[2];
int index = Collections.binarySearch(list, key, new Comparator<float[]>() {
public int compare(float[] f1, float[] f2) {
return f1.length - f2.length;
}
});
System.out.println(index);
}
}
```
Compile errors:
```
C:\Users\mravn\Desktop>"c:\Program Files\Java\jdk1.5.0_22"\bin\javac A.java
A.java:4: incompatible types
found : java.util.List<<nulltype>[]>
required: java.util.List<float[]>
List<float[]> list = Arrays.asList(new float[1], new float[3]);
^
A.java:6: cannot find symbol
symbol : method binarySearch(java.util.List<float[]>,float[],<anonymous java.util.Comparator<float[]>>)
location: class java.util.Collections
int index = Collections.binarySearch(list, key, new Comparator<float[]>() {
^
2 errors
C:\Users\mravn\Desktop>
``` | 2012/01/09 | [
"https://Stackoverflow.com/questions/8790926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1138964/"
] | I'm going to give the answer for the 1st compiler error and keep digging to see if I can find the one for the 2nd compiler error...
Running the following by itself produces no errors using jdk1.5.0\_22:
```
System.out.println(Arrays.asList(new float[1]).size());
```
Running this by itself...
```
System.out.println(Arrays.asList(new float[1], new float[3]).size());
```
produces this nasty compiler error...
```
An exception has occurred in the compiler (1.5.0_22). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.AssertionError: unexpected type: <nulltype>
at com.sun.tools.javac.tree.TreeMaker.Type(TreeMaker.java:531)
at com.sun.tools.javac.tree.TreeMaker.Type(TreeMaker.java:525)
at com.sun.tools.javac.comp.Lower.boxArgs(Lower.java:2510)
at com.sun.tools.javac.comp.Lower.visitApply(Lower.java:2420)
at com.sun.tools.javac.tree.Tree$Apply.accept(Tree.java:813)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.comp.Lower.visitSelect(Lower.java:3019)
at com.sun.tools.javac.tree.Tree$Select.accept(Tree.java:987)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.comp.Lower.visitApply(Lower.java:2474)
at com.sun.tools.javac.tree.Tree$Apply.accept(Tree.java:813)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1893)
at com.sun.tools.javac.comp.Lower.boxArgs(Lower.java:2517)
at com.sun.tools.javac.comp.Lower.visitApply(Lower.java:2420)
at com.sun.tools.javac.tree.Tree$Apply.accept(Tree.java:813)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.tree.TreeTranslator.visitExec(TreeTranslator.java:227)
at com.sun.tools.javac.tree.Tree$Exec.accept(Tree.java:728)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.tree.TreeTranslator.translate(TreeTranslator.java:54)
at com.sun.tools.javac.tree.TreeTranslator.visitBlock(TreeTranslator.java:145)
at com.sun.tools.javac.comp.Lower.visitBlock(Lower.java:2933)
at com.sun.tools.javac.tree.Tree$Block.accept(Tree.java:535)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.tree.TreeTranslator.visitMethodDef(TreeTranslator.java:129)
at com.sun.tools.javac.comp.Lower.visitMethodDefInternal(Lower.java:2267)
at com.sun.tools.javac.comp.Lower.visitMethodDef(Lower.java:2186)
at com.sun.tools.javac.tree.Tree$MethodDef.accept(Tree.java:478)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.comp.Lower.visitClassDef(Lower.java:1989)
at com.sun.tools.javac.tree.Tree$ClassDef.accept(Tree.java:434)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1881)
at com.sun.tools.javac.comp.Lower.translate(Lower.java:1901)
at com.sun.tools.javac.comp.Lower.translateTopLevelClass(Lower.java:3070)
at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:487)
at com.sun.tools.javac.main.Main.compile(Main.java:592)
```
So I followed the compilers advice and did some searching on Oracle's bug database and found the bug by searching for "java.lang.AssertionError: unexpected type: ". You can check it out here: [Primitive arrays and varargs inference leads to crash in TreeMaker.Type(TreeMaker.java:531)](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6222762)
Using the Float wrapper class is the work around as you discovered.
**EDIT - answer for 2nd compiler error**
I believe the 2nd compiler error to be a bug and I've submitted it to the [Bug Database](http://bugs.sun.com/bugdatabase/)
I was able to compile the following list, key and comparator by themselves with no compiler errors:
```
List<float[]> list=new ArrayList<float[]>();
list.add(new float[] {0.0f});
list.add(new float[] {1.0f});
float[] key = new float[2];
Comparator<float[]> c = new Comparator<float[]>() {
public int compare(float[] f1, float[] f2) {
return f1.length - f2.length;
}
};
```
When I try to run "Collections.binarySearch(list, key, c)" with them, I get the "cannot find symbol" error. If I change "float" to "Float", it compiles fine with both cases.
I believe that the list, key and comparator I posted above fulfills the binary search contract completely according to the [Java 5 spec on it](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#binarySearch%28java.util.List,%20T,%20java.util.Comparator%29) | Generics don't handle primitives consistently. This is because Generics it is just a compile time addition to a single class. |
38,021,348 | I have the following code:
```
for x in "${array[@]}"
do
echo "$x"
done
```
The results are something like this (I sort these later in some cases):
```
1
2
3
4
5
```
Is there a way to print it as `1 2 3 4 5` instead? Without adding a newline every time? | 2016/06/24 | [
"https://Stackoverflow.com/questions/38021348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6263005/"
] | Yes. Use the `-n` option:
```
echo -n "$x"
```
From `help echo`:
>
> -n do not append a newline
>
>
>
This would strips off the last newline too, so if you want you can add a final newline after the loop:
```
for ...; do ...; done; echo
```
---
**Note:**
This is not portable among various implementations of `echo` builtin/external executable. The portable way would be to use `printf` instead:
```
printf '%s' "$x"
``` | ```
printf '%s\n' "${array[@]}" | sort | tr '\n' ' '
```
`printf '%s\n'` -- more robust than `echo` and you want the newlines here for `sort`'s sake
`"${array[@]}"` -- quotes unnecessary for your particular array, but good practice as you don't generally want word-spliting and glob expansions there |
108,803 | I moved my website from old hosting to new hosting and its giving me error every were like following
please any one sort this out
```
There has been an error processing your request
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY'
Trace:
#0 C:\inetpub\vhosts\dotnpixel.uk\intu.online\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#1 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Zend\Db\Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#2 C:\inetpub\vhosts\dotnpixel.uk\intu.online\lib\Zend\Db\Adapter\Abstract.php(480): Zend_Db_Statement->execute(Array)
#3 C:\inetpub\vhosts\dotnpixel.uk\intu.online\lib\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('INSERT INTO `ad...', Array)
#4 C:\inetpub\vhosts\dotnpixel.uk\intu.online\lib\Varien\Db\Adapter\Pdo\Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('INSERT INTO `ad...', Array)
#5 C:\inetpub\vhosts\dotnpixel.uk\intu.online\lib\Zend\Db\Adapter\Abstract.php(576): Varien_Db_Adapter_Pdo_Mysql->query('INSERT INTO `ad...', Array)
#6 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\AdminNotification\Model\Resource\Inbox.php(120): Zend_Db_Adapter_Abstract->insert('adminnotificati...', Array)
#7 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\AdminNotification\Model\Inbox.php(118): Mage_AdminNotification_Model_Resource_Inbox->parse(Object(Mage_AdminNotification_Model_Inbox), Array)
#8 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\AdminNotification\Model\Feed.php(97): Mage_AdminNotification_Model_Inbox->parse(Array)
#9 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\AdminNotification\Model\Observer.php(50): Mage_AdminNotification_Model_Feed->checkUpdate()
#10 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Model\App.php(1338): Mage_AdminNotification_Model_Observer->preDispatch(Object(Varien_Event_Observer))
#11 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Model\App.php(1317): Mage_Core_Model_App->_callObserverMethod(Object(Mage_AdminNotification_Model_Observer), 'preDispatch', Object(Varien_Event_Observer))
#12 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\Mage.php(448): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)
#13 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Controller\Varien\Action.php(527): Mage::dispatchEvent('controller_acti...', Array)
#14 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Adminhtml\Controller\Action.php(160): Mage_Core_Controller_Varien_Action->preDispatch()
#15 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Controller\Varien\Action.php(407): Mage_Adminhtml_Controller_Action->preDispatch()
#16 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Controller\Varien\Router\Standard.php(250): Mage_Core_Controller_Varien_Action->dispatch('index')
#17 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Controller\Varien\Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#18 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\code\core\Mage\Core\Model\App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#19 C:\inetpub\vhosts\dotnpixel.uk\intu.online\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#20 C:\inetpub\vhosts\dotnpixel.uk\intu.online\index.php(90): Mage::run('', 'store')
#21 {main}
``` | 2016/03/31 | [
"https://magento.stackexchange.com/questions/108803",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/38093/"
] | I agree with Fabian's answer in that I would assume that your table lost it's last increment id. On that table, back it up, then either set the increment id to a number higher than your largest id, or clear out the values in that table.
```
ALTER TABLE adminnotification_inbox AUTO_INCREMENT=X;
```
(set X to a number higher than your largest notification\_id) | You should run Magento's database checking tool.
I don't know how this happens, but I have seen Magento installations where many or all of the foreign key restraints are missing. In your case, the auto increment setting seems to be turned off for that table, but you might have other errors too. Do you know which method was used to backup the DB on the original server?
`mysqldump` saves all key constraints correctly by default. But if someone inexperienced used the phpMyAdmin database backup function, I think they could have easily messed this up.
The error says you have a duplicate key "0". There should never be primary key auto-increment value of 0. They start at 1. So I think one record was already added to your table on the new server with ID "0". Now the second attempt is failing.
As a quick fix ( backup your database first):
1. Find the max value of your primary key.
2. Change the "0" value to be the max value +1.
3. Add back the autoincrement setting for your primary key.
I'll use "table" for your table name and "id" as your primary key. Replace with your own values.
```
# 1
SELECT MAX(`id`) FROM `table`; # suppose your result is "55";
# 2
UPDATE `table` SET `id` = 56 WHERE `id` = 0; # Now, no more id of "0";
# 3
ALTER TABLE `table` CHANGE `id` `id` INT( 11 ) NOT NULL AUTO_INCREMENT;
# assuming datatype(length) would likely be INT(11)
``` |
9,366,755 | I worked a lot lately on android stuff in my favorite IDE, NetBeans. It was a pain to simply set up the basic android sdk in it, but now i need to make an app with facbook connection. Is there a way to make the Facebook-related classes work with NetBeans? Has anyone done it? Thanks for any help, and sorry for my english! | 2012/02/20 | [
"https://Stackoverflow.com/questions/9366755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1126273/"
] | I tried to find a solution to this problem many times when I found the solution provided by bali182. However I couldn't properly understand the solution so I decided to give more explanations about the it:
1. You need to create a new android project
2. get github.com/facebook/facebook-android-sdk (only facebook directory will be useful)
3. copy from facebook directory src to your root project src
4. copy from facebook directory res to your root project res
5. copy from facebook directory libs to your root project libs directory
6. right click on your project and properties
7. within properties, click on library left hand side menu entry
8. tick is library
9. then you can buil the project
Now you are good and can link the new created library to any android project. In order to link the library to your facebook project, you'll simply need to right click on your android project, click on library and add the facebook sdk library path.
The problem that I had at the begining was due to the fact that I was directly copying src, res, libs directly to my main project (phonegap project) and that caused issues when compiling it. Linking the newly created library to my main project was the key! ;) | Well thanks to Rstar-s tutorial, i finally found the solution. I tought, that i need to install an extension, similar to the core Android SDK, but no, here is what you need to do:
1.) go to github.com/facebook/facebook-android-sdk
2.) download the facebook directory ONLY! The other directories are only examples.
3.) Put the files from the src (you can copy the drawables too, if you want to) in the package, you are currently working with
4.) You are good to go, you can use the facebook "SDK"
Thank you RStar for the answer! |
6,527,783 | I want call OnClick function on page load with out user clicking. Can we do that in jQuery or javascript?
```
<input name="ctl00$PlaceHolderMain$ButtonSection$RptControls$BtnSubmit"
class="ms-ButtonHeightWidth"
id="ctl00_PlaceHolderMain_ButtonSection_RptControls_BtnSubmit"
accessKey="o" onclick="javascript:WebForm_DoPostBackWithOptions(new
WebForm_PostBackOptions("ctl00$PlaceHolderMain
$ButtonSection$RptControls$BtnSubmit",
"", true, "", "", false, true))"
type="button" value="OK"/>
``` | 2011/06/29 | [
"https://Stackoverflow.com/questions/6527783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/158008/"
] | ```
$(document).ready(function() {
$("#ctl00_PlaceHolderMain_ButtonSection_RptControls_BtnSubmit").click();
});
```
This will trigger the `click` event on the element with the supplied `id`, and it will run when the document is fully loaded. | You can try doing a `$("#ctl00_PlaceHolderMain_ButtonSection_RptControls_BtnSubmit").trigger('click');` This would emulate a click on the button more info [here](http://api.jquery.com/trigger/) |
11,300,200 | Can someone please explain why ?\_\_\_SID=U is appearing in some Magento URLs on my site and not others?
I think it has something to do with sessions but I am not entirely clear. Also, what makes it more confusing is the fact that it's only appearing in some URLs and not others.
I don't need to know how to remove it as I am aware of the setting in the admin area. I would really like an explanation of what it is, what its purpose is and why it would show on some pages and not others. id rather understand what's going on fully than blindly follow some advice as to how to remove it. | 2012/07/02 | [
"https://Stackoverflow.com/questions/11300200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I addition to Brendan's answer, the `___SID=U` is used in the cache as a placeholder for the session ID. It is replaced by `Mage_Core_Model_Url::sessionUrlVar()` which in turn calls `Mage_Core_Model_Url::sessionVarCallback()`. These methods are called from `Mage_Core_Block_Abstract::_afterCacheUrl()`, which means that any URL found in block output will contain the correct session ID (if needed).
So to get rid of the parameter in your own code the "right way" use this:
```
$url = Mage::getUrl('some/magento/route'); // might append ___SID parameter
$url = Mage::getModel('core/url')->sessionUrlVar($url); // process ___SID
```
If the string still displays in the rendered page that is a bug. Are you using some custom caching module, or generating URL's using a non-standard way? | The SID is a "session ID". Magento uses this to track a user's activity within the same Magento installation. Normally, Magento powers one website and one store from one installation (database).
Magento could power multiple websites with multiple stores from one installation though. The SID allows users to stay logged in while navigating across these websites/stores.
I *think* if you have the function enabled, the SID is sent when accessing catalog URLs so Magento can update the session with the user's location/state for the current website/store.
If you're not running a multi-website or multi-store environment, it's safe to disable the SID on the frontend. |
33,766,963 | Is it possible to add an `imageView` behind a `UITableView`? How would I add this image:

So that users could see it behind a tableview (background set to clear)? | 2015/11/17 | [
"https://Stackoverflow.com/questions/33766963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5571164/"
] | The following should work:
```
tableView.backgroundColor = UIColor(patternImage: UIImage(named: "your_image_name")!)
```
As the function names imply, a `UIColor` is created from the image you supply.
Refer to the Apple documentation [here](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/#//apple_ref/occ/clm/UIColor/colorWithPatternImage:) for more information. | Funny, I just did a tutorial that had this in it, but code was used instead of an image. In Swift 2.0 you create a file (let's call it BackgroundView) of type `UIView`, add this code in the pre-made `drawRect` function:
```
// Change these colors to the ones you want.
let lightPurple: UIColor = UIColor(red: 0.377, green: 0.075, blue: 0.778, alpha: 1.000)
let darkPurple: UIColor = UIColor(red: 0.060, green: 0.036, blue: 0.202, alpha: 1.000)
let context = UIGraphicsGetCurrentContext()
//// Gradient Declarations
let purpleGradient = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [lightPurple.CGColor, darkPurple.CGColor], [0, 1])
//// Background Drawing
let backgroundPath = UIBezierPath(rect: CGRectMake(0, 0, self.frame.width, self.frame.height))
CGContextSaveGState(context)
backgroundPath.addClip()
CGContextDrawLinearGradient(context, purpleGradient,
CGPointMake(160, 0),
CGPointMake(160, 568),
[.DrawsBeforeStartLocation, .DrawsAfterEndLocation])
```
Then create a `configureView` function in the `TableViewController` and put this line of code in it:
```
tableView.backgroundView = BackgroundView()
```
Then call the function in the `viewDidLoad`. |
50,359,814 | I want to create TableLayout in my fragment to insert data.
I used for that this methode below.
I have to call the methode **updateTable** outside of the onCreated view method.
But I got always this error:
>
> java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
>
>
>
The complete code of the error:
```
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tharwa.tdm2_exo2, PID: 5480
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.view.ViewConfiguration.get(ViewConfiguration.java:364)
...
at com.tharwa.tdm2_exo2.TableAgent.TablePresentation.updateTable(TablePresentation.kt:61)
```
I have tried several ways to avoid this error but still always appear. I tried to get the context from `onCreatedView` too but does not work.
Here is my function:
```
class TablePresentation : DialogFragment(),tableContract.View
{
....
override fun updateTable(temps: ArrayList<Double>)
{
for (i in 0 until temps.size) {
val row = TableRow(activity)
row.setLayoutParams(LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT))
row.setWeightSum(2.0f)
val tv1 = TextView(activity)
val tv2= TextView(activity)
...
table!!.addView(row, i)
}
}
}
```
Here is the complete code of the class:
```
class TablePresentation : DialogFragment(),tableContract.View
{
var table: TableLayout?=null
override fun onCreateView(inflater: LayoutInflater?, parent: ViewGroup?, state: Bundle?): View? {
super.onCreateView(inflater, parent, state)
val view = activity.layoutInflater.inflate(R.layout.table_fragment, parent, false)
view.findViewById<View>(R.id.button_close)?.setOnClickListener({ dismiss() })
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
table = view?.findViewById<View>(R.id.simpleTableLayout) as TableLayout
}
override fun onCreate(savedInstanceState: Bundle?) {
...
}
override fun onStart() {
...
}
override fun updateTable(temps: ArrayList<Double>)
{
....
}
}
```
and here is how I attach the view to the controller:
```
class PaletteController
{
var father: FatherController?=null
val view: PaletterPresentation
var model:PaletteAbstraction?=null
var TableSon:TableController?=null
constructor(view:PaletterPresentation)
{
this.view=view
view.controller=this
this.model= PaletteAbstraction()
}
....
fun notifyTableChild()
{
TableSon= TableController(view.getTableChild())
setChildSFather()
TableSon?.updateTable( father!!.giveTemps())
}
}
```
Here is why I create the fragment:
```
class PaletterPresentation: Fragment(), PaletteContract.View
{
var views: View? = null
var controller: PaletteController?=null
val tablePresentation=TablePresentation()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
views = inflater!!.inflate(R.layout.palette_fragement, container, false)
return views
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fab.setOnClickListener { view ->
val ft = childFragmentManager.beginTransaction()
tablePresentation.show(ft, ContentValues.TAG)
controller?.notifyTableChild()
}
}
override fun getTableChild(): TablePresentation {
return tablePresentation
}
}
```
I really do not know how to fix this problem. | 2018/05/15 | [
"https://Stackoverflow.com/questions/50359814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9039646/"
] | Your fragment is not attached.
You're doing this:
```
TableSon= TableController(view.getTableChild())
setChildSFather()
TableSon?.updateTable( father!!.giveTemps())
```
Where `getTableChild` returns what has been initialized like this:
```
val tablePresentation=TablePresentation()
```
This creates an "rogue" Fragment that is not attached to anything.
One way to fix this particular issue would be to remember the array in the `TablePresentation` fragment and call `updateTable` from `onAttach`.
EDIT: By "remember" I mean save it into the arguments, not just store in a member. | @Dennis K weel we can call the method from onAttach or even from onViewCreated.
I know that work perfectly.
But my question was why we can not do that \*\*the call of the method i mean \*\* outside of those 2 methode.Why could not we do that?
Finally because i have not found the answer to my why i have called my methode from onViewCreated.or even on onAttached.like have u said @Dennis K.
Here is the call
```
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
table = view?.findViewById<View>(R.id.simpleTableLayout) as TableLayout
updateTable()
}
```
Here is the function
```
fun updateTable()
{
val temps=controller?.getTemps()
for (i in 0 until temps!!.size) {
val row = TableRow( activity)
row.setLayoutParams(LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT))
row.setWeightSum(2.0f)
val tv1 = TextView( activity)
val tv2= TextView(activity)
tv1.setLayoutParams(TableRow.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f))
tv2.setLayoutParams(TableRow.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f))
tv1.setGravity(Gravity.CENTER)
tv2.setGravity(Gravity.CENTER)
tv1.setText((i+1).toString())
tv2.setText(temps.get(i).toString())
// finally add our textviews to TableRow
row.addView(tv1)
row.addView(tv2)
//finally add our TableRow to Tablelayout
table!!.addView(row, i)
}
}
```
Why why why outside of onAttach/onViewCreated we can not receive a valid activity (which is a Context). |
4,204,378 | This may be a very silly question, but I've been wanting to ask it for a while so here goes. I've been reviewing basic high school math in preparation for analysis, and I find myself questioning a lot of things - especially basic algebra - to the point I'm going a little mad.
For instance, polar coordinates can be related to rectangular coordinates like so: $x=r \cos\theta$, $y=r \sin\theta$. So, $x^2+y^2=1$ can be rewritten as $r^2=1$, so $r=1$. And surely enough, it's the same graph. But why does this work? I know it algebraically makes sense but it just feels a bit odd to me. I guess a broader version of this question is: I've been taught that if something is algebraically derived/true, it must produce the right answer. But how do I know that other than saying, "if you broke zero algebraic rules, it holds." The manipulation of these variables is just odd to me. Maybe this feeling will pass.
Another example:
$$\iint 1-x^2-y^2\,dx\,dy = \iint 1-r^2\,rdr\,d\theta $$
This algebraically holds since $x^2+y^2=r^2$ but how do I know it works other than saying "algebra works"?
I'm definitely overthinking this but it keeps nagging me. | 2021/07/21 | [
"https://math.stackexchange.com/questions/4204378",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/827203/"
] | Your question is not silly. Some aspect of it drove hard-core mathematicians totally crazy in the 20'th century. People like Hilbert, one of the greatest, never quite got over it; a guy called Gödel actually *proved* that it is *impossible* to create a "perfect" kind of maths and was the big destroyer of dreams. You can read up on the fascinating history of that, maybe starting with Wikipedia's article on [the Foundations of Mathematics](https://en.wikipedia.org/wiki/Foundations_of_mathematics).
But back to your current situation of being at the end of school education and wondering whether it all really works.
In maths, this happens the same as in all other complicated fields:
First, you are learning some aspects which are probably at least partially, more probably massively simplified, and not deduced from first principles in a thorough manner. This does not give you a complete insight into the topic, and basically summarizes school-level education.
This kind of introduction gives you a good idea what the topic is about, and may make you familiar with some very basic concepts. And with basic I *do* mean basic. This is the same as talking about a few of Einsteins famous thought experiments - this gives you an idea what Relativity is about, but gives you zero insight on how it *actually* works (i.e., the maths behind it).
Also, this gives you a chance to detect whether maths, in this case, interests you and whether you want to go deeper. One may argue that this could be the main function of school-level education; you probably do not need your integrals for everyday life, ever. It certainly does not give you a chance of really knowing that it all is correct, there is a lot of belief involved.
When actually studying maths at the uni level, at least when I did it some decades ago, the education process is totally different. Back then, we started from first principles (e.g., with the construction of numbers with the Peano Axioms; with formal ZF set theory; with Rings and Groups and such). Starting from literally nothing (all of these basically start out with the empty set as the only object), you build up the whole of maths.
This is founded in formal logic (i.e., concepts like "for all", "there exists", "and", "or" and so on). In my experience, this was introduced relatively intuitively in my maths courses - the symbols were displayed and quickly explained, and that was that; I also studied computer science, where you formalize it excessively in the context of "lambda calculus" and similar areas; and it is also a big topic in classical philosophy.
All the little steps in these deductions are, individually, dead simple, very easy to understand, require *only* the axioms and every previous deduction, and are in themselves "atomic". So much so, that when learning every little piece for the first time, you constantly ask yourself what this madness is all about.
The benefit is that as it *is* so simple, there is never a point where you really doubt that it is "true" and "works" (for some definition of truth and "working", which is not an easy topic at all) - it is better to think in terms of *consistency*. That is, is all of what you're doing and learning *consistent* with the basic axioms you found your maths on (which there can be different sets you can choose, but usually it's all founded on the Peano Axioms and ZF(C) set theory).
All operations you do with your mathematical objects have been proven by some mathematician, based on simpler operations. If you so wish, you can buy volumes of books where you can trace back all your questions right back to the original few axioms in *excruciating* detail.
How to get an *intuitive* understanding, which is required to work forward (i.e., to find new proofs, or even new areas of maths) is a totally different beast, and probably best left for another question... | You've got two good answers. Here are some points about polar coordinates that seems not to be addressed, but that consistently bother at least some students in ways that sound similar to your doubts.
The equations $x = r\cos\theta$ and $y = r\sin\theta$ define a *mapping* from the plane to itself, which we might express
$$
P(r,\theta) = (x, y) = (r\cos\theta, r\sin\theta).
$$
Often we speak of mapping "the $(r, \theta)$ plane" to "the $(x, y)$ plane".
These coordinates are not intrinsically associated to the planes, but in the context of working with polar coordinates it's efficient to fix the meanings of all four variables. Note carefully that $(r, \theta)$ are *Cartesian* coordinates for the domain of $P$, and are *polar* coordinates for the $(x, y)$ plane.
The mapping $P$ is *surjective* or *onto*: For every point $(x, y)$, there exists a pair $(r, \theta)$ such that $(x, y) = P(r, \theta)$. Loosely, every point in the plane *has a set of polar coordinates*.
By contrast, the mapping $P$ is *not injective*, or *not one-to-one*: There exist distinct sets of polar coordinates that map to (or "represent") the same $(x, y)$. It's a good exercise to work out precisely when two points in the $(r, \theta)$ plane map to the same $(x, y)$, partly to review trigonometry, and partly because I think this underlies the unease motivating the question.
Answer:
>
> We have $P(0, \theta) = (0, 0)$ for all real $\theta$, while if $r \neq 0$, then $P(r, \theta) \neq (0, 0)$ for all real $\theta$. For every integer $k$ and every real $r$, we have $P(r, \theta) = P(r, \theta + 2k\pi)$ and $P(r, \theta) = P(-r, \theta + (2k+1)\pi)$. Conversely, if $P(r\_{1}, \theta\_{1}) = P(r\_{2}, \theta\_{2})$, then either $r\_{1} = r\_{2}$ and $\theta\_{2} - \theta\_{1} = 2k\pi$ for some integer $k$, or $r\_{1} = -r\_{2}$ and $\theta\_{2} - \theta\_{1} = (2k+1)\pi$ for some integer $k$.
>
>
>
---
Why should this be bothersome? For one thing, the equations $r^{2} = 1$ and $r = 1$ *are not equivalent* for real numbers $r$. Well then, why should they define the same locus, the unit circle $x^{2} + y^{2} = 1$, in the $(x, y)$ plane? Because without constraints on the angle $\theta$, *each* of the lines $r = 1$ and $r = -1$ "traces out under $P$" the entire circle. (To be more formal, we can express this using *images* of sets under a mapping.)
It may be instructive to sketch the images under $P$ of segments of the form $(r, \theta)$ with $r = 1$ and $0 \leq \theta \leq \pi/2$, or with $r = -1$ and $0 \leq \theta \leq \pi/2$. We get visibly-different curves: It's only when we let the angle range over an interval of length at least $2\pi$ that the difference ceases to be visual, and we recover the entire locus $x^{2} + y^{2} = 1$.
Another worrisome property of polar coordinates arises if we ask, "What are the polar coordinates of a point $(x, y)$?" This is a sneaky trap: By using the article *the*, the question implicitly suggests each point $(x, y)$ *has unique polar coordinates*, when in reality every point $(x, y)$ has *infinitely many* distinct sets of polar coordinates.
My suspicion is, if you (beginner, or future reader) closely examine your unease with polar coordinates, "sketchy" claims will originate with *different* sets in the $(r, \theta)$ plane that map to the *same* set in the $(x, y)$ plane when you're trying to discern something by looking only at the $(x, y)$ plane.
More generally, understanding the polar coordinates mapping in detail clarifies abstract concepts, including images and preimages of sets, surjectivity and injectivity of mappings, and one-sided inverses; this example justifies giving these properties special names and expending time on them in analysis and elsewhere. (In fact, the humble polar coordinates mapping concretely touches on more subtle concepts, such as covering maps and factoring one mapping through another, lifting and sections of fibre bundles, simple-connectedness, and de Rham cohomology!) |
19,186,208 | I'm sorry if question is not clear, let me explain:
I need to achieve the following:
```
<div>
<div>art 1</div>
<div>art 2</div>
</div>
<div>
<div>art 3</div>
<div>art 4</div>
</div>
<div>
<div>art 5</div>
<div>art 6</div>
</div>
etc
```
where each art is inside an array. So far I have tried the following code:
```
foreach $articles as $article{
for($i=1; $i<3; $i++){
if($i==1){
echo '<div>';
}
echo '<div>'.$article->title.'</div>';
if($i==2){
echo '</div>';
}
}
```
}
but what i get is not the result i want:
```
<div>
<div>art 1</div>
<div>art 1</div>
</div>
<div>
<div>art 2</div>
<div>art 2</div>
</div>
<div>
<div>art 3</div>
<div>art 3</div>
</div>
etc
```
I don't have a clue how to change value of array every two divs. I haven't found a similar question mainly because I don't know how to search for it. If it is a duplicate please kindly point me to one.
Thanks for your time and help! | 2013/10/04 | [
"https://Stackoverflow.com/questions/19186208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2158500/"
] | What you need is a modulo. A modulo divides by the number and returns the remainder. it's perfect for determining where you are in your count. The character for a modulo is %
```
$counter = 1;
foreach($articles as $article) {
if($counter % 2 == 1) echo '<div>';
echo '<div>'.$article->title.'</div>';
if($counter % 2 == 0) echo '</div>';
$counter++;
}
if($counter % 2 == 0) echo '</div>';
```
Here's how the math works
First loop, counter is 1. Modulos are only concerned with the **remainder** so it divides whole numbers only. So 1/2 returns 0 with a remainder of 1.
Second loop counter is 2. So 2/2 returns 1 with a remainder of 0.
Here's the same loop with a modulo 3
1 % 3 = 1/3 = 0 remainder 1
2 % 3 = 2/3 = 0 remainder 2
3 % 3 = 3/3 = 1 remainder 0
I hope that helps | Try:
```
foreach( $articles as $key => $article ){
$key++;
if( $key % 2 == 0 ){
echo '<div>'.$article->title.'</div>';
echo '</div><div>';
}else{
echo '<div>'.$each['title'].'</div>';
}
}
``` |
60,580,625 | I'm new in programming and I'd like to ask you how can I write my code so that it read all the pic whitin a directory, process it one by one, and then save the output images in another directory.
```
%pylab
%matplotlib inline
import cv2
import glob
import os
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
filename = [img for img in glob.glob("outp/*.png")]
flist=sorted(filename)
images = []
for img in flist:
n = cv2.imread(img, 0)
images.append(n)
blur = cv.GaussianBlur(n, (9,9), 0)
cv.imwrite(flist, blur) #definitly wrong!! but idk how to do it
``` | 2020/03/07 | [
"https://Stackoverflow.com/questions/60580625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13024064/"
] | You don't need to create a list of all the pixel data of all the images in memory, that is just wasteful of memory. So, remove the lines:
```
images = []
```
and
```
images.apoend(...)
```
Then change your `imwrite()` to overwrite the current image:
```
cv2.imwrite(img,blur)
```
---
Here's a more complete version:
```
#!/usr/bin/env python3
import cv2
import glob
import os
import numpy as np
import cv2
# Go to where the images are
os.chdir('outp')
# Get list of filenames to convert
files = glob.glob("*.png")
for file in files:
n = cv2.imread(file, 0)
blur = cv2.GaussianBlur(n, (9,9), 0)
cv2.imwrite('blurred_' + file, blur)
``` | Try this way:
`cv2.imwrite("mypicture.jpg", gray[y:y+h,x:x+w])` |
3,205,256 | I've encountered a rather odd case in Java EE 6 where using the JPA EntityManager's `find` method along with an entity's primary id returns null, but using the Criteria API to select all entities with that id works fine.
Here is the code I'm using for `find`:
```
// Always returns null, even for records I know for sure are in there.
user = em.find(User.class, userId);
```
...and here's the code I'm using with the Criteria API:
```
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> u = criteria.from(User.class);
TypedQuery<User> query = em.createQuery(
criteria.select(u).where(builder.equal(u.get("id"), userId)));
user = query.getSingleResult();
```
Any idea why `find` returns null but Criteria finds the User? I tried these two alternate methods in the exact same spot in the program.
Here are the relevant portions of the User entity:
```
@Entity
@Table(name = "USERS")
@Access(AccessType.PROPERTY)
public class User implements Serializable {
...
private Long id;
...
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_generator")
@SequenceGenerator(name = "user_id_generator", sequenceName = "user_sequence", allocationSize = 1)
@Column(name="id")
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
...
}
``` | 2010/07/08 | [
"https://Stackoverflow.com/questions/3205256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62571/"
] | I figured out the problem. It was due to a field in the database being `null` where it should not have been permitted. This was due to me editing it by hand. After I added a value to that field, the problem went away. | One reason could be that the "id" field has not been correctly marked as the id for the User entity. |
58,042,010 | I'm trying to display "Number not found" when i input a number that is not in the list ...
I can't figure out what is wrong with the code.
my code:
```
import java.util.*;
public class Searchu {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int [][] x = new int [1][5];
int k , z=0 , y , item , item1 ;
System.out.println( "Enter 5 numbers: ");
for ( y= 0 ; y < 5 ; y++)
for ( z =0 ; z < 1 ; z++)
x[z][y] = console.nextInt();
System.out.println( "Search Number: ");
k = console.nextInt();
for ( item= 0 ; item < 5 ; item++) {
for ( item1= 0 ; item1 < 1 ; item1++) {
if (x[item1][item] == k) {
System.out.println( " Position: "+ (item+1));
break;
}}}
if (x[z][y] == 5)
System.out.print("Number not found...");
}}
``` | 2019/09/21 | [
"https://Stackoverflow.com/questions/58042010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12099992/"
] | Your error was the last checking. I added a flag about whether we found the number. I agree with the comments, you do not need to use 2D array.
```
public static void main(String[] args) {
int[][] x = new int[1][5];
int k, z = 0, y, item, item1;
System.out.println("Enter 5 numbers: ");
for (y = 0; y < 5; y++)
for (z = 0; z < 1; z++)
x[z][y] = console.nextInt();
System.out.println("Search Number: ");
k = console.nextInt();
boolean isFound = false;
for (item = 0; item < 5; item++) {
for (item1 = 0; item1 < 1; item1++) {
if (x[item1][item] == k) {
System.out.println(" Position: " + (item + 1));
isFound = true;
break;
}
}
}
if (!isFound)
System.out.print("Number not found...");
}
```
If you use a one-dimensional array, your code will look like this:
```
public static void main(String[] args) {
int[] array = new int[5];
int target;
System.out.println("Enter 5 numbers: ");
for (int i = 0; i < 5; i++) {
array[i] = console.nextInt();
}
System.out.println("Search Number: ");
target = console.nextInt();
boolean isFound = false;
for (int i = 0; i < 5; i++) {
if (array[i] == target) {
System.out.println("Position: " + (i + 1));
isFound = true;
break;
}
}
if (!isFound) {
System.out.print("Number not found...");
}
}
``` | With the "break" you are exiting only from the second for loop,please try the below code.
```
import java.util.*;
public class Searchu {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int [][] x = new int [1][5];
int k , z=0 , y , item , item1,pos=0 ;
boolean flag=false;
System.out.println( "Enter 5 numbers: ");
for ( y= 0 ; y < 5 ; y++)
for ( z =0 ; z < 1 ; z++)
x[z][y] = console.nextInt();
System.out.println( "Search Number: ");
k = console.nextInt();
for ( item= 0 ; item < 5 ; item++) {
for ( item1= 0 ; item1 < 1 ; item1++) {
if (x[item1][item] == k) {
flag=true;
pos=item+1;
}}}
if(flag)
{
System.out.println( " Position: "+ (pos));
}
else
{
System.out.print("Number not found...");
}
}}
``` |
7,327,497 | I dont want to use the "loop" related keyword, how can I implement loop with basic sql command in oracle ?
I have two table :
```
A:
ID, Color
B,
ID, AID, Type
```
I want to loop all records in B, and if ID = AID, then set the A.Color = B.Type
Thanks in advance ! | 2011/09/07 | [
"https://Stackoverflow.com/questions/7327497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140899/"
] | An alternate method:
```
MERGE INTO a
USING b
ON (b.aid = a.id)
WHEN MATCHED THEN UPDATE SET a.color = b.type;
``` | To do that you will have to write a stored procedure using PL/SQL. [Here](http://www.oracle.com/technetwork/database/features/plsql/index.html) is the oracle page with some info and papers on the topic. |
57,571,402 | I'm trying to do conditional formatting with a vlookup. The problem is that I don't know how to skip the first occurrence of the vlookup if the value that the vlookup is not the one that I want.
For example :
```
a 5
b 2
c 9
a 3
d 4
```
Here is a table I'm looking in column A the value 'a' but if the value in column B is not '3' then I want to check the second occurrence of the value 'a' then it rechecks if the value in column B is equal to '3'.
I don't know if I'm clear but any help is welcome. Thank you!
I also tried the combo index and match. | 2019/08/20 | [
"https://Stackoverflow.com/questions/57571402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703952/"
] | ### its not value - its [input-value](https://github.com/vuetifyjs/vuetify/blob/f55071368fe0bc99d6bda8538ccfa83875c8df63/packages/vuetify/src/mixins/selectable/index.ts#L20)
```js
new Vue({
el: '#app',
data(){
return {
t:false
}
},
methods: {
change(){
console.log("change");
this.t=!this.t;
}
},
vuetify: new Vuetify(),
})
```
```html
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@3.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<div id="app">
<v-app>
<v-content>
<v-switch :input-value="!t" @change="change">Hello world</v-switch>
</v-content>
</v-app>
</div>
```
but you can also define `false` as truish
=========================================
```js
new Vue({
el: '#app',
data(){
return {
t:false
}
},
vuetify: new Vuetify(),
})
```
```html
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@3.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<div id="app">
<v-app>
<v-content>
<v-switch v-model="t" :false-value="true" :true-value="false">Hello world</v-switch>
</v-content>
</v-app>
</div>
```
### but this breaks [colors](https://github.com/vuetifyjs/vuetify/blob/f55071368fe0bc99d6bda8538ccfa83875c8df63/packages/vuetify/src/mixins/selectable/index.ts#L38) - [imo a bug](https://github.com/vuetifyjs/vuetify/issues/8629) | Decompose `model` on `value` and `change` and reverse the algorithm, like this:
```
<v-switch :value="!mute" @change="(v) => mute = !v" :label="`Switch mute: ${mute.toString()}`"></v-switch>
```
**v-model & reversed**
```
<div id="app">
<v-app id="inspire">
<v-container fluid>
<v-switch v-model="mute" :label="`Switch mute: ${mute.toString()}`"></v-switch>
<v-switch :value="!mute" @change="(v) => mute = !v" :label="`Switch mute reversed: ${mute.toString()}`"></v-switch>
</v-container>
</v-app>
</div>
<script>
new Vue({
el: '#app',
data () {
return {
mute: true
}
}
})
</script>
```
**For an Array**
```
<div id="app">
<v-app id="inspire">
<v-container fluid>
<div v-for="(sound, index) in sounds" :key="index">
<v-switch v-model="sound.mute" :label="`Switch mute of ${sound.name}: ${sound.mute.toString()}`"></v-switch>
<v-switch :value="!sound.mute" @change="(v) => sound.mute = !v" :label="`Switch mute of ${sound.name} reversed: ${sound.mute.toString()}`"></v-switch>
</div>
</v-container>
</v-app>
</div>
new Vue({
el: '#app',
data () {
return {
sounds: [{name:'first', mute: true}, {name:'second', mute: true}]
}
}
})
```
Live example: <https://codepen.io/andriykuba/pen/abomQYe> |
24,107,234 | I have a dataset on excel with more than 40k entries, and there are 2 columns.
I want to find if there exists an entry for example with 1 in the first column and 1687 in the second column, I tried using this following IF function:
=IF(COUNTIF(B2:B178,"1687"),"Yes","No)
where A1:A178 have 1 in the first column.
This function works perfectly alright, however in terms of selecting the range for Countif, it requires much work as sometimes the range i have is more than 3 to 4k. This is way too time consuming as I have to repeat this search for many pairs of numbers.
I then tried by adding a helper column, where the 1st entry would be "=A2&B2"
My plan was to search this entire helper column for "11687" instead, however this fails to identify entries where it has 1 in the first column, 1687 in the second, and 11 in the first column, and 687 in the second column.
Ideally if the "find" function (Ctrl+F) could find 2 columns for different values it will be exactly what I need.
Could anyone please advise me on how to do this search?
Thank you very much! | 2014/06/08 | [
"https://Stackoverflow.com/questions/24107234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3719861/"
] | Try this formula and fill it all the way down, should be more efficient than `COUNTIF`:
```
=IF(AND($A1="1",$B1="1687"),TRUE,FALSE)
```
Then you have a column of `TRUE`/`FALSE` that you can use to do what you want. | Change your range into a table and use built in Excel filtering capabilities. See <http://office.microsoft.com/en-001/excel-help/filter-data-in-a-range-or-table-HP010073941.aspx#BMfilter_text> |
51,609,953 | I have a method that receives a format string and a set of values provided by a user, and uses these to write an output to a screen.
```
def makestring(fmt, vals):
s = fmt.format(*vals)
return s
fmt_expecting_three = 'a={:0.2f}, b={:0.4f}, c={:0.1f}'
threevalues = [(x+1)/7. for x in range(3)]
makestring(fmt_expecting_three, threevalues)
```
produces
```
'a=0.14, b=0.2857, c=0.4'
```
I would like to perform a test to discover the number of values matches what the format is "expecting".
I show an ugly test below, that can give incorrect results if you don't set `maxcheck` high enough. Is there a more natural, less ugly way to find out how many values are expected?
```
def checkit(fmt, maxcheck=None):
if maxcheck == None:
maxcheck = 10
for i in range(maxcheck-1, 0, -1):
try:
fmt.format(*range(i))
except:
return i+1
fmt_expecting_three = 'a={:0.2f}, b={:0.4f}, c={:0.1f}'
checkit(fmt_expecting_three)
```
returns
```
3
``` | 2018/07/31 | [
"https://Stackoverflow.com/questions/51609953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3904031/"
] | Though learning regex is painful, it pays off!
Modified from <http://www.rexegg.com/regex-cookbook.html>
```
things = ['pi={:0.2f}, e={:0.4f}', 'pi={:0.2f}, e={q', '{{}',
'{}wow', 'wow', '{}'] # includes some pathologicals
import re
for thing in things:
print len(re.findall('{([^{)]*)}', thing)), thing
```
returns
```
2 pi={:0.2f}, e={:0.4f}
1 pi={:0.2f}, e={q
1 {{}
1 {}wow
0 wow
1 {}
```
yay! | For something like this, I tend to look at the way the Python interpreter solves the problem, rather than reinventing the wheel.
I found a [C function in python 3](https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Python/modsupport.c#L43) called `countformat()`. (This also [looks about the same in Python 2.7](https://github.com/python/cpython/blob/2.7/Python/modsupport.c#L110).)
Next step would be to see if this function is exposed, or is strictly C. I did a [code search](https://github.com/python/cpython/search?q=countformat&unscoped_q=countformat). It looks like the answer is no, so I'd probably just copy whatever they did but do it in Python instead. It might be more efficient to write a regular expression, but that C function at least gives you an idea of how to define your regex.
The general algorithm is as follows:
* Set level to 0 and count to 0.
* Iterate through the format string. For each character:
* If you encounter an opening format marker `(`, `[`, `{`:
+ If level is 0, increment count.
+ Increment level.
* Else if you encounter a closing format marker `)`, `]`, `}`:
+ If level is 0, decrement count.
+ Decrement level.
* Else if you find some other marker `#`, `&`, `:`, , `\t`:
+ Do nothing.
* Else (some other character):
+ If level is 0, increment count.
* Return count. |
14,890,911 | In my custom control I have 2 textboxes. When either one of them is focused, it changes its style slightly... it looses a bit of its border. I would like to prevent this behaviour, which seems to be default textbox behaviour.
Now, I assume that its something to do with the style, possibly with the part of the textbox template
```
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
```
However, is there anyway to prevent this? | 2013/02/15 | [
"https://Stackoverflow.com/questions/14890911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1051751/"
] | @Daniel You have to edit `Focussed State StoryBoard`. For that edit your `TextBox Template` for changing the State.If you have `Expression Blend` it will be easy for you. | You have to edit the default `TextBox ControlTemplate` which you can find [here](http://msdn.microsoft.com/en-us/library/ms752068%28v=vs.85%29.aspx). |
96,568 | How do the statements *if p then q* and *p only if q* compare | 2023/01/31 | [
"https://philosophy.stackexchange.com/questions/96568",
"https://philosophy.stackexchange.com",
"https://philosophy.stackexchange.com/users/64529/"
] | In simple cases at least, "if p, then q" and "p only if q" have the same truth conditions. But this is not the same as saying that they mean the same thing.
Typically with conditionals, the antecedent is logically, epistemologically or temporally prior to the consequent. David Sanford, in his book "If P then Q" gives an example of the difference as follows:
1. If you learn to play the cello, I'll buy you a cello.
2. You'll learn to play the cello only if I buy you a cello.
In both cases, what is ruled out is you learning to play cello and me not buying you one. But the first suggests by implicature that if you first learn the cello I'll buy you one, while the second suggests that me buying you a cello is a precondition of you learning it. | **How does "if p, then q" compare to "p only if q"?**
"If p, then q" says that there is *at least* one event p that will result in event q. "p only if q" says that there is *exactly* one event q that will result in event p.
The difference is important to analyzing statements for fallacies. In the first example, "if not-p, then not-q" is fallacious. The problem is *denying the antecedent*; the terms of the if-then statement also allow for events x, y, or z to result in event q.
However, in the second example, "if not-q, then not-p" is valid; here, q is the only event in the world that will result in event p. Once q is negated, then so is p. |
1,454,896 | I have php condition basically static if the page is "biz-los-angeles.php" show specific html. I would like to add another condition for example "retail-biz-los-angeles.php". What would be the easiest way to do this. Basically i just want to script to pick up "retail" text at the beginning of the url and return specific html. Below is the code to do this but would be too cumbersome to go over each city.
```
<?php
$currentpage = basename($_SERVER['SCRIPTNAME']);
if ($currentpage == 'retail-biz-los-angeles.php')
echo 'HTML ';
else if ($currentpage == 'biz-los-angeles.php')
echo 'HTML';
?>
``` | 2009/09/21 | [
"https://Stackoverflow.com/questions/1454896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can check something like this:
```
if (strpos($currentpage, 'retail-') === 0))
...
```
Depending on your server / CMS / whatever you might also consider using mod\_rewrite.
```
RewriteRule ^retail-(.*)$ $1?retail=1 [L,QSA]
```
This would give you `$_GET['retail'] == 1` on the retail pages. | you could make it more robust by making a switch statement. I haven't tested the code, but something like the following would make it easier to maintain.
```
$currentpage = basename($_SERVER['SCRIPTNAME']);
$pageParts = explode('-',$current_page);
$section = $pageParts[0];
switch($section){
case 'biz':
echo 'BIZ';
break;
case 'retail':
echo 'Retail';
break;
default:
echo 'catchall';
break;
}
``` |
68,980,539 | I basically have the below code:
// To identify the Active Spreadsheet and link to Google Calendar
```
function scheduleNotifications(){
var sheet = SpreadsheetApp.getActiveSheet();
var eventCal = CalendarApp.getCalendarById("xyz@gmail.com");
```
// To identify the rows and columns to collect the data from
```
var notifications = spreadsheet.getRange("B2:D1000").getValues();
for (x=0; x<notifications.length; x++) {
var shift = notifications[x];
var startTime = shift[0];
var endTime = shift[];
var tag = shift[2];
```
// To create the event:
```
eventCal.createEvent(tag, startTime, endTime);
}
```
But the above doesn't work as there is no data in any of the rows from 9 onwards
However I want to get the script to collect data from these rows if they do become populated once I share with my team
Any suggestions? | 2021/08/30 | [
"https://Stackoverflow.com/questions/68980539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16784981/"
] | *Edit: As the comment by user Botje detailed, C++ doesn't recognise files, only code. I realise I've said things like "main file" which are practically correct, but technically wrong.*
Whichever file contains the `main()` function will run as the main file, so if you only want the second file to run, put the main function in the second file. The other file will only have an effect on the program if it is referenced in some way, so check for any ways the first file is referenced by the second file at all (things like the second file including a header that is implemented in the first file).
I'm not sure why you want to do this at all, though. The above should work but if I were you, I would just either delete the first file if it's never being used, or delete the section of code that I never want to be run. You could just comment out all the code that you don't want to use if you want to keep it. | As the previous comments by @JackBennett and @MSalters suggests,
The C++ projects should have **one main function** from where the execution would start.
But I have come across situations where I had to compile a library separately, *which I guess you are referring here*, so you can check [this post [Compile .so in Windows]](https://stackoverflow.com/questions/4630109/compile-so-in-windows) for some help.
Again, C++ program, in VS should be viewed as project instead of files with proper file structure for clarity and re-usability. And thus programmer should ensure one entry point (i.e. main function) and include relative header files and libraries being used appropriately. |
39,603,449 | Images with examples of the problem: <http://imgur.com/gallery/vmMyk>
Hi,
I need some help with rendering 2D objects in 3D scene with 3D camera. I think I managed to solve 2D coordinates with LH world coordinates. However, my rendered 2D objects are in a correct place, only when camera is at `[0.0f, 0.0f, 0.0f]` coordinates. In every other position, the location of 2D objects on scene is malformed. I think my matrices are screwed up, but don't know where to look further. I'd appreciate good ideas, please comment if something's missing for you, I'll edit the main post to provide you more information.
I'm using simple 3D color HLSL (VS and PS ver: 4.0) shader with alpha blending for the bigger triangle:
```
cbuffer ConstantBuffer : register( b0 )
{
matrix World;
matrix View;
matrix Projection;
}
struct VS_INPUT
{
float4 Pos : POSITION;
float4 Color : COLOR;
};
struct PS_INPUT
{
float4 Pos : SV_POSITION;
float4 Color : COLOR;
};
PS_INPUT VS ( VS_INPUT input )
{
PS_INPUT output = (PS_INPUT)0;
input.Pos.w = 1.0f;
output.Pos = mul ( input.Pos, World );
output.Pos = mul ( output.Pos, View );
output.Pos = mul ( output.Pos, Projection );
output.Color = input.Color;
return output;
}
float4 PS ( PS_INPUT input ) : SV_Target
{
return input.Color;
}
```
That's my Vertex data struct:
```
struct Vertex
{
DirectX::XMFLOAT3 position;
DirectX::XMFLOAT4 color;
Vertex() {};
Vertex(DirectX::XMFLOAT3 aPosition, DirectX::XMFLOAT4 aColor)
: position(aPosition)
, color(aColor)
{};
};
```
Render call for object:
```
bool PrimitiveMesh::Draw()
{
unsigned int stride = sizeof(Vertex);
unsigned int offset = 0;
D3DSystem::GetD3DDeviceContext()->IASetVertexBuffers(0, 1, &iVertexBuffer, &stride, &offset);
D3DSystem::GetD3DDeviceContext()->IASetIndexBuffer(iIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
D3DSystem::GetD3DDeviceContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
return true;
}
```
Draw call with initialization:
```
static PrimitiveMesh* mesh;
if (mesh == 0)
{
std::vector<PrimitiveMesh::Vertex> vertices;
mesh = new PrimitiveMesh();
DirectX::XMFLOAT4 color = { 186 / 256.0f, 186 / 256.0f, 186 / 256.0f, 0.8f };
vertices.push_back({ DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f), color });
vertices.push_back({ DirectX::XMFLOAT3(0.0f, 600.0f, 0.0f), color });
vertices.push_back({ DirectX::XMFLOAT3(800.0f, 600.0f, 0.0f), color });
mesh->SetVerticesAndIndices(vertices);
}
// Getting clean matrices here:
D3D::Matrices(world, view, projection, ortho);
iGI->TurnZBufferOff();
iGI->TurnOnAlphaBlending();
mesh->Draw();
XMMATRIX view2D = Camera::View2D();
iColorShader->Render(iGI->GetContext(), 3, &world, &view2D, &ortho);
iGI->TurnZBufferOn();
```
These are my 2D calculations for camera:
```
up = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
lookAt = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
rotationMatrix = DirectX::XMMatrixRotationRollPitchYaw(0.0f, 0.0f, 0.0f); // (pitch, yaw, roll);
up = DirectX::XMVector3TransformCoord(up, rotationMatrix);
lookAt = DirectX::XMVector3TransformCoord(lookAt, rotationMatrix) + position;
view2D = DirectX::XMMatrixLookAtLH(position, lookAt, up);
```
I'll appreciate any help.
Kind regards. | 2016/09/20 | [
"https://Stackoverflow.com/questions/39603449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408335/"
] | Well, I fixed my problem. For some weird reason, DirectXMath was generating false XMMATRIX. My `XMMatrixOrtographicLH()` was completely incorrect for good parameters. I solved my problem with classic definition of Ortohraphic matrix, [found in this article](http://www.codinglabs.net/article_world_view_projection_matrix.aspx) (definition in Fig. 10)
```
auto orthoMatrix = DirectX::XMMatrixIdentity();
orthoMatrix.r[0].m128_f32[0] = 2.0f / Engine::VideoSettings::Current()->WindowWidth();
orthoMatrix.r[1].m128_f32[1] = 2.0f / Engine::VideoSettings::Current()->WindowHeight();
orthoMatrix.r[2].m128_f32[2] = -(2.0f / (screenDepth - screenNear));
orthoMatrix.r[2].m128_f32[3] = -(screenDepth + screenNear) / (screenDepth - screenNear);
``` | galop1n give a good solution but on my system
`cbuffer ConstantBuffer : register( b0 ) {
float2 rcpDim; // 1 / renderTargetSize
}`
NEED to be a multiple of 16 for made like here:
```
struct VS_CONSTANT_BUFFER
{
DirectX::XMFLOAT2 rcpDim;
DirectX::XMFLOAT2 rcpDim2;
};
// Supply the vertex shader constant data.
VS_CONSTANT_BUFFER VsConstData;
VsConstData.rcpDim = { 2.0f / w,2.0f / h};
// Fill in a buffer description.
D3D11_BUFFER_DESC cbDesc;
ZeroMemory(&cbDesc, sizeof(cbDesc));
cbDesc.ByteWidth = sizeof(VS_CONSTANT_BUFFER);
cbDesc.Usage = D3D11_USAGE_DYNAMIC;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
cbDesc.MiscFlags = 0;
cbDesc.StructureByteStride = 0;
// Fill in the subresource data.
D3D11_SUBRESOURCE_DATA InitData;
ZeroMemory(&InitData, sizeof(InitData));
InitData.pSysMem = &VsConstData;
InitData.SysMemPitch = 0;
InitData.SysMemSlicePitch = 0;
// Create the buffer.
HRESULT hr = pDevice->CreateBuffer(&cbDesc, &InitData,
&pConstantBuffer11);
```
or aligned
```
__declspec(align(16))
struct VS_CONSTANT_BUFFER
{
DirectX::XMFLOAT2 rcpDim;
};
``` |
29,286,882 | I have a few activities and can't figure out a way to make it work with the backstack.
Is there a way to do this:
MainActivity ->(intent) subActivity ->(intent)subsubActivity->(back press)subActivity->\*(back press)MainActivity
\*This is where I am having problems. Since I am coming from my subsubActivity, even thought I used android:noHistory="true" in the manifest, it doesn't go back to main activity.
Thanks for any help! | 2015/03/26 | [
"https://Stackoverflow.com/questions/29286882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4451244/"
] | This is a perfect candidate for using a combination of `startActivityForResult` and overriding `onActivityResult` in the calling `Activity`.
Assuming you have `Activity A`, which starts `Activity B` (which we cannot move back to), which starts `Activity C`:
`Activity A` will call `Activity B` the way you are now. `Activity B`, however, will call `startActivityForResult(Intent, int)` instead of just `startActivity(Intent)`. This way, when we return from `Activity C`, we can call `finish()` on `Activity B` and return to `Activity A`, like so:
```
public class ActivityB extends Activity {
private static final int REQUEST_CODE_ACTIVITY_C = 1001;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE_ACTIVITY_C) finish(); // If coming back from Activity C, finish()
}
private void openActivityC(){
Intent intent = new Intent(this, ActivityC.class);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_C);
}
}
```
Now when you call `openActivityC()`, you're ensuring that `onActivityResult()` will be called when returning from `Activity C`, thus allowing you to end the `Activity` and return back to `Activity A`.
You can provide even more specific actions (such as setting/checking the result code (e.g. if it canceled (`Activity.RESULT_CANCELED`) or successful (`Activity.RESULT_OK`)) for statuses, to better determine what that calling `Activity` should do.
Hopefully that helps explain it a bit.
Edit: Also an afterthought, if there's no chance you'll ever want to go back to Activity B, then @Kay 's solution of just calling finish() after firing the Intent for Activity C would be the simplest approach. | If i get what you want You can use [startActivities](http://developer.android.com/reference/android/content/Context.html#startActivities(android.content.Intent[])) with an array of intents which will be fired one after another activity1->activity2->activity3 -back-activity2 -back-acitivty1 |
29,326,666 | I am planning to have a web application.
To do so, I studied about ruby and ruby on rails. I am using linux server from amazon clouding system.
I bought a domain from godday, and I put the IP address on DNS setting. When I run 'rails s' command, I can connect to the wep page through port 3000 in such a way that domain.com:3000. However, I cannot directly connect to domain.com. How can I my domain works without port 3000?
And Do I have to run 'rails s' every time to make the wep page work? Actually I tried to use 'rails s &' to make it run in background. But it fails. How can I make the server run even though I am not connected to the linux server?
Thank you! | 2015/03/29 | [
"https://Stackoverflow.com/questions/29326666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358807/"
] | **EDIT 2017** - *With **XAMLC** (XAML-Compiler, read more [here](https://developer.xamarin.com/guides/xamarin-forms/xaml/xamlc/)) XAML is compiled to IL code at **build time** so no XAML parsing is involved at runtime anymore. In many cases this makes XAML as fast or very close to coding the UI in code-behind C#. With the latest improvements in XAML compilation, there is now **strongly typed** data binding (read more [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/compiled-bindings)), which is faster and the data binding errors are caught during **build time**. Some errors in XAML are caught at **design time**, when you edit the XAML in the Visual Studio XAML editor*
I assume you're asking about Xamarin Forms.
It would be interesting if you could mention the reasons why you heard XAML is bad.
~~The only reason I would think that someone could discourage you from using XAML is performance.~~
~~I came across some posts on Xamarin Forms talking about performance issues when using XAML for creating some of the UI with Xamarin Forms.
But given than Xamarin Forms is an early technology, I guess these issues are temporary and will be fixed.~~
I don't agree declarative UI (XAML) vs coded UI is just a matter of personal taste.
A declarative UI (today is XAML, tomorrow it can be something else) can be a better approach than doing the UI by code, for the following reasons:
* **It's coincise, it's impersonal**. Except few things, XAML looks the same for everyone. You can't say the same thing about actual code, which is more verbose, there are methods called, variables declared, etc.
* **It's more maintainable**. It's easier to read and modify than actual code.
* It helps with a **clear separation of concerns**, between the UI and logic. Same thing can be achieved without XAML, but just by using XAML you are closer to this goal.
* **Tooling friendly**. ~~Unfortunately Xamarin Forms today still doesn't have a previewer or designer, but this is supposed to change~~ There is a XAML Previewer baked-in in Visual Studio when you edit XAML, but it still doesn't work 100%. See more about Xamarin Forms XAML Previewer [here](https://blog.xamarin.com/live-xaml-previewing-with-the-xamarin-forms-previewer/) and [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-previewer?tabs=windows)
I am NOT saying XAML is perfect. But I think it's better than manually coding the UI. XAML uses same C# classes and properties of controls. The XAML syntax is the same with XML, because actually all XAML documents are valid XML documents. XAML is based on XML.
When someone says XAML is bad, I can't help thinking about HTML. Is HTML bad too? Is it better to create HTML elements in Javascript? Obviously it's not.
I know some will say you can't really compare XAML vs HTML because XAML is not as "native" as HTML, but aren't both just related to the presentation layer?
Xamarin (now Microsoft) has some nice introduction to XAML you can read [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/xaml/).
I think developers with native iOS background have a strong inclination towards not using a declarative UI because that's how unfortunately native iOS development mostly works. You are forced to use code to implement different things which are not available in the designer and there's no native declarative UI markup language available(there's one but the format is not public and it's not meant to be directly modified).
You might know this by now but Xamarin Forms is not the only way to build apps with Xamarin. **Xamarin != Xamarin Forms**.
You can build your UI natively and still share the logic (ViewModels, services, etc). On Android, you can build your UI in the AXML. You will get as closer to the metal you can get with Xamarin with that. But you will need data-binding, so a framework like MvvmCross can help with that. | In my opinion, and it's definitely just an opinion, I prefer to have a almost zero lines of code in a code behind class, where all the definitions of the view will residue in the Xaml file only.
This way, you'll **separate the UI from your code logic** and will probably have a much cleaner code eventually.
Having said that, Xamarin forms is still very young framework, and many times I've encountered in plugins that don't have support for Xaml, so I had to manipulate the UI using the code behind, but I do it only as a last resort. |
6,092 | How can I find out what my AUCTeX version is? I have Googled this question to no avail. | 2015/01/06 | [
"https://emacs.stackexchange.com/questions/6092",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/4084/"
] | It is contained in the `AUCTeX-version` variable:
```
C-h v AUCTeX-version RET
``` | If you installed AUCTeX from ELPA (which I generally recommend), then `M-x list-packages` will give you that information (the good thing about this method, is that it works for all packages installed from ELPA). |
14,382,636 | I have two questions:
1. How can I force IE10 to render in IE9 document mode? Currently it's rendering my page in Standard document mode.
2. In IE10's developer toolbar, I am not able to see the option of document mode of IE10. Is it not implemented, or is my browser version is out of date?
Thanks for all your help.
---
Edit: thanks everyone for the solutions provided. Earlier I was using a meta tag
`<meta http-equiv="x-ua-compatible" content="IE=edge" >`
just to make sure that IE will render the page in highest document mode, but I was facing some issues with IE10 standard mode, so I changed the meta tag to render the page in IE9 mode:
`<meta http-equiv="x-ua-compatible" content="IE=9" >`. | 2013/01/17 | [
"https://Stackoverflow.com/questions/14382636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/739658/"
] | You can force IE10 to render in IE9 mode by adding:
`<meta http-equiv="X-UA-Compatible" content="IE=9">`
in your `<head>` tag.
See [MSDN](http://msdn.microsoft.com/en-us/library/ie/ms533876%28v=vs.85%29.aspx) for more information... | there are many ways can do this:
add X-UA-Compatible
tag to head
http response header
using IE tools F12
change windows Registry |
65,636 | I've got a message from a peer programmer (over a conflict happened due to his changes in the code I'm responsible for, done over my head). He wrote that they (he and PM) already decided to do it this way, aren't going to change anything and my opinion means nothing. That guy is in the same position, and I wasn't told about any promotions. The PM is elusive and I couldn't get any certain statements from him.
Any ideas how to resolve this situation? Because I see only 2 solutions - bow or resign, and I don't like either.
UPD I wasn't told about any problems on my side before this happened. These changes don't address any specific problems, it's just a "slight refactoring". The problem is that this refactoring is not small at all, and it breaks things.
UPD2 this question is not about a senior colleague. It's about a peer.
UPD3 so, I talked to the manager and explained him that the situation when another guy rewrites my code without asking me anything is not how the things should be done. However, if he really wants to keep his changes - he has to take full responsibility for the project from now on. Some time later, I was kicked out of the company "in a process of working teams optimization". | 2016/04/21 | [
"https://workplace.stackexchange.com/questions/65636",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/22134/"
] | I get you are getting beat up over this but I would consider quitting also.
In summary
----------
* Code you are responsible for
* You had not been informed of any problems
* Peer meets with PM over refactoring code you are responsible for
You are not included nor informed
* According to peer an executive decision is made to refactor the code you are responsible for
You are not included in this decision
* You are informed of the executive decision by peer not PM
**At a minimum this executive decision should have come from the PM**
* The change is characterized as "slight refactoring"
In the opinion of the OP responsible for the code it is not slight and breaks a lot of stuff
This not proper. If you are responsible for the code then you deserve to be part of design decision. Even if you are shot down on every detail you should have a say. If they characterize as "slight refactoring" and you say it is not slight and breaks stuff then clearly there is a major disconnect. At a minimum they should explain to you how this "slight". Maybe you are missing something and maybe they are wrong. This is not how to manage a software team. This not how to manage software design.
You have couple problems:
1. Change is not minor
2. Process going forward
On the first I would outline in writing that the change is not minor. Outline how it effects the code overall and the stuff it would break. Ask for a meeting to discuss the matter.
On the second you need to have a heart to heart with the PM. Tell him straight up you think you deserve to be involved in design decisions regarding your code. If he tells you no I will make executive decision and may or may not include you then just tell him don't agree that is effective but you will follow orders. From there make a decision to suck it up look for another job. If the PM refuses to even have a process meeting with you then need to make a decision to suck it up or look for another job. Don't threaten to quit - nothing good would come from that. I personally would look for another job. I don't mind losing an architecture decision about code I am responsible for but I feel like I deserve to be part of the discussion. | I want to stress something: You need to cover your \*ss in writing. Compose an email (yes, email, not an IM that can go away) officially stating that 1) The code change was done by your colleague, 2) That it breaks the product, 3) That in your professional opinion the change should be reverted. You need to get all of this on the record now, because it sounds like poop will hit the fan and you will get blamed. Do not revert the code without permission. Just go on the record with the above info. Then you have performed due diligence.
EDIT: Also seriously consider 2A) The code was apparently not tested. In this day & age, you do not test in Production, you test in UAT/Dev. If your colleague had tested in Production where I work, he'd be in big trouble. |
10,633,628 | We have a time management system where our employees or contractors (resources) enter the hours they have worked, and we derive a cost for it. I have a table with the historic costs:
```
CREATE TABLE ResourceTimeTypeCost (
ResourceCode VARCHAR(32),
TimeTypeCode VARCHAR(32),
EffectiveDate DATETIME,
CostRate DECIMAL(12,2)
)
```
So I have one date field which marks the effective date. If we have a record which is
```
('ResourceA', 'Normal', '2012-04-30', 40.00)
```
and I add a record which is
```
('ResourceA', 'Normal', '2012-05-04', 50.00)
```
So all hours entered between the 30th April and the 3rd of May will be at £40.00, all time after midnight on the 4th will be at £50.00. I understand this in principle but how do you write a query expressing this logic?
Assuming my time table looks like the below
```
CREATE TABLE TimeEntered (
ResourceCode VARCHAR(32),
TimeTypeCode VARCHAR(32),
ProjectCode VARCHAR(32),
ActivityCode VARCHAR(32),
TimeEnteredDate DATETIME,
HoursWorked DECIMAL(12,2)
)
```
If I insert the following records into the TimeEntered table
```
('ResourceA','Normal','Project1','Management1','2012-04-30',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-01',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-02',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-03',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-04',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-07',7.5)
('ResourceA','Normal','Project1','Management1','2012-05-08',7.5)
```
I'd like to get a query that returns the total cost by resource
So in the case above it would be 'ResourceA', (4 \* 7.5 \* 40) + (3 \* 7.5 \* 50) = 2325.00
Can anyone provide a sample SQL query? I know this example doesn't make use of TimeType (i.e. it's always 'Normal') but I'd like to see how this is dealt with as well
I can't change the structure of the database. Many thanks in advance | 2012/05/17 | [
"https://Stackoverflow.com/questions/10633628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174045/"
] | ```
IF OBJECT_ID ('tempdb..#ResourceTimeTypeCost') IS NOT NULL DROP TABLE #ResourceTimeTypeCost
CREATE TABLE #ResourceTimeTypeCost ( ResourceCode VARCHAR(32), TimeTypeCode VARCHAR(32), EffectiveDate DATETIME, CostRate DECIMAL(12,2) )
INSERT INTO #ResourceTimeTypeCost
SELECT 'ResourceA' as resourcecode, 'Normal' as timetypecode, '2012-04-30' as effectivedate, 40.00 as costrate
UNION ALL
SELECT 'ResourceA', 'Normal', '2012-05-04', 50.00
IF OBJECT_ID ('tempdb..#TimeEntered') IS NOT NULL DROP TABLE #TimeEntered
CREATE TABLE #TimeEntered ( ResourceCode VARCHAR(32), TimeTypeCode VARCHAR(32), ProjectCode VARCHAR(32), ActivityCode VARCHAR(32), TimeEnteredDate DATETIME, HoursWorked DECIMAL(12,2) )
INSERT INTO #TimeEntered
SELECT 'ResourceA','Normal','Project1','Management1','2012-04-30',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-01',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-02',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-03',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-04',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-07',7.5
UNION ALL SELECT 'ResourceA','Normal','Project1','Management1','2012-05-08',7.5
;with ranges as
(
select
resourcecode
,TimeTypeCode
,EffectiveDate
,costrate
,row_number() OVER (PARTITION BY resourcecode,timetypecode ORDER BY effectivedate ASC) as row
from #ResourceTimeTypeCost
)
,ranges2 AS
(
SELECT
r1.resourcecode
,r1.TimeTypeCode
,r1.EffectiveDate
,r1.costrate
,r1.effectivedate as start_date
,ISNULL(DATEADD(ms,-3,r2.effectivedate),GETDATE()) as end_date
FROM ranges r1
LEFT OUTER JOIN ranges r2 on r2.row = r1.row + 1 --joins onto the next date row
AND r2.resourcecode = r1.resourcecode
AND r2.TimeTypeCode = r1.TimeTypeCode
)
SELECT
tee.resourcecode
,tee.timetypecode
,tee.projectcode
,tee.activitycode
,SUM(ranges2.costrate * tee.hoursworked) as total_cost
FROM #TimeEntered tee
INNER JOIN ranges2 ON tee.TimeEnteredDate >= ranges2.start_date
AND tee.TimeEnteredDate <= ranges2.end_date
AND tee.resourcecode = ranges2.resourcecode
AND tee.timetypecode = ranges2.TimeTypeCode
GROUP BY tee.resourcecode
,tee.timetypecode
,tee.projectcode
,tee.activitycode
``` | You might give this a try. [CROSS APPLY](http://riteshshah.wordpress.com/2009/03/03/cross-apply-and-outer-apply-clause-in-sql-server-2005/) will find first ResourceTimeTypeCost with older or equal date and same ResourceCode and TimeTypeCode as current record from TimeEntered.
```
SELECT te.ResourceCode,
te.TimeTypeCode,
te.ProjectCode,
te.ActivityCode,
te.TimeEnteredDate,
te.HoursWorked,
te.HoursWorked * rttc.CostRate Cost
FROM TimeEntered te
CROSS APPLY
(
-- First one only
SELECT top 1 CostRate
FROM ResourceTimeTypeCost
WHERE te.ResourceCode = ResourceTimeTypeCost.ResourceCode
AND te.TimeTypeCode = ResourceTimeTypeCost.TimeTypeCode
AND te.TimeEnteredDate >= ResourceTimeTypeCost.EffectiveDate
-- By most recent date
ORDER BY ResourceTimeTypeCost.EffectiveDate DESC
) rttc
```
Unfortunately I can no longer find article on msdn, hence the blog in link above.
[Live test @ Sql Fiddle](http://sqlfiddle.com/#!3/19d2c/5). |
29,248 | I have data for a test on three groups. The measured variable is ratio scaled. The R code is
```
g1a<-c(7, 3, 40)
g2a<-c(1,1,2)
g3a<-c(0,0,0)
```
Since the sample is small and normality cannot be guaranteed, I run a Kruskal Wallis test to check for significance:
```
l<-list(g1a,g2a,g3a)
kruskal.test(l)
```
The p-value is 0.02336, which is nice.
Now I run a post-hoc test, using the Mann-Whitney U:
```
wilcox.test(g1a,g2a,paired=FALSE,exact=TRUE)
wilcox.test(g2a,g3a,paired=FALSE,exact=TRUE)
wilcox.test(g1a,g3a,paired=FALSE,exact=TRUE)
```
All the resulting p-values are above 0.05 (0.07652, 0.0636, 0.05935). This is very strange. Shouldn't one of these tests give a much lower p-value? Especially since I'd have to use some sort of correction to account for the multiple comparisons in the post-hoc test. In other words: how can I interpret this result? | 2012/05/27 | [
"https://stats.stackexchange.com/questions/29248",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/1048/"
] | Your mistake is in choosing the Wilcoxon/Mann-Whitney rank-sum tests as your *post hoc* tests following the rejection of the Kruskal-Wallis. The appropriate *pos hoc* test is *Dunn's test*\* which properly (1) accounts for *pooled variance* assumed by the null hypothesis, and (2) uses *the same ranks* for your data as used in the construction of the Kruskal-Wallis test. The vanilla rank-sum tests entail separate estimates of variance for each pair-wise test, and ignore the rankings of the total data set as performed with a Kruskal-Wallis test.
Dunn's test is implemented for Stata in the [**dunntest**](https://alexisdinno.com/stata/dunntest.html) package (within Stata type `net describe dunntest, from(https://alexisdinno.com/stata)`), and for R in the [**dunn.test**](http://cran.r-project.org/web/packages/dunn.test/) package. Not sure about implementations in SAS.
**Reference**
Dunn, O. J. (1964). Multiple comparisons using rank sums. *Technometrics*, 6(3):241–252.
\* There are some far less used alternatives to Dunn's test including the Conover-Iman (like Dunn, but based on the *t* distribution, rather than the *z* distribution, implemented for Stata in the [**conovertest**](https://alexisdinno.com/stata/conovertest.html) package, and for R in the [**conover.test**](http://cran.r-project.org/web/packages/conover.test/) package), and the Dwass-Steel-Citchlow-Fligner tests.
The second issue, which arises even when using appropriate tests, is that you are making the false assumption that rejection of an omnibus null hypothesis means there must be at least one rejection of pairwise *post hoc* null hypothesis. | This is a well-known problem in two-stage comparisons, observed e.g., already by Gabriel [Gabriel KR (1969) Simultaneous test procedures - some theory of multiple comparisons.
The Annals Mathematical Statistics 40(1):224-250]. |
35,087,625 | This question is about HTTP *Request* headers -- not HTTP Response headers.
Is there any way to programmatically make User Agents add or change any HTTP Request Header e.g. by means of HTML, JavaScript, for links or resources from a web page. There exists some HTTP Request Headers that one would think should be able to be controlled programmatically, for example `max-stale`.
(One could for example imagine that some optional attribute for HTML-elements `<a>`, `<link>`, `<img>` `<script>` etc, could exist that would cause the User Agent to add/change a HTTP request header in its request to the server, but I have not found such an attribute. Similarly, one could think that there should exist some mechanism to control HTTP Request Headers when AJAX is used.)
Turning around the question ...: Why does the HTTP Request Header `max-stale` exist at all if it cannot be controlled?
Thanks! | 2016/01/29 | [
"https://Stackoverflow.com/questions/35087625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/977241/"
] | Thanks for your input. I have chosen to create the intervals using a simple loop, to ensure that the intervals were of the desired size.
I created a data.frame with sizes of chromosomes
```
chrSizes <- data.frame(chromosome = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "X", "Y"), length = c("249250621","243199373", "198022430", "191154276", "180915260", "171115067", "159138663", "146364022", "141213431", "135534747", "135006516", "133851895", "115169878", "107349540", "102531392", "90354753", "81195210", "78077248", "59128983", "63025520", "48129895", "51304566", "155270560", "59373566"), stringsAsFactors = FALSE)
```
Then I looped through each chromosome creating the intervals, by finding the precise chunk size and then rounding down. The remainder then was used to add one to the first many intervals.
```
numOfBins <- 10000
chrBinList <- list()
for (i in 1:24) {
chrBins <- c()
chrLength <- as.numeric(chrSizes[i,2])
chunkSize <- floor(chrLength/numOfBins)
remainder <- chrLength %% chunkSize
counter <- 1
# Adding remainder to the first intervals
for (j in 1:(remainder-1)) {
chrBins <- c(chrBins, counter)
counter <- counter + chunkSize + 1
chrBins <- c(chrBins, counter)
}
# Adding normal sized chunks to remaining intervals
for (k in remainder:numOfBins) {
chrBins <- c(chrBins, counter)
counter <- counter + chunkSize
chrBins <- c(chrBins, counter)
}
# Creating a data.frame with intervals
interval.df <- as.data.frame(matrix(chrBins,ncol = 2, byrow = TRUE))
colnames(interval.df) <- c("start", "end")
# Adding to list
chrBinList[[chrSizes[i,1]]] <- interval.df
}
```
As for testing whether values fall within the different bins, I have come up with a slow solution using apply. I am, however, currently look into the parallel apply functions. | If the bin range is constant, this works:
```
mydata <- data.frame(position = c(20000, 30000, 60000,
49850, 49851, 99700, 99701))
mydata$bin <- ceiling(mydata$position / 49850)
```
More generally, if the bin range is not constant but you have defined the cut points already, you can use `cut` by giving that as `breaks`.
```
cutpoints <- c(0, 49850, 99700, 149550)
mydata$bin2 <- cut(mydata$position, breaks = cutpoints)
```
You can edit your labels with a little tweak.
```
mydata$bin3 <- cut(mydata$position, breaks = cutpoints,
labels = seq(length(cutpoints)-1))
``` |
7,411,362 | For example if an error occurs inside the constructor (e.g. the parameters pass in were invalid) and I wanted to stop an object being created would it be possible to return null rather than a reference to a new object. (I know the term return is technically correct in this case but you know what I mean).Basically, is it possible to cancel object creation?
Please guide me to get out of this issue... | 2011/09/14 | [
"https://Stackoverflow.com/questions/7411362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/452680/"
] | Yes, you can throw an exception, which will terminate object creation. You cannot return null or any other value from a constructor. | If the parameters passed in are invalid, you should throw an `IllegalArgumentException` with a descriptive message. `NullPointerException` should be thrown in case of illegal `null` values.
Here's an example of a `BigCar` class that requires its engine to be > 4000 CC.
```
public class BigCar {
private final Engine engine;
public BigCar(Engine engine) {
if (engine == null)
throw new NullPointerException("Must provide an engine to our car");
if (engine.getCC() <= 4000)
throw new IllegalArgumentException(
"Engine should be bigger than 4000 CC");
this.engine = engine;
}
public static void main(String... args) {
// Size of engine is 2000CC
Engine engine = new Engine(2000);
BigCar myBigCar = new BigCar(engine); // Exception; Engine should be
// bigger than 4000 CC
}
}
``` |
7,550 | >
> I wonder why they are so late. They *should have* arrived a long time ago.
>
>
>
Does this sentence have two possible meanings? How would we choose between them?
>
> 1) I expected (predicted) their arrival would have taken place a long time ago.
>
>
> 2) It would have been better for them to arrive much earlier, maybe they have missed something at the party.
>
>
> | 2013/06/23 | [
"https://ell.stackexchange.com/questions/7550",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/1616/"
] | The ambiguity is real, but in practice will be overcome by context.
In the context of *I wonder why they are so late* the natural interpretation of *should* is *epistemic* referring to probability or expectation: your 1).
>
> I wonder why they are so late. They should have arrived long ago. I hope nothing's happened ...
>
>
>
But it in another context the natural interpretation might be *deontic*, referring to obligation or advisability: your 2).
>
> What a pity they're arriving now. They should have arrived a long time ago, when we were having fun. Now the party's started breaking up.
>
>
>
And then of course it's possible that *both* meanings are intended.
>
> What a pity they're so late. They should have arrived a long time ago, when the party was rocking. Gosh, you don't suppose something's happened to them?
>
>
> | Lots of words in English have multiple possible meanings. Usually you can tell which is meant from context. Usually the intended meaning is so obvious that the reader does not even pause to think about it, he just naturally infers the correct meaning. It is certainly true that writers sometimes slip up and have one meaning in mind, but write a sentence in which the intended meaning is not clear.
For example, the word "trunk" can mean, 1) the main body of a tree, 2) the storage compartment of a car, 3) a large suitcase, or 4) the nose of an elephant. If I wrote, "We went to the zoo where my children were delighted to see the elephant blow water out of his trunk", I don't think anyone would think for a moment that I am talking about the trunk of a car. But if I read, "Bob accidentally backed his car into a tree. The trunk was badly damaged", I'd guess the writer means that the trunk of Bob's car was damaged, but he might mean that the trunk of the tree was damaged. The sentence was poorly worded to leave such an ambiguity.
Many jokes are based on such ambiguities: The reader is set up to think that one meaning is intended and then suddenly an alternate meaning is sprung. Like:
>
> "My job requires me to travel a lot."
>
>
> "Oh, does your wife miss you much?"
>
>
> "No, she's got a deadly accurate overhand."
>
>
>
Or consider the delightful pair of sentences:
>
> Time flies like an arrow. Fruit flies like honey.
>
>
>
This throws you off because it uses a double ambiguity. In the first sentence, "flies" is a verb meaning "travels through the air"; in the second it is a noun referring to a type of bug. In the first sentence "like" is a preposition meaning "as" or "in the manner of". In the second it is a verb meaning "enjoy" or "favor". |
16,458,538 | I need to select a value from dropdown can some one help me on that. Html part is below
```
<div id="element11_chzn" class="chzn-container chzn-container-single" style="width: 320px;">
<a class="chzn-single" href="javascript:void(0)" tabindex="0">
<div class="chzn-drop" style="left: -9000px; width: 318px; top: 29px;">
<div class="chzn-search">`enter code here`
<ul class="chzn-results">
<li id="element11_chzn_o_1" class="active-result" style="">ActiveLearn Course</li>
<li id="element11_chzn_o_2" class="active-result" style="">ActiveLearn Player</li>
<li id="element11_chzn_o_3" class="active-result result-selected" style="">ActiveLearn Skin</li>
<li id="element11_chzn_o_4" class="active-result" style="">ActiveLearn Template</li>
<li id="element11_chzn_o_5" class="active-result" style="">Activity</li>
<li id="element11_chzn_o_6" class="active-result" style="">Animation</li>
<li id="element11_chzn_o_7" class="active-result" style="">Assessment</li>
<li id="element11_chzn_o_8" class="active-result" style="">Bookmarks</li>
<li id="element11_chzn_o_9" class="active-result" style="">Character</li>
<li id="element11_chzn_o_10" class="active-result" style="">Click to prompt</li>
<li id="element11_chzn_o_11" class="active-result" style="">Click to prompt override</li>
<li id="element11_chzn_o_12" class="active-result" style="">EBook</li>
<li id="element11_chzn_o_13" class="active-result" style="">Exercise</li>
<li id="element11_chzn_o_14" class="active-result" style="">Game</li>
<li id="element11_chzn_o_15" class="active-result" style="">Glossary</li>
<li id="element11_chzn_o_16" class="active-result" style="">Glossary Term</li>
<li id="element11_chzn_o_17" class="active-result" style="">Glossary Term</li>
<li id="element11_chzn_o_18" class="active-result" style="">Imported file</li>
<li id="element11_chzn_o_19" class="active-result" style="">Interactive activity</li>
<li id="element11_chzn_o_20" class="active-result" style="">Interactive page</li>
</ul>
</div>
```
I have to make it dynamic so I need to get the value from xls. | 2013/05/09 | [
"https://Stackoverflow.com/questions/16458538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2365661/"
] | This should work for you :
```
Select select = new Select(yourDropdownElement);
select.selectByVisibleText(text);
``` | ```
driver.findElement(By.id("element11_chzn")).click();
driver.findElement(By.id("element11_chzn_o_7")).click(); /*It will select 'Assessment' from drop down.*/
```
Hope it will help you. |
39,884 | I wish to know how to handle a certain situation regarding chess etiquette. Consider the following:
I went for an OTB tournament recently - rapid 15 + 10 time control. Organizers stated that recording is not compulsory, but I still recorded for the purpose of post-mortem analysis. One of my opponents didn't record the game himself but he asked me for a photo of my recording sheet after the game ended, which I had recorded on my own time during the game.
Should I let him take a photo or ask him to record his game himself if he wants to do post-mortem analysis? I let him take a photo but I feel a bit sour now, considering that it's pretty unfair that I spent some of my own time recording instead of thinking - or am I being a bit petty? Also we'll probably meet in some other tournament again just that he's in a better position to prepare against me now. | 2022/05/27 | [
"https://chess.stackexchange.com/questions/39884",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/30282/"
] | >
> Should I let him take a photo or ask him to record his game himself if he wants to do post-mortem analysis?
>
>
>
The [FIDE Laws of Chess](https://handbook.fide.com/chapter/E012018) say this about the ownership of the scoresheet:
>
> 8.3 The scoresheets are the property of the organiser of the competition.
>
>
>
and they say this about sharing the scoresheet:
>
> 8.5.2 If only one player has not kept score under Article 8.4, he must, as soon as either flag has fallen, update his scoresheet completely before moving a piece on the chessboard. Provided it is that player’s move, he may use his opponent’s scoresheet, but must return it before making a move.
>
>
>
So, you are not allowing your opponent to take a photo of *your* scoresheet, you are allowing your opponent to take a photo of the *organiser's* scoresheet for your game and there are certain events which can happen during the game which *require* you to share the scoresheet you are keeping.
Although the rules are silent on what happens after the game regarding sharing the scoresheet it would appear churlish to deny your opponent a photo. Arguably your opponent needs the permission of the organiser, the owner of the scoresheet, not you, in order to make a copy. | This is too long for a comment, but Brian Towers answer as it currently stands is legally wrong. It is true that the score sheets are property of the organizers. But the document you wrote during the game is not a score sheet as understood by the rules, these are just your personal notes that happen to have a form that is very similar to a score sheet.
Score sheets have to satisfy a whole bunch of rules on what is and isn't written there, how it is written and which notation has to be used. Your personal notes are not bound by any of these rules. You could have skipped a few moves, you could have written down some variant that wasn't actually played in the game, you could have used your personal notation, maybe you didn't even write down the game at all but rather some general impressions of the tournament. All of these things would get you in trouble on an official scoresheet. None of them matter on your personal notes.
What you wrote are your personal notes and you are free to do with them as you please.
All that being said, personally I would consider it impolite to not share them if the other player asks nicely. This is just information, you lose nothing by sharing but the other player gains something. |
18,175,098 | In ruby, there is a function called `gsub`, where g stands for `global` and sub stands for `substitution`.
What `p` from `preg_match`?
I suppose `reg` is for `regular` and `match` is really `match`. Is that correct? | 2013/08/11 | [
"https://Stackoverflow.com/questions/18175098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413494/"
] | It stands for [PCRE - Perl Compatible Regular Expressions](http://www.pcre.org/). | P stands for Perl in 'preg'.
They comes under Function list.[PCRE : Perl Compatible Regular Expressions](http://www.php.net/manual/en/ref.pcre.php) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.