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 |
|---|---|---|---|---|---|
30,868,288 | I have elements with class **.tab** and hover for them:
```
.tab:hover {
background-color: #A9E59E;
}
```
Now, I'm adding additional class to some of those element in JS:
```
this.classList.toggle('tab2');
```
the problem is, I do not wan't hover to fire on those elements with two classes
**classList.length > 1**.
Is there a way in CSS to exclude those elements with two classes, so that hover fires only on **.tab** class, and not on **.tab .tab2**
or I need to move all *hover logic* to JS? | 2015/06/16 | [
"https://Stackoverflow.com/questions/30868288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2933141/"
] | Try this syntax.
```
[class="tab"]:hover{
background-color: #A9E59E;
}
```
Which will select the class tab ,if it has other class attributes it wont get selected. | I would do something like this:
```
.tab.tab2:hover{
/*apply the same style as for the non hover element */
}
``` |
3,031,110 | How can I set default value for DateTime in optional parameter?
```
public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???)
{
//Init codes here
}
``` | 2010/06/13 | [
"https://Stackoverflow.com/questions/3031110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132917/"
] | There is a workaround for this, taking advantage of nullable types and the fact that `null` is a compile-time constant. (It's a bit of a hack though, and I'd suggest avoiding it unless you really can't.)
```
public void SomeClassInit(Guid docId, DateTime? addedOn = null)
{
if (!addedOn.HasValue)
addedOn = DateTime.Now;
//Init codes here
}
```
In general, I'd prefer the standard overloading approach suggested in the other answers:
```
public SomeClassInit(Guid docId)
{
SomeClassInit(docId, DateTime.Now);
}
public SomeClassInit(Guid docId, DateTime addedOn)
{
//Init codes here
}
``` | [.NET 4.0 does have optional parameters](http://msdn.microsoft.com/en-us/library/dd264739.aspx). ([google is also your friend](http://www.google.com.au/#hl=en&source=hp&q=optional+paramters+.net+4.0&aq=f&aqi=&aql=&oq=&gs_rfai=&fp=6754f67ee51d4c5b), here.)
EDIT (because of Anthony Pegram correct, comment)...
And yes, that is how you would do it.
But `DateTime.`*Now* (static property, on that class) is not know until *run-time*. As such, you can't use that as an optional *value*.
.NET 3.5 doesn't ... so then you would have to do what JS Bangs said...
```
public SomeClassInit(Guid docId)
{
return SomeClassInit(docId, DateTime.Now);
}
public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???)
{
//Init codes here
}
```
or even the null checking/null value parameter from munificent's answer.
Cheers Anthony. |
6,047,996 | I'm using the Jersey Client library to run tests against a rest service running on jboss.
I have https set up fine on the server (running on localhost), using a self signed cert.
However whenever I run my tests with the https url I get the following error:
```
com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:131)
at com.sun.jersey.api.client.Client.handle(Client.java:629)
at com.sun.jersey.oauth.client.OAuthClientFilter.handle(OAuthClientFilter.java:137)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:601)
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:459)
at test.helper.Helper.sendSignedRequest(Helper.java:174)
... And so on
```
I know this is because my self signed cert is not in the java keystore. Is there any way I can make the `Client` not check the validity of the ssl cert and just use it regardless?
This code will only ever be run against test servers so I don't want to go to the hassle of adding new trusted certs each time we set up a new test server.
Here's the code which is making the call:
```
OAuthParameters params = new OAuthParameters();
// baseline OAuth parameters for access to resource
params.signatureMethod(props.getProperty("signature_method"));
params.consumerKey(props.getProperty("consumer_key"));
params.setToken(props.getProperty("token"));
params.setVersion("1.0");
params.nonce();
// OAuth secrets to access resource
OAuthSecrets secrets = new OAuthSecrets();
secrets.consumerSecret(props.getProperty("consumer_secret"));
secrets.setTokenSecret(props.getProperty("token_secret"));
// Jersey client to make REST calls to token services
Client client = Client.create();
// OAuth test server resource
WebResource resource = client.resource(props.getProperty("url"));
// if parameters and secrets remain static, filter cab be added to each web resource
OAuthClientFilter filter = new OAuthClientFilter(client.getProviders(), params, secrets);
// filter added at the web resource level
resource.addFilter(filter);
WebResource.Builder wbr = resource.getRequestBuilder().accept(props.getProperty("accept"));
return wbr.get(ClientResponse.class);
```
Any help would be greatly appreciated. | 2011/05/18 | [
"https://Stackoverflow.com/questions/6047996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105223/"
] | For Jersey 2.\*:
```
Client client = ClientBuilder.newBuilder()
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).build();
```
-> <https://jersey.java.net/documentation/latest/migration.html> | I noticed that when using the Apache http client configuration with a pooling manager, the accepted answer doesn't work.
In this case it appears that the `ClientConfig.sslContext` and `ClientConfig.hostnameVerifier` setters are silently ignored. So if you are using connection pooling with the apache client http client config, you should be able to use the following code to get ssl verification to be ignored:
```
ClientConfig clientConfig = new ClientConfig();
// ... configure your clientConfig
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
}, null);
} catch (NoSuchAlgorithmException e) {
//logger.debug("Ignoring 'NoSuchAlgorithmException' while ignoring ssl certificate validation.");
} catch (KeyManagementException e) {
//logger.debug("Ignoring 'KeyManagementException' while ignoring ssl certificate validation.");
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext, new AbstractVerifier() {
@Override
public void verify(String host, String[] cns, String[] subjectAlts) {
}
}))
.build();
connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
return ClientBuilder.newClient(clientConfig);
``` |
45,084,255 | ```
if(!parent[0] || parent[0].style.display !== 'none') {
console.log('1');
}
```
I am trying to do this in one line, but it is failing in Firefox giving Type Error that parent[0] is undefined. But here I am trying to check and just do the if loop if it is. So my only solution to break it in two if's like this:
```
if(!parent[0]) {
console.log('1');
return;
}
if(parent[0].style.display !== 'none') {
console.log('1');
}
```
How can I make it in one line? Why the first code fails and says that parent[0] is undefined, how can I prevent that and just do the console log which is inside. | 2017/07/13 | [
"https://Stackoverflow.com/questions/45084255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5390206/"
] | This should do the work:
```
if(parent[0] && parent[0].style.display !== 'none') {
console.log('1');
}
```
Using `someVariable && condition` means that `someVariable` is defined and condition is met.
In my opinion the most readable code is:
```
function doSomething() {
// if condition is not met we quit the function
if(parent[0] === undefined) {
return false;
}
// parent[0] is defined we proceed
// Perhaps other conditions that should quit the function
if(parent[0].style.display === 'none') {
return false;
}
// parent[0] is defined we proceed and all checks are done
// All your logic here
}
``` | Change the logic to `&&`.
```
if(parent[0] && parent[0].style.display !== 'none') {
console.log('1');
}
``` |
58,739,513 | On GKE, K8s Ingress are LoadBalancers provided by Compute Engine which have some cost. Example for 2 months I payed 16.97€.
In my cluster I have 3 namespaces (`default`, `dev` and `prod`) so to reduce cost I would like to avoid spawning 3 LoadBalancers. The question is how to configure the current one to point to the right namespace?
GKE requires the ingress's target Service to be of type `NodePort`, I am stuck because of that constraint.
I would like to do something like:
```
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
namespace: dev
annotations: # activation certificat ssl
kubernetes.io/ingress.global-static-ip-name: lb-ip-adress
spec:
hosts:
- host: dev.domain.com
http:
paths:
- path: /*
backend:
serviceName: dev-service # This is the current case, 'dev-service' is a NodePort
servicePort: http
- host: domain.com
http:
paths:
- path: /*
backend:
serviceName: prod-service # This service lives in 'dev' namespace and is of type ExternalName. Its final purpose is to point to the real target service living in 'prod' namespace.
servicePort: http
- host: www.domain.com
http:
paths:
- path: /*
backend:
serviceName: prod-service
servicePort: http
```
As GKE requires service to be `NodePort` I am stuck with `prod-service`.
Any help will be appreciated.
Thanks a lot | 2019/11/06 | [
"https://Stackoverflow.com/questions/58739513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6643803/"
] | OK here is what I have been doing. I have only one ingress with one backend service to nginx.
```
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: ingress
spec:
backend:
serviceName: nginx-svc
servicePort: 80
```
And In your nginx deployment/controller you can define the config-maps with typical nginx configuration. This way you use one ingress and target mulitple namespaces.
```
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
default.conf: |
server {
listen 80;
listen [::]:80;
server_name _;
location /{
add_header Content-Type text/plain;
return 200 "OK.";
}
location /segmentation {
proxy_pass http://myservice.mynamespace.svc.cluster.local:80;
}
}
```
And the deployment will use the above config of nginx via config-map
```
apiVersion: extensions/v1
kind: Deployment
metadata:
labels:
app: nginx
name: nginx
spec:
replicas: 2
template:
metadata:
labels:
app: nginx
spec:
#podAntiAffinity will not let two nginx pods to run in a same node machine
affinity:
podAntiAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
- labelSelector:
matchExpressions:
- key: app
operator: In
values:
- nginx
topologyKey: kubernetes.io/hostname
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
volumeMounts:
- name: nginx-configs
mountPath: /etc/nginx/conf.d
livenessProbe:
httpGet:
path: /
port: 80
# Load the configuration files for nginx
volumes:
- name: nginx-configs
configMap:
name: nginx-config
---
apiVersion: v1
kind: Service
metadata:
name: nginx-svc
spec:
selector:
app: nginx
type: NodePort
ports:
- protocol: "TCP"
nodePort: 32111
port: 80
```
This way you can take advantage of ingress features like tls/ssl termination like managed by google or cert-manager and also if you want you can also have your complex configuration inside nginx too. | One alternative (and probably the most flexible GCP native) solution for http(s) load-balancing is the use [standalone NEGs](https://cloud.google.com/kubernetes-engine/docs/how-to/standalone-neg). This requires you to setup all parts of the load-balancer yourself (such as url maps, health-checks etc.)
There are multiple benefits, such as:
1. One load-balancer can serve multiple namespaces
2. The same load-balancer can integrate other backends as-well (like other instance groups outside your cluster)
3. You can still use container native load balancing
One challenge of this approach is that it is not "GKE native", which means that the routes will still exist even if you delete the underlying service. This approach is therefore best maintained through tools like terraform which allows you to have GCP wholistic deployment control. |
11,739,931 | .project files contain references to the project natures used in the project.
These project natures are dependent on the plugins installed on the local developers machine.
So, should this file be excluded from SVN?
Will nautures unknown to other developers cause problems?
Thanks | 2012/07/31 | [
"https://Stackoverflow.com/questions/11739931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1399539/"
] | Copy paste this:
```
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
(function animloop(){
requestAnimFrame(animloop);
render();
})();
function render()
{
// DO YOUR STUFF HERE (UPDATES AND DRAWING TYPICALLY)
}
```
The original author is: <http://paulirish.com/2011/requestanimationframe-for-smart-animating/> | I made this to emulate orbiting with human characteristics (jerky) but it can be used for other animations like object translations, positions and rotations.
```
function twController(node,prop,arr,dur){
var obj,first,second,xyz,i,v,tween,html,prev,starter;
switch(node){
case "camera": obj = camera; break;
default: obj = scene.getObjectByName(node);
}
xyz = "x,y,z".split(",");
$.each(arr,function(i,v){
first = obj[prop];
second = {};
$.each(v,function(i,v){
second[xyz[i]] = v;
})
tween = new TWEEN.Tween(first)
.to(second, dur)
.onUpdate(function(){
$.each(xyz,function(i,v){
obj[prop][xyz[i]] = first[xyz[i]];
})
})
.onComplete(function(){
html = [];
$.each(xyz,function(i,v){
html.push(Math.round(first[xyz[i]]));
})
$("#camPos").html(html.join(","))
})
if(i >0){
tween.delay(250);
prev.chain(tween);
}
else{
starter = tween;
}
prev = tween;
});
starter.start();
}
``` |
37,536,881 | I would like to move the code to customize `UIButtons` out of my `viewcontroller` classes as a best practice. The code I have below is to add a white border to `UIButtons` and I would like to easily call it on buttons throughout my project.
```
//White Border
let passwordBorder = CALayer()
let width = CGFloat(5.0)
passwordBorder.borderColor = UIColor.whiteColor().CGColor
passwordBorder.frame = CGRect(x: 0, y: 0, width: passwordField.frame.size.width, height: passwordField.frame.size.height)
passwordBorder.borderWidth = width
passwordField.layer.addSublayer(passwordBorder)
passwordField.layer.masksToBounds = true
```
How would I put this code into a helper function so I could call it easily?
I am new to coding and am having trouble with helper functions on anything `UI`. Thanks! | 2016/05/31 | [
"https://Stackoverflow.com/questions/37536881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412407/"
] | In helper class make method like
```
func customiseButton(button:UIButton){
//White Border
let passwordBorder = CALayer()
let width = CGFloat(5.0)
passwordBorder.borderColor = UIColor.whiteColor().CGColor
passwordBorder.frame = CGRect(x: 0, y: 0, width: button.frame.size.width, height: button.frame.size.height)
passwordBorder.borderWidth = width
button.layer.addSublayer(passwordBorder)
button.layer.masksToBounds = true
}
```
and in ViewController call this method as
```
HelperClass().customiseButton(passwordField)
``` | You can try with this Extension for round button:
```
extension UIButton{
func roundCorners(corners:UIRectCorner, radius: CGFloat){
let borderLayer = CAShapeLayer()
borderLayer.frame = self.layer.bounds
borderLayer.strokeColor = UIColor.green.cgColor
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineWidth = 10.5
let path = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius))
borderLayer.path = path.cgPath
self.layer.addSublayer(borderLayer)
}
}
``` |
6,044,818 | I have table in which a constraint has been set on a field called LoginId.While inserting a new row i am getting an error on this constratint associated with this field(LoginID)stating the below error.
The insert command is below:
Type 1 with sequence
```
insert into TemplateModule
(LoginID,MTtype, Startdate TypeId, TypeCase, MsgType, MsgLog, FileName,UserName, CrID, RegionaltypeId)
values
(MODS_SEQ.NEXTVAL,3434,2843,2453,2392,435,2390,'pension.txt','rereee',454545,3434);
Failed with error
```
Type 2 without sequence a hardcoded value::
```
insert into TemplateModule
(LoginID,MTtype, Startdate TypeId, TypeCase, MsgType, MsgLog, FileName,UserName, CrID, RegionaltypeId)
values
(3453,3434,2843,2453,2392,435,2390,'pension.txt','rereee',454545,3434)
```
I crosschecked many times for duplicates.But nothing found.What could be the rootcause
```
ORA-00001: unique constraint error (LGN_INDEX)violated
``` | 2011/05/18 | [
"https://Stackoverflow.com/questions/6044818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682571/"
] | First, do a describe on LGN\_INDEX on that table to make absolutely certain you are looking at the right column. Is LGN\_INDEX a constraint+index or just an index? Try re-building your index to make sure it isn't corrupt. Make sure you don't have any other constraints that might be interfering.
Second, perform a `SELECT MAX(LOGINID) FROM TEMPLATEMODULE` and compare that to the next sequence value to make sure your sequence isn't set lower than the maximum ID you are working with.
Third, check if you have any triggers on that table.
If none of these things work, try re-creating the table using just the schema. Cross-load the data and try again. There might be a configuration setting on that table that is causing the issue. `CREATE TABLE MY_TEMP AS SELECT * FROM TEMPLATEMODULE`. | I encountered the same problem.
An Insert statement populating an Integer value (not in the table) to the Primary Key column.
The problem was a before trigger tied to a sequence. The next\_val for the sequence was already present in the table.
The trigger fires, grabs the sequence number and fails with a Primary Key violation. |
118,483 | I'm trying to work out how best to design a home network which contains (potentially hostile) devices. I'm running into my limits of networking knowledge!
I have two challenges.
**Unsecure Devices**
On my home network I have a Lifx WiFi lightbulb. Lifx doesn't provide any security (no passwords) so any other device on the LAN can control it.
I'm happy for my phone and laptop to connect to the bulb - but I don't want my TV to have access to it. Or vice-versa.
**Hostile Devices**
In a similar vein, I have a Nest Protect WiFi Smoke Alarm. It is (theoretically) possible for a Nest employee to tunnel in to the device and gain full access to my network.
Is it possible to create a network which allows a device to connect to the Internet, but nothing on the LAN?
**Design**
So, what sort of steps can I take on a domestic Internet router to isolate devices which I don't necessarily want to give full access to my LAN?
My thoughts are...
1. Disconnect the devices. That said, I *really* like being able to control my TV from my phone!
2. Create a different subnet for each device. My [router](http://www.ispreview.co.uk/index.php/2015/11/new-virgin-media-superhub3-cable-broadband-router-to-target-voip.html) allows me to create a main network and a guest network. I could put all my semi-trusted devices on a secondary network - but I'd lose the ability to control them while connected to the main network. Additionally, they'd still have the ability to interfere with each other.
3. DMZ? I'm unsure about this - would it isolate the IoT devices from the main LAN while still giving them Internet access? I understand that the devices would be totally exposed to the net - giving anyone the ability to control the password-less devices, is that right?
4. Something else...?
I have the feeling that what I want to do is impossible. Should I just accept that devices on my network can access each other and attempt to secure what I can? | 2016/03/24 | [
"https://security.stackexchange.com/questions/118483",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/13328/"
] | First you need to break the devices into classes of connectivity:
1. Need just a constant "cloud" connection to work properly
2. Need no connection except for initial config/updates, need local connection
3. Need both a cloud connection and a local connection to work
If you have a class of devices that are truly cloud-based (i.e. they don't use any local traffic, it all must go out to the internet and back) creating a SSID and VLAN that segregates traffic is a simple measure to make sure that any hostile activity it might be repurposed for is sheltered from high value targets like your backup server. Putting devices that need some sort of always-on connection in their own class keeps them sidelined if there is some sort of remote compromise of their command and control structure (the cloud.)
If you still need local access to some of those devices, say to give your phone just the ability to access port 80 on your TV or your light bulb (if that's how the smart remote works) a stateful firewall rule can enforce that only your phone, to only that port on the TV, will be allowed. If your TV needs no internet access and only protected local access, this would fall into another category which would need its own SSID, and if you really want it to be able to talk to the internet but no other devices, and be all by itself, it would need its very own SSID and VLAN, which many can be created if needed.
One measure that could also go a long way if your network is subject to transient devices (i.e. relatives tablets or laptops dropping by from time to time) is putting just those on a different VLAN, since for example your smart light bulb, unless you purposefully open a port from the internet at large, is of no harm even without a password since you (hopefully) trust all the other devices on your network to not be under malicious control.
Several inexpensive Wifi/Router devices that can be loaded with OpenWRT or DDWRT can be configured this way. The challenge isn't how to pull all this off, it's how to keep it all working smoothly and not throwing up your hands admitting that it's easier to just live under the spectre of network Armageddon in order to not have to unblock a port every time your phone TV app updates, and it says your TV firmware is now out of date. If you're like most people, you just harden what you can: automatic or alerted updates on all devices that support it, smart firewall rules with anything like uPNP disabled, and then carry on with your life. | I bought for that purpose an Ubiquiti EdgeRouterX and UniFi AP AC LITE.
The access point supports up to 4 SSID, each goes to another VLAN.
I have set up a 'main' wireless network and 'guest' (that I also use for untrusted devices).
The router allows internet access for every VLAN, but does not allow traffic to cross between VLANs, with the exception that I can connect from the 'main' network to the 'guest', but not the other way around.
I think that this setup is pretty secure and also quite cheap for the performance. I even did not have to touch the CLI. The UniFi controller has to run on a PC only to set up the wireless access points, later they can work without it. |
18,802,491 | I have my incoming xml like
```
<?xml version="1.0" encoding="UTF-8"?>
<RootName>
<RandomRootNode>
<RandomNode>
<Identity>1</Identity>
<Name>abc</Name>
</RandomNode>
<RandomNode>
<Identity>2</Identity>
<Name>def</Name>
</RandomNode>
<RandomNode>
<Identity>3</Identity>
<Name>ghi</Name>
</RandomNode>
</RandomRootNode>
<SeriesRootNode>
<Series>
<Identity>2</Identity>
<Total>25</Total>
</Series>
<Series>
<Identity>3</Identity>
<Total>25</Total>
</Series>
<Series>
<Identity>2</Identity>
<Total>20</Total>
</Series>
</SeriesRootNode>
</RootName>
```
And my output xml has an element `<sum>` which will be populated as per the following rules using xslt
1. First find all the matching values of `<Identity>` in the `<RandomNode>` and `<Series>` nodes
2. If they exists then sum the `<Total>`
So as per the above example -
```
<output>
<ResultSet>
<Identity>2</Identity>
<sum>45</sum>
<Identity>3</Identity>
<sum>25</sum>
</ResultSet>
</output>
```
Please let me know if anyone has any idea how to achieve it. | 2013/09/14 | [
"https://Stackoverflow.com/questions/18802491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2779255/"
] | I noticed this same problem. I haven't found a permanent solution yet, but what works for me is the following:
```
omxplayer -o local file.mp3
```
The audio comes out over HDMI, by the way, and the -o local flag forces it to line-out (local). | Run
```
sudo amixer cset numid=3 1
```
to re-direct the output to the 3.5 mm jack
```
last digit
0 = auto
1 = 3.5 mm
2 = HDMI
``` |
43,359,808 | **Test Data :-**
1)Java java version "1.8.0\_121" Java(TM) SE Run-time Environment (build 1.8.0\_121-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
2)Eclipse Eclipse IDE for Java Developers Version: Neon.2 Release (4.6.2) Build id: 20161208-0600
3)OS Microsoft Windows 10 Home - 64-Bit
**myFeature.feature**
```
Feature: This is my dummy feature file
Scenario: This is my first dummy scenario
Given This is my first dummy given step
When This is my second dummy given step
Then This is my third dummy given step
```
**steps.java**
```
package com.cucumber.mavenCucumberPrototype;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class steps
{
@Given("^This is my first dummy given step$")
public void This_is_my_first_dummy_given_step() throws Throwable
{
System.out.println("Executed the first given step");
}
@When("^This is my second dummy given step$")
public void This_is_my_second_dummy_given_step() throws Throwable
{
System.out.println("Executed the first when step");
}
@Then("^This is my third dummy given step$")
public void This_is_my_third_dummy_given_step() throws Throwable
{
System.out.println("Executed the first then step");
}
}
```
**RunnerTest.java**
```
package com.cucumber.mavenCucumberPrototype;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "classpath:features"
)
public class RunnerTest
{
}
```
**POM.XML**
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
```
<groupId>com.cucumber</groupId>
<artifactId>mavenCucumberPrototype</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mavenCucumberPrototype</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-picocontainer</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
```
**[Stack Trace :-](https://i.stack.imgur.com/wKUqF.jpg)**
```
java.lang.TypeNotPresentException: Type cucumber.junit.Cucumber not present
at sun.reflect.annotation.TypeNotPresentExceptionProxy.generateException(TypeNotPresentExceptionProxy.java:46)
at sun.reflect.annotation.AnnotationInvocationHandler.invoke(AnnotationInvocationHandler.java:84)
at com.sun.proxy.$Proxy2.value(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: cucumber.junit.Cucumber
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:114)
at sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:125)
at sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:49)
at sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:439)
at sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:420)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:349)
at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72)
at java.lang.Class.createAnnotationData(Class.java:3521)
at java.lang.Class.annotationData(Class.java:3510)
at java.lang.Class.getAnnotation(Class.java:3415)
at org.junit.internal.builders.IgnoredBuilder.runnerForClass(IgnoredBuilder.java:10)
... 11 more
```
COmmand Line Output :-
```
C:\Users\Pragati Chaturvedi\workspace\mavenCucumberPrototype>mvn clean
install
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mavenCucumberPrototype 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @
mavenCucumberPrototype ---
[INFO] Deleting C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @
mavenCucumberPrototype ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @
mavenCucumberPrototype ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mavenCucumberPrototype ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @
mavenCucumberPrototype ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @
mavenCucumberPrototype ---
[INFO] Surefire report directory: C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.cucumber.mavenCucumberPrototype.RunnerTest
No features found at [classpath:features]
0 Scenarios
0 Steps
0m0.000s
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.331 sec
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ mavenCucumberPrototype
---
[WARNING] JAR will be empty - no content was marked for inclusion!
[INFO] Building jar: C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\target\mavenCucumberPrototype-
0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.4:install (default-install) @
mavenCucumberPrototype ---
[INFO] Installing C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\target\mavenCucumberPrototype-
0.0.1-SNAPSHOT.jar to C:\Users\Pragati
Chaturvedi\.m2\repository\com\cucumber\mavenCucumberPrototype\0.0.1-
SNAPSHOT\mavenCucumberPrototype-0.0.1-SNAPSHOT.jar
[INFO] Installing C:\Users\Pragati
Chaturvedi\workspace\mavenCucumberPrototype\pom.xml to C:\Users\Pragati
Chaturvedi\.m2\repository\com\cucumber\mavenCucumberPrototype\0.0.1-
SNAPSHOT\mavenCucumberPrototype-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.794 s
[INFO] Finished at: 2017-04-12T01:36:58-04:00
[INFO] Final Memory: 17M/194M
[INFO] ------------------------------------------------------------------------
```
<http://cwiki.apache.org/confluence/display/MAVEN/MissingProjectException>`C:\Use
rs\PragatiChaturvedi\workspace\mavenCucumberPrototype\src\test\java\com\cu
cumber\mavenCucumberPrototype>javac RunnerTest.java
RunnerTest.java:5: error: package cucumber.api does not exist
import cucumber.api.CucumberOptions;
^
RunnerTest.java:6: error: package cucumber.api.junit does not exist
import cucumber.api.junit.Cucumber;
^
RunnerTest.java:9: error: cannot find symbol
@CucumberOptions(
^
symbol: class CucumberOptions
RunnerTest.java:8: error: cannot find symbol
@RunWith(Cucumber.class)
^
symbol: class Cucumber
4 errors
C:\Users\PragatiChaturvedi\workspace\mavenCucumberPrototype\src\test\java\com\ ucumber\mavenCucumberPrototype>javac steps.java
steps.java:3: error: package cucumber.api.java.en does not exist
import cucumber.api.java.en.Given;
^
steps.java:4: error: package cucumber.api.java.en does not exist
import cucumber.api.java.en.Then;
^
steps.java:5: error: package cucumber.api.java.en does not exist
import cucumber.api.java.en.When;
^
steps.java:9: error: cannot find symbol
@Given("^This is my first dummy given step$")
^
symbol: class Given
location: class steps
steps.java:14: error: cannot find symbol
@When("^This is my second dummy given step$")
^
symbol: class When
location: class steps
steps.java:19: error: cannot find symbol
@Then("^This is my third dummy given step$")
^
symbol: class Then
location: class steps
6 errors | 2017/04/12 | [
"https://Stackoverflow.com/questions/43359808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7712486/"
] | I tried with this in my POM.XML and it's works
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>CucumberBasic</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.2.3</version>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>4.2.3</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
``` | This is a maven project and *javac* is not the way to compile/build the project.
Correct me if I am wrong, but I would assume that you are not aware of maven. These are few tutorials on maven.
* <https://www.tutorialspoint.com/maven/>
* <http://tutorials.jenkov.com/maven/maven-tutorial.html>
Try running `mvn clean install` from C:\Users\PragatiChaturvedi\workspace\mavenCucumberPrototype and see if tests are getting executed. |
64,854,545 | ```
def num(x=[], y=[],result=[]):
x.append(120), y.append(0)
result.append(print("Progress"))
x.append(0), y.append(120)
result.append(print("Exclude"))
print(len(result))
print(result)
num()
``` | 2020/11/16 | [
"https://Stackoverflow.com/questions/64854545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14646535/"
] | print is build\_in function and after call the function it print its argument and return None.So when you append print("Progress") to a list actually you append None to list. | Try adding a return statement to the function:
```
return (x, y, result)
``` |
31,313,925 | i have a website and i want to restrict that the user should not use the previous 3 password as a new password when resetting password. | 2015/07/09 | [
"https://Stackoverflow.com/questions/31313925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4856983/"
] | ```
#if defined(Q_OS_ANDROID)
QAndroidJniObject activity = QtAndroid::androidActivity();
if (activity.isValid()) {
QAndroidJniObject window = activity.callObjectMethod("getWindow", "()Landroid/view/Window;");
if (window.isValid()) {
const int FLAG_KEEP_SCREEN_ON = 128;
window.callMethod<void>("addFlags", "(I)V", FLAG_KEEP_SCREEN_ON);
}
QAndroidJniEnvironment env; if (env->ExceptionCheck()) { env->ExceptionClear(); } //Clear any possible pending exceptions.
}
#endif
```
Got it from [here](https://forum.qt.io/topic/57625/solved-keep-android-5-screen-on/2), works for me on 5.1 android well | I ended up doing this in Java instead.
Here is java code:
```
package org.qtproject.visualization;
import org.qtproject.qt5.android.bindings.*;
import android.os.Bundle;
import android.view.WindowManager;
public class ScreenOnActivity extends QtActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
super.onCreate(savedInstanceState);
}
}
```
This is then integrated into the rest of application. |
6,435,213 | How can I find the next `<div>` with the same class as the current one.
I have a `<div>` with `class="help"`, now when some clicks on a button inside this `<div>` I want to select the next `<div>` with the same "help" class.
```
<div class="help">
<div>....OTHER HTML CONTENT......<div>
<input type='submit' class='ok'>
</div>
<div>....OTHER HTML CONTENT......<div>
<div class="help"></div>
<div>....OTHER HTML CONTENT......<div>
<div>....OTHER HTML CONTENT......<div>
<div>....OTHER HTML CONTENT......<div>
<div class="help"></div>
<div>....OTHER HTML CONTENT......<div>
<div class="help"></div>
``` | 2011/06/22 | [
"https://Stackoverflow.com/questions/6435213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/406659/"
] | [.next()](http://api.jquery.com/next/) - Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Example :
```
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li class="third-item">list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>
$('li.third-item').next().css('background-color', 'red');
```
**EDIT:**
[.nextAll()](http://api.jquery.com/nextAll/) : Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
So that in your case
```
$('div.help').nextAll(''div.help:first).css('background-color', 'red');
``` | well, provide some basic scripts, the classic handler of cls made by Andrew Hayway && Simon Willison
```
function cls(c,tag){
var r=[];
var reg=new RegExp("(^|\s)"+c+"($|\s)");
var e=document.getElementsByTagName(tag||"*");
for(var i=0;i<e.length;i++){
if(e[i].className.match(reg))
r.push(e[i]);
}
return r;
}
var helps=cls('help','div');
for(var i=0;i<helps.length;i++){
helps[i].onclick=function(){
var next_index=helps.indexOf(this)+1;
if(helps[next_index]){
//here is the next dom with the class help
var next=helps[next_index];
//then your code...
}
}
}
``` |
250,442 | I've installed Django multiple ways, via `apt-get` and `pip install`. They all say I have the most recent version of Django. Now whenever I run python in Terminal and type in import django, I receive
```
ImportError: No module named django
```
However, when I run `django-admin --version` I receive
```
1.4.3
```
I know it's installed, but why is python not finding the django module? | 2013/02/02 | [
"https://askubuntu.com/questions/250442",
"https://askubuntu.com",
"https://askubuntu.com/users/79507/"
] | I had the same problem when I was using PyCharm Community Edition for making Django projects.
For me, the following steps worked:
It turns out that python wants you to create a virtual environment, install django in that and then run the server. To do this,
### Create a Virtual Environment
>
> 1) Install virtual environment using `pip install virtualenv`.
>
>
> 2) Navigate to the project folder and type `virtualenv env` (Here *`env`* is the name of the virtual environment.) This will create a new folder named *`env`* inside the project folder.
>
>
> 3) Navigate to `*env*/Scripts` inside your Project Folder using `cd *env*/Scripts`.
>
>
> 4) Type `activate` and press Enter. This should start the virtual environment. You can verify this as `(*env*)` would be prefixed to your current path.
>
>
>
### Install Django
>
> 1) Once inside the virtual environment, head back to your project folder using `cd ../..` and type `pip install django`.
>
>
> 2) You can verify its installation by typing `django-admin --version`. It should display the django version number installed inside the virtual environment.
>
>
>
Now type `python manage.py runserver` to start the python server. | I've got this problem when I renamed the project folder in PyCharm.
1. Terminal tab stopped getting into the Virtual Environment (`venv` folder). To fix that, I went to the `Settings -> Project -> Project` Interpreter and changed the folder there.
2. Django "disappeared". `django-admin --version` did not respond. To fix, I did `pip install django` within the `venv`.
It helped. |
6,663,039 | `If` logic given below works well in C language but it doesn't work in java....Why..??
It gives an error in java while compiling.
```
class test
{
public static void main(String[] args)
{
int i;
if(i=4)
System.out.println("hello");
}
}
``` | 2011/07/12 | [
"https://Stackoverflow.com/questions/6663039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776084/"
] | You need to use the comparison operator (`==`) instead of the assignment operator (`=`) in your if statement.
In C, the result of a valid assignment operator [is the value that is assigned](http://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Value_of_an_assignment). If your example was in C, the resultant code would be equivalent to `if(4)`, which evaluates to a true statement, and the code is always executed without any complaints by the compiler. Java checks for a few cases where you probably mean something else, such as this one. | It will compile in C because the condition of and if statement in C can be of type int. However, you assign 4 to `i` in your condition, and it will not do what you expect it to do in C either. |
22,570,887 | Assume we have a class `Car` with subclasses mini and sedan, both have same safety checks to I call a common function called safety() which is like a template. So:
```
class Car {
safety() {
check1();
check2();
check3();
check4();
}
}
class Mini extends Car {
// use the safety() belonging to Car
}
class Sedan extends Car {
// use the safety() belonging to Car
}
```
But then things change, and we have a new types and new safeties
1. `sports` needs check1, check3 and a new check5
2. `jeep` needs check1, check4 and new check6
3. `luxury` needs check2 and check3 only
Which design patterns help us work around this issue ? | 2014/03/21 | [
"https://Stackoverflow.com/questions/22570887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2458372/"
] | **Forget patterns** and implement your classes in a way that fits your **use case**. In your example, I would argue, that safety is not really a property of a Car, but rather the *result* of some procedure *applied to* a Car.
```
class CrashTestDummy
{
public Safety check(Car car) {...}
public Safety check(Mini mini) {...}
public Safety check(Sedan sedan) {...}
}
```
This way you can *compare* Safeties to one another, make decisions based on them, *aggregate* them or save them over time. | In my opinion very suitable would be a Visitor pattern <http://en.wikipedia.org/wiki/Visitor_pattern>
There are two basic interfaces:
```
public interface Visitable {
void accept(Visitor visitor);
}
public interface Visitor {
void visit(Mini mini);
void visit(Sedan sedan);
}
```
Example implementations of Visitable could look like this (note the accept methods):
```
public class Mini extends Car implements Visitable {
private int miniSafetyCageCondition;
public Mini(int breaksCondition, int miniSafetyCageCondition) {
super(breaksCondition);
this.miniSafetyCageCondition = miniSafetyCageCondition;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public int getMiniSafetyCageCondition() {
return miniSafetyCageCondition;
}
}
public class Sedan extends Car implements Visitable {
private final boolean frontAirbagsPresent;
private final boolean sideAirbagsPresent;
public Sedan(int breaksCondition, boolean frontAirbagsPresence, boolean sideAirbagsPresent) {
super(breaksCondition);
this.frontAirbagsPresent = frontAirbagsPresence;
this.sideAirbagsPresent = sideAirbagsPresent;
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
public boolean isSideAirbagsPresent() {
return sideAirbagsPresent;
}
public boolean isFrontAirbagsPresent() {
return frontAirbagsPresent;
}
}
public class Car {
private final int breaksCondition;
public Car(int breaksCondition) {
this.breaksCondition = breaksCondition;
}
public int getBreaksCondition() {
return breaksCondition;
}
}
```
And this could be example implementation of Visitor (note the visit methods):
```
public class SafetyVisitor implements Visitor {
private boolean result;
private CarBasicCheck carBasicCheck = new CarBasicCheck();
private MiniSpecificCheck miniSpecificCheck = new MiniSpecificCheck();
private SedanSpecificCheck sedanSpecificCheck = new SedanSpecificCheck();
@Override
public void visit(Mini mini) {
result = carBasicCheck.hasWorkingBreaks(mini) &&
miniSpecificCheck.hasDurableSafetyCage(mini);
}
@Override
public void visit(Sedan sedan) {
result = carBasicCheck.hasWorkingBreaks(sedan) &&
sedanSpecificCheck.hasEnoughAirbags(sedan);
}
public boolean getResult() {
return result;
}
}
public class MiniSpecificCheck {
boolean hasDurableSafetyCage(Mini mini) {
return mini.getMiniSafetyCageCondition() > 5;
}
}
public class SedanSpecificCheck {
public boolean hasEnoughAirbags(Sedan sedan) {
return sedan.isFrontAirbagsPresent() || sedan.isSideAirbagsPresent();
}
}
```
And this is the example client code:
```
public class Client {
public static void main(String[] args) {
SafetyVisitor safetyVisitor = new SafetyVisitor();
Mini safeMini = new Mini(6, 6);
Mini unsafeMini = new Mini(6, 3);
Sedan safeSedan = new Sedan(6, true, false);
Sedan unsafeSedan = new Sedan(6, false, false);
safetyVisitor.visit(safeMini);
System.out.println("safeMini is safe: " + safetyVisitor.getResult());
safetyVisitor.visit(unsafeMini);
System.out.println("unsafeMini is safe: " + safetyVisitor.getResult());
safetyVisitor.visit(safeSedan);
System.out.println("safeSedan is safe: " + safetyVisitor.getResult());
safetyVisitor.visit(unsafeSedan);
System.out.println("unsafeSedan is safe: " + safetyVisitor.getResult());
}
}
```
The advantage here is that you dont need to know the type of object that is being checked. So you could easily have list of Visitable objects, that you would check all at once. In case of simple checking class like the one below its not possible:
```
public interface CarSaeftyChecker {
boolean check(Mini mini);
boolean check(Sedan sedan);
}
``` |
3,422,220 | I'm confused with the next exercise:
Take $\left\{ 1,e^t,e^{-t}\right\}$ a basis for a vector space $V$ (note that $V$ is a space of continuous functions). Take a linear transformation $T:V\to V$ defined by $T(f)=f'$ (derivative). The question is: find all the invariant subspaces of $V$ under $T$.
After a lot of time thinking, I think that the answers is: every subspace generated by a non-empty subset of the basis, i.e., take $W$ an invariant subspace, then, there exist $\emptyset\neq B\subseteq \left\{ 1,e^t,e^{-t}\right\}$ such that $\text{span}(B)=W$. But, how to prove? I can prove that if $\emptyset\neq B\subseteq \left\{ 1,e^t,e^{-t}\right\}$ then $\text{span}(B)$ is invariant under T but the other direction seems too dificult for me and I can't find how to prove. Any hint? I really appreciate any help you can provide. | 2019/11/04 | [
"https://math.stackexchange.com/questions/3422220",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/356536/"
] | $\require{cancel}$The $n^{\textrm{th}}$ partial sum is
$$S\_n =\sum\limits\_{k=1}^n\left(\frac{1}{2k}-\frac{1}{2(k+2)}\right)$$
$$=\sum\limits\_{k=1}^n\frac{1}{2k} - \sum\limits\_{k=1}^n\frac{1}{2(k+2)}$$
$$=\sum\limits\_{k=1}^n\frac{1}{2k} - \sum\limits\_{k=3}^{n+2}\frac{1}{2k}$$
$$=\left(\underbrace{\frac12 + \frac14}\_{\textrm{terms for }k=1,2} + \cancel{\sum\limits\_{k=3}^n\frac{1}{2k}}\right)-\left( \cancel{\sum\limits\_{k=3}^{n}\frac{1}{2k}}+\underbrace{\frac1{n+1}+\frac1{n+2}}\_{\textrm{terms for }k=n+1,n+2}\right)$$
$$=\frac12 + \frac14-\frac1{n+1}-\frac1{n+2}$$
$$=\frac34 -\frac1{n+1}-\frac1{n+2}$$
So the infinite series is, by definition, the limit of the partial sums:
$$\sum\limits\_{k=1}^{\infty}\left(\frac{1}{2k}-\frac{1}{2(k+2)}\right)
\stackrel{\textrm{def}}{=} \lim\limits\_{n\to\infty}S\_n = \boxed{\frac34}$$
Note that finding the limit of the partial sums is the ONLY correct way to find the sum of the infinite series. An infinite series is a limit, not a sum. | In the partial fraction decomposition:
$$\frac1{n(n+2)}=\frac12\biggl(\frac1n-\frac1{n+2}\biggr)$$
the first term is cancelled by the term with a minus sign in the second group before this group, and conversely the term with a minus sign is cancelled by the first term in the second group after:
$$\sum\_{k\ge 1}\frac1{k(k+2}=\frac12\biggr[\biggl(\frac11-\frac13\biggr)+\biggl(\frac12-\frac 14\biggr)+\biggl(\frac13-\frac15\biggr)+\biggl(\frac14-\frac16\biggr)+\dotsb\:\biggr], $$
so there remains in the end:
$$\frac12\biggl(\frac11+\frac12\biggr)=\frac 34.$$ |
21,673,861 | If you were to look at the following website in Chrome, you would see the printers in 2 rows. Which is how it is supposed to be. But in FireFox and Internet Explorer the 4th product is aligned on the right by itself.
I have tried everything I can think of, and scoured the web. I would really welcome any help anybody can give me regarding this issue.
<http://www.thewideformatgroup.co.uk/Products/general-office-use> | 2014/02/10 | [
"https://Stackoverflow.com/questions/21673861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2746483/"
] | Change `float: left` to `display: inline-block` on the items (`.shop-main li`, to be exact).
If you float items to do this, then the height of the items needs to be exactly the same. In this case, the items are rendered in such a fashion that the 3rd item is slightly less high than the second. That is causing the fourth item to float next to the second as well.
If a bit exaggerated, it looks like this. Notice how 3 is slightly less high, causing 4 to be stuck behind 2 as well.

This might be caused by a weird scaling of the product image, for instance, or by any other rounding difference. Also, it might look good at first, but change as soon as a user starts zooming in or out, or messes with their font settings.
By using `inline-block`, you basically create a long text-line of items, that will wrap as soon as the line is full. It is a better approach when you want a wrapping list of items like this, because you won't at all be affected by the rounding problems I mentioned above.
Now, you might be tempted to solve this rounding issue so every block is the same size. And you might do that as well, because it might look a bit weird when the red line that appears on hover is shifted a pixel or so. But start by using inline-block, so you prevent incorrect wrapping, so even if some unpredictable rounding errors occur, they surface only in detail and won't mess up your entire page. | Have you tried to make the elements float or give them a relative positioning? The way i'm seeing it is that they inherit their positions from the parent div but on ie and firefox it's rendered differently.
I've had this problem and the solution for me was to make everything float left and give it margins and clearing as needed, the end-result was that it had a certain margin from the top so the elements always remained at a certain distance from the top and each other while maintaining their position |
38,566 | I'm having some trouble solving a couple of problems:
* I know this one must be pretty easy but can't find the way to solve it.
I need to find the arc length of a curve described by $ r=1- \theta ; 1\leq \theta \leq 2.$
From my notes, this should be solved with $$\int\_{C} f(\sigma
(t)) \left \|\sigma
'(t)\right \| dt$$ I would use $\sigma (t)= (1-t, t)$ since that describes $C$, but what $F$ am I supposed to use?
* Again, I feel like this should be really easy, but can't figure it out:
$$C = {(x,y,z,): y = 1 - x^2 ; x + y + z = 1 ; x,y \geq 0} $$
a) I need to find a regular parametrization of $C$ that starts in $(0,1,0)$ and ends in $(1,0,0).$
b) I need to find $ \int\_{C} F. ds$ with $ F = (2x, y, -x).$
My problem here is finding the parametrization. I think I could use
$$ 1 \leq z \leq x + y - 1 , 0 \leq x \leq a(x,y,z) , 0 \leq y \leq b(x,y,z).$$
I can't really decide what those $a$ and $b$ should be. Once that is done, I think solving b) should be pretty easy.
Anyway, I'll be grateful for any pointers on how to solve this and similar problems, since I can't seem to grasp the concepts behind most of this.
**EDIT 1**: Regarding problem 1, I think I should do $$\int\_{1}^{2} \left \|\frac{\partial (1-\theta ; \theta )}{\partial \theta } \right \| d\theta = \sqrt{2} $$ and that should be the length. I had actually tried that but didn't seem right, but after looking around a little bit more and finding nothing, I think this is it.
**EDIT 2**: EDIT 1 was wrong. I had to use $$\int\_{a}^{b} \sqrt{(r(\theta))^{2} + (\frac{\partial{r(\theta)}}{\partial{\theta}})^{2}}d\theta$$ with $r(\theta)=1-\theta$ which gives me $$\int\_{1}^{2} \sqrt{2-2\theta+(\theta)^{2}} d\theta $$ which is pretty hard to solve. I'm guessing I still have something wrong.
Regarding problem 2: I wrote $$\sigma(t) = (t, 1-t^{2}, t^{2}-t) \in C^1$$ and also $\sigma'(t) \neq (0,0,0) $, noting that $\sigma(0)=(0,1,0)$ and $\sigma(1)=(1,0,0).$
So point a) is done.
Now I needed to solve $$\int\_{C} F. ds \Rightarrow \int\_{0}^{1} F(\sigma(t))\sigma'(t)dt$$ I got $$\int\_{0}^{1} (2t,2-2t^2, -t)(1,-2t, 2t-1)dt = \frac{-1}{6}$$
This one I think is right, but I'm not sure what the result means. Does F goes through $\sigma$ the other way around?
**EDIT 3**: The integral from the second excercise should be $$\int\_{0}^{1} (2t,1-t^2, -t)(1,-t,2t-1) dt = \frac{1}{3}$$ which is a lot nicer. Thanks J.M.
Still not sure about the first one though. | 2011/05/11 | [
"https://math.stackexchange.com/questions/38566",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/9852/"
] | Let $x=(\Theta-1)$,
$dx= d\Theta$,
$r=(1-\Theta)$,
$\frac{dr}{d\Theta}=-1$,
and $s= \int\sqrt{(-1)^2 +(1-\Theta)^2}d\Theta$
We know that
$$\int\sqrt{x^2+a^2}dx=\frac{x\sqrt{x^2+a^2}}{2}+\frac{a^2}{2}\ln(x+\sqrt{x^2+a^2})+C$$.
With substitution of $x$ for $(\Theta-1)$ and taking the limits between 1 and 2, we get the answer $\frac{\sqrt{2}}{2}0.5\ln(1 +\sqrt{2})$ which comes to 1.1477936. | You want to find the arc-length of the curve given in polar form by the equation $r = 1- \theta$ for $1 \le \theta \le 2.$ Well, if you have a polar equation, say $r = f(\theta)$, and you want to find the arc-length of the resulting curve for $\theta\_1 \le \theta \le \theta\_2$ then you need to use the following formula:
$$s = \int\_{\theta\_1}^{\theta\_2} \sqrt{r^2 + \left(\frac{dr}{d\theta}\right)^{\!\! 2}} \, d\theta \, . $$
In the case where $r = 1-\theta$ and $1 \le \theta \le 2$, we have:
$$ s = \int\_1^2 \sqrt{(1-\theta)^2+(-1)^2} \, d\theta \, , $$
$$ s = \int\_1^2 \sqrt{\theta^2-2\theta+2} \ d\theta \, , $$
$$ s = \int\_1^2 \sqrt{(\theta-1)^2+1} \ d\theta \, , $$
$$ s = \int\_0^1 \sqrt{\psi^2+1} \ d\psi \, , $$
$$ s = \frac{1}{2}\left[\psi\sqrt{\psi^2+1} + \sinh^{-1} \psi \right]\_0^1 \, , $$
$$ s = \frac{1}{2}\left(\sqrt{2} - \ln\left(\sqrt{2}-1\right) \right) . $$ |
24,954,374 | I'm developing an ASP.NET MVC 4 Web Api, with C#, .NET Framework 4.0, Entity Framework Code First 6.0 and Ninject.
I have two different `DbContext` custom implementations to connect with two different databases.
This is my `NinjectConfigurator` class (partial):
```
private void AddBindings(IKernel container)
{
container.Bind<IUnitOfWork>().
To<TRZICDbContext>().InRequestScope().Named("TRZIC");
container.Bind<IUnitOfWork>().
To<INICDbContext>().InRequestScope().Named("INIC");
container.Bind<IGenericRepository<CONFIGURATIONS>>().
To<GenericRepository<CONFIGURATIONS>>();
container.Bind<IGenericRepository<INCREMENTAL_TABLE>>().
To<GenericRepository<INCREMENTAL_TABLE>>();
// More implementation...
}
```
`CONFIGURATIONS` is a `TRZIC` table and `INCREMENTAL_TABLE` is an `INIC` table.
I'm using a `IGenericRepository` and here it's where I have the problems:
```
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> DbSet;
private readonly DbContext dbContext;
public GenericRepository(IUnitOfWork unitOfWork)
{
dbContext = (DbContext)unitOfWork;
DbSet = dbContext.Set<TEntity>();
}
// Hidden implementation..
}
```
I don't know how to use the `[Named("TRZIC")]` here `public GenericRepository(IUnitOfWork unitOfWork)` or maybe I need to use it elsewhere.
Here the `IUnitOfWork` implementation depends on TEntity.
Any advice? | 2014/07/25 | [
"https://Stackoverflow.com/questions/24954374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68571/"
] | Let's start with the basics.
As far as i know named bindings work only with constant values attributed in code, like the `[Named("foo")]` attribute, or otherwise by using "service location" like `IResolutionRoot.Get<T>(string name)`. Either does not work for your scenario, so a named binding is out of the question.
That leaves you with conditional bindings (`.When(...)` methods).
---
You've got 2 database with n entities each.
2 Database means two configurations means 2 different `IUnitOfWork` configuration.
However, the "user" is not requesting a specific database, but a specific entity.
Thus you'll need a map `entity-->database` (a dictionary). I don't think there's a way to get around that, but you may devise some kind of convention & implement it by convention, so you don't have to type and maintain a lot of code.
**Solution 1: `.WhenInjectedInto<>`**
with out of the box ninject features, and lots of manual labor:
```
Bind<IUnitOfWork>().To<UnitOfWorkOfDatabaseA>()
.WhenInjectedInto<IRepository<SomeEntityOfDatabaseA>>();
Bind<IUnitOfWork>().To<UnitOfWorkOfDatabaseA>()
.WhenInjectedInto<IRepository<SomeOtherEntityOfDatabaseA>>();
Bind<IUnitOfWork>().To<UnitOfWorkOfDatabaseB>()
.WhenInjectedInto<IRepository<SomeEntityOfDatabaseB>>();
```
you get the drift,.. right?
---
**Solution 2.1: Custom `When(..)` implementation**
Not so much manual labor and maintenance anymore.
Let me just dump the code on you, see below:
public interface IRepository
{
IUnitOfWork UnitOfWork { get; }
}
```
public class Repository<TEntity> : IRepository<TEntity>
{
public IUnitOfWork UnitOfWork { get; set; }
public Repository(IUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
}
public interface IUnitOfWork { }
class UnitOfWorkA : IUnitOfWork { }
class UnitOfWorkB : IUnitOfWork { }
public class Test
{
[Fact]
public void asdf()
{
var kernel = new StandardKernel();
kernel.Bind(typeof (IRepository<>)).To(typeof (Repository<>));
kernel.Bind<IUnitOfWork>().To<UnitOfWorkA>()
.When(request => IsRepositoryFor(request, new[] { typeof(string), typeof(bool) })); // these are strange entity types, i know ;-)
kernel.Bind<IUnitOfWork>().To<UnitOfWorkB>()
.When(request => IsRepositoryFor(request, new[] { typeof(int), typeof(double) }));
// assert
kernel.Get<IRepository<string>>()
.UnitOfWork.Should().BeOfType<UnitOfWorkA>();
kernel.Get<IRepository<double>>()
.UnitOfWork.Should().BeOfType<UnitOfWorkB>();
}
private bool IsRepositoryFor(IRequest request, IEnumerable<Type> entities)
{
if (request.ParentRequest != null)
{
Type injectInto = request.ParentRequest.Service;
if (injectInto.IsGenericType && injectInto.GetGenericTypeDefinition() == typeof (IRepository<>))
{
Type entityType = injectInto.GetGenericArguments().Single();
return entities.Contains(entityType);
}
}
return false;
}
}
```
---
**Solution 2.2 Custom convention based `When(...)`**
Let's introduce a small convention. Entity names of database TRZIC start with `TRZIC`, for example `TRZIC_Foo`. Entity names of database INIC start with `INIC`, like `INIC_Bar`. We can now adapt the previous solution to:
```
public class Test
{
[Fact]
public void asdf()
{
var kernel = new StandardKernel();
kernel.Bind(typeof (IRepository<>)).To(typeof (Repository<>));
kernel.Bind<IUnitOfWork>().To<UnitOfWorkA>()
.When(request => IsRepositoryFor(request, "TRZIC")); // these are strange entity types, i know ;-)
kernel.Bind<IUnitOfWork>().To<UnitOfWorkB>()
.When(request => IsRepositoryFor(request, "INIC"));
// assert
kernel.Get<IRepository<TRZIC_Foo>>()
.UnitOfWork.Should().BeOfType<UnitOfWorkA>();
kernel.Get<IRepository<INIC_Bar>>()
.UnitOfWork.Should().BeOfType<UnitOfWorkB>();
}
private bool IsRepositoryFor(IRequest request, string entityNameStartsWith)
{
if (request.ParentRequest != null)
{
Type injectInto = request.ParentRequest.Service;
if (injectInto.IsGenericType && injectInto.GetGenericTypeDefinition() == typeof (IRepository<>))
{
Type entityType = injectInto.GetGenericArguments().Single();
return entityType.Name.StartsWith(entityNameStartsWith, StringComparison.OrdinalIgnoreCase);
}
}
return false;
}
}
```
This way we don't need explicit mapping `(EntityA, EntityB, EntityC) => DatabaseA`, `(EntityD, EntityE, EntityF) => DatabaseB)`. | If you say that `IUnitOfWork` depends on `TEntity` why not make `IUnitOfWork` generic too?
```
public class TRZIC {}
public class INIC {}
public interface IUnitOfWork<TEntity> {}
public class TRZICDbContext : DbContext, IUnitOfWork<TRZIC> {}
public class INICDbContext : DbContext, IUnitOfWork<INIC> {}
public interface IGenericRepository<TEntity> {}
public class GenericRepository<TEntity> : IGenericRepository<TEntity>
where TEntity : class
{
public GenericRepository(IUnitOfWork<TEntity> unitOfWork)
{
var dbContext = (DbContext) unitOfWork;
}
}
private static void AddBindings(IKernel container)
{
container
.Bind<IUnitOfWork<TRZIC>>()
.To<TRZICDbContext>();
container
.Bind<IUnitOfWork<INIC>>()
.To<INICDbContext>();
container
.Bind<IGenericRepository<TRZIC>>()
.To<GenericRepository<TRZIC>>();
container
.Bind<IGenericRepository<INIC>>()
.To<GenericRepository<INIC>>();
}
``` |
51,767,935 | I'm currently making a frontend app for a project using angular 4, from the backend I get some actions called with a POST that are the same:
>
> actions.response.ts
>
>
>
```
export class actions{
AGREEMENTS_VIEW :string;
PROSPECTS_VIEW :string;
AGREEMENTS_INSERT_UPDATE :string;
PRODUCTS_INSERT_UPDATE :string;
PROSPECTS_INSERT_UPDATE :string;
DOCUMENTS_VIEW :string;
DOCUMENTS_INSERT_UPDATE :string;
}
```
Now, what I want to do:
Based on each actions (agreements\_view, prospects\_view.. etc) i want to enable or disable a component or some input/select/button...
How can I do that?
>
> http post:
>
>
>
```
securityActions(): Observable<actions> {
return this.http.post<actions>(
`${this.ENDPOINT}/security-actions`,
null,
);
}
```
>
> How i called the post inside the component:
>
>
>
```
securityActions() {
this.securityService.securityActions().subscribe(
(res: actions) => {
this.actionsSecurity = res;
console.log(res);
},
errors => {
Utils.notifyErrors(errors, this.notificationsService);
});
}
```
Sorry if my question sounds stupid but im new to angular and im kinda lost! | 2018/08/09 | [
"https://Stackoverflow.com/questions/51767935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10133710/"
] | In my current project we created a permission directive. You give it some conditions and it deletes the tags from the view when it doesn't match.
Here is a sample of it :
```js
export class HasPermissionDirective implements OnInit, OnDestroy {
private permissionSub: Subscription;
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private authorizationService: AuthorizationService) {
}
ngOnInit(): void {
this.applyPermission();
}
@Input()
set hasPermission(checkedPermissions: Permission[]) {
// The input where we set the values of our directive
}
private applyPermission(): void {
this.permissionSub = this.authorizationService.checkPermission(/* our permissions to check for authorization*/)
.subscribe(authorized => {
if (authorized) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
ngOnDestroy(): void {
this.permissionSub.unsubscribe();
}
}
``` | For what i understand you want to activate or deactivate access to a component or button regarding some rules. For example if the user is logged in or not or if your form is properly validated.
If you want to deactivate a button you can use this directive here [disabled]:
```
<button class="btn btn-lg btn-primary btn-block" type="submit"[disabled] ="!registerForm.valid">
Submit
</button>
```
for example if your form is not valid you cant submit the data.
For components you can do this on routes.
You need first to make a service that implements the `CanActivate` interface.
And for example for authetication you could do like this:
```
canActivate(): Observable<boolean> {
return Observable.from(this.user)
.take(1)
.map(state => !!state)
.do(authenticated => {
if
(!authenticated) {
this.router.navigate([ '/login' ]);
}
});
```
And finally on your routes files just add the rule there.
For example to have access to dashboard only if is authenticated.
```
{path: 'dashboard', component: DashboardComponent, canActivate: [the serviceYouDid]}
```
I hope this example can help you.And let me know if you need anything or its not this your looking for. |
57,822,215 | I am creating a new React Native app but facing errors like "No bundle URL present" while running it on iOS Simulator.
*Command to Run App on iOS:*
```
react-native run-ios --port=8089
```
I tried every possible solution suggested on the below links.
[What is the meaning of 'No bundle URL present' in react-native?](https://stackoverflow.com/questions/42610070/what-is-the-meaning-of-no-bundle-url-present-in-react-native)
<https://www.andrewcbancroft.com/2017/04/22/solving-react-natives-no-bundle-url-present-error/>
and lots of other references but no luck at all.
**Solution 1:** I tried to add `AppTranportSecurity` flags in `info.plist`.
```
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>localhost</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
```
**Solution 2:** Try to remove the build from the iOS folder and build it again.
* Remove the build folder with `rm -r build`
* Run `react-native run-ios` again
**Solution 3:** Added below the line in **Package.json** file
```
"build:ios": "react-native bundle --entry-file ./index.js --platform ios --bundle-output ios/main.jsbundle"
```
No luck at all.
Even my metro builder running on **port 8089** as **8081** uses by the MacFee firewall app.
[](https://i.stack.imgur.com/rihqN.png) | 2019/09/06 | [
"https://Stackoverflow.com/questions/57822215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706020/"
] | Finally, I resolved the above issue. Below is the solution which helps me to resolve this issue.
So As I mentioned in my question I tried all most every solution posted on SO or another portal but didn't succeed. So I investigate more on generated iOS code and come to know the below points.
1. My `main.jsbundle` generating but no JS code inside that file so that is my first issue in this app.
**Solution:** Try to generate your `main.jsbundle` file with the below `react-native` command and verify it in your iOS folder.
```
react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios' --assets-dest='./ios'
```
Or
```
react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios
```
**Que:** What it will do?
**And:** It will manually generate `main.jsbundle` file with all JS code.
2. After generating `main.jsbundle` file I tried to run the app again and getting the same error "**No bundle url**"
**Solution:** I found that the manually generated file is not added in my Project target so I added `main.jsbundle` file into my app target.
**Step1:** Select Your `main.jsbundle` in XCode -> Project Navigator pane
**Step2:** Check Related Project Target in Target Membership section.
[](https://i.stack.imgur.com/yt5rf.png) [](https://i.stack.imgur.com/8Q3Bx.png)
And last and final step is to add the build script command for iOS in `package.json`
```
"scripts": {
...
"bundle:ios": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios",
"postinstall": "npm run bundle:ios"
}
```
Hope this will helps those who struggle with this issue.
I literally struggle with this issue for the last 3 days.
Thanks to StackOverflow & Github issues.
Ref Links:<https://github.com/facebook/react-native/issues/18472> | I would like to add the solution that I found as I had initially buried but not solved the error using the build:ios method. This answer is for others also struggling and might be a solution:
My main.bundle.js wasn't present because the node\_modules/react-native/scripts/react-native-xcode.sh failed to bundle because the relative import paths differ in debug vs releases in RN.
I was attempting to import SVG files using babel-inline-import + react-native-svg. Because react-native runs the debug mode from your command line the root will match in the files importing the svg's, but because when React Native builds in release mode (on the CI or when you do Xcode->Product->Archive) it runs the .sh script to make the bundle with the iOS folder as root. So now the patbs are broken.
If you use the build:iOS trick you skip that error but the app crashes immediately, because it's still missing the assets.
The tricky part was finding the relatively simple error in the logs.
Spent a three days on this as well. |
28,605,833 | Is there a simple way I can easily override an autowired bean in specific unit tests? There is only a single bean of every type in the compile classes so it's not a problem for autowiring in this case. The test classes would contain additional mocks. When running a unit test I'd simply like to specify an additional Configuration that says basically, while running this unit test use this mock instead of the standard bean.
Profiles seem a bit overkill for what I require and I'm not sure this would be achievable with the Primary annotation as different unit test could have different mocks. | 2015/02/19 | [
"https://Stackoverflow.com/questions/28605833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447522/"
] | In Spring Boot 1.4 there's a simple way for doing that:
```
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MyApplication.class })
public class MyTests {
@MockBean
private MyBeanClass myTestBean;
@Before
public void setup() {
...
when(myTestBean.doSomething()).thenReturn(someResult);
}
@Test
public void test() {
// MyBeanClass bean is replaced with myTestBean in the ApplicationContext here
}
}
``` | As mats.nowak commented, `@ContextConfiguration` is useful for this.
Say a parent test class is like:
```
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/some-dao-stuff.xml"
,"classpath:spring/some-rest-stuff.xml"
,"classpath:spring/some-common-stuff.xml"
,"classpath:spring/some-aop-stuff.xml"
,"classpath:spring/some-logging-stuff.xml"
,"classpath:spring/some-services-etc.xml"
})
public class MyCompaniesBigTestSpringConfig {
...
```
Create a child test class:
```
package x.y.z;
@ContextConfiguration
public class MyOneOffTest extends MyCompaniesBigTestSpringConfig {
...
```
and put in src/test/resources/x/y/z/MyOneOffTest-context.xml
```
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="widgetsService" class="com.mycompany.mydept.myservice.WidgetsService" primary="true" />
</beans>
```
That `widgetsService` bean will override (take the place of) the bean defined in the main config xml (or Java config). See about [inheritLocations](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/ContextConfiguration.html#inheritLocations--)
Also Note the default -context.xml file. Example of that [here](https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles).
Update: I had to add `primary="true"`, apparently it's needed. |
2,394,603 | For the past couple of months I've been working on a game in java for a university project. It's coming up to the end of the project and I would like to compile the project into a single file which is easy to distribute. The game currently runs from inside the IDE and relies on the working directory being set somewhere specific (i.e. the content directory with sounds/textures etc). What's the best way to put all this together for portability? I'm hoping there is some way to compile the content into the jar file...
NB. I'm using NetBeans, so any solutions which are easy in netbeans get extra credit ;)
Addendum::
For future reference, I found a way of accessing things by directory, ythis may not be the best way but it works:
```
File directory = new File(ClassLoader.getSystemResource("fullprototypeone/Content/Levels/").toURI());
```
And now I can just use that file object as normal | 2010/03/07 | [
"https://Stackoverflow.com/questions/2394603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108234/"
] | Here is the code I promised in another comment... it isn't quite what I remember but it might get you started.
Essentially you call: String fileName = FileUtils.getFileName(Main.class, "foo.txt");
and it goes and finds that file on disk or in a JAR file. If it is in the JAR file it extracts it to a temp directory. You can then use "new File(fileName)" to open the file which, no matter where it was before, will be on the disk.
What I would do is take a look at the getFile method and look at what you can do with the JAR file to iterate over the contents of it and find the files in a given directory.
Like I said, not exactly what you want, but does do a lot of the initial work for you.
```
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
public class FileUtils
{
public static String getFileName(final Class<?> owner,
final String name)
throws URISyntaxException,
ZipException,
IOException
{
String fileName;
final URI uri;
try
{
final String external;
final String decoded;
final int pos;
uri = getResourceAsURI(owner.getPackage().getName().replaceAll("\\.", "/") + "/" + name, owner);
external = uri.toURL().toExternalForm();
decoded = external; // URLDecoder.decode(external, "UTF-8");
pos = decoded.indexOf(":/");
fileName = decoded.substring(pos + 1);
}
catch(final FileNotFoundException ex)
{
fileName = null;
}
if(fileName == null || !(new File(fileName).exists()))
{
fileName = getFileNameX(owner, name);
}
return (fileName);
}
private static String getFileNameX(final Class<?> clazz, final String name)
throws UnsupportedEncodingException
{
final URL url;
final String fileName;
url = clazz.getResource(name);
if(url == null)
{
fileName = name;
}
else
{
final String decoded;
final int pos;
decoded = URLDecoder.decode(url.toExternalForm(), "UTF-8");
pos = decoded.indexOf(":/");
fileName = decoded.substring(pos + 1);
}
return (fileName);
}
private static URI getResourceAsURI(final String resourceName,
final Class<?> clazz)
throws URISyntaxException,
ZipException,
IOException
{
final URI uri;
final URI resourceURI;
uri = getJarURI(clazz);
resourceURI = getFile(uri, resourceName);
return (resourceURI);
}
private static URI getJarURI(final Class<?> clazz)
throws URISyntaxException
{
final ProtectionDomain domain;
final CodeSource source;
final URL url;
final URI uri;
domain = clazz.getProtectionDomain();
source = domain.getCodeSource();
url = source.getLocation();
uri = url.toURI();
return (uri);
}
private static URI getFile(final URI where,
final String fileName)
throws ZipException,
IOException
{
final File location;
final URI fileURI;
location = new File(where);
// not in a JAR, just return the path on disk
if(location.isDirectory())
{
fileURI = URI.create(where.toString() + fileName);
}
else
{
final ZipFile zipFile;
zipFile = new ZipFile(location);
try
{
fileURI = extract(zipFile, fileName);
}
finally
{
zipFile.close();
}
}
return (fileURI);
}
private static URI extract(final ZipFile zipFile,
final String fileName)
throws IOException
{
final File tempFile;
final ZipEntry entry;
final InputStream zipStream;
OutputStream fileStream;
tempFile = File.createTempFile(fileName.replace("/", ""), Long.toString(System.currentTimeMillis()));
tempFile.deleteOnExit();
entry = zipFile.getEntry(fileName);
if(entry == null)
{
throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName());
}
zipStream = zipFile.getInputStream(entry);
fileStream = null;
try
{
final byte[] buf;
int i;
fileStream = new FileOutputStream(tempFile);
buf = new byte[1024];
i = 0;
while((i = zipStream.read(buf)) != -1)
{
fileStream.write(buf, 0, i);
}
}
finally
{
close(zipStream);
close(fileStream);
}
return (tempFile.toURI());
}
private static void close(final Closeable stream)
{
if(stream != null)
{
try
{
stream.close();
}
catch(final IOException ex)
{
ex.printStackTrace();
}
}
}
}
```
Edit:
Sorry, I don't have time to work on this right now (if I get some I'll do it and post the code here). This is what I would do though:
1. Look at the [ZipFile](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html) class and use the [entries()](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html#entries%28%29) method to find all of the files/directories in the zip file.
2. the [ZipEntry](http://java.sun.com/javase/6/docs/api/java/util/zip/ZipEntry.html) has an isDirectory() method that you can use to figure out what it is.
3. I think the code I posted in [this answer](https://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java/617438#617438) will give you a way to pick a temporary directory to extract the contents to.
4. I think the code I posted in [this answer](https://stackoverflow.com/questions/625420/what-is-the-fastest-way-to-read-a-large-number-of-small-files-into-memory/625810#625810) could help with copying the ZipEntry contents to the file system.
5. once the items are on the file system the code you already have for iterating over the directory would still work. You would add a new method to the FileUtils class in the code above and be able to find all of the files as you are doing now.
There is probably a better way to do it, but off the top of my head I think that will work. | yes ! put your compiled .class files and your resources with folders in a jar file .. you ll have to build a manifest file as well .. you can find the tutorial about making a .jar file on
google. most probably you ll be referred to java.sun.com . |
41,486,855 | I have a string with a bunch of values like `aaa, bbb, ccc, ddd, eee, fff`. The length is always different.
I need to the remove the last value without the `,` so it should be like:
```
aaa, bbb, ccc, ddd, eee,
```
Is there a way to do that? | 2017/01/05 | [
"https://Stackoverflow.com/questions/41486855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444381/"
] | You can use regex to do that:
```
"aaa, bbb, ccc, ddd, eee, fff".replace(/[^,]+$/, "");
```
Here I replace as much possible characters `+` that are not `,` : `[^,]` and are at the end of the string: `$` | You could replace the last word and the whitespace before.
```js
var string = 'aaa, bbb, ccc, ddd, eee, fff';
console.log(string.replace(/\s+\w+$/, ''));
``` |
38,286,022 | Question (My problem is with B) :
Assuming DX = 0XDB00
A) What is the value of DH after these commands :
```
SHR DX, 1
OR DH,DL
XOR DL, DL
```
B) Write 1 line to replace the above 3 lines
And this is what I got to :
[](https://i.stack.imgur.com/A29zr.png)
At first I thought, maybe its "SHR AH, 1" but that would leave the MSB 0 and not 1.
I also tried looking at the DEC and HEX values with no luck of finding a pattern.
NOTE : I'm starting to think that maybe the question was badly written and they meant how to get to the result we got in A in the particular case where DX is 0XDB00. Althought that doesn't sound right since the answer could just be `mov DX,0xED00` | 2016/07/09 | [
"https://Stackoverflow.com/questions/38286022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168837/"
] | Is the answer supposed to be `ror dh, 1`?
That gives the same result as your sequence when `dl` is already 0, but doesn't work in the general case where DX holds an arbitrary 16bit value. If you can't assume that, I don't think the question is answerable (unless you take it literally as "one line", and just put multiple instructions on the same line, which is possible in GAS and NASM syntax at least.)
---
Here's how the original does the same thing as a rotate (assuming DL is zero):
`SHR` always leaves the high bit zero, and shifts the low bit of DH into the high bit of DL.
The `OR` sets the high bit of DH to the bit shifted out into the high bit of DL. (And if DL was non-zero initially, those bits will affect DH)
`XOR` zeroes DL again. | `ADD DX,1200` will get the same result into the DX register as the 3 lines above.
Used ollydbg for this, opened up one of my programs and edited it.
First I tested the code that you have given me.
`MOV DX,0xDB00
SHR DX,1
OR DH,DL
XOR DL,DL`
and after this I checked the DX register.
Once I had the value I just needed to use a hex calculator. |
23,130,529 | I am using PHP mail and trying to send BCC, but for some reason since I've added the lines with //ADDED NEW on it , it's just now sending any emails at all.
Here is the full code:
```
$to = "me@gmail.com";
$bcc = $row['recipients']; //ADDED NEW
$subject = $row['subject'];
$message = $row['text_body'];
$headers = "From: " . strip_tags('me@gmail.com') . "\r\n";
$headers .= "Reply-To: ". strip_tags('me@gmail.com') . "\r\n";
$headers .= "Bcc: $emailList\r\n"; //ADDED NEW
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $bcc, $subject, $message, $headers); // $bcc ADDED NEW
```
Why is this not sending? | 2014/04/17 | [
"https://Stackoverflow.com/questions/23130529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683553/"
] | This behaviour could come if you use implicit injection, instead of explicit declaring your dependencies. In my experience I faced this kind of problem with particular kind of Angular.js services that return instantiable class (for example to create abstract controller Classes or some other particular cases).
For example: [AbstractBaseControllerClass](https://github.com/williamverdolini/discitur-web/blob/master/app/modules/main/DisciturBaseCtrl.js#L53)
During minification I had the same problem. I solved using internal declaration of dependency injection.
Hope this helps | For the ones that doesn't like CoffeeScript.
I just took some of my code and put it in.
```
$stateProvider
.state('screen', {
url: '/user/',
templateUrl: 'user.html',
controller: 'UserController',
controllerAs: 'user',
location: "User",
resolve: ['$q', 'UserService', '$state', '$timeout', authenticateUser
]
})
function authenticateUser($q, UserService, $state, $timeout) {
UserService.getLoginStatus().then(function () {
if (UserService.user) {
console.log("is user");
return $q.when();
} else {
console.log("not user");
$timeout(function () {
// This code runs after the authentication promise has been rejected.
// Go to the log-in page
$state.go('login')
});
return $q.reject()
}
});
}
``` |
94,144 | I understand that it is hard to define when pasta is properly 'cooked'. It's a subjective topic.
But I think that 'really not cooked enough' is a state that most of use would agree on.
I noticed that regardless of the continent, city, stove type (electric or gas) and pasta type, pasta will never be 'cooked enough to eat' if I follow the time on the box.
I always lived by the sea, at sea level, so I'm assuming all these years, water boiled at the same temperature (100c)
I'd had cooking ranges from high end Viking models to some no name crap ones.
When the box says cook 11min (as in tonight's Barilla Penne Rigate), they start to bee cooked enough to eat at 17min. I never cover the cooking pot, could it be it?
Unless I have a life long curse regarding cooking pasta, why is it that following the box instructions has never resulted in pasta cooked enough in my 30 odd years of cooking them? :) | 2018/11/21 | [
"https://cooking.stackexchange.com/questions/94144",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/59283/"
] | Obviously those figures can only be a guideline. There's a good measure of subjectivity to pasta cooking, but most likely the package directions are not totally random, and you should be getting pretty close to a good state if you were following them to the letter. Still, the real method to tell whether your pasta is cooked is to taste it, not time it.
But more importantly, can I guess that you're an American? Barilla pasta is Italian, and I'm pretty sure they'd give you figures that'd lead to pasta properly cooked by Italian standards, ie 'al dente', which means literally that there is still some bite to it. I've never really had any pasta cooked that way in any US establishment, the standard is.. mush :-). So if you think 'tender' is the only standard for properly cooked pasta, I invite you to try the Italian way and see whether that in fact might be a better state to aim for. You could start by cutting the time difference in half, and see for yourself that the pasta is still quite edible when it's not completely soft? And then work back to the suggested time, testing at each stage.
Another factor that re-inforces this wrong-headed US standard is that good Italian pasta is made from durum-wheat flour, a much harder variety of wheat than what is generally available in the US. That flour means that the pasta cooks evenly, first it's raw, then it's a bit hard, then it's perfect, then it's getting overcooked, and only (50% in your case) later does it reach that US-favored mush stage, possibly not even ever. But soft American flour doesn't just reach a much softer final state, it reaches it *instantly*. Which means you go from raw to overcooked in a blink, it's exceedingly difficult to catch it at the right stage of 'al dente'. That is probably the main reason why this mushy US standard has developed to that degree, people have never had the right thing to learn with. So Thomas, do stick with the Barilla while you figure this out... | I am Italian and I agree with you.
Following the box instruction leads to an almost uncooked pasta.
The issue is certainly matter of taste but the same is said by all the persons to whom I share meals with or I have discussed this subject.
I do personally got to know pasta based on format and company.
Spaghetti usually need a + 2' but extra time can increase and considerably do so with other formats.
I suggest you do as I do or you taste while cooking starting when the indicated time has already elapsed.
As another user said, the indicated time starts counting from the moment in which the water restart boiling, or ideally, from the moment you down the pasta as boiling shouldn't stop.
Buon appetito. |
2,130 | When crocheting, there are 2 grips for holding the hook: like a knife or like a pen. The choice is - of course - a matter of what you've been taught and what you prefer, but can anything in general be said about the (dis)advantages of both grips?
For instance,
* is any grip better for your finger joints and wrist,
* does it help to crochet faster,
* is it easier when crocheting larger (heavier) projects,
* does it allow you to switch yarns more easily or anything else that occasionally needs to be done during crocheting, etc.
Also, if there is another way to hold the hook, please don't hesitate to mention it. | 2016/08/26 | [
"https://crafts.stackexchange.com/questions/2130",
"https://crafts.stackexchange.com",
"https://crafts.stackexchange.com/users/137/"
] | I crochet using knife grip, and tried to learn pen grip, since it is considered 'right' in my country.
When learning, I found that pen grip allows you smaller hand movements, so it is better joints and wrists. It was also easier when working with fine yarns; when I tried to crochet thicker yarns, my hand would quickly return to knife grip. Additionally my gauge was tighter with pen grip.
The speed greatly depends on your proficiency with each grip, so it is not really a point for any of the grips.
Ultimately I returned to knife grip, because I found inserting the hook in a stitch much easier this way - for pen grip I had to twist fabric so that I would have trouble seeing the stitch (I would commonly insert the hook under only front loop or split the back loop), because the hook points somewhat downwards, left and slightly forwards, while with knife grip my hook points left, slightly upwards and parallel to my body.
Illustration of this difference:
Pen hold, pointing downwards
[](https://i.stack.imgur.com/hhZmR.jpg)
Crocheting using pen hold
[](https://i.stack.imgur.com/SWsN7.jpg)
Knife hold, pointing upwards
[](https://i.stack.imgur.com/1MLQc.jpg)
Crocheting using knife hold
[](https://i.stack.imgur.com/GSrhK.jpg) | I use knife grip for most stitches, but for a few, such as crab stitch (reverse single crochet), the pen grip works much better. |
45,279,115 | How can I update/replace a value on a comma separated string column?
i.e:
```
121720 | 121716 | false,true,34,1,1,true,1,true
118220 | 118191 | false,true,731,11,11,true,11,true
142125 | 142037 | false,true,34,28,28,true,28,true
182105 | 182012 | false,true,34,3,3,true,3,true,,
185268 | 185191 | false,true,34,2,2,true,2,true,,
```
How to replace just the second value on the strings (true) for (false)?
What if I want to replace it in a different "position" like sixth or eighth?
I have been able to use the split\_part function on `SELECT` but not on `UPDATE`. | 2017/07/24 | [
"https://Stackoverflow.com/questions/45279115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8357214/"
] | [`ShellExecute()`](https://www.autoitscript.com/autoit3/docs/functions/ShellExecute.htm) is perfect for calls like this. But if you really want to go through a Run Prompt window you can use this too :
```
Local $shell = ObjCreate("shell.application")
$shell.FileRun()
```
The benefit is that you don't have to use an emulated-keyboard-stroke to open the Run Prompt because `Win` + `R` could be linked to an other command launcher, it's cleaner that way. | This works like expected:
```
Send('{LWINDOWN}r{LWINUP}')
```
Your question was'nt clear. You want to open the windows Run-box with its native function call, is it?
Do it so:
```
ShellExecute(@SystemDir & '\rundll32.exe', 'shell32.dll #61')
``` |
25,887,448 | I have next code:
```
void f(int){}
struct A
{
void f()
{
f(1);
}
};
```
This code is not well-formed with the error message (GCC): `error: no matching function for call to ‘A::f(int)’` or (clang) `Too many arguments to function call, expected 0, have 1; did you mean '::f'?`
**Why do I need to use `::` to call the non-member function with the same name as the member function, but with different signature? What is the motivation for this requirement?**
I think the compiler should be able to figure it out I want to call the non-member function as the signature is different (clang even puts that in the error message!).
Please don't mark this as duplicate - it is a different question from this [Calling in C++ a non member function inside a class with a method with the same](https://stackoverflow.com/questions/2207628/calling-in-c-a-non-member-function-inside-a-class-with-a-method-with-the-same) | 2014/09/17 | [
"https://Stackoverflow.com/questions/25887448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/336578/"
] | >
> Why do I need to use :: to call the non-member function with the same name as the member function, but with different signature? What is the motivation for this requirement?
>
>
>
That is the whole point of having namespaces. A local (closer-scoped) name is preferred and more visible over a global name. Since a `struct` is again a scope, its `f` is shadowing the visibility of `::f`. When you've to have the global one, you've to say you do. Why?
This is provided as a feature to make sure you can peacefully call functions you defined assuming they would get called, and when you need one from a different namespace, say the standard library, you'd state that explicitly, like `std::`. It's just a clean form of disambiguation, without leaving room for chance to play its part. | To understand the reason of your error and why you need to explicitly use the `::f()` syntax, you may want to consider some aspects of the C++ compiler process:
The first thing the compiler does is **name lookup**.
Unqualified name lookup starts from the current scope, and then moves outwards; it stops as soon as it finds a declaration for the name of the function, even if this function will be later determined to not be a viable candidate for the function call.
Then, **overload resolution** is executed over the set of the functions that name lookup found.
(And, finally, **access check** is executed on the function that overload resolution picked up.) |
744,527 | My professor would like me to solve a system similar to the following:
$$ dx\_i=[f\_i(x\_1,x\_2,...x\_n)]dt + g\_ix\_idW\_i$$
Where $g\_i$ are positive constants that measure the amplitude of the random perturbations, and $W\_i$ are random variables normally distributed.
Im not sure how I can implement this in Matlab for `ode45` to solve. What is throwing me off is the $dt$ tacked on to $f\_i(x\_1,...)$ and $dW\_i$.
Is it as simple as coding
```
function dxdt=money(t,x,a,b,c)
x1=x(1);
x2=x(2);
x3=x(3);
dx1=x1.*(x2-a)+x3 + 10*rand();
dx2=1-b*x2-x1.^2 + 10*rand;
dx3=-x1-c*x3 +10*rand();
dxdt=[dx1;dx2;dx3];
end
``` | 2014/04/08 | [
"https://math.stackexchange.com/questions/744527",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/91951/"
] | You absolutely cannot use `ode45` to simulate this. ODEs and [SDEs](http://en.wikipedia.org/wiki/Stochastic_differential_equation) are different beasts. Also note that [`rand`](http://www.mathworks.com/help/matlab/ref/rand.html) in Matlab is uniformly, not normally, distributed, so you're also not even generating proper [Wiener increments](http://www.me.ucsb.edu/%7Emoehlis/APC591/tutorials/tutorial7/node2.html). Before proceeding, you should take some time to read up on SDEs and how to solve them numerically. I recommend this paper, which includes many Matlab examples:
>
> Desmond J. Higham, 2001, An Algorithmic Introduction to Numerical Simulation of Stochastic Differential Equations, SIAM Rev. (Educ. Sect.), 43 525–46. <http://dx.doi.org/10.1137/S0036144500378302>
>
>
>
The URL to the Matlab files in the paper won't work; [use this one](https://www.maths.ed.ac.uk/%7Edhigham/algfiles.html).
If you are familiar with `ode45` you might look at my [SDETools](https://github.com/horchler/SDETools) Matlab toolbox on GitHub. It was designed to be fast and has an interface that works very similarly to Matlab's ODE suite. Here is how you might code up your example using the [Euler-Maruyma](http://en.wikipedia.org/wiki/Euler%E2%80%93Maruyama_method) solver and [anonymous functions](http://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html):
```
a = ...
b = ...
c = ...
f = @(t,x)[ x(1)*(x(2)-a)+x(3);
1-b*x(2)-x(2)^2;
-x(1)-c*x(3)]; % drift function
g = 10; % or @(t,x)10; % diffusion function, constant in this case
dt = 1e-3; % time step
t = 0:dt:1; % time vector
x0 = [...]; % 3-by-1 initial condition
opts = sdeset('RandSeed',1); % Set random seed
y = sde_euler(f,g,t,x0,opts); % Integrate
figure;
plot(t,y);
```
In your example, the drift function, $g(t,x)$, doesn't depend on the state variable, $x$. This is so-called additive noise. In this case, more complex SDE integration schemes like [Milstein](http://en.wikipedia.org/wiki/Milstein_method) reduce to Euler-Maruyma. More importantly, if you do use more complex diffusion functions (e.g., multiplicative noise where $g(t,x) = g\_1(t)x$ like in the equation at the beginning of your question), you need to specify what SDE formulation you're using, [Itô](http://en.wikipedia.org/wiki/Ito_calculus) (most common in finance) or [Stratonovich](http://en.wikipedia.org/wiki/Stratonovich_integral). My SDETools currently defaults to Stratonovich, but you can change it via `opts = sdeset('SDEType','Ito');`. | Unfortunately, I don't think you can use `ode45` to solve it, whereas, since $dW$ distributes like $N(0,\sqrt{dt})$ you must use the following discretisation:
$$
x\_{n+1,i}=x\_{n,i}+f\_i(x\_{n,i})\Delta t+g\_i(x\_{n,i})x\_{n,i}\sqrt{\Delta t}\cdot\epsilon\_i,
$$
$$
\epsilon\_i=\mbox{randn()}
$$
$$
x\_{n,i}\approx x\_i(t)
$$ |
12,202,986 | I've inherited an MVC asp.net app using framework 4.0.
I'm getting the dreaded "A potentially dangerous Request.Form value was detected from the client" error and all my research leads me to believe that this should fix it:
```
<system.web>
<httpRuntime requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
```
However, I've added that to my web.config and still get the error. I'm at the end of my rope here, what am I missing? | 2012/08/30 | [
"https://Stackoverflow.com/questions/12202986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1612706/"
] | In addition to what you did you also have to decorate your methods with the `ValidateInput` attribute.
```
[ValidateInput(false)]
public ActionResult MyActionMethod(string myParameter)
{
// Method implementation goes here...
}
```
There is an alternative though, you can implement your own request validator and bind that in your web.config if you want to handle validation for your entire site. Take a look at [this blog post](http://jefferytay.wordpress.com/2010/04/15/creating-your-own-custom-request-validation/) on how to fully implement it.
Basically, create a class that inherits from `RequestValidator` and then hook it up on the web.config.
```
<httpRuntime requestValidationType=”Globals.CustomRequestValidation”/>
```
Hopefully this helps! | The simplest way is to remove the characters you want from the validation system.
Here is the `requestPathInvalidCharacters` attribute from the [`httpRuntime` element](https://msdn.microsoft.com/en-us/library/e1f13641(v=vs.100).aspx) with its default value.
```
<httpRuntime requestPathInvalidCharacters="<,>,*,%,&,:,\" />
<!-- the unescaped characters are: < > * % & : \ -->
```
Remove the characters you want to authorize and the request will work. |
12,509,284 | >
> **Possible Duplicate:**
>
> [How to get screen size and respond to it?](https://stackoverflow.com/questions/6577430/how-to-get-screen-size-and-respond-to-it)
>
>
>
Can I get the size of the screen android phone, similar to the same method in the computer. I'm interested in the screen resolution and (or) diagonal screen.
Is there a possibility to find me interesting information, it can be anologii transaction for Computer:
```
Toolkit toolkit = getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int widthScreen = screenSize.width;
int heightScreen = screenSize.height;
``` | 2012/09/20 | [
"https://Stackoverflow.com/questions/12509284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1651851/"
] | <http://developer.android.com/reference/android/util/DisplayMetrics.html>
You can use it as follows:
```
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
```
for density, there's
```
int densitiy = displaymetrics.densityDpi;
``` | use this code:
```
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int wwidth = displaymetrics.widthPixels;
``` |
17,827,753 | Is there any in-built feature is there in spree or we only need to customize that? | 2013/07/24 | [
"https://Stackoverflow.com/questions/17827753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2515588/"
] | I recently published a blog post about this topic, hope it helps.
<http://nebulab.it/blog/one-page-checkout-with-spree>
The approach describes how to:
1. change the checkout/edit.html.erb view to display all relevant checkout steps.
2. add a `:remote => true` to all form\_for but the last one.
3. create a js view in checkout/edit.js.coffee which will replace the content of the next step in the right place. | you can try our the [spree\_one\_page\_checkout gem](https://github.com/RacoonsGroup/spree_one_page_checkout)
But i really don't know if its worked correctly. |
6,310,688 | I always try to create my Applications with memory usage in mind, if you dont need it then don't create it is the way I look at it.
Anyway, take the following as an example:
```
Form2:= TForm2.Create(nil);
try
Form2.ShowModal;
finally
Form2.FreeOnRelease;
end;
```
I actually think Form2.Destroy is probably the better option, which brings me to my question..
What is the difference between calling:
```
Form2.Destroy;
Form2.Free;
Form2.FreeOnRelease;
```
They all do the same or similar job, unless I am missing something.
And also when should any of the above be used? Obviously when freeing an Object I understand that, but in some situations is `Destroy` better suited than `Free` for example? | 2011/06/10 | [
"https://Stackoverflow.com/questions/6310688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The idiomatic usage is
```
procedure SomeProc;
var
frm: TForm2;
begin
frm := TForm2.Create(nil);
try
frm.ShowModal;
finally
frm.Free;
end;
end;
```
or, unless you hate the `with` construct,
```
with TForm2.Create(nil) do
try
ShowModal;
finally
Free;
end;
```
You should never call `Destroy`, according to [the documentation](http://docwiki.embarcadero.com/VCL/en/Forms.TCustomForm.Destroy). In fact, `Free` is exactly equivalent to `if Self <> nil then Destroy;`. That is, it is a 'safe' version of `Destroy`. It doesn't crash totally if the pointer happens to be `nil`. [To test this, add a private field `FBitmap: TBitmap` to your form class, and then OnCreate (for instance), try `FBitmap.Free` vs. `FBitmap.Destroy`.]
If you create the form using the approach above, `Free` is perfectly safe, unless you do some strange things in the form class.
However, if you use `CreateForm(TForm2, Form2)` to create the form and store the form object in the global instance variable `Form2` and you don't free it immediately [for instance, if you want the window to stick around next to the main form in a non-modal way for a few minutes], you should probably use `Release` instead of `Free`. From [the documentation](http://docwiki.embarcadero.com/VCL/en/Forms.TCustomForm.Release),
>
> Release does not destroy the form
> until all event handlers of the form
> and event handlers of components on
> the form have finished executing.
> Release also guarantees that all
> messages in the form's event queue are
> processed before the form is released.
> Any event handlers for the form or its
> children should use Release instead of
> Free (Delphi) or delete (C++). Failing
> to do so can cause a memory access
> error.
>
>
>
[`FreeOnRelease`](http://docwiki.embarcadero.com/VCL/en/Classes.TComponent.FreeOnRelease) has nothing in particular do to with forms. From the docs:
>
> It should not be necessary to call
> FreeOnRelease directly.
>
>
> | the other way is passing caFree to Action of formonclose
```
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end
``` |
30,267,316 | I am using lodash to split up usernames that are fed to me in a string with some sort of arbitrary separator. I would like to use \_.words() to split strings up into words, except for hyphens, as some of the user names contain hyphens.
Example:
```
_.words(['user1,user2,user3-adm'], RegExp)
```
I want it to yield:
```
['user1', 'user2', 'user3-adm']
```
not this (\_.words(array) without any pattern):
```
['user1', 'user2', 'user3', 'adm']
```
What is the right String/RegExp to use to make this happen? | 2015/05/15 | [
"https://Stackoverflow.com/questions/30267316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294591/"
] | The initial case can be solved by this:
```
_.words(['user1,user2,user3-adm'], /[^,]+/g);
```
Result:
```
["user1", "user2", "user3-adm"]
```
---
**[EDITED]**
If you want to add more separators, add like this:
```
_.words(['user1,user2,user3-adm.user4;user5 user7'], /[^,.\s;]+/g);
```
Result:
```
["user1", "user2", "user3-adm", "user4", "user5", "user7"]
```
Last snippet will separate by:
commas (`,`),
dots (`.`),
spaces (`\s`),
semicolons (`;`)
---
Alternatively you can use:
```
_.words(['user1,user2,user3-adm.user4;user5 user7*user8'], /[-\w]+/g)
```
Result:
```
["user1", "user2", "user3-adm", "user4", "user5", "user7", "user8"]
```
In this case you can add what you **don't want** as delimiter. Here it will will be separated by every character which is not `\w` (same as `[_a-zA-Z0-9]`) or `-`(dash) | `words` accept a regex expression to match the words and **not to split** them, being so, just use a regex that matches everything besides a comma, i.e.:
```
_.words(['user1,user2,user3-adm'], /[^,]+/g);
```
---
Alternatively, you can use `split`.
```
result = wordlist.split(/,/);
```
---
<https://lodash.com/docs#words> |
50,667,509 | I'm using the selenium library in python to open google chrome and visit google.com automatically, this is how my script looks like at the moment
```
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chromedriver = "/usr/bin/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
chrome_options = webdriver.ChromeOptions()
chrome_options.accept_untrusted_certs = True
chrome_options.assume_untrusted_cert_issuer = True
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--allow-http-screen-capture")
chrome_options.add_argument("--disable-impl-side-painting")
chrome_options.add_argument("--disable-setuid-sandbox")
chrome_options.add_argument("--disable-seccomp-filter-sandbox")
chrome_options.add_options("--enable-automation")
chrome_options.add_options("--disable-infobar")
driver = webdriver.Chrome(chromedriver, chrome_options=chrome_options)
driver.get("http://google.com/")
```
My browser tab never displays google.com and it just hangs there [This is the picture of how my browser looks like when I run the script](https://i.stack.imgur.com/tn6b4.png)
[](https://i.stack.imgur.com/09RgY.png)
My version of chromedriver is: ChromeDriver 2.39
My Google Chrome version is : Google Chrome 67.0
After doing Ctrl+c, i get this output
```
Traceback (most recent call last):
File "auto-run.py", line 16, in <module>
driver = webdriver.Chrome(chrome_path, chrome_options=chrome_options)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/chrome/webdriver.py", line 75, in __init__
desired_capabilities=desired_capabilities)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute
response = self.command_executor.execute(driver_command, params)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/remote_connection.py", line 472, in execute
return self._request(command_info[0], url, body=data)
File "/usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/remote_connection.py", line 496, in _request
resp = self._conn.getresponse()
File "/usr/lib/python3.6/http/client.py", line 1331, in getresponse
response.begin()
File "/usr/lib/python3.6/http/client.py", line 297, in begin
version, status, reason = self._read_status()
File "/usr/lib/python3.6/http/client.py", line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
KeyboardInterrupt
```
Any help as to why --enable-automation does not work would be greatly appreciated! | 2018/06/03 | [
"https://Stackoverflow.com/questions/50667509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7705100/"
] | make sure the returned form of the snapshot you get is json that matches what was read. If the return from the snapshot is in the form of an array [] then it must match, if it is an array object [{ }] then it must also match | change the name of the collection in the cloud firestore and in each query you have in the project.
that will change the name on the firebase page, at least that solved my problem
```
stream: Firestore.instance.collection("colection").snapshots(),
```
to
```
stream: Firestore.instance.collection("collection").snapshots(),
``` |
35,486,439 | That's my code. What i'm trying to do here is a code that Asks for a name ( like a pass ) if the name is wrong, then the program says those 3 error messages and asks the name again, until one of the 2 white-listed names is given, then just keep going with the code.
```
int main(void)
{
setlocale(LC_ALL, "Portuguese");
string Name = "";
cout << "Whats your name dude ?" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
cout << "Welcome friend =D" << endl;
system("pause");
system("cls");
}
else
{
do
{
cout << "Sorry, wrong name =[" << endl;
system("pause");
system("cls");
cout << "I'll give you another chance =]" << endl;
system("pause");
system("cls");
cout << "Write your name again" << endl;
cin >> Name;
if (Name == "ighor" ||
Name == "indio")
{
continue;
}
} while (Name != "ighor" ||
Name != "indio");
}
cout << "Whats up" << Name << endl;
system("pause");
system("cls");
return 0;
}
```
My tests with this code gave me this :
If i put a white-listed name ( indio or ighor ) i get the massage of correct name
>
> "Welcome friend =]".
>
>
>
If i put a wrong name, i get the massage of wrong name, nice, then i'm asked to enter the name again, i put one of the white-listed names and it keeps saying that it's the wrong name, wrong names also show wrong name message. | 2016/02/18 | [
"https://Stackoverflow.com/questions/35486439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5946129/"
] | The logic in the `do-while` loop is flawed. Instead of
```
continue;
```
you need
```
break;
```
`continue;` continues with the next iteration of the loop. `break;` breaks the loop.
Also, the `while` statement logic incorrect. You need to use:
```
while (Name != "ighor" && Name != "indio");
^^^ not ||
```
Having said that, you only need one of the checks, not both.
You can use:
```
do
{
...
if (Name == "ighor" || Name == "indio")
{
break;
}
} while (true);
```
or
```
do
{
...
} while (Name != "ighor" && Name != "indio");
``` | Thanks for all the answers i did changed
```
continue;
```
for
```
`break;`
```
and it worked perfect =)
But as the code was too confusing i may study a bit the other tips you guys gave me so i can make it cleaner =D
I just have another doubt with this piece of code
```
cin >> RPI;
if (RPI == "Sim"||RPI == "sim"||RPI == "vou"||RPI == "Vou")
```
What i wanted here was to "check" the answer and make something if i was "Sim" or "Vou" which(means "Yes" and "i will", but anyway)
I think that i can use what you guys told me about the "II" replacement for "&&" so it makes the condition correctly.
If there was a way or a command, so it don't differentiate Capital and lowercase just for this answer, so didn't i need to put both ways that the person can write would also help.
Thats just a learning code, only for studding propose
It was the first time i posted and really surprised, those lot of answers and it was too fast, thanks you all for the support.
You guys rule.
Good codding. |
49,469,258 | I am currently doing some tasks in Javascript.
I created a 2D Array at the beginning, completely empty:
```
let stonearray =[[]];
```
Now whenever the user clicks on a certain position, i save the values and want to push them into the array so that the values are saved there:
```
var posx2 = Math.floor(x/colSize)*colSize+colSize/2;
var posy2 = Math.floor(y/rowSize)*rowSize+rowSize/2;
var pusharr = [[posx2, posy2]];
stonearray.push([pusharr]);
```
Now i want to know if the array pair (value of pusharray) is already stored in the stonearray - which it should be by now. But whenever i try to check if "stonearray" already contains the "pusharr" it always says false.
I tried these versions to check:
```
//first attempt:
var contains = stonearray.includes([pusharr]);
//second attempt:
function checkContain(stonearray,pusharr) {
let a;
alert(pusharr);
for (a = 0; a < stonearray.length; a++) {
if (stonearray[a] === pusharr) {
return true;
}
}
return false;
}
```
It is always returning false. But why? I am pretty new to Javascript. Please don't be to harsh on me :( | 2018/03/24 | [
"https://Stackoverflow.com/questions/49469258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7912377/"
] | Using a string to define the name of a method within the scope of a class or a JS Object is acceptable.
```
j@j-desktop:~$ node
> function 'add'(x, y) {
function 'add'(x, y) {
^^^^^
SyntaxError: Unexpected string
> 'add'(x, y) {
... function 'add'(x, y) {
^^^^^
SyntaxError: Unexpected string
> 'add'(x, y) {
... return x + y;
... }
...
... ;
...
> class A {
... 'add'(x, y) {
..... return x + y;
..... }
...
... }
undefined
> let a = new A();
undefined
> a.add(1, 1);
2
> let obj = {
... 'addTwo'(x) {
..... return x + 2;
..... }
... }
undefined
> obj.addTwo(4);
6
``` | The `Metor.methods()` defines the server-side methods of your Meteor application.
It is not a simple function calling. With that you are defining which functions are going to be called by the client.
This is a way to your templates interact your dataBase, check, validate and make changes.
You can only call: `Meteor.call('stringName_ofFunction', {params}, (err, result)=>{CallBack});` if you previously defined this `'stringName_ofFunction'` as a function inside a `Meteor.methods();`.
The thing is, as your application gets bigger you can define different files for your serverSide methods, so you can get more organized. You are going to use Meteor.Methods(); to tell Meteor that those functions inside that method are your server side functions to be called by Meteor.call() on the client-side. |
43,463,246 | Basically here im using url connection to connect to php, everything is work find in log in and register phase, now i want to fetch the json object that i create in php file and then display it in a string view, so anyone got idea regarding this?
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
dataField = (TextView) findViewById(R.id.data);
btnDis = (Button) findViewById(R.id.btnClick);
btnDis.setOnClickListener (new View.OnClickListener(){
@Override
public void onClick(View v){
strUrl ="http://10.0.2.2/android/display.php";
new jsonParse().execute();
}
});
}
public class jsonParse extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(EditActivity.this,""+result,Toast.LENGTH_LONG ).show();
}
@Override
protected String doInBackground(String... params) {
try{
URL url = new URL (strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.connect();
//get response from server
BufferedReader bf = new BufferedReader(new InputStreamReader(con.getInputStream()));
String value = bf.readLine();
System.out.println("result is"+value);
result = value;
String finalJson = bf.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
JSONObject finalObject= parentArray.getJSONObject(0);
String username = finalObject.getString("NAME");
String age = finalObject.getString("AGE");
String result = username +" - "+age;
return result;
}
catch(Exception e){
System.out.println(e);
}
return null;
}
}
```
}
Here is my php file called display.php
```
<?php
require "conn.php";
require_once "global.php";
//get record from databases
$query = "SELECT * FROM user";
if($result = mysqli_query($conn, $query)){
// printf("%d", mysqli_num_rows($result));
if(mysqli_num_rows($result) > 0){
$status = 'true';
$message = 'data retrieved successfully';
while($row = mysqli_fetch_assoc($result)){
$name = $row['name'];
$age = $row['age'];
$username = $row['username'];
// echo $name."\n\n";
// echo $age."\n\n";
// echo $username."\n\n";
$data .= '{"NAME" : "'.$name.'", "AGE" : "'.$age.'", "USERNAME" : "'.$username.'"},';
}
}else{
$status = 'false';
$message = 'data retrieved failed';
$data = '';
}
mysqli_free_result($result);
mysqli_close($conn);
}else{
$message = mysqli_error($conn);
}
$output = '{"status": "'.$status.'","message":"'.$message.'", "data": ['.rtrim($data, ',').']}';
echo $output;
?>
``` | 2017/04/18 | [
"https://Stackoverflow.com/questions/43463246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7881785/"
] | add style to `.tab-item-active` class like this
```
.tab-item-active {
background:green;
}
```
see this codepen:<http://codepen.io/edisonpappi/pen/aWvmjz> | You can also use the SCSS **`$tabs-ios-tab-icon-color-active`** var inside your **theme/variables.scss**, for example :
```
// App iOS Variables
// --------------------------------------------------
// iOS only Sass variables can go here
$tabs-ios-tab-icon-color: #00f;
$tabs-ios-tab-icon-color-active: #f00;
// App Material Design Variables
// --------------------------------------------------
// Material Design only Sass variables can go here
$tabs-md-tab-icon-color: #00f;
$tabs-md-tab-icon-color-active: #f00;
```
which will give you something like this :
[](https://i.stack.imgur.com/Oolkn.png)
For more, take a look [here](https://ionicframework.com/docs/api/components/tabs/Tabs/#sass-variables).
Hope that can help. |
22,367,794 | I am currently debugging a DB application originally written in VBA 2005 that doesn't work with VBA 2010 and above versions. One of the (many) problems is that it uses the function IsNothing to test if an object variable has an object attached to it. This function seems to have been deprecated in 2010 and 2013. Is there an equivalent to this function in VBA 2013? | 2014/03/13 | [
"https://Stackoverflow.com/questions/22367794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3413388/"
] | As others have indicated, `IsNothing` has never been a VBA function and was likely written as syntactic sugar for `Is Nothing`.
[VB has an `IsNothing` function](http://msdn.microsoft.com/en-us/library/5adx7fxz%28v=vs.90%29.aspx) that serves the same purpose. In my experience, defining VBA functions that mirror familiar VB functions is common.
Here is a [VBA `IsNothing` implementation from Tek-Tips](http://www.tek-tips.com/faqs.cfm?fid=3834) that should be what you need - either to make the `IsNothing` calls work as-is...or provide a basis to inline them with equivalent code and strip the syntactic sugar:
```
'**********************************************************
'* Function: Returns true if argument evaluates to nothing
'* 1. IsNothing(Nothing) -> True
'* 2. IsNothing(NonObjectVariableOrLiteral) -> False
'* 3. IsNothing(ObjectVariable) -> True if instantiated,
'* otherwise False
'**********************************************************
Public Function IsNothing(pvarToTest As Variant) As Boolean
On Error Resume Next
IsNothing = (pvarToTest Is Nothing)
Err.Clear
On Error GoTo 0
End Function 'IsNothing
```
In fairness, note that this is essentially what @HansUp suggested already, just sourced elsewhere - and prefaced by a best-guess how the code you're debugging likely got the way it is. | IsNothing itself has never been a VBA function...
```
If obj Is Nothing Then...
```
may work for you, but may not yield the same results as the IsNothing function you are expecting. You may need to code more specific checks depending on what you want to determine. |
31,704,845 | Let's say I have a non-empty vector `z`.
I would like to replicate and shape this vector into a matrix with dimensions `[r, c, length(z)]`.
For example:
```
z = 1:5;
r = 3;
c = 3;
```
I am looking for a function that gives me:
```
ans(:, :, 1) =
[ 1 1 1 ]
[ 1 1 1 ]
[ 1 1 1 ]
ans(:, :, 2) =
[ 2 2 2 ]
[ 2 2 2 ]
[ 2 2 2 ]
...
ans(:, :, 5) =
[ 5 5 5 ]
[ 5 5 5 ]
[ 5 5 5 ]
```
NOTE:
Doing something like
```
tmp = zeros(r,c,length(z));
tmp = repmat(z, 3, 3, 1);
```
doesn't work. Instead it returns a 15x15 matrix as
```
tmp =
[ 1:5, 1:5, 1:5 ]
[ 1:5, 1:5, 1:5 ]
[ 1:5, 1:5, 1:5 ]
```
which is *not what I want*.
Transposing `z` first doesn't work either.
**The only solution I know** is to initially set `z` to be the 3rd dimension of a vector:
```
z(1,1,:) = 1:5;
```
Is there more efficient way to do this? Or is this the most effective approach?
COROLLARY: Is there a "transpose"-like function that transposes a vector into singleton dimension? That is, if [`transpose()`](http://www.mathworks.com/help/matlab/ref/transpose.html) shapes row vectors into column vectors and vice versa, is there a function that shapes a row/column vector into singleton dimensions and back?
Thanks in advance! | 2015/07/29 | [
"https://Stackoverflow.com/questions/31704845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3427580/"
] | What about a subquery ?
```
SELECT * FROM tableA
LEFT JOIN (SELECT tableB.id FROM tableB
JOIN tableC
ON tableC.id=tableB.id) tableZ
ON tableZ.id=tableA.id
``` | I think you might want this logic:
```
SELECT *
FROM tableA LEFT JOIN
(tableB JOIN
tableC
ON tableC.id = tableB.id
)
ON tableB.id = tableA.id ;
```
Normally, with `LEFT JOIN` you want to chain them, but there are some exceptions. |
626,641 | I would like to have a LED indicator that is on when the fuse is not blown and off when the fuse is blown. This is not hard to do as you can place a LED on the output of the fuse. What makes it very hard for me is that the bus that is fused has variable voltage, from 5 to 24 V. This still can be done with the method I mentioned previously but the LED will not be of constant brightness, faint on 5 V and bright on 24 V.
Is there a circuit that lets me maintain the current on the LED regardless of voltage? I found out that 1 mA is the perfect brightness for me. Since this is only a fuse indicator I would like it to be as simple less components it can possibly be. I assume you would need some op-amps or transistors for this to work.
I have already done a bit of research,
Using [op-amps](https://www.youtube.com/watch?v=7kLTBIQNXuU)
[](https://i.stack.imgur.com/M3UVj.png)
and using [transistors](https://www.nexperia.com/applications/sub-systems/constant-current-source.html)
[](https://i.stack.imgur.com/BPCvj.png)
I do not know if these circuits works and it looks like I only need about 1 or 2 IC/components. | 2022/07/08 | [
"https://electronics.stackexchange.com/questions/626641",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/250358/"
] | LM334 is the ideal solution, although two transistors will do a plenty acceptable job in this application:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fpAgZg.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
[](https://i.stack.imgur.com/no2Em.png) | Here is a circuit with a zener diode that will keep the LED current constant.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fEY2EI.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Note the differences to Lundins circuit.
The current through R1 needs to be bigger than the current through R2 and D2. But for 24 V instead of 5V the current through R1 is much bigger, so a lot of power is wasted in R1.
**I do not recommend this circuit, the other circuits by Andy Aka and Kuba are much better and waste much less power.** |
6,626,038 | How can I print the contents of an NSData object using NSLog:
```
-(void) post:(NSString*) msg to:(NSString*) link{
NSString *myRequestString = [NSString stringWithFormat:@"message=%@", msg];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: link]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSLog("%@", *returnData); //doesn't work
}
```
I would like to print the contents of \*returnData... | 2011/07/08 | [
"https://Stackoverflow.com/questions/6626038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559142/"
] | If you do this:
```
NSLog(@"%@", returnData);
```
The NSData will be logged in hex format. I think that is probably what you are after.
If you want to turn it into a string and log the string, you first need to find out what character set was used. **The default character set for HTTP is not UTF-8, it is ISO-8859-1**. One way to do that is to examine the `Content-Type` header for the charset section. | Check this answer if you need to have your data bytes as string
<https://stackoverflow.com/a/7520655/1344237> |
13,841,404 | I am trying to convert from Hex To BCD in Verilog. I am not using any clocks. In my program, I give one input at a time and convert it and show the result. But, my program is giving undefined result. How can I fix it?
```
module HexToBCD(num,result);
input num;
output [7:0]result;
assign result[0]=num%2;
assign num=num/2;
assign result[1]=num%2;
assign num=num/2;
assign result[2]=num%2;
assign num=num/2;
assign result[3]=num%2;
assign num=num/2;
assign result[4]=num%2;
assign num=num/2;
assign result[5]=num%2;
assign num=num/2;
assign result[6]=num%2;
assign num=num/2;
assign result[7]=num%2;
assign num=num/2;
endmodule
``` | 2012/12/12 | [
"https://Stackoverflow.com/questions/13841404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1830544/"
] | I see a few unusual things with your module.
1. `num` is 1 bit wide, but you are trying to divide it by 2.
2. You are assigning to an `input`.
3. You make the same assignment to `num` 8 times. Verilog does not work that way; all continuous assignments are evaluated in parallel. | The following code do the conversion of a 8 bit binary number to a BCD equivalent. For explanation about the algorithm refer to [this link](http://www.eng.utah.edu/~nmcdonal/Tutorials/BCDTutorial/BCDConversion.html).
```
module bcd (
input [7:0] binary,
output reg [3:0] hundreds,
output reg [3:0] tens,
output reg [3:0] ones);
integer i;
always @(binary) begin
// set 100's, 10's, and 1's to zero
hundreds = 4'd0;
tens = 4'd0;
ones = 4'd0;
for (i=7; i>=0; i=i-1) begin
// add 3 to columns >= 5
if (hundreds >= 5)
hundreds = hundreds + 3;
if (tens >= 5)
tens = tens + 3;
if (ones >= 5)
ones = ones + 3;
// shift left one
hundreds = hundreds << 1;
hundreds[0] = tens[3];
tens = tens << 1;
tens[0] = ones[3];
ones = ones << 1;
ones[0] = binary[i];
end
end
endmodule
``` |
37,987,798 | In my app, I'm getting JSON data from a php script. When I get the data, I have an `onClick()` method in my Fragment which changes a `TextView` to the parsed JSON.
However, when I swipe to a different fragment(it's a swipe/tabbed activity) my `TextView` does not retain the value I gave it, it changes to the original value.
I want it to retain the value.
MainActivity.java (I don't think this is important)
```
package me.anshsehgal.lunchmenu;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
String JSON_STRING;
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter; //make all the variables
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout)findViewById(R.id.tabLayout);
viewPager = (ViewPager)findViewById(R.id.viewPager); //reference them
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(),"Mon");
viewPagerAdapter.addFragments(new MondayFragment(),"Tue");
viewPagerAdapter.addFragments(new TuesdayFragment(),"Wed");
viewPagerAdapter.addFragments(new WednesdayFragment(), "Thu");
viewPagerAdapter.addFragments(new ThursdayFragment(), "Fri"); //adding fragments to view page adapter
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
HomeFragment frag = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.homeFragment);
}
```
HomeFragment.java (this is where things going wrong)
```
package me.anshsehgal.lunchmenu;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.Void;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements View.OnClickListener {
String JSON_STRING;
String jsonData;
TextView txt;
String day;
String soup;
String non_veg_main;
String non_veg_side;
String veg_main;
String veg_side;
String MondayMenu;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
txt = (TextView) view.findViewById(R.id.textJSON);
Button btn = (Button) view.findViewById(R.id.buttonGetJSON);
btn.setOnClickListener(this);
new BackgroundTask().execute();
return view;
}
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
try{
//JSON parsing
JSONObject parentObject = new JSONObject(jsonData);
JSONArray parentArray = parentObject.getJSONArray("server_response");
JSONObject finalObject = parentArray.getJSONObject(0);
//JSON data assigning to variables
day = finalObject.getString("day");
soup = finalObject.getString("soup");
non_veg_main = finalObject.getString("non_veg_main");
non_veg_side = finalObject.getString("non_veg_side");
veg_main = finalObject.getString("veg_main");
veg_side = finalObject.getString("veg_side");
}catch (JSONException e){
e.printStackTrace();
}
MondayMenu = "Soup: "+soup+"\n"+"Non Veg Main: "+non_veg_main+"\n"+"Non Veg Side: "+non_veg_side+"\n"+"Veg Main: "+veg_main+"\n"+"Veg Side: "+veg_side;
txt.setText(MondayMenu);
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
@Override
protected void onPreExecute() {
json_url="http://192.168.0.12/json_get_data.php";
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
jsonData = result;
}
}
}
``` | 2016/06/23 | [
"https://Stackoverflow.com/questions/37987798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6495580/"
] | ```
my_df <- data.frame(matrix(nrow=3,ncol=10))
my_df
# X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
# 1 NA NA NA NA NA NA NA NA NA NA
# 2 NA NA NA NA NA NA NA NA NA NA
# 3 NA NA NA NA NA NA NA NA NA NA
class(my_df)
# [1] "data.frame"
dim(my_df)
# [1] 3 10
# If column names are available
names(my_df) <- LETTERS[1:10]
my_df
# A B C D E F G H I J
# 1 NA NA NA NA NA NA NA NA NA NA
# 2 NA NA NA NA NA NA NA NA NA NA
# 3 NA NA NA NA NA NA NA NA NA NA
my_df<- data.frame(x= character(0), y= numeric(0), a = character(0), b= integer(0))
str(my_df)
# 'data.frame': 0 obs. of 4 variables:
# $ x: Factor w/ 0 levels:
# $ y: num
# $ a: Factor w/ 0 levels:
# $ b: int
``` | Using the previously suggested answer of
```
as.data.frame(matrix(0, nrow = ?, ncol = ?))
```
the parameter can be entered to create the predefined data frame
```
Components = 3
Forecast.Days = 200
Share.of.Room.Nights = as.data.frame(matrix(0, nrow = Forecast.Days, ncol = Components))
```
Using `if("Destination.1" %in% colnames(Share.of.Room.Nights))` allows determination of whether the column exists, after which the loops can be run to populate the columns that exist depending on the pre-defined parameters. |
106,295 | Let's say given an angle A = 46 °, side a = 2.29 and b = 2.71
I figured that the angle B = 58.4 by saying:
$$B = \sin^{-1} \left(\frac{ 2.71 \sin{46^{\circ}}}{2.29}\right)=58.4^{\circ}$$
But I think that angle C is incorrect:
$$C = \sin^{-1} \left(\frac{2.29 \sin{58.4^{\circ}}}{2.71}\right)=46.03^{\circ}$$
Someone who can help me? what do I do wrong and how should it be done? | 2012/02/06 | [
"https://math.stackexchange.com/questions/106295",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/24410/"
] | While the other answers have covered the basic use of the Law of Sines, they've all missed a critical point: there are **two** triangles that fit your given information. Here is the triangle you've found:

But, when you're solve $\sin B=\frac{b\sin A}{a}$, there are *two* solutions that could be angles in a triangle, $B\_1=\arcsin\left(\frac{b\sin A}{a}\right)$ (the one you found) and $B\_2=180°-\arcsin\left(\frac{b\sin A}{a}\right)$. Using this second possible measure for $B$ won't always yield a triangle, but in this case it does:

Here are both triangles pictured together:

This issue with the Law of Sines, sometimes called the "ambiguous case," is almost certainly what [the picture in your question here](https://math.stackexchange.com/q/106047/72) is about.
See also [my answer here on general techniques for triangle-solving](https://math.stackexchange.com/a/106540/72). | According to Sine Law :
$$\frac{b}{\sin \beta} =\frac{a}{\sin \alpha} \Rightarrow \beta = \arcsin \left(\frac{b\cdot \sin \alpha}{a}\right)$$
Once you find angle $\beta$ you can calculate $\gamma$ from :
$$\gamma = 180° - (\alpha + \beta)$$ |
58,593,768 | I want to be able to check if one list contains 2 elements of another list (that in total has 3 elements)
e.g:
```
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if #list2 contains any 2 elements of list1:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
``` | 2019/10/28 | [
"https://Stackoverflow.com/questions/58593768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12087286/"
] | I would use a similar description of the one described in the following question, only this time check the length of the sets intersection:
[How to find list intersection?](https://stackoverflow.com/questions/3697432/how-to-find-list-intersection)
```
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
if len(list(set(a) & set(b))) == 2:
print("yes, list 2 contains 2 elements of list 1")
else:
print("no, list 2 does not contain 2 elements of list 1")
``` | ```
count = 0
for ele in list2:
if ele in list1:
count += 1
if count == 2:
print ("yes, list 2 contains 2 elements of list 1")
else:
print ("no, list 2 does not contain 2 elements of list 1")
``` |
15,841,916 | If I put my service and activity in the same package, Can I exchange data between them using some global variables? I want optimized performance, so, global variables idea seems good but is it possible? If not, what is the best option. If intents is the way to go, then would the performance be good enough? BTW, the service has a big hashMap (may be multiple). This map needs to be accessed by the activity?
Thanks,
Rahul. | 2013/04/05 | [
"https://Stackoverflow.com/questions/15841916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1176304/"
] | ```
SELECT rating, ratetext, date, first
FROM rating r INNER JOIN client c
ON r.clientid = c.id
WHERE r.userid = 3;
``` | Presumably you want to select ratings with the explicitly specified ID, and the corresponding clients because on the `clientid` stored in the `rating` record:
```
SELECT rating,ratetext,date,first FROM rating r
INNER JOIN client c ON c.id = r.clientid
WHERE r.userid = 3;
``` |
52,593,859 | I want convert "Thu Jan 18 00:00:00 CET 2018" to "2018-01-18" -> yyyy-mm-dd.
But I get error -> java.text.ParseException: Unparseable date: "Thu Jan 18 00:00:00 CET 2018".
```
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
stringValue = String.valueOf(cell.getDateCellValue());
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(stringValue);
System.out.println(date);
break;
case Cell.CELL_TYPE_STRING:...
break;
}
```
Maybe is why I have `cell.getCellType()` and `Cell.CELL_TYPE_NUMERIC` deprecated ? | 2018/10/01 | [
"https://Stackoverflow.com/questions/52593859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8658782/"
] | You can use the Microsoft.Recognizers.Text.DataTypes.TimexExpression package [from NuGet](https://www.nuget.org/packages/Microsoft.Recognizers.Text.DataTypes.TimexExpression/). It's part of the Microsoft Recognizers Text project [here on github](https://github.com/microsoft/Recognizers-Text)
I found two ways you can use this library:
### Parse the expression using a TimexProperty and guess the year yourself:
```
var parsed = new Microsoft.Recognizers.Text.DataTypes.TimexExpression.TimexProperty("XXXX-10-28");
Console.WriteLine(parsed.Year); // = null
Console.WriteLine(parsed.Month); // = 28
Console.WriteLine(parsed.DayOfMonth); // = 10
```
### Resolve times useing the TimexResolver
```
var resolution = Microsoft.Recognizers.Text.DataTypes.TimexExpression.TimexResolver.Resolve(new [] { "XXXX-10-28" }, System.DateTime.Today)
```
The `resolution.Values` will contain an array with two resolution entries, one for the previous occurrence of that date and one for the next occurrence of that date (based on the DateTime you pass into the Resolve method.
Note that from personal experience and from what I saw on github, that at the time of writing, this package can be quite [buggy](https://github.com/microsoft/Recognizers-Text/issues/1560) with the more advanced expressions. | Use a custom format pattern:
```
using System;
using System.Globalization;
class MainClass {
public static void Main (string[] args) {
var format = "1234-10-30";
var date = DateTime.ParseExact(format, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine (date.ToString("dd/MM/yyyy"));
}
}
```
[Example](https://repl.it/@BanksySan/LightblueCostlyTelephones) |
43,904,295 | I have a function that is giving me some trouble. The code below returns the error message "Cannot read property 'value' of undefined". The function should just search through the values in the accountlist and return the one that starts with the submitted string. In the example, submitting "000555" should return 0.
```js
var accountlist = [{
"value": "000555 - TEST ACCOUNT NAME1",
"data": "184"
}, {
"value": "006666 - TEST ACCOUNT NAME2",
"data": "450"
}, {
"value": "007777 - TEST ACCOUNT NAME2",
"data": "451"
}];
function startswith(inputlist, searchkey, inputstring) {
var searchlength = inputstring.length;
console.log("starting search");
for (var il = 0; il < inputlist.length; il++) {
if (inputlist[il].window[searchkey].substring(0, (searchlength - 1)) == inputstring) {
console.log("FOUND IT " + il + " " + inputstring);
return il
}
}
}
startswith(accountlist, "value","000555");
``` | 2017/05/10 | [
"https://Stackoverflow.com/questions/43904295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2093112/"
] | You could use the find function:
```js
var accountlist = [{
"value": "000555 - TEST ACCOUNT NAME1",
"data": "184"
}, {
"value": "006666 - TEST ACCOUNT NAME2",
"data": "450"
}, {
"value": "007777 - TEST ACCOUNT NAME2",
"data": "451"
}];
var searchString = '000555';
var result = accountlist.findIndex((account) => { return account.value.startsWith(searchString);}, searchString)
console.log(result)
``` | You should use **filter** & **startsWith** method.
---
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
---
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
```js
const stateList = [
{ name: 'Alabama', shortName: 'AL' },
{ name: 'Alaska', shortName: 'AK' },
{ name: 'Arizona', shortName: 'AZ' },
{ name: 'Arkansas', shortName: 'AR' },
{ name: 'California', shortName: 'CA' },
{ name: 'Colorado', shortName: 'CO' },
{ name: 'Connecticut', shortName: 'CT' },
{ name: 'Delaware', shortName: 'DE' },
{ name: 'District of Columbia', shortName: 'DC' },
{ name: 'Florida', shortName: 'FL' },
{ name: 'Georgia', shortName: 'GA' },
];
var filterValue = 'Ala';
var result = stateList.filter(option => option.name.startsWith(filterValue));
console.log(result);
``` |
1,810,083 | This question goes out to the C gurus out there:
In C, it is possible to declare a pointer as follows:
```
char (* p)[10];
```
.. which basically states that this pointer points to an array of 10 chars. The neat thing about declaring a pointer like this is that you will get a compile time error if you try to assign a pointer of an array of different size to p. It will also give you a compile time error if you try to assign the value of a simple char pointer to p. I tried this with gcc and it seems to work with ANSI, C89 and C99.
It looks to me like declaring a pointer like this would be very useful - particularly, when passing a pointer to a function. Usually, people would write the prototype of such a function like this:
```
void foo(char * p, int plen);
```
If you were expecting a buffer of an specific size, you would simply test the value of plen. However, you cannot be guaranteed that the person who passes p to you will really give you plen valid memory locations in that buffer. You have to trust that the person who called this function is doing the right thing. On the other hand:
```
void foo(char (*p)[10]);
```
..would force the caller to give you a buffer of the specified size.
This seems very useful but I have never seen a pointer declared like this in any code I have ever ran across.
My question is: Is there any reason why people do not declare pointers like this? Am I not seeing some obvious pitfall? | 2009/11/27 | [
"https://Stackoverflow.com/questions/1810083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220177/"
] | Maybe I'm missing something, but... since arrays are constant pointers, basically that means that there's no point in passing around pointers to them.
Couldn't you just use `void foo(char p[10], int plen);` ? | On my compiler (vs2008) it treats `char (*p)[10]` as an array of character pointers, as if there was no parentheses, even if I compile as a C file. Is compiler support for this "variable"? If so that is a major reason not to use it. |
147,302 | I want to manage Document permission in document library using SharePoint Designer workflow like manage item level permission of list using workflow.
Can I manage permission of document using SharePoint Designer?
I got some [resources](http://spcycle.blogspot.in/2012/01/how-to-create-workflow-to-change-item.html) to manage item level permission of list, but I want to manage document permission through workflow. | 2015/06/25 | [
"https://sharepoint.stackexchange.com/questions/147302",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/43176/"
] | There is a workflow feature in the standard SP designer 2010 template (you have it if you are on sp 2010 or 13 or online, you do not have it if you are on SP 2007) called impersonation step.
This is one of the many pages that explain it
<http://blogs.sharepoint911.com/blogs/jennifer/Lists/Posts/Post.aspx?ID=91>
If you google sharepoint workflow impersonation step you find more documentation.
Basically the workflow that starts automatically when a document is added will detach the single entity and attribute the permissions you want on it (certain people as editors or viewers or certain groups as sole editors etc). | However, there is another way to handle your problem using a list and placing the document as attachment. This only if you do not need any feature on the document (versioning, approval etc).
This is a workaround if you want to avoid depending on a workflow. I have tested and if you send the link to a person that does not have rights to view the entry, even the attachment is access denied. |
5,201,282 | I'm trying to find an easy and slick way to do the following requirement.
I have a XML message with this arrangement:
```
<persons>
<person>
<firstName>Mike</firstName>
<middleName>K.</middleName>
<lastName>Kelly</lastName>
</person>
<person>
<firstName>Steve</firstName>
<lastName>David</lastName>
</person>
<person>
<firstName>Laura</firstName>
<middleName>X.</middleName>
<lastName>Xavier</lastName>
</person>
</persons>
```
I want to parse this XML using xPath expressions.
```
persons/person/firstName
persons/person/middleName
persons/person/lastName
```
My objective is store firstName, middleName and lastName tag values like this into a list of string objects like this:
```
firstNameList[0] = "Mike";
firstNameList[1] = "Steve";
firstNameList[2] = "Laura";
middleNameList[0] = "K.";
middleNameList[1] = null;
middleNameList[2] = "X.";
lastNameList[0] = "Kelly";
lastNameList[1] = "David";
lastNameList[2] = "Xavier";
```
In my C# code, I do this:
```
XmlNodeList firstNameNodeList = xmlDoc.SelectNodes("persons/person/firstName", nsmgr);
XmlNodeList middleNameNodeList = xmlDoc.SelectNodes("persons/person/middleName", nsmgr);
XmlNodeList lastNameNodeList = xmlDoc.SelectNodes("persons/person/lastName", nsmgr);
```
The problem with this code is that for middle name, I don't have it for 2nd person in my XML list. So the middleNameNodeList returns 2 values (K. and X.) but I wouldn't know whether the 1st or 2nd or 3rd person's middle name is missing.
I was hoping that SelectNodes() API would provide an iteration or index ID as which repeating element has a given value.
Please suggest me an easiest way to achieve what I needed? Thanks so much for your help, JK | 2011/03/05 | [
"https://Stackoverflow.com/questions/5201282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/645681/"
] | How about this?
```
foreach (Node person in xmlDoc.SelectNodes("persons/person", nsmgr))
{
firstNameNodeList.Add(person.SelectSingleNode("firstName", nsmgr));
middleNameNodeList.Add(person.SelectSingleNode("middleName", nsmgr));
lastNameNodeList.Add(person.SelectSingleNode("lastName", nsmgr));
}
``` | You just have to iterate over `persons/person` and handle each individually - this would work:
```
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"test.xml");
var persons = xmlDoc.SelectNodes("persons/person");
foreach (XmlNode person in persons)
{
string firstName = person.SelectSingleNode("firstName").InnerText;
string middleName = (person.SelectSingleNode("middleName") != null)
? person.SelectSingleNode("middleName").InnerText
: null;
string lastName = person.SelectSingleNode("lastName").InnerText;
}
``` |
62,198,198 | I have one-to-many relation between tables user and tag:
```
Users:
id username
--------------
1 Bob
2 Alice
3 Eve
Tags:
id user_id name
--------------------
1 1 java // Bobs tags...
2 1 java script
3 1 C#
4 2 java // Alices tags...
5 3 java // Eves tags...
6 3 java script
```
My goal is to extract all users with tags java or java script only, but not users which have java, java script and C# together.
As output of the query I expect to receive following result:
```
Result:
id username
--------------
2 Alice
3 Eve
```
I've tried to use query from [SQL one-to-many relationship - How to SELECT rows depending on multiple to-many properties?](https://stackoverflow.com/questions/51153040/sql-one-to-many-relationship-how-to-select-rows-depending-on-multiple-to-many), but as I noticed it is a bit different idea behind of it | 2020/06/04 | [
"https://Stackoverflow.com/questions/62198198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1589723/"
] | Try this one:
```
const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());
```
As moment is modifying the original moment object, either use toString() or toDate() to get the modified date.
```js
const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());
console.log('In local time => ', toNextDay.toString());
const toUTC = moment.utc("2020-06-30T00:00:00");
const toNextDayUTC = moment.utc(toUTC.add(1, 'days').toDate());
console.log('In UTC => ', toNextDayUTC.toString());
```
```html
<script src="https://momentjs.com/downloads/moment.min.js"></script>
``` | Check the rest of the code because this part is correct
```
const to = moment("2020-06-30T00:00:00")
//undefined
to.format()
//"2020-06-30T00:00:00+02:00"
const nextDay = to.add(1, "day")
//undefined
nextDay.format()
//"2020-07-01T00:00:00+02:00"
to.format()
//"2020-07-01T00:00:00+02:00"
```
A little warning, Moment.add() mutates the moment so after to.add(1, "day") to and nextDay are the same date, 2020-07-01. Use to.clone().add(1, "day") if you don't want to lose the original moment |
26,764,320 | My question is: how do I delete all the lowercase words from a string that is an element in a list? For example, if I have this list: `s = ["Johnny and Annie.", "She and I."]`
what do I have to write to make python return `newlist = ["Johnny Annie", "She I"]`
I've tried this, but it sadly doesn't work:
```
def test(something):
newlist = re.split("[.]", something)
newlist = newlist.translate(None, string.ascii_lowercase)
for e in newlist:
e = e.translate(None, string.ascii_lowercase)
``` | 2014/11/05 | [
"https://Stackoverflow.com/questions/26764320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869552/"
] | use `filter` with `str.title` if you just want the words starting with uppercase letters:
```
from string import punctuation
s = ["Johnny and Annie.", "She and I."]
print([" ".join(filter(str.istitle,x.translate(None,punctuation).split(" "))) for x in s])
['Johnny Annie', 'She I']
```
Or use a lambda not x.isupper to remove all lowercase words:
```
[" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]
``` | Translate is not the right tool here. You can do it with a loop:
```
newlist = []
for elem in s:
newlist.append(' '.join(x for x in elem.split(' ') if x.lower() == x))
``` |
778,803 | I installed a Windows XP x86 on my PC. But when I open the system information window in the *System Summary* tab, in the right-hand pane and at bottom the following are written:
*Total Physical memory 768.00 MB
Available Physical memory 270.41 MB !!*
Why *Available Physical memory* is 270.41 MB please?
PS: My system is very slow and also very slower when start up. Isn't that less Available Physical memory the source of that slowness? | 2014/07/09 | [
"https://superuser.com/questions/778803",
"https://superuser.com",
"https://superuser.com/users/337339/"
] | The Operating System will always consume some amount of memory to do it's work and reserve some for caching data.
Furthermore, any programs that you might have installed and have components that load on startup will consume memory. Eg: Antivirus.
Memory is also consumed by the inbuilt graphics capabilities of your processor/motherboard.
The total amount consumed can also vary depending on how much RAM is currently available.
Finally, for a good example, I have a desktop system at home with 512 MB RAM but only 448MB is available as 64MB goes for inbuilt graphics. After booting, I have only about 80MB available and this gets used up really quickly once I open a browser, leading to slowdowns.
To boost performance significantly, perhaps you should consider upgrading your RAM. | * I assume your harddisk is working overtime as well ?
* You can reduce memory usage. Firstly, install a program called CLEANMEM (from PcWinTech) and let the program also collapse the filecache. Reduced memory usage also means that Win XP doesn't need to access the harddisk that often. It improves overall system performance.
* The best way is to add more memory. I assume you must remove the existing memory modules (3x 256 MB) and install 2 512 MB or 2 1 GB modules. GOOGLE it, to find out how much memory can be installed on your system. |
5,959,825 | What is purpose of the following code?
```
preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
```
What kind of **$string** match this expression?
Why there is a character **@**? | 2011/05/11 | [
"https://Stackoverflow.com/questions/5959825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672470/"
] | `@` is used as a delimiter like `/`, and it's totally acceptable.
The pattern is matching *script* and *style* tags I assume. | *[Is there anything like RegexBuddy in the open source world?](https://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world)* (now deleted) lists a few tools which analyze regular expressions. There are also online tools, *[Is there an online RegexBuddy-like regular expression analyzer?](https://stackoverflow.com/questions/2491930/is-there-an-online-regexbuddy-like-regular-expression-analyzer)* for the same purpose.
The `@` is the PCRE delimiter in your example regex.
See: *[Delimiters](http://php.net/manual/en/regexp.reference.delimiters.php)* |
11,786,050 | I'm using `ArrayAdapter` to bind my data from my `ArrayList`to my `ListView` and i use an `AlertDialog`to insert data into my `Arraylist`. My problem is that i'm unable to refresh my `ListView` after the changes done.
**Code**
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config_hidden);
listView=(ListView) findViewById(R.id.hiddenList);
xmlFileManager=new XmlFileManager(this);
addNumber=(Button) findViewById(R.id.addNum);
addNumber.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(HiddenCall.this);
final View alertDialogView = factory.inflate(R.layout.add_number, null);
AlertDialog.Builder adb = new AlertDialog.Builder(HiddenCall.this);
adb.setView(alertDialogView);
adb.setTitle(R.string.dialog_title);
adb.setIcon(R.drawable.phone);
final AlertDialog alertDialog = adb.create();
adb.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
numberToAdd=(EditText) alertDialogView.findViewById(R.id.numberToAdd);
String number = numberToAdd.getText().toString();
if(number.length()>0){
xmlFileManager.addNumberToXml(number , HIDDEN_NUMBER_TYPE);
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, xmlFileManager.getHiddenNumbers());
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
}
} });
adb.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
} });
adb.show();
}
});
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, xmlFileManager.getHiddenNumbers());
adapter.notifyDataSetChanged();
adapter.setNotifyOnChange(true);
listView.setAdapter(adapter);
}
``` | 2012/08/02 | [
"https://Stackoverflow.com/questions/11786050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1382540/"
] | If you have a small ArrayList, to force update a ListView when the ArrayList changes you can use this code snippet:
```
ArrayAdapter.clear();
ArrayAdapter.addAll(ArrayList);
ArrayAdapter.notifyDataSetChanged();
``` | Every click you create new adapter. You don't need to do this. You can modify existing adapter data and call notifyDataSetChanged(). In your case you should call listView.setAdapter(adapter) in onClick method. |
56,038,135 | I am trying to create a query which - when executed - will show a date, status (where there are there are several status options) and the number of events on that date - distinguished by status.
I was able to create a query which shows all data I desire, but I am getting repetitions in dates. I think the way to do it is to use the aliases, but I can't figure out the way. I also tried the case statement, but with no success neither.
```sql
SELECT cast(event_date AS date) AS date, count(event_status) AS amount, status
FROM events
GROUP BY date, status
```
Right now this is what I'm getting:
```sql
date | amount | status
---------------------------------------
2019-05-07 | 5 | YES
2019-05-07 | 1 | NO
2019-05-06 | 4 | YES
2019-05-05 | 3 | YES
2019-05-04 | 6 | YES
2019-05-04 | 2 | MAYBE
```
And this is what I want to get:
```sql
date | POSITVE | Negative
---------------------------------------
2019-05-07 | 5 | 1
2019-05-06 | 4 | 0
2019-05-05 | 3 | 0
2019-05-04 | 6 | 2
```
where any status which isnt't equal to 'Yes' is negative.
Any suggestions?
Just to clarify: my desired output is just one of the options, I know there could be different ways to solve my problem, but this will suit me fine. Thanks | 2019/05/08 | [
"https://Stackoverflow.com/questions/56038135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11079649/"
] | You can do conditional aggregation :
```
select cast(event_date AS date) AS date,
sum(case when status = 'Yes' then 1 else 0 end) as Positive,
sum(case when status <> 'Yes' then 1 else 0 end) as Negative
from events e
group by cast(event_date AS date);
```
However, `mariaDB` has shorthand version for that :
```
select cast(event_date AS date) AS date,
sum( status = 'Yes' ) as Positive,
sum( status <> 'Yes' ) as Negative
from events e
group by cast(event_date AS date);
``` | Use `case` and `Sum` like:
```
SELECT cast(event_date AS date) AS date,
SUM(CASE WHEN status='YES' THEN 1 ELSE 0 END) as POSITIVE,
SUM(CASE WHEN status !='YES' THEN 1 ELSE 0 END) as NEGATIVE
FROM events
GROUP BY date
``` |
20,863 | Scenario
--------
I have a bunch of standalone PSTricks files. Each of those files can be compiled by `latex-dvips-ps2pdf-pdfcrop-pdftops` to produce a PDF image. I have made a batch file to do `latex-dvips-ps2pdf-pdfcrop-pdftops`.
In my main input file, I will iterate through the PSTricks files.
For each iteration, I check whether or not the corresponding PDF exists. If the corresponding PDF already exists, I check whether or not its time stamp is newer than that of its `.tex` file. Otherwise I will invoke `\immediate\write18 mybatch.bat filename.tex` to produce or re-produce the corresponding PDF file.
Question
--------
Can (La)TeX compare the time stamps of two external files? Providing the complete working source code for my scenario above is preferred. :-)
Note: Actually I can make an external script to iterate through the PSTricks files and invoke this script only once from within the main input file. But I am interested in creating the hybrid solution. | 2011/06/15 | [
"https://tex.stackexchange.com/questions/20863",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/2099/"
] | I wrote the `filemod` package just for this task which I also need for the upcoming version of `standalone`. It requires pdf(La)TeX or Lua(La)TeX but doesn't work with Xe(La)TeX.
Basic Usage:
```
\Filemodcmp{<file 1>}{<file 2>}{<1 is newer>}{<2 is newer>}
```
There is also a fully expandable version called `\filemodcmp` and also macros to find the newest or oldest file from a given list. | ```
\def\comparetimestamp#1#2{%
\ifnum\pdfstrcmp{\pdffilemoddate{#1}}{\pdffilemoddate{#2}}<0
\message{#1 is older than #2}%
\fi}
```
Change the `\message` line to what you need. Not usable with XeLaTeX, only with (pdf)latex. It may give problems if there's a change in the time zone (for example when changing to or from DST) between runs, but this should not be a problem. |
2,461,521 | I need to express the solution of this initial value problem about vibration below using Convolution Integral;
>
> $$my''+cy'+ky=f(t) \quad y(0)=0,\quad y'(0)=0$$
>
>
>
But don't have any idea where do i use the Convolution Integral. So how do I do it?
I tried to take laplace transform of both sides.
$$
(ms^2+cs+k)Y(s)=L(f(t))\quad (assuming \quad L(y(t))=Y(s))
$$
I presumed;
$$
f(t)=\int\_0^t g(t-T)h(T) \,dT \quad L(g(t))=G(s) \quad L(h(t))=H(s)
$$
So the Convolution theorem gives me the laplace transform of the right side;
$$
L(f(t))=G(s)H(s)
$$
and putting it into the equation;
$$
(ms^2+cs+k)Y(s)=G(s)H(s)
$$
$$
Y(s)=\frac{G(s)H(s)}{ms^2+cs+k}
$$
$$
y(t)=L^{-1}(\frac{G(s)H(s)}{ms^2+cs+k})
$$
I don't know if this solution is enough or correct. | 2017/10/07 | [
"https://math.stackexchange.com/questions/2461521",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/488616/"
] | >
> **Obtaining a Series Representation of the Inverse Laplace Transform**
>
>
>
Given the expression $s\bar x(s)-1=\frac1s(1-e^{-s})+e^{-s}\bar x(s)$, we find directly that
$$\begin{align}
\bar x(s)&=\frac{\frac1s(1-e^{-s})+1}{s-e^{-s}}\\\\&=\frac1s\left( \frac{\frac1s(1-e^{-s})+1}{1-\frac{e^{-s}}{s}}\right)\tag 1
\end{align}$$
Note that from $(1)$ we have
$$\bar x(s)-\frac1s =\frac1{s^2}\frac{1}{1-\frac{e^{-s}}{s}}\tag 2$$
Next, we can expand the denominator term $1-\frac{e^{-s}}{s}$ and write
$$\frac1{1-\frac{e^{-s}}{s}}=\sum\_{k=0}^\infty \frac{e^{-ks}}{s^k}\tag3$$
Using $(3)$ in $(2)$ reveals
$$\bar x(s)-\frac1s=\frac1{s^2}\sum\_{k=0}^\infty \frac{e^{-ks}}{s^k}$$
whence we find that
$$\bar x(s)=\frac1s+\frac1{s^2}\sum\_{k=0}^\infty \frac{e^{-ks}}{s^k}$$
as was to be shown!
---
>
> **NOTE: Inverse Laplace Transform**
>
>
>
The inverse Laplace Transform of $\frac1{s^n}$ is $\frac{t^{n-1}}{(n-1)!}u(t)$ and the inverse Laplace Transform of $F(s)e^{-s\tau}$ is $f(t-\tau)u(t-\tau)$.
Hence, the inverse Laplace Transform of $\frac{e^{-ks}}{s^{k+2}}$ is $\frac{(t-k)^{k+1}}{(k+1)!}u(t-k)$.
Finally, we have
$$x(t)=1+\sum\_{k=0}^\infty \frac{(t-k)^{k+1}}{(k+1)!}u(t-k)$$
whereupon shifting the summation index yields
$$\begin{align}
x(t)&=1+\sum\_{k=1}^\infty \frac{(t+1-k)^k}{k!}u(t+1-k)\\\\
&=\sum\_{k=0}^{\lfloor t+1\rfloor} \frac{(t+1-k)^k}{k!}
\end{align}$$ | From $$s\bar{x}(s)-1= \frac{1}{s}(1-e^{-s})+e^{-s}\bar{x}(s)$$
you get
$$s\bar{x}(s)-e^{-s}\bar{x}(s)=1+\frac{1}{s}(1-e^{-s})$$
collect $\bar{x}(s)$
$$(s-e^{-s})\bar{x}(s)=1+\frac{1}{s}(1-e^{-s})$$
$$\color{red}{\bar{x}(s)=\frac{1+s-e^{-s}}{s(s-e^{-s})}}$$
Now prove the second part
$$\sum \_{k=0}^{\infty } \frac{e^{-k s}}{s^k}=\sum \_{k=0}^{\infty } \left(\frac{e^{- s}}{s}\right)^k=\frac{1}{1-\frac{e^{- s}}{s}}=\frac{s}{s-e^{-s}}$$
Therefore
$$\bar{x}(s)=\frac{1}{s}+\frac{1}{s^2}\sum \_{k=0}^{\infty } \frac{e^{-k s}}{s^k}=\frac{1}{s}+\frac{1}{s^2}\frac{s}{s-e^{-s}}=\frac{1}{s}+\frac{1}{s(s-e^{-s})}=\color{red}{\frac{1+s-e^{-s}}{s(s-e^{-s})}}$$ |
34,337,811 | Isn't it a generally a bad idea to convert from a larger integral type to a smaller signed if there is any possibility that overflow errors could occur? I was surprised by this code in C++ Primer (17.5.2) demonstrating low-level IO operations:
```
int ch;
while((ch = cin.get()) != EOF)
cout.put(ch); //overflow could occur here
```
Given that
* cin.get() converts the character it obtains to `unsigned char`, and then to `int`. So `ch` will be in the range `0-255` (exluding EOF). All is good.
* But then in the `put(ch)` expression `ch` gets converted back to `char`. If `char` is `signed` then any value of `ch` from `128-255` is going to cause an overflow, surely?
Would such code be generally bad practice if I'm expecting something outside of ordinary input `0-127`, since there are no guarantees how overflow is treated? | 2015/12/17 | [
"https://Stackoverflow.com/questions/34337811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5627734/"
] | There are rules for integer demotion.
>
> When a long integer is cast to a short, or a short is cast to a char,
> the least-significant bytes are retained.
>
>
>
As seen in: <https://msdn.microsoft.com/en-us/library/0eex498h.aspx>
So the least significant byte of `ch` will be retained. All good. | Use [itoa](http://www.cplusplus.com/reference/cstdlib/itoa/), if you want to convert the integer into a null-terminated string which would represent it.
```
char * itoa ( int value, char * str, int base );
```
or you can convert it to a string , then char :
```
std::string tostr (int x){
std::stringstream str;
str << x;
return str.str();}
```
convert string to char
```
string fname;
char *lname;
lname = new char[fname.lenght() + 1];
strcpy(f, lname.c_str());
```
if you see "Secure Error" disable it with #Pragma |
58,391 | I am a bit rubbish at CSS and have mainly based my website off another website, in hope it would look different, although it didn't. I just want comments and tips how to change things but still keep it looking nice.
I just want advice about the [home page](http://prntscr.com/86svoc) at the moment.
[](https://i.stack.imgur.com/UuVHR.jpg) | 2015/08/20 | [
"https://graphicdesign.stackexchange.com/questions/58391",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/48641/"
] | I would advise the following:
* *Grid alignment:* Scoot your main content and top nav to the left so it lines up with "home page"
* *Content Justification:* the secondary information on the right is calling a lot of attention to itself, I would change the blue to something less eye catching, and put more color emphasis on the main content somehow. Perhaps make it not as wide, or center both columns in the middle of the page.
* *Unified illustration style:* The icon on the left is very different from the pixel style, if the pixel style is important, use it on all imagery, or have more uses of the icon style on the top left.
Best of luck! | I guess this would be a start. Taking into account you based this website on another one and it turned out pretty much the same, you might wanna consider changing the colors and the font too.
Good luck.
PS: I took out your design on the upper right corner cause it had nothing to do with what's going on in your actual website design.
[](https://i.stack.imgur.com/kx5wp.jpg) |
63,460,465 | I have a dataframe like:
```
df = pd.DataFrame([['A', 3, 'fox'], ['A', 3, 'cat'], ['A', 3, 'dog'],
['B', 2, 'rabbit'], ['B', 2, 'dog'], ['B', 2, 'eel'],
['C', 6, 'fox'], ['C', 6, 'elephant']],
columns=['group', 'val', 'animal'])
df
```
Output:
```
group val animal
0 A 3 fox
1 A 3 cat
2 A 3 dog
3 B 2 rabbit
4 B 2 dog
5 B 2 eel
6 C 6 fox
7 C 6 elephant
```
For a given group, the `val` is always the same (so always 3 for `A`, 2 for `B`, 6 for `C`).
How can I generate a dataframe with all combinations of `group` and `animal` elements? Also `val` should be carried over and there should be a column indicating whether this row was present in the original data or added in the permutations.
Desired result:
```
df = pd.DataFrame([['A', 3, 'fox', 1], ['A', 3, 'cat', 1], ['A', 3, 'dog', 1], ['A', 3, 'rabbit', 0], ['A', 3, 'eel', 0], ['A', 3, 'elephant', 0],
['B', 2, 'rabbit', 1], ['B', 2, 'dog', 1], ['B', 2, 'eel', 1], ['B', 2, 'fox', 0], ['B', 2, 'cat', 0], ['B', 2, 'elephant', 0],
['C', 6, 'fox', 1], ['C', 6, 'elephant', 1], ['C', 6, 'cat', 0], ['C', 6, 'dog', 0], ['C', 6, 'rabbit', 0], ['C', 6, 'eel', 0]],
columns=['group', 'val', 'animal', 'occurred'])
df
```
Output:
```
group val animal occurred
0 A 3 fox 1
1 A 3 cat 1
2 A 3 dog 1
3 A 3 rabbit 0
4 A 3 eel 0
5 A 3 elephant 0
6 B 2 rabbit 1
7 B 2 dog 1
8 B 2 eel 1
9 B 2 fox 0
10 B 2 cat 0
11 B 2 elephant 0
12 C 6 fox 1
13 C 6 elephant 1
14 C 6 cat 0
15 C 6 dog 0
16 C 6 rabbit 0
17 C 6 eel 0
```
How can I do this?
Edit: there have been a few answers which work. I'll give 'best' to whichever can be made to handle the possibility of multiple columns joined to `group` (e.g. not just `'val'` but `['val1','val2']`) in an elegant way. | 2020/08/18 | [
"https://Stackoverflow.com/questions/63460465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12384851/"
] | Try:
```
df2 = pd.DataFrame(list(product(df.group.unique(), df.animal.unique())), columns=['group', 'animal'])
df2['val'] = df2['group'].map(df.set_index('group')['val'].to_dict())
df2.merge(df.drop('val', axis=1).assign(occurred=1), how='outer').fillna(0, downcast='infer')
``` | You want to make a pivot table.
This is done in Pandas with the pandas.pivot\_table(data, values=None, index=None, columns=None, aggfunc='mean', fill\_value=None, margins=False, dropna=True, margins\_name='All', observed=False) command.
As you can see there are many arguments that pandas.pivot\_table() takes, but there are some main ones. In your case, you are looking for pandas.pivot\_table(df, columns=["group", "animal"], aggfunc = custom).
custom is a function you would have to write above the execution of the pivot\_table() line to get the functionality you described: "val should be carried over and there should be a column indicating whether this row was present in the original data or added in the permutations". |
16,453,468 | Why is this printing 1??? Its driving me INSANE. Should be printing 1.01005016708
I am using bloodshed dev c++ to compile
```
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
double rate = .05;
double time = (1/5);
double p = exp(rate*time);
cout<<p<<endl;
system("PAUSE");
return 0;
}
``` | 2013/05/09 | [
"https://Stackoverflow.com/questions/16453468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681664/"
] | ```
double time = (1/5);
```
should be
```
double time = (1.0/5);
```
Otherwise, `time` will get `0.0` because of integer division truncation. Therefore, `p = exp(0.0)` will be 1. | Sorry this isn't the answer to your question, but Thomas and tacop got that covered.
You should look for a new IDE to use, i myself switched to code::blocks and i think it's great, but here are some reasons why:
>
> 1. Dev-C++ has not been updated since 2005, and is not currently maintained. The software is very buggy. At the time of my writing
> there are 340 known bugs that will never be fixed.
> 2. It’s hard to get help, because the programming community have moved on to newer software.
> 3. Dev-C++ lacks features that are present in more modern solutions. Code completion, intellisense, and proper debugging facilities (among
> others) are not provided. These tools can greatly improve the
> workflow and efficiency of an experienced programmer, and may aid the
> learning of beginners.
> 4. Error messages and the steps required to solve them are poorly documented compared to more modern solutions, and because most
> programmers have moved on from Dev-C++ it can be difficult (if not
> impossible) to find anyone who is able to help you. Some problems may
> not be able to be solved at all. The compiler included with Dev-C++ is
> very out-dated, and buggy. An out-dated compiler can result in buggy
> and inefficient code, and may be damaging to the learning process for
> a beginner.
> 5. The provided “devpack” system is no longer supported by modern libraries. Using external libraries in Dev-C++ can be a confusing and
> difficult process for beginners who are expecting this simple system
> to handle it for them. There are plenty of modern, freely available
> alternatives that do not suffer from the same problems, and it is
> simply ridiculous that any beginner should end up using such a
> horrible and out-dated tool as Dev-C++.
>
>
>
Plus you can get rid of that wretched `system("PAUSE");` |
7,080 | Think of the following balls as individuals of populations.
Say I have $U$ urns, and some balls. Both numbers are *really* large. So large, that authors like Blanchard and Diamond have approximated the binomial operations that follow with Poisson probabilities.
The balls are either red ($R$) or green ($G$). At the beginning of the period, every ball is (randomly, iid) tossed into an urn. There is no miss chance (i.e. every ball is in *some* urn). Some urns will have more than one ball, some might have none.
There are two exercises I want to do in this setup, and I'm not sure to what extent they're overlapping (i.e. helping me understand one would help me understand the other one as well), so I will post both.
My issue is kind of that I have a binomial thinking going on, and you can see that from the structure that I have imposed onto solving the following probabilities. Should I switch to Poisson probabilities instead? What is the *neatest* way to solve the following setups?
### Red Ball Solo
I would like to compute the ex-ante probability of a red ball (from the perspective of a red ball) of being tossed into an urn where there is no other red ball.
So far, I was thinking about doing
$$
Prob(\text{sole red ball}) = \sum\_{x = 1}^{R + G} Prob(\text{Urn has $x$ balls}) \cdot \sum\_{y=0}^{x-1}Prob(\text{No other red ball } | x \text{ balls})
$$
### Red Ball Super Ball
Out of each urn, one red ball becomes a super ball. This probability is uniform. I would like to compute the probability of a red ball becoming a super ball.
My abstract idea was again similar:
$$
Prob(\text{red ball becomes super ball}) = \sum\_{x = 1}^{R + G} Prob(\text{Urn has $x$ balls}) \cdot \sum\_{y=0}^{x-1}Prob(\text{$y$ other red balls | $x$ total balls }) \frac{1}{1+y}
$$ | 2015/08/30 | [
"https://economics.stackexchange.com/questions/7080",
"https://economics.stackexchange.com",
"https://economics.stackexchange.com/users/43/"
] | *(If urns are vacancies and balls are unemployed, what distinction between unemployed workers does the Red/Green dichotomy reflects?)*
Each ball has in front of it an identical box, each with the exact same lottery tickets, its ticket has a number on it, and each number corresponds to an urn.
We say "Go!" and each ball draws "randomly" (i.e. with equal probability) a ticket from the box in front of it. Note that the requirement that the probabilities are Uniform, impose the condition that, if we want to have proper distributions, the number of urns must be *finite* (not even countably infinite -see [this post in statistics.se](https://stats.stackexchange.com/questions/103930/discrete-uniform-random-variable-taking-all-rational-values-in-a-closed-inter)) Then:
**RED BALL SOLO**
**From the point of view of a single Red ball, what is the probability that it will draw a number that no other Red ball draws?**
Since each ball draws independently from the others, it is clear that we don't care at all about the existence of Green balls, to the degree that no upper limit of "number of balls in an urn" exists (if it existed the draws would not be independent). So Green balls (their number and what they draw from their boxes) can be kept out of the picture.
Since Red balls are indistinguishable, let's take $R\_1$ as our hero. If it draws the number $1$ (i.e. conditional on) we want the probability
$$\Pr(R\_j \neq 1 \mid R\_1 =1)\;\; j=2,...N\_R$$
But draws are independent so we want simply
$$\Pr(R\_j \neq 1) = \prod\_{j=2}^{N\_R}[1-\Pr(R\_j = 1)] = (1-1/N\_U)^{N\_R-1}$$
But $R\_1$ can draw not just $"1"$, but any number, and each with probability $1/N\_U$. So the probability of the event that we want, denote it $\Pr(\text{RBS})$ is ([Law of Total Probability](https://en.wikipedia.org/wiki/Law_of_total_probability))
$$ \Pr(\text{RBS}) = \sum\_{i=1}^{N\_U}\left(\frac {1}{N\_U}\right)\cdot \Pr(R\_j \neq i \mid R\_1 =i) = \left(\frac {1}{N\_U}\right)\sum\_{i=1}^{N\_U}(1-1/N\_U)^{N\_R-1}$$
$$\implies \Pr(\text{RBS}) = \left(\frac {1}{N\_U}\right) \cdot N\_U \cdot (1-1/N\_U)^{N\_R-1} = (1-1/N\_U)^{N\_R-1}$$
...again.
This is intuitive: the greater the number of urns, the higher the probability. The greater the number of Red balls, the lower the probability.
Now, define job market tightness as usual by
$$\theta = N\_U/N\_R \implies N\_R = \frac 1 {\theta} N\_U$$
(here "U" denotes "urns" so vacancies). Then
$$\Pr(\text{RBS}) = \left(1-\frac 1{N\_U}\right)^{\frac 1 {\theta} N\_U-1}$$
If $N\_U$ grows "large" then the above is well approximated by
$$\Pr(\text{RBS}) \approx e^{-\frac 1 {\theta} }$$
The higher job market tightness, the higher the probability that an unemployed will be matched solo to a vacancy (again, ignoring what the Greens represent). | This is a complement/comment to Alecos' answer, who said that
>
>
> >
> > Note that the requirement that the probabilities are Uniform, impose the condition that, if we want to have proper distributions, the number of urns must be finite
> >
> >
> >
>
>
>
Denote the total size of the world as $N$. Denote urns as $U\_N$, balls as $B\_N$, and say that we randomly toss every ball into an urn. Urns and balls are "scaled", i.e. $U\_N = uN$, $B\_N = bN$, for two constants $u$, $b$. Then the distribution of balls for any urn is Binomial
$$ Prob(k \text{ balls arrive}) = Binomial(k; n=B\_N, p=1/U\_N)$$
In the next step, I want to let the number of urns and balls go to infinity. Note that if $np$ converges to a finite number as we let $N\to \infty$, the distribution of ball arrivals for any particular urn is approximated (pretty accurately) by
$$ Prob(k \text{ balls arrive for N ``large''}) = Poisson(k; \lambda=np)$$
And indeed, due to the setup, $np = B\_N/U\_N = b/u$ converges as $N\to \infty$. |
57,423,057 | I want to remove the max `2` value(outliers) of each column and then analyze the left dataframe.
```
> data.frame(q1 = c(2, 4, 5,8,8), q2 = c(1, 6, 3,8,5), q3 = c(5, 3, 6,5,2))
q1 q2 q3
1 2 1 5
2 4 6 3
3 5 3 6
4 8 8 5
5 8 5 2
```
The max 2 value in `q1`:8,8,then row 5,4 should be removed
The max 2 value in `q2`:8,6,then row 4,2 should be removed
The max 2 value in `q3`:6,5,then row 3,4(**not 1**,to keep the left dataframe as long as possible,which means remove rows as less as possible) should be removed
The expect result as below:
```
q1 q2 q3
1 2 1 5
```
How to do it? | 2019/08/09 | [
"https://Stackoverflow.com/questions/57423057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7936836/"
] | The only way I found until now is to run an npm script to copy sass files on dist folder (using copyfiles) before package the .tgz for internal use.
**Here my package.json:**
```
{
...
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"uiutils_build": "ng build my-library",
"uiutils_styles": "copyfiles -f projects/my-library/src/scss/*.scss dist/@my-namespace/my-library/scss",
"uiutils_pack": "cd dist/@my-namespace/my-library && npm pack",
"uiutils_copy": "copyfiles -f dist/@my-namespace/my-library/*.tgz ../infraestructure.tourbitz.com/packages/@my-namespace/my-library",
"uiutils_package": "npm run uiutils_build && npm run uiutils_styles && npm run uiutils_pack && npm run uiutils_copy"
},
...
}
```
the important script is uiutils\_styles.
**¿How to use?**
In my style files, I included the styles:
```
@import "~@my-namespace/ui-uitils/scss/my_style.scss";
```
And for registering global styles I did on the project section of the angular.json file:
```
{
...
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"styles": [
"node_modules/@my-namespace/my-library/scss/my_style.scss",
"src/styles.scss"
],
...
},
...
}
``` | **Update for Angular 9**:
In the library, next to the `lib`-directory, create a `styles`-directory and then add it as assets to `ng-rollout.yaml` like so:
```
"assets": [
"styles/**/*.scss"
]
```
This will copy all SCSS-files found recursively in the `styles`-directory into a `styles` directory in the output directory of your library. |
16,026,858 | I'm trying to retrieve the coordinates of cursor in a VT100 terminal using the following code:
```
void getCursor(int* x, int* y) {
printf("\033[6n");
scanf("\033[%d;%dR", x, y);
}
```
I'm using the following ANSI escape sequence:
>
> Device Status Report - ESC[6n
>
>
> Reports the cursor position to the
> application as (as though typed at the keyboard) ESC[n;mR, where n is
> the row and m is the column.
>
>
>
The code compiles and the ANSI sequence is sent, but, upon receiving it, the terminal prints the `^[[x;yR` string to the `stdout` instead of `stdin` making it imposible for me to retrieve it from the program:

Clearly, the string is designated for the program, though, so I must be doing something incorrectly. Does anybody know what it is? | 2013/04/16 | [
"https://Stackoverflow.com/questions/16026858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/657401/"
] | I ask for the cursor position. If I do not have answer after 100ms (this is arbitrary) I suppose the console is not ansi.
```
/* This function tries to get the position of the cursor on the terminal.
It can also be used to detect if the terminal is ANSI.
Return 1 in case of success, 0 otherwise.*/
int console_try_to_get_cursor_position(int* x, int *y)
{
fd_set readset;
int success = 0;
struct timeval time;
struct termios term, initial_term;
/*We store the actual properties of the input console and set it as:
no buffered (~ICANON): avoid blocking
no echoing (~ECHO): do not display the result on the console*/
tcgetattr(STDIN_FILENO, &initial_term);
term = initial_term;
term.c_lflag &=~ICANON;
term.c_lflag &=~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &term);
//We request position
print_escape_command("6n");
fflush(stdout);
//We wait 100ms for a terminal answer
FD_ZERO(&readset);
FD_SET(STDIN_FILENO, &readset);
time.tv_sec = 0;
time.tv_usec = 100000;
//If it success we try to read the cursor value
if (select(STDIN_FILENO + 1, &readset, NULL, NULL, &time) == 1)
if (scanf("\033[%d;%dR", x, y) == 2) success = 1;
//We set back the properties of the terminal
tcsetattr(STDIN_FILENO, TCSADRAIN, &initial_term);
return success;
}
``` | ```
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
void readCoord(void* row, void* col){
int i = 0;
char* input = malloc(10);
printf("\e[6n");
while(!_kbhit()) _sleep(1);
while(_kbhit()) *(input + (i++)) = getch();
*(input + i) = '\0';
sscanf(input, "\e[%d;%dR", row, col);
}
void main(void){
int i = 0, r, c;
char* coord = malloc(10);
printf("Hello");
readCoord(&r , &c);
printf("\nYour coordinate is (%d, %d)", c, r);
}
```
`_kbhit()` is used to detect input (DSR are treated as though typed at the keyboard), and
`getch()` to read and remove the character from standard input
This program relies on `conio.h`, which is not a standard and hence not recommended for portable C programs. |
49,099,637 | Is it possible to tell if there was an exception once you're in the `finally` clause? Something like:
```
try:
funky code
finally:
if ???:
print('the funky code raised')
```
I'm looking to make something like this more DRY:
```
try:
funky code
except HandleThis:
# handle it
raised = True
except DontHandleThis:
raised = True
raise
else:
raised = False
finally:
logger.info('funky code raised %s', raised)
```
I don't like that it requires to catch an exception, which you don't intend to handle, just to set a flag.
---
Since some [comments](https://stackoverflow.com/questions/49099637/how-to-determine-if-an-exception-was-raised-once-youre-in-the-finally-block#comment85224289_49099637) are asking for less "M" in the MCVE, here is some more background on the use-case. The actual problem is about escalation of logging levels.
* The funky code is third party and can't be changed.
* The failure exception and stack trace does not contain any useful diagnostic information, so using `logger.exception` in an except block is not helpful here.
* If the funky code raised then some information which I need to see has already been logged, at level DEBUG. We do not and can not handle the error, but want to escalate the DEBUG logging because the information needed is in there.
* The funky code does not raise, most of the time. I don't want to escalate logging levels for the general case, because it is too verbose.
Hence, the code runs under a log capture context (which sets up custom handlers to intercept log records) and some debug info gets re-logged retrospectively:
```
try:
with LogCapture() as log:
funky_code() # <-- third party badness
finally:
# log events are buffered in memory. if there was an exception,
# emit everything that was captured at a WARNING level
for record in log.captured:
if <there was an exception>:
log_fn = mylogger.warning
else:
log_fn = getattr(mylogger, record.levelname.lower())
log_fn(record.msg, record.args)
``` | 2018/03/04 | [
"https://Stackoverflow.com/questions/49099637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674039/"
] | Okay, so what it sounds like you actually just want to either modify your existing context manager, or use a similar approach: `logbook` actually has something called a [`FingersCrossedHandler`](https://github.com/getlogbook/logbook/blob/bcae0a58177476c395c73d343c7d6f4320ec594c/logbook/handlers.py#L1723) that would do exactly what you want. But you could do it yourself, like:
```
@contextmanager
def LogCapture():
# your existing buffer code here
level = logging.WARN
try:
yield
except UselessException:
level = logging.DEBUG
raise # Or don't, if you just want it to go away
finally:
# emit logs here
```
---
**Original Response**
You're thinking about this a bit sideways.
You *do* intend to handle the exception - you're handling it by setting a flag. Maybe you don't care about anything else (which seems like a bad idea), but if you care about doing something when *an* exception is raised, then you want to be explicit about it.
The fact that you're setting a variable, but you want the exception to continue on means that what you *really* want is to raise your own specific exception, from the exception that was raised:
```
class MyPkgException(Exception): pass
class MyError(PyPkgException): pass # If there's another exception type, you can also inherit from that
def do_the_badness():
try:
raise FileNotFoundError('Or some other code that raises an error')
except FileNotFoundError as e:
raise MyError('File was not found, doh!') from e
finally:
do_some_cleanup()
try:
do_the_badness()
except MyError as e:
print('The error? Yeah, it happened')
```
This solves:
* Explicitly handling the exception(s) that you're looking to handle
* Making the stack traces and original exceptions available
* Allowing your code that's going to handle the original exception somewhere else to handle your exception that's thrown
* Allowing some top-level exception handling code to just catch `MyPkgException` to catch all of your exceptions so it can log something and exit with a nice status instead of an ugly stack trace | If it was me, I'd do a little re-ordering of your code.
```
raised = False
try:
# funky code
except HandleThis:
# handle it
raised = True
except Exception as ex:
# Don't Handle This
raise ex
finally:
if raised:
logger.info('funky code was raised')
```
I've placed the raised boolean assignment outside of the try statement to ensure scope and made the final except statement a general exception handler for exceptions that you don't want to handle.
This style determines if your code failed. Another approach might me to determine when your code succeeds.
```
success = False
try:
# funky code
success = True
except HandleThis:
# handle it
pass
except Exception as ex:
# Don't Handle This
raise ex
finally:
if success:
logger.info('funky code was successful')
else:
logger.info('funky code was raised')
``` |
309,495 | I'm currently using `Win32ShellFolderManager2` and `ShellFolder.getLinkLocation` to resolve windows shortcuts in Java. Unfortunately, if the Java program is running as a service under Vista, `getLinkLocation`, this does not work. Specifically, I get an exception stating "Could not get shell folder ID list".
Searching the web does turn up mentions of this error message, but always in connection with `JFileChooser`. I'm not using `JFileChooser`, I just need to resolve a `.lnk` file to its destination.
Does anyone know of a 3rd-party parser for `.lnk` files written in Java I could use?
I've since found unofficial documentation for the .lnk format [here](http://mediasrv.ns.ac.yu/extra/fileformat/windows/lnk/shortcut.pdf), but I'd rather not have to do the work if anyone has done it before, since the format is rather scary. | 2008/11/21 | [
"https://Stackoverflow.com/questions/309495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15255/"
] | I can recommend this repository on GitHub:
<https://github.com/BlackOverlord666/mslinks>
There I've found a simple solution to **create** shortcuts:
`ShellLink.createLink("path/to/existing/file.txt", "path/to/the/future/shortcut.lnk");`
If you want to **read** shortcuts:
```
File shortcut = ...;
String pathToExistingFile = new ShellLink(shortcut).resolveTarget();
```
If you want to **change the icon** of the shortcut, use:
```
ShellLink sl = ...;
sl.setIconLocation("/path/to/icon/file");
```
You can edit most properties of the shortcutlink such as **working directory, tooltip text, icon, command line arguments, hotkeys, create links to LAN shared files and directories** and much more...
Hope this helps you :)
Kind regards
Josua Frank | I've also worked( now have no time for that) on '.lnk' in Java. My code is [here](http://kac-repo.xt.pl/cgi-bin/gitweb.cgi?p=jshortcut.git;a=summary "git repo")
It's little messy( some testing trash) but local and network parsing works good. Creating links is implemented too. Please test and send me patches.
Parsing example:
```
Shortcut scut = Shortcut.loadShortcut(new File("C:\\t.lnk"));
System.out.println(scut.toString());
```
Creating new link:
```
Shortcut scut = new Shortcut(new File("C:\\temp"));
OutputStream os = new FileOutputStream("C:\\t.lnk");
os.write(scut.getBytes());
os.flush();
os.close();
``` |
9,574,971 | I have a text field in my UI that when it's selected presents a UIDatePicker instead of the default keyboard, how could I set up a button as to dismiss the picker when the user is done? | 2012/03/05 | [
"https://Stackoverflow.com/questions/9574971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478108/"
] | Create a UIView (namely customDatePickerView) and in that view ,create datepicker and a done button and a cancel button in the xib.
In the textfield delegate:
```
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if (textField == textfieldName) {
[textfieldName resignFirstResponder];
//show the view
self.customDatePickerView.hidden = NO;
}
}//dismisses keyboard
```
Function on Date Picker Value Changed
```
- (IBAction)onDatePickerClick:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/YYYY"];
NSDate *selectedDate = [self.wellRecordDatePicker date];
NSString *recordDate = [dateFormatter stringFromDate:selectedDate];
self.yourTextfieldName.text = recordDate;
}
- (IBAction)onDoneBtnClick:(id)sender
{
self.customDatePickerView.hidden = YES;
}
- (IBAction)onCancelBtnClick:(id)sender
{
self.customDatePickerView.hidden = YES;
}
```
Hope this will help you. | I've done a similar thing where I've created a view with a button and the `UIDatePicker`, then presented that view instead of the `UIDatePicker` alone. Then the button is just connected to an `IBAction` that moves the view out.
This way, the button moves in with the `UIDatePicker` view and they look "connected" to the user. You can even define this `UIView` in your nib and use `addSubview:` at runtime. |
271,059 | How do you do a neutral special/attack with the right joystick on the Wii-u-Gamepad/ProController/GamecubeController? When you change the right joystick to special. | 2016/06/23 | [
"https://gaming.stackexchange.com/questions/271059",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/138083/"
] | **Yes, it is possible, but quite difficult.**
From [Smash Wiki](http://www.ssbwiki.com/C-Stick) (emphasis mine):
>
> In Brawl and Smash U, functions that can be assigned to the C-stick are:
>
> [...]
>
> Special: Tilt the stick to do the special that corresponds to that direction. This is known as B-sticking. Tilting the stick in one horizontal direction while holding the control stick in the other causes wavebouncing. In addition, **tilting the stick diagonally allows a neutral special, though the angle required for this is very strict**.
>
>
>
The article is not wrong when it says the angle is very strict; I've been testing it and cannot get it to work reliably. But with a bit of practice I'm sure it's possible to confidently pull it off in combat.
Additionally, this also works with tilts and aerials when you set the function to "Attack":
>
> Attack: Shortcuts to tilt attacks, and aerial attacks just like with the Smash function when in midair. In Brawl, tilting the stick in the direction opposite the player is facing will cause the character to do a neutral attack, whereas in Smash U, the fighter will turn around and attack with their forward tilt. Known as A-sticking. In both games, **tilting the C-stick in a diagonal angle produces neutral attacks on the ground and neutral aerials in midair, with a wider angle than that do to neutral specials with the Special function**: as such, this function also enables players to use neutral aerials without losing momentum.
>
>
>
I've been testing this, and it is *much* easier to do than for special attacks.
---
\*Note that while it refers to the C-stick in the article, it explains that the right analog stick on the GamePad and Classic Controller function the same:
>
> The right Control Stick on the Wii U GamePad and Classic Controllers also works like the C-stick for the Smash games these controllers are compatible with.
>
>
> | You can't, neutral/special attacks (assuming you've got the default layout on your controller) are made pressing the B or A button without moving the left joystick. The right joystick is only used to do smash attacks, and, smash attacks are all directional and there is no neutral smash.
This is the default layout of the controller
 |
219,758 | I never use Siri, but when I look what has been draining my battery it says it's Siri!
[](https://i.stack.imgur.com/iwPaQ.jpg) | 2015/12/15 | [
"https://apple.stackexchange.com/questions/219758",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/106120/"
] | None of these suggestions helped me. What caused this problem was that my phone was set to automatically connect to a WiFi network that required a separate webpage-based login. They're called "captive networks" like the ones in restaurants and coffee shops, where you have to first open your web browser, and then fill in a login form, or click an "Accept" or "Go Online" button before you can connect to the Internet.
What happens is that my phone connected to the network automatically, but since I didn't open a web browser and manually login, I had no Internet connection. Then, Siri detected that I was connected on WiFi and tried over and over again to get out to the Internet, sucking up all my battery. (Perhaps Apple should have Siri do a progressive increasing of Siri's connection interval if the Internet fails? Kind of like Gmail does.)
To solve the problem, I just went into `Settings->WiFi` and selected the WiFi network that was causing my problem, and then clicked `Forget this Network` to stop my phone from automatically connecting. (You could also just leave your WiFi turned off, but that's no fun.)
Next day, I had 90+% battery life when I was heading home at 6pm. | I don't have an answer, but I have a theory. I'm having a hard time believing "Siri" is really "Siri". I have a phone that is waiting for a number port and sitting on my desk doing nothing. After 24 hours of sitting off Wi-Fi and looking for a network, not using it for anything, with the screen off, it says 90% of the usage was "Siri". Hence, I think "Siri" is synonymous with "System". |
5,142,065 | Main model classes are as follows :
```
public class UserAddressesForm {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
private List<AddressForm> addresses;
// setters and getters
}
```
---
```
public class AddressForm {
@NotEmpty
private String customName;
@NotEmpty
private String city;
@NotEmpty
private String streetAn;
@NotEmpty
private String streetHn;
@NotEmpty
private String addressCountry;
@NotEmpty
private String postCode;
// setters and getters
}
```
An endpoint in one of my controllers :
```
@RequestMapping(value = "/up", method = RequestMethod.POST)
public String completeForm(@Valid @ModelAttribute("userAddressesForm") UserAddressesForm userAddressesForm,
BindingResult result, HttpServletRequest req) {
// logic here
}
```
A `.jsp` page :
```
<form:form commandName="userAddressesForm" action="registered">
<table>
<tr>
<td class="formLabels"><form:label path="firstName">
<spring:message code="label.name" />
</form:label></td>
<td><form:input path="firstName" /></td>
<td><form:errors path="firstName" cssClass="error" /></td>
</tr>
<tr>
<td class="formLabels"><form:label path="lastName">
<spring:message code="label.surname" />
</form:label></td>
<td><form:input path="lastName" /></td>
<td><form:errors path="lastName" cssClass="error" /></td>
</tr>
</table>
<c:forEach items="${userAddressesForm.addresses}" varStatus="gridRow">
<div id="main_address" class="address_data_form">
<fieldset>
<legend><spring:message code="label.stepThreeMainAddressInfo" /></legend>
<a href="#" class="deleteItem"></a>
<table>
<tr>
<td class="formLabels">
<spring:message code="label.address.custom.name" />
</td>
<td>
<spring:bind path="addresses[${gridRow.index}].customName">
<input type="input" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" />
<form:errors path="${status.expression}"/>
</spring:bind>
</td>
</tr>
<tr>
<td class="formLabels">
<spring:message code="label.streetAnStreetHn" />
</td>
<td>
<spring:bind path="addresses[${gridRow.index}].streetAn">
<input type="input" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" />
</spring:bind>
<spring:bind path="addresses[${gridRow.index}].streetHn">
<input type="input" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" >
<form:errors path="addresses[${gridRow.index}].streetHn"/>
</spring:bind>
</td>
</tr>
<tr>
<td class="formLabels">
<spring:message code="label.postCode" />
</td>
<td>
<spring:bind path="addresses[${gridRow.index}].postCode">
<input type="input" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" />
</spring:bind>
</td>
</tr>
<tr>
<td class="formLabels">
<spring:message code="label.city" />
</td>
<td>
<spring:bind path="addresses[${gridRow.index}].city">
<input type="input" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>" />
<form:errors path="addresses[${gridRow.index}].city" cssClass="error" />
</spring:bind>
</td>
</tr>
</table>
</fieldset>
</div>
</c:forEach>
```
Why `@Valid` is not validating the `List<AddressForm> addresses` present in `UserAddressesForm` class ? | 2011/02/28 | [
"https://Stackoverflow.com/questions/5142065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/612925/"
] | Adding to @Ritesh answer, `@Valid` constraint will instruct the Bean Validator to delve to the type of its applied property and validate all constraints found there. Answer with code to your question, the validator, when seeing a `@Valid` constraint on `addresses` property, will explore the `AddressForm` class and validate all `JSR 303` constraints found inside, as follows:
```
public class UserAddressesForm {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
@Valid
private List<AddressForm> addresses;
...
setters and getters
public class AddressForm {
@NotEmpty
private String customName;
@NotEmpty
private String city;
@NotEmpty
private String streetAn;
@NotEmpty
private String streetHn;
@NotEmpty
private String addressCountry;
@NotEmpty
private String postCode;
...
setters and getters
``` | In the class UserAddressesForm add the following lines
```
@Valid
private List<AddressForm> addresses;
``` |
20,444,062 | I have a function which given a `Name` of a function it augments it, yielding another function applied to some other stuff (details not very relevant):
```
mkSimple :: Name -> Int -> Q [Dec]
mkSimple adapteeName argsNum = do
adapterName <- newName ("sfml" ++ (capitalize . nameBase $ adapteeName))
adapteeFn <- varE adapteeName
let args = mkArgs argsNum
let wrapper = mkApply adapteeFn (map VarE args)
-- generates something like SFML $ liftIO $ ((f a) b) c)
fnBody <- [| SFML $ liftIO $ $(return wrapper) |]
return [FunD adapterName [Clause (map VarP args) (NormalB fnBody) []]]
where
mkArgs :: Int -> [Name]
mkArgs n = map (mkName . (:[])) . take n $ ['a' .. 'z']
-- Given f and its args (e.g. x y z) builds ((f x) y) z)
mkApply :: Exp -> [Exp] -> Exp
mkApply fn [] = fn
mkApply fn (x:xs) = foldr (\ e acc -> AppE acc e) (AppE fn x) xs
```
This works, but it's tedious to pass externally the number of args the adaptee function has. There exists some TH function to extract the number of args? I suspect it can be achieved with [reify](http://hackage.haskell.org/package/template-haskell-2.5.0.0/docs/Language-Haskell-TH.html#t%3areify) but I don't know how.
Thanks! | 2013/12/07 | [
"https://Stackoverflow.com/questions/20444062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479553/"
] | Sure, you should be able to do
```
do (VarI _ t _ _) <- reify adapteeName
-- t :: Type
-- e.g. AppT (AppT ArrowT (VarT a)) (VarT b)
let argsNum = countTheTopLevelArrowTs t
...
where
countTheTopLevelArrowTs (AppT (AppT ArrowT _) ts) = 1 + countTheTopLevelArrowTs
countTheTopLevelArrowTs _ = 0
```
The above is just from my head and may not be quite right. | A slight improvement on jberryman's answer that deals with type constraints such as `(Ord a) -> a -> a` is:
```
arity :: Type -> Integer
arity = \case
ForallT _ _ rest -> arity rest
AppT (AppT ArrowT _) rest -> arity rest +1
_ -> 0
```
usage:
```
do (VarI _ t _ _) <- reify adapteeName
let argsNum = arity t
``` |
428,117 | I am having a real brain fart here, and I would appreciate some help.
Now, I read this here - <http://grammartips.homestead.com/adverbs2.html> - but for some reason, in several cases my head just can't make the connection between the provided example for an adverb just modifying the verb and not the whole clause.
The example given:
>
> Often the introductory adverb modifies just the verb, as does the word "often" in this sentence.
>
>
>
The cases my brain refuses to compute:
>
> A) Usually it's the age that's a problem.
>
>
> B) Finally he's had enough and stops me.
>
>
> C) Eventually my eyes settle on a bottle of whiskey.
>
>
>
My purpose here is to know whether there should be commas after these words or not. And why.
My problem is that I could, possibly, see each of these as just modifying the verb:
A) it's
B) had
C) settle
And maybe I am stupid. Right now I feel stupid. Or is it: Right now, I feel stupid? I just don't know, anymore. Commas are really killing me. So if anyone could help me out here, in layman's terms, I would really appreciate it.
Thanks. | 2018/01/26 | [
"https://english.stackexchange.com/questions/428117",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/278088/"
] | [Ellipsis](https://en.m.wikipedia.org/wiki/Ellipsis_(linguistics)) is the omission of a word or words from a clause as understood, redundant, or superfluous:
>
> Did you buy any chocolate milk? No, the store was out [*of chocolate milk*].
>
>
> When they were children, John learned French and his brother [*learned*] Spanish.
>
>
> Rachel ordered something for lunch but I don't know what [*she ordered*].
>
>
> Peter wants to fly to Mexico City, but his wife doesn't want to [*fly to Mexico City*].
>
>
> Peter wants to fly to Mexico City, but his wife doesn't [*want to fly to Mexico City*].
>
>
>
The only time ellipsis is mandatory is in comparisons:
>
> John is taller than I [*am tall*].
>
>
>
Rather than solve the daunting question of whether something that is never there ever was in the first place, many casual speakers analyze *than* as a preposition, so that John is taller than *me*. | This is quite a coincidence. [I just mentioned this in chat not too long ago.](https://chat.stackexchange.com/transcript/95?m=42482184#42482184) There are a few terms that could be used for this, but I think the word ellipsis is the one you probably want to use the most:
>
> In grammar, omission; a figure of syntax by which a part of a sentence or phrase is used for the whole, by the omission of one or more words, leaving the full form to be understood or completed by the reader or hearer: as, “the heroic virtues I admire,” for “the heroic virtues which I admire”; “prythee, peace,” for “I pray thee, hold thy peace.”[—The Century Dictionary and Cyclopedia (C.D.C.)]
>
>
>
Wikipedia, which licenses its text under the CC-BY-S.A. 3.0 terms, describes a few types of ellipsis in its [Ellipsis\_(linguistics)](https://en.wikipedia.org/w/index.php?title=Ellipsis_(linguistics)&oldid=811081822) article. I think The most interesting and easy to understand form of ellipsis is this:
>
> Answer ellipsis […]
> Answer ellipsis involves question-answer pairs. The question focuses an unknown piece of information, often using an interrogative word (e.g. who, what, when, etc.). The corresponding answer provides the missing information and in so doing, the redundant information that appeared in the question is elided, e.g.:
>
>
>
> >
> > Q: Who has been hiding the truth?
> > A: Billy has been hiding the truth.
> > Q: What have you been trying to accomplish?
> > A: I have been trying to accomplish This darn crossword.
> >
> >
> >
>
>
> The fragment answers in these two sentences are verb arguments (subject and object NPs). The fragment can also correspond to an adjunct, e.g.:
>
>
>
> >
> > Q: When does the circus start?
> > A: The circus starts Tomorrow.
> > Q: Why has the campaign been so crazy?
> > A: The campaign has been so crazy Due to the personalities.
> >
> >
> >
>
>
> Answer ellipsis occurs in most if not all languages. It is a very frequent type of ellipsis that is omnipresent in everyday communication between speakers.
>
>
>
Part of why answer ellipsis interests me is that it explains why so many questions end in prepositions: The prepositional object is supposed to be the answer. You can read more about answer ellipsis in particular in [Fragments and Ellipsis](http://home.uchicago.edu/merchant/pubs/fragments.pdf) (P.D.F.) by Jason Merchant
You may recollect that these three successive periods (…) are also sometimes referred to as an ellipsis. The "ellipsis points" as the Chicago Manual of Style, 15th edition terms them, are named after the syntactical construct. I have noticed a great deal of people around here are using elision instead, but please try to avoid that in favor of greater specificity. Elision, being a noun for the act of [eliding](http://www.micmap.org/dicfro/search/century-dictionary/elide), is a construct of pronunciation, not syntax, and refers to the reduction of syllables, and perhaps most specifically just the vowel sounds. |
16,338,669 | I've a method , that retrieves to me some data according to some type I passed in parameter, like this :
```
protected void FillList<TEntity>()
{
doWorkForTEntity();
}
```
I Need to dynamically call this method :
```
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
FillList<currentEntity>();
```
I got this error :
>
> The type or namespace name 'currentEntity' could not be found (are you missing a using directive or an assembly reference?)
>
>
>
I've tried an intermediate object type, no success
Any Idea please ? | 2013/05/02 | [
"https://Stackoverflow.com/questions/16338669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2154952/"
] | You need to do that with reflection as well, so it won't fail in compile time (compiler checks):
**Generic class:**
```
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
Type fillListType= typeof(FillList<>);
Type constructedGenericClass = fillListType.MakeGenericType(currentEntity);
object myList = Activator.CreateInstance(constructedGenericClass );
```
**Generic Method:**
```
Type[] entities = System.Reflection.Assembly.GetAssembly(typeof(User)).GetTypes();
Type currentEntity = (from entity in entities
where entity.Name.Equals(this.targetEntity)
select entity).FirstOrDefault();
MethodInfo methodinfo = this.GetType().GetMethod("FillList");
MethodInfo genericMethod = method.MakeGenericMethod(currentEntity);
genericMethod.Invoke(this, null);
``` | Change your method to take an instance of the Type TEntity:
```
protected void FillList<TEntity>(TEntity instance)
{
doWorkForTEntity();
}
```
Create a dynamic instance from the Type name and then call the modified method:
```
dynamic instance = Activator.CreateInstance(this.targetEntity);
FillList(instance);
```
The dynamic type is basically doing what the other answers have shown you - but IMHO this code is neater and clearer in its intent. |
18,645,740 | I'm using the following stub to protect against leaving console.log statements in a production application:
```
// Protect against IE8 not having developer console open.
var console = console || {
"log": function () {
},
"error": function () {
},
"trace": function () {
}
};
```
This works fine in the sense that it prevents exceptions from being thrown when I call console.log in IE8 without the developer tools open. However, I dislike the fact that if I open dev. tools after the code has loaded -- I still don't see my log messages.
Is it possible to have both? My attempts have led me to infinite recursions of console.log calls. I also found this: <http://log4javascript.org/> but I'd rather not unless entirely necessary
**EDIT:** To clarify: I simply want to not throw an exception if dev. console isn't open, but use the console if it is opened later. | 2013/09/05 | [
"https://Stackoverflow.com/questions/18645740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/633438/"
] | PHP has separate `boolean` type, its values of `TRUE` and `FALSE` (case-insensitive constants) are not identical to integer values of 1 and 0.
When you use strict comparison (`===`), it does not work: `TRUE !== 1` and `FALSE !== 0`.
When you use type juggling, `TRUE` is converted to 1 and `FALSE` is converted to 0 (and, vice versa, 0 is converted to `FALSE`, any other integer is converted to `TRUE`). So, `TRUE == 1` and `FALSE == 0`.
In PHPUnit, `assertTrue` and `assertFalse` are type-dependent, strict checks. `assertTrue($x)` checks whether `TRUE === $x`, it is the same as `assertSame(TRUE, $x)`, and not the same as `assertEquals(TRUE, $x)`.
In your case, one possible approach would be to use explicit type casting:
```
$this->assertTrue((boolean)preg_match('/asdf/', 'asdf'));
```
However, PHPUnit happens to have dedicated assertion for checking string against regular expression:
```
$this->assertRegExp('/asdf/', 'asdf');
``` | Please do not use a bunch of `assertTrue` or `assertFalse` checks with the real logic embedded in a complicated function call when there are more specific test functions available.
PHPUnit has a very vast set of assertions that are really helpful in the case they are not met. They give you a bunch of context of what went wrong, which aids you in debugging.
To check for a regular expression, use `assertRegExp()` (see <http://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions.assertRegExp>) |
16,655,010 | For my current purposes I have a Maven project which creates a `war` file, and I want to see what actual classpath it is using when creating the `war`. Is there a way to do that in a single command -- without having to compile the entire project?
One idea is to have Maven generate the `target/classpath.properties` file and then stop at that point. | 2013/05/20 | [
"https://Stackoverflow.com/questions/16655010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10608/"
] | To get the classpath all by itself in a file, you can:
```
mvn dependency:build-classpath -Dmdep.outputFile=cp.txt
```
Or add this to the POM.XML:
```
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<!-- configure the plugin here -->
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
[...]
</project>
```
From: <http://maven.apache.org/plugins/maven-dependency-plugin/usage.html> | This is a **single command solution** but **does compile the code**.
```
mvn -e -X -Dmaven.test.skip=true clean compile | grep -o -P '\-classpath .*? ' | awk '{print $2}'
```
* It's based in [Philip Helger](https://stackoverflow.com/users/15254/philip-helger)'s previous [answer](https://stackoverflow.com/a/16655088/2265487) (Thanks by the way)
**Shell script example usage**
```
MAVEN_CLASSPATH=$(mvn -e -X -Dmaven.test.skip=true clean compile | grep -o -P '\-classpath .*? ' | awk '{print $2}')
```
I used a variation of it in a shell script to run a standalone main() (for Hibernate schema generation) this way
```
#/bin/bash
MAVEN_TEST_CLASSPATH=$(mvn -e -X clean package | grep -o -P '\-classpath .*?test.*? ')
java $MAVEN_TEST_CLASSPATH foo.bar.DBSchemaCreate
```
**File output example**
```
mvn -e -X -Dmaven.test.skip=true clean compile | grep -o -P '\-classpath .*? ' | awk '{print $2}' > maven.classpath
``` |
8,999 | Given a graph $G$ we will call a function $f:V(G)\to \mathbb{R}$ discrete harmonic if for all $v\in V(G)$ , the value of $f(v)$ is equal to the average of the values of $f$ at all the neighbors of $v$. This is equivalent to saying the discrete Laplacian vanishes.
Discrete harmonic functions are sometimes used to approximate harmonic functions and most of the time they have similar properties. For the plane we have Liouville's theorem which says that a bounded harmonic function has to be constant. If we take a discrete harmonic function on $\mathbb{Z}^2$ it satisfies the same property (either constant or unbounded).
Now my question is: If we take a planar graph $G$ so that every point in the plane is contained in an edge of $G$ or is inside a face of $G$ that has less than $n\in \mathbb{N}$ edges, does a discrete harmonic function necessarily have to be either constant or unbounded?
I know the answer is positive if $G$ is $\mathbb{Z}^2$, the hexagonal lattice and triangular lattice, I suspect the answer to my question is positive, but I have no idea how to prove it.
Edited the condition of the graph to "contain enough cycles". (So trees are ruled out for example) | 2009/12/15 | [
"https://mathoverflow.net/questions/8999",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2384/"
] | The answer is no.
I first describe the graph $G$. Let $N\_i$ be a sequence of positive integers; we will choose $N\_i$ later. Let $T$ be an infinite tree which has one root vertex, the root has $N\_1$ children; the children of that root have $N\_2$ children, those children have $N\_3$ children and so forth. Let $V\_0$ be the set containing the root, $V\_1$ be the set of children of the root, $V\_2$ the children of the elements of $V\_1$, and so forth. To form our graph, take $T$ and add a sequence of cycles, one going through the vertices of $V\_1$, one through $V\_2$ and so forth. (In the way which is compatible with the obvious planar embedding of $T$.)
Every face of $G$ is either a triangle or a quadrilateral.
We will build a harmonic function $f$ on $G$ as follows: On the root, $f$ will be $0$. On $V\_1$, we choose $f$ to be nonzero, but average to $0$. On $V\_i$, for $i \geq 2$, we compute $f$ inductively by the condition that, for every $u \in V\_{i-1}$, the function $f$ is constant on the children of $u$. Of course, we may or may not get a bounded function depending on how we choose the $N\_i$. I will now show that we can choose the $N\_i$ so that $f$ is bounded. Or, rather, I will claim it and leave the details as an exercise for you.
Let $a\_i$ be a decreasing sequence of positive reals, approaching zero. Take $N\_i = 6/(a\_{i+1} - a\_i)$. **Exercise:** If $f$ on $V\_1$ is taken between $-1+a\_1$ and $1-a\_1$, then $f$ on $V\_i$ will lie between $-1+a\_i$ and $1-a\_i$. In particular, $f$ will be bounded between $-1$ and $1$ everywhere. | [Benjamini and Schramm](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.5100) proved that an infinite, bounded degree, planar graph is non-Liouville if and only if it is transient. |
49,033,398 | Hi I want to remove certain words from a long string, there problem is that some words end with "s" and some start with a capital, basically I want to turn:
`"Hello cat Cats cats Dog dogs dog fox foxs Foxs"`
into:
`"Hello"`
at the moment I have this code but I want to improve on it, thanks in advance:
```
.replace("foxs", "")
.replace("Fox", "")
.replace("Dogs", "")
.replace("Cats", "")
.replace("dog", "")
.replace("cat", "")
``` | 2018/02/28 | [
"https://Stackoverflow.com/questions/49033398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9318281/"
] | Maybe you can try to match everything except the word `Hello`.
Something like:
```
string.replaceAll("(?!Hello)\\b\\S+", "");
```
You can test it in [this link](https://regex101.com/r/XUwzM1/1).
The idea is to perform a negative lookahead for `Hello` word, and get any other word present. | So you could pre-compile a list of the words you want and make it case insensitive something like:
```
String str = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
Pattern p = Pattern.compile("fox[s]?|dog[s]?|cat[s]?", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
String result = m.replaceAll("");
System.out.println(result);
```
[s]? handles if there is a plural form, where the ? character will match 0 or 1 |
8,488,442 | I want to drag an image on the screen.
how can i do this?
In my case, the image is simply download from the URL and placed on an activity.
I just want to drag this.
Thanks in advance!! | 2011/12/13 | [
"https://Stackoverflow.com/questions/8488442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/829066/"
] | This is not inheritance that you are doing. In your ViewController implementation, you have the following code
```
NewClass *myClass = [[[NewClass alloc] init] autorelease];
[myClass setLabelText];
```
This is just creating an instance of the class NewClass and setting the labelText on that instance. You are never displaying it or adding it to a view. | Wait... from the looks of it you are going to have some serious issues with stack overflows: when you load a ViewController, it in turn creates myClass. Because myClass is a subclass of ViewController, this in turn will create it's own variable 'myClass' when loaded... etc. This will continue forever, or until you get a stack overflow error.
In fact, I'm pretty confused by your code. Perhaps it might be time to rethink what you are trying to achieve and what your code should be doing? |
2,932,110 | A view with a table gets pushed onto the screen and I want it to scroll to a certain row in the table before the screen actually displays. I use this code within the final viewcontroller.
```
NSIndexPath *scrollToPath = [NSIndexPath indexPathForRow:5 inSection:0];
[theTable scrollToRowAtIndexPath:scrollToPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
```
When I put it in viewDiDAppear method, then it briefly flashes from the intial position of the table (at the top) to the row I want. I don't want it to show the initial position. If I put it in viewDidLoad or viewWillAppear then it crashes with a NSRangeException, presumably because the table isn't set up yet.
How would I get it to scroll without showing the initial position? | 2010/05/28 | [
"https://Stackoverflow.com/questions/2932110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/121646/"
] | Thanks to Shaggy and Dying Cactus for pointing me in the right direction. The answer is to load the table and scroll in viewWillAppear:
```
-(void)viewWillAppear:(BOOL)animated
{
[theTable reloadData];
NSIndexPath *scrollToPath = [NSIndexPath indexPathForRow:5 inSection:0];
[theTable scrollToRowAtIndexPath:scrollToPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
``` | I just finished wrestling with this. Mine was adding a search bar to the top of the list, initially tucked under the top... ala some of the core apps. I was actually going to ask this same question!
I fear to offer this up, as it seems those who offer things up get pounded down.. but... I was surprised that there was not an easy solution... so I ended up doing this:
I use ABTableViewCell (you can google it) for custom drawn cells (nice and fast!), and when I get called to DRAW the second row (you could do this in your customly drawn cells without ABTableViewCell), I set it there, with a single fire semaphore:
```
if ( self.mOnlyOnce == NO && theRow > 1 ) {
self.mOnlyOnce = YES;
[self.mParentTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
```
(choose your proper row/section, as suits you... if they were in the same section, you'd probably be setting row to something other than 0)
If you hate my solution (as I can't comment yet), please do me the favor of just leaving it at zero & letting a better solution come to the top.
Oh, also, there is an entry about hiding your search at the top... but mine was already done as a custom cell... here is that [link](https://stackoverflow.com/questions/1081381/iphone-hide-uitableview-search-bar-by-default).
enjoy |
54,277,735 | While preparing for a test, I am solving tests from previous years.
Write the function `compress(lst)` that receives a non empty list of repetitive letters and returns a list of tuples, each tuple containing the letter and the number or subsequent repetitions. ( see example)
e.g.:
for:
```
['a','a', 'b', 'b', 'b', 'c', 'a', 'a']
```
the function should return:
```
[('a', 2), ('b', 3), ('c', 1), ('a', 2)]
```
Here's my code:
```
def compress(lst):
res = []
i = 0
for letter in lst:
letter_count = 0
while i < len(lst) and lst[i] == letter:
letter_count += 1
i +=1
res.append((letter, letter_count))
return res
```
My function returns:
```
[('a', 2), ('a', 0), ('b', 3), ('b', 0), ('b', 0), ('c', 1), ('a', 2), ('a', 0)]
```
I can see why it does that, but I cant see how to change *my* code to solve the problem. | 2019/01/20 | [
"https://Stackoverflow.com/questions/54277735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10666115/"
] | Use [**`groupby`**](https://docs.python.org/3/library/itertools.html#itertools.groupby) from `itertools` module which perfectly fits here:
```
from itertools import groupby
lst = ['a','a', 'b', 'b', 'b', 'c', 'a', 'a']
print([(k, len(list(v))) for k, v in groupby(lst)])
# [('a', 2), ('b', 3), ('c', 1), ('a', 2)]
``` | The issue is that the `while` loop correctly counts occurrences, the `for` loop marches on inexorably, one character at a time. Since you're already incrementing the index correctly in the `while` loop, the simplest thing would be to get rid of either the `for` or `while` loop entirely. The only purpose to having multiple loops here is to attempt to avoid an `if`, and as you see, that doesn't really work.
```
res = []
prev = ''
for letter in lst:
if prev == letter:
letter_count += 1
else:
if prev:
res.append((prev, letter_count))
letter_count = 1
prev = letter
```
This is similar to what you'd get from `itertools.groupby`:
```
[(k, len(list(g))) for k, g in groupby(lst)]
``` |
1,107,672 | I am trying to access member variables of a class without using object. please let me know how to go about.
```
class TestMem
{
int a;
int b;
public:
TestMem(){}
void TestMem1()
{
a = 10;
b = 20;
}
};
void (TestMem::*pMem)();
int main(int argc, char* argv[])
{
TestMem o1;
pMem = &(TestMem::TestMem1);
void *p = (void*)&pMem;
// How to access a & b member variables using variable p
getch();
return 0;
}
``` | 2009/07/10 | [
"https://Stackoverflow.com/questions/1107672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] | Simple answer: Don't do it.
There just can not be any situation where you can justify accessing like this. There just has to be a different solution. | I wanted to comment the answer provided by John Kugelman, being a new member didn't have enough reputation, hence posting it like an answer.
offsetof - is a C function used with structures where every member is a public, not sure whether we can refer the private variables as referred in the answer.
However the same can be achieved replacing the offsetof with a simple sizeof, ofcourse when we are sure of the type of the data members.
```
int vala = *reinterpret_cast<int *>(reinterpret_cast<char *>( ptr ) );
int valb = *reinterpret_cast<int *>(reinterpret_cast<char *>( ptr ) + sizeof ( int ) );
```
To my knowledge, you wouldn't be able to access.
By the time you have assigned p, it doesn't refer to o1 here and
p cannot replace pMem in (o1.\*pMem)(), as p is not defined as function member to TestMem. |
407,569 | I have a trouble with estimation of logic utilization.
I am Ph.D student who research the efficient implementation of signal processing algorithms. So, I have to compare the logic utilization of proposed method with conventional method.
Therefore, the comparison of gate counts for each methods is the best way to evaluate efficiency of logic utilization.
Unfortunately, as you know, the Xilinx simulator does not provide the gate counts anymore.
Instead of gate count, we can estimate the logic utilization with the number of LUTs and FFs.
So, I did not use the DSP48 and Block memory by using synthesis settings so that every logic can be implemented by LUTs and FFs.
However, although I had configured –max\_dsp = 0,
the decimation filter/FFT generated by IPs,FIR compiler/FFT, still used DSP48 and BRAM.
Here are the questions.
**1.How can I generate decimation filter without DSP48 using FIR Compiler.
I would like to generate decimation filter only with CLBs using FIR compiler.**
**2.Is there any criteria convert the number of DSP48 to the number of LUTs and FFs?**
**3.In addition, is there any criteria convert the number of block memory to the number of LUTs or Memory LUTs?** | 2018/11/19 | [
"https://electronics.stackexchange.com/questions/407569",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/204825/"
] | Definitely point 3 is wrong. Memory has a totally different structure from gates. in the ASIC world, where I come from, the area of a block is always split in gates-area and memory-area.
The reason is that the size of a memory is non-linear. Small memories use up a lot more area per cell then large ones. Very small memories are therefore implemented using what we call a 'register file'.
A register file is a memory comprised of real registers but due to the regular structure are in density between random registers+gates and memories.
By the way: counting LUTS does not help either. A LUT can represent a singe NAND gate or a complex group as big as many, many NAND gates. (The area of a NAND gate is used as unit for ASIC circuit area).
Last but not least: area alone is not enough.
Your new algorithm may be 'smaller' in gates but unsuitable for pipe-lining and thus can not run at high speeds. In which case it will be discarded in favor of one which can be pipe-lined or one which is easier to lay out using a datapath compiler. | >
> I am Ph.D student who research the efficient implementation of signal
> processing algorithms.
>
>
>
This will be an interesting topic - first you need to define "efficient". As others have noted, you cannot really compare "area" using LUTs anymore (and that's been the case for a very long time!).
As a practising engineer, what is usually important in the real world is more likely to be "how much does it cost?" or "how much power does it consume?" etc.
>
> So, I have to compare the logic utilization of
> proposed method with conventional method.
>
>
>
I don't think you *have* to compare logic utilisation...
Can you perhaps target a device in different ways and compare
* the "equivalent cost" (based on "how many of the block you could fit in your selected device)
* or amount of power consumed?
You
could perhaps compare different device families this way, or even different size devices in the same family, to see where the sweet spot for cost of silicon area or power comes etc. |
22,810,644 | I a using Spring security with an HTML page using thymeleaf. I have a problem to use the "sec:authorize" property in this case:
```
<ul class="nav nav-tabs margin15-bottom">
<li th:each="criteriaGroup,iterGroups : ${aGroupList}"
th:class="${iterGroups.index == 0}? 'active'">
<a th:href="'#' + ${criteriaGroup.id}" data-toggle="tab"
th:text="${criteriaGroup.groupName}"></a>
</li>
</ul>
```
Now I want to add a spring security property like: if I have this particular criteria, I need a authorization (`sec:authorize="hasRole('Criteria')"`) although I will not see the tab corresponding to this criteria:
```
<ul class="nav nav-tabs margin15-bottom">
<li th:each="aGroup,iterGroups : ${aGroupList}" th:class="${iterGroups.index == 0}? 'active'"
th:sec:authorize="$({criteriaGroup.id =='criteriaA'} || ${criteriaGroup.id =='criteriaB'}) ? 'hasRole('Criteria')'">
<a th:href="'#' + ${criteriaGroup.id}" data-toggle="tab"
th:text="${criteriaGroup.groupName}"></a>
</li>
</ul>
```
But when I am doing this I have the following error:
```
org.thymeleaf.exceptions.TemplateProcessingException: Error processing template: dialect prefix "th" is set as non-lenient but attribute "th:sec:authorize" has not been removed during process
```
How can I avoid it? | 2014/04/02 | [
"https://Stackoverflow.com/questions/22810644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3458613/"
] | Remove th: in front of sec:authorize
The Spring Security 3 integration module is a Thymeleaf dialect. More information can be found [here](https://github.com/thymeleaf/thymeleaf-extras-springsecurity3). | Perhaps you'd want to use the #authentication object instead of the sec dialect.
From the docs:
```
<div th:text="${#authentication.name}">
The value of the "name" property of the authentication object should appear here.
</div>
``` |
16,237,471 | i'm kinda new to regular expressions. I have this case where i want to split many words like
"foo\_bar\_21", "bla\_keks\_38", etc. to
["foo\_bar", "21"], ["bla\_keks", "38"]
basically i want the last element which is always a number to be separated and the underscore before only that number removed.
How do I do that?
thanks for your help guys, very much appreciated.
\*edit: i forgot to mention that i try to do this in java ^^' | 2013/04/26 | [
"https://Stackoverflow.com/questions/16237471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/957370/"
] | ```
-(IBAction)goRestore
{
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
```
//delegate Methods
```
- (void) paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue
{
NSLog(@"Access Apple successfully");
NSMutableArray *purchasedItemIDs = [[NSMutableArray alloc] init];
NSLog(@"Received restored transactions: %i", queue.transactions.count);
for (SKPaymentTransaction *transaction in queue.transactions)
{
NSString *productID = transaction.payment.productIdentifier;
[purchasedItemIDs addObject:productID];
NSLog(@"Lan thu %i tra ve ID = %@",[purchasedItemIDs count],productID);
}
//purchasedItemIDs you get all purchase product identifier and compere from your side
}
-(void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error{
NSLog(@"Error when purchasing: %@",error);
}
``` | ```
You need handle in this method
-(void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error
{
// Wrote Your code Here
}
```
Please refer [apple doc](http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/StoreKitGuide/MakingaPurchase/MakingaPurchase.html) |
17,234,558 | I have a code for my project in Java and one of the classes is as shown below but when I want to run this code I will get compile error in this class one part of code is:
```
package othello.view;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import othello.ai.ReversiAI;
import othello.controller.AIControllerSinglePlay;
import othello.controller.AIList;
import othello.model.Board;
import othello.model.Listener;
@SuppressWarnings("serial")
public class TestFrameAIVSAI extends JFrame implements ActionListener, Logger,
Listener {
private static Border THIN_BORDER = new EmptyBorder(4, 4, 4, 4);
public JComboBox<Object> leftAICombo;
public JComboBox<Object> rightAICombo;
private JButton startTest;
private JButton pauseTest;
```
The error is from the two lines `public JComboBox<Object> leftAICombo;` and `public JComboBox<Object> rightAICombo;` and the error is:
`The type JComboBox is not generic; it cannot be parameterized with arguments <Object>`
What is the problem? | 2013/06/21 | [
"https://Stackoverflow.com/questions/17234558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2298069/"
] | Change the below lines
```
public JComboBox<Object> leftAICombo;
public JComboBox<Object> rightAICombo;
```
to
```
public JComboBox leftAICombo;
public JComboBox rightAICombo;
```
Here `JComboBox<Object>` type parameter introduced in java7 only.if you are using jdk below 7 it gives error | Generics were added to `JComboBox` in Java 7. It appears you are using an eariler version of the JDK. Either upgrade to Java 7 or remove the generics. The former is recommended as it offers more features/fixes as well as being up-to-date. |
15,758 | I have a collection of REST API tests, WebDriver based tests, Appium based tests and additional tests that run via shell. All written in C#.
All tests are written as VS unit tests, and in the case of the shell tests, are executed via a visual studio unit test.
Currently all I have is a collection of VS unit tests, which I'm pretty happy with. However, I need to support some extra flow control for the test run.
If one of the tests fails, I wish to run some other specific tests, and run the failed one again at the end.
Which tool or tools can support this logic?
Thanks in advance! | 2015/11/22 | [
"https://sqa.stackexchange.com/questions/15758",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/15369/"
] | I run my Coded UI tests from the commandline with `/Logger:trx` this generates a .trx file
```
vstest.console.exe "MyApp\Debug\MyApp.CodedUI.Test.dll" /tests:TestCase1,TestCase2 /Logger:trx
```
You find the vstest.console.exe in your VS directory: `C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\` | As far as I know, we couldn’t get the .trx file when we run the coded UI test in the VS 2012 IDE now, one solution is that you could run it in [command line](https://msdn.microsoft.com/en-us/library/ms182488.aspx) eg.
```
MSTest /testmetadata:Bank.vsmdi /resultsfile:BanktestResults.trx
``` |
168,451 | How do i disable remote access for non-root users over ssh? i would like to do this on demand if possible. | 2010/08/09 | [
"https://serverfault.com/questions/168451",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | Everyone is doing this the hard way.. he said deny for all non-root users.. so just edit
```
/etc/ssh/sshd_config
```
Add the following
```
AllowGroups wheel root
```
Then restart ssh
Anyone in the wheel or root group will be allowed to ssh in | If you want it to be on-demand, the standard way is to use `/etc/nologin` (have a look at `man 5 nologin`).
Creating this file (with an optional message inside) will deny non-admin logins and display the message instead; removing the file will allow logins back.
It can be applied to ssh, local logins, and anything else that uses PAM; just make sure that
the PAM configuration for the service requires `pam_nologin.so`. (It does by default for ssh and console logins on many distributions) |
60,909 | >
> I would look strange on your body,
>
>
> but not on your phone.
>
>
> You appreciate me most
>
>
> when you're not home.
>
>
> There's not enough clues,
>
>
> so let's make this a twofer...
>
>
> I watch what you do,
>
>
> and I have no future.
>
>
> **What am I?**
>
>
>
---
**Edit History:** Started with four lines written in third-person. It was too vague so I made small edits and adjusted the title to match. It was too open-ended so I added a second half with more clues. Also added the "wordplay" tag. | 2018/02/23 | [
"https://puzzling.stackexchange.com/questions/60909",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/-1/"
] | I think it should be
>
> Camera
>
>
>
I would look strange on your body,
>
> Picture from CCTV is always look strange or it would be weird if you wore a camera. (credit to [rm-vanda](https://puzzling.stackexchange.com/users/4616/rm-vanda))
>
>
>
but not on your phone.
>
> Picture from Mobile is almost look good.
>
>
>
You appreciate me most
when you're not home.
>
> CCTV camera safe when we are not at home.
>
>
>
**Updated:**
I watch what you do,
>
> Camera watch everything.
>
>
>
and I have no future.
>
> Camera see only present moment.
>
>
> | This will probably not be what you were searching for but you never know.
Are you:
>
> Free Wifi?
>
>
>
I would look strange on your body,
>
> This would be a weird Tattoo!
>
>
>
but not on your phone.
>
> Wifi on the phone is normal
>
>
>
You appreciate me most when you're not home.
>
> Free wifi is always a nice thing so you won't have to use mobile data.
>
>
> |
3,557,489 | >
> **Possible Duplicate:**
>
> [Is there a performance difference between i++ and ++i in C++?](https://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c)
>
>
>
In terms of usage of the following, please rate in terms of execution time in C.
In some interviews i was asked which shall i use among these variations and why.
```
a++
++a
a=a+1
a+=1
``` | 2010/08/24 | [
"https://Stackoverflow.com/questions/3557489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196146/"
] | The circumstances where these kinds of things actually matter is very rare and few in between. Most of the time, it doesn't matter at all. In fact I'm willing to bet that this is the case for you.
What is true for one language/compiler/architecture may not be true for others. And really, the fact is irrelevant in the bigger picture anyway. Knowing these things do not make you a better programmer.
You should study algorithms, data structures, asymptotic analysis, clean and readable coding style, programming paradigms, etc. Those skills are a lot more important in producing performant and manageable code than knowing these kinds of low-level details.
Do not optimize prematurely, but also, do not micro-optimize. Look for the big picture optimizations. | Well, you could argue that `a++` is short and to the point. It can only increment `a` by one, but the notation is very well understood. `a=a+1` is a little more verbose (not a big deal, unless you have `variablesWithGratuitouslyLongNames`), but some might argue it's more "flexible" because you can replace the `1` or either of the `a`'s to change the expression. `a+=1` is maybe not as flexible as the other two but is a little more clear, in the sense that you can change the increment amount. `++a` is different from `a++` and some would argue against it because it's not always clear to people who don't use it often.
In terms of efficiency, I think most modern compilers will produce the same code for all of these but I could be mistaken. Really, you'd have to run your code with all variations and measure which performs best.
(assuming that `a` is an integer) |
13,867,035 | If you take a look at [this website](http://hockeyapp.net/), you'll see that as you scroll and hit certain areas, a fade in animation plays, and brings the content to view. I've tried looking through the source to try to understand how they do this, but I haven't found any luck yet.
I'm guessing they use Javascript/jQuery to add a class when the DIV appears like so:
```
$('#element').addClass('animation');
```
But the question remains of how do they know when the DIV appears to call such Javascript? | 2012/12/13 | [
"https://Stackoverflow.com/questions/13867035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/458960/"
] | It's in <http://hockeyapp.net/javascripts/jquery.features.js>
Here it is *slightly* prettier:
```
function f_scrollTop() {
return f_filterResults(
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
)
}
function f_filterResults(e, t, n) {
var r = e ? e : 0;
return t && (!r || r > t) && (r = t), n && (!r || r > n) ? n : r
}
$(document).ready(function() {
var e = navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? !0 : !1;
e ? ($("#crashes").css("opacity", 1),
$("#feedback").css("opacity", 1),
$("#distribution").css("opacity", 1),
$("#analytics").css("opacity", 1),
$("#customers").css("opacity", 1))
: ($(window).scroll(function() {
var e = $("body").height(),
t = f_scrollTop(),
n = 0;
t > 250 && (n = 1), $("#crashes").css("opacity", n)
}), $(window).scroll(function() {
var e = $("body").height(),
t = f_scrollTop(),
n = 0;
t > 2250 && (n = 1), $("#feedback").css("opacity", n)
}), $(window).scroll(function() {
var e = $("body").height(),
t = f_scrollTop(),
n = 0;
t > 3100 && (n = 1), $("#distribution").css("opacity", n)
}), $(window).scroll(function() {
var e = $("body").height(),
t = f_scrollTop(),
n = 0;
t > 4400 && (n = 1), $("#analytics").css("opacity", n)
}), $(window).scroll(function() {
var e = $("body").height(),
t = f_scrollTop(),
n = 0;
t > 3200 && (n = 1), $("#customers").css("opacity", n)
})), $(".switch-monthly").live("click", function(e) {
$(this).addClass("switch-yearly"), $(this).removeClass("switch-monthly"), $(".price.monthly").fadeOut(), $(".price.yearly").fadeIn(), $(".save").slideDown(), e.preventDefault()
}), $(".switch-yearly").live("click", function(e) {
$(this).removeClass("switch-yearly"), $(this).addClass("switch-monthly"), $(".price.monthly").fadeIn(), $(".price.yearly").fadeOut(), $(".save").slideUp(), e.preventDefault()
}), $(".fancybox").fancybox({openEffect: "elastic",closeEffect: "elastic"})
});
```
`f_scrollTop` and `f_filterResults` form a cross-browser way to find how far the page has been scrolled.
On `document.ready`, they bind five functions to `$(window).scroll`. Every time you scroll, it gets the distance using `t = t_scrollTop()`, and sets `n` to 1 or 0 depending on the value of `t`. Then sets the opacity of each of the divs (`#crashes`, `#feedback`, `#distribution`, `#analytics`, `#customers`) to `n`. (Better explanation below)
So, they don't know when the `div` appears - each time you scroll it checks whether or not it has and sets the opacity accordingly. Also, they don't use `animate`, but instead have a CSS `transition` set for four of the `div`s in <http://hockeyapp.net/stylesheets/public.css> (don't try reading that):
```
#distribution,
#crashes,
#feedback,
#analytics {
opacity: 0;
-webkit-transition:opacity .5s ease-in-out 0s
}
```
---
On lines like this:
```
t > 250 && (n = 1), $("#crashes").css("opacity", n)
```
The comma operator says "evaluate each expression and the value of the whole expression is the value of the last." Here it's probably just used for brevity, since the source has been minified.
Since `n` is already 0 and `&&` short circuits, if `t > 250` then it will evaluate `(n = 1)`, otherwise it will leave `n` as 0. Then it sets the opacity to `n`. | You can track to see how far down the page the user has scrolled with a little bit of jQuery like this:
```
$(window).scroll(function(e){
if($(this).scrollTop() > 150) //the 150 here is the height in pixels
{
$('#element').addClass('animation');
}
});
```
In this code, the height in pixels is where you would specify how far down the page you would like for the animation to occur. You may have to play with the heights a bit to get it exactly how you want it. |
102,492 | Using a DEM, I assigned slope values to individual segments in a street network feature class. In some areas the slope values seem suspect, such as where a highway overpasses a local road. Is there a method to find those segments whose slope is radically different from adjoining segments (e.g. 5 to 25%) to locate possible inaccuaracies? | 2014/06/18 | [
"https://gis.stackexchange.com/questions/102492",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/32575/"
] | I would imagine that the most efficient way would be to 1) convert your "house" values to a point feature class, 2) create a grouping attribute using a minimum distance criteria with the [near](http://resources.arcgis.com/en/help/main/10.1/index.html#//00080000001q000000) tool, 3) loop through each group to generate minimum convex polygons using the [Minimum Bounding Geometry](http://resources.arcgis.com/en/help/main/10.1/index.html#//00170000003q000000) tool. You can then convert the combined minimum convex polygons back to a raster. | I recently had a similar problem where I needed to recognize clusters of items. I ended up using a hierarchical clustering algorithm provided by the [clusterfck](http://harthur.github.io/clusterfck/) library. Demo [here](http://bl.ocks.org/ryanthejuggler/10911656).
To apply this to your problem, you'd first traverse the image and make a list of points fitting your criteria.
For drawing the boundaries, you could use any of several techniques: you could compute a [convex hull](http://en.wikipedia.org/wiki/Convex_hull) or perhaps use [Voronoi cells](http://bl.ocks.org/mbostock/9927735).
I'm not sure if these algorithms are implemented in the language you're using, but it's not too difficult to do. |
1,384,908 | Prove that, for $n \geq 3$, the sum of the residues of all the isolated singularities of
$$\frac{z^n}{1+z+z^2+\cdots+z^{n-1}}$$
is 0
Can someone show me how to do this problem. Thank you. | 2015/08/05 | [
"https://math.stackexchange.com/questions/1384908",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/176662/"
] | Let
$$
F(z)=\frac{z^n}{1+z+z^2+\ldots+z^{n-1}}=\frac{P(z)}{Q(z)}.
$$
Since $Q(1)=n\ne 0$, then, for every $z\ne 1$ we have
$$
Q(z)=\frac{1-z^n}{1-z},
$$
and $F$ can be redefined as
$$
F(z)=\begin{cases}
\frac{(z-1)z^n}{z^n-1} &\mbox{ for } z\ne 1\\
\frac1n &\mbox{ for } z=1
\end{cases}
$$
Therefore, the set of isolated singularities of $F\_n$ is given by:
$$
Q^{-1}(0)=\{z\_{k,n}=z\_n^k:\, 1\le k\le n-1\},\quad z\_n=e^{i\frac{2\pi}{n}}
$$
We want to calculate the sum
$$
S\_n=\sum\_{k=1}^{n-1}\mathrm{Res}(F\_n,z\_n^k),
$$
where
$$
\mathrm{Res}(F,z\_n^k)=\frac{(z\_n^k-1)(z\_n^k)^n}{n(z\_n^k)^{n-1}}=\frac{(z\_n^k)^2-z\_n^k}{n},
$$
and we should assume that $n\ge 3$, because for $n=2$ the set $Q^{-1}(0)$ contains one element.
We get:
\begin{eqnarray}
nS\_n&=&\sum\_{k=1}^{n-1}\left[(z\_n^k)^2-z\_n^k\right]=\sum\_{k=1}^{n-1}(z\_n^2)^k-\sum\_{k=1}^{n-1}z\_n^k=\sum\_{k=0}^{n-1}(z\_n^2)^k-\sum\_{k=0}^{n-1}z\_n^k\\
&=&\frac{1-(z\_n^2)^n}{1-z\_n^2}-\frac{1-z\_n^n}{1-z\_n}=\frac{1-(z\_n^n)^2}{1-z\_n^2}-\frac{1-z\_n^n}{1-z\_n}.
\end{eqnarray}
Using the fact that $z\_n^n=1$, we conclude that
$$
S\_n=\frac1n\left[\frac{1-(z\_n^n)^2}{1-z\_n^2}-\frac{1-z\_n^n}{1-z\_n}\right]=0.
$$ | Let $\lambda\_j, j = 1,\ldots,n-1$ be $j^{th}$ root of $1 + z+ \cdots + z^{n-1}$ and $\alpha\_j$ be the corresponding residue. The key is $\lambda\_j$ are all distinct. We have following partial fraction decomposition:
$$\frac{z^n}{1+z+\cdots+z^{n-1}} = \frac{z^n}{z^n - 1}(z-1)
= z - 1 + \frac{z-1}{z^n-1}
= z - 1 + \sum\_{j=1}^{n-1}\frac{\alpha\_j}{z - \lambda\_j}$$
This implies
$$\sum\_{j=1}^{n-1}\frac{\alpha\_j}{z - \lambda\_j} = \frac{z-1}{z^n-1}$$
As a consequence, we can evaluate the sum of residues as
$$\sum\_{j=1}^{n-1}\alpha\_j = \lim\_{|z|\to\infty}z \left(\sum\_{j=1}^{n-1}\frac{\alpha\_j}{z - \lambda\_j}\right)
= \lim\_{|z|\to\infty} \frac{z(z-1)}{z^n-1} = 0 \quad\text{ when }\quad n > 3.
$$ |
153,829 | Following [the advice of Dave Ramsey](https://en.wikipedia.org/wiki/Dave_Ramsey#Teachings), I'm getting rid of my credit cards. The problem is, the alternatives don't seem safe. There are people who stand around the cash machines watching people take out large sums of cash. And there are merchants who have personal scanners who steal card details. It seems safer to use a credit card, because at least my actual bank balance can't be immediately drained.
Is there another way to make card payments that lacks the risk of being without my money if I paid with debit card, but also stops me from running up debt and interest? | 2022/11/25 | [
"https://money.stackexchange.com/questions/153829",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/6443/"
] | In the US (I can't vouch for elsewhere) debit cards are under different regulations than credit cards and are not as safe, but can be used in most places credit cards can be. You do have to maintain a high enough balance in the account behind the debit card to cover all anticipated purchases/holds/whatever.
Personally, I'm perfectly happy continuing to use credit cards and making darned sure I pay them off in full every month, so I never pay interest But if you can't resist the temptation to let payments slide, there are definitely arguments for not having one.
EDIT: Other folks have mentioned one-time credit card numbers, and prepaid cards. I'd add that some banks will let you turn a card on and off via their website or phone app, and a few may now offer the option of doing two-factor authentication on a card. All of these add some security, and may remind you to consider your budget before buying; the prepaid in particular is like taking out a cash withdrawal in that you can find only spend what you've loaded it with. | **PREPAID CREDIT CARD**
If your goal is just to protect your bank account by minimizing how frequently you directly access it while also avoiding building up debt and interest on a credit card, you can buy yourself a prepaid credit card.
You can only spend the amount of money you put onto the prepaid credit card and because of that you can't spend money you don't have. It protects your bank account because it has no link to your bank account and you can't go into debt on it like a normal credit card.
Don't lose the card though because the card is worth whatever you put onto it and there's no other way to access that money.
EDIT: Actually, it seems that if your prepaid credit card is stolen it is possible to lock it down and get it re-issued. That means the credit card is not the sole access point to those funds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.