qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
38,158,756 |
Haxe porgramming beginner here and I can't seem to find a solution for my problem.
I'm simply running another program on the computer via sys.io.Process.
```
import sys.io.Process;
import neko.Lib;
class Main
{
static function main()
{
var cProcess = new Process(pClient + sArgs);
}
}
```
I only want my Haxe program to be running as long as the "cProcess" exists.
So I need some kind of Eventhandler that calls a function when the cProcess is being closed.
Does anyone have an idea how to solve this problem?
Any suggestions welcome!
Thanks!
|
2016/07/02
|
[
"https://Stackoverflow.com/questions/38158756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6483376/"
] |
If all you want to do is wait for the process to complete it's execution
just call `exitCode()`, it will block until launched process exits.
```
var cProcess = new Process(pClient + sArgs);
cProcess.exitCode();
trace("Done!");
```
|
54,869,027 |
SQL CODE:
```
select student.sex, class.date
from ((student INNER JOIN student_course ON student.name=student_course.Student)
INNER JOIN class ON student_course.Course=class.Course);
```
Result:
```
sex date
m 25.2.19
m 27.2.19
m 27.2.19
m 27.2.19
m 25.2.19
m 27.2.19
m 25.2.19
f 25.2.19
f 27.2.19
f 27.2.19
f 25.2.19
f 26.2.19
```
Now my target is to get the date where both male and female student appear. So
I modified the code to be:
```
SELECT o.date
FROM ( select student.sex, class.date
from ((student INNER JOIN student_course ON student.name=student_course.Student)
INNER JOIN class ON student_course.Course=class.Course)) AS o
WHERE o.sex='m' AND o.sex='f';
```
The result is NULL. But I want the result as:
```
date
25.2.19
27.2.19
```
|
2019/02/25
|
[
"https://Stackoverflow.com/questions/54869027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10434854/"
] |
If an application's domain model is hierarchically, Pyramid offers the idea of resources to build a resource tree. Traversal is used to map URLs to code and to identify a resource within the resource tree. You typically do not use resources and traversal when working with a relational database.
Excerpt from ["Defending the design - Pyramid Does Traversal, and I Don't Like Traversal"](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/designdefense.html#pyramid-does-traversal-and-i-don-t-like-traversal)
>
> In Pyramid, traversal is the act of resolving a URL path to a resource object in a resource tree. Some people are uncomfortable with this notion, and believe it is wrong. Thankfully if you use Pyramid and you don't want to model your application in terms of a resource tree, you needn't use it at all. Instead use URL dispatch to map URL paths to views.
>
>
> Relational databases aren't naturally hierarchical, so traversing one like a tree is not possible.
>
>
> You can be assured that if you don't want to understand traversal, you don't have to. You can happily build Pyramid applications with only URL dispatch.
>
>
>
Excerpt from [Resources](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/narr/resources.html)
>
> A resource is an object that represents a "place" in a tree related to
> your application. (...) A resource tree is a set of nested
> dictionary-like objects which you can use to represent your website's
> structure.
>
>
> In an application which uses traversal to map URLs to code, the
> resource tree structure is used heavily to map each URL to a view
> callable. When traversal is used, Pyramid will walk through the
> resource tree by traversing through its nested dictionary structure in
> order to find a context resource. Once a context resource is found,
> the context resource and data in the request will be used to find a
> view callable.
>
>
> In an application which uses URL dispatch, the resource tree is only
> used indirectly, and is often "invisible" to the developer. (...) This root resource sometimes has security
> declarations attached to it, but is not required to have any. In
> general, the resource tree is much less important in applications that
> use URL dispatch than applications that use traversal.
>
>
>
I think the topic is covered extensively in the docs.
* [Resources](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/narr/resources.html)
* [Much ado about traversal](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/narr/muchadoabouttraversal.html)
* [Traversal](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/narr/traversal.html)
* [Combining Traversal and URL Dispatch](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/narr/hybrid.html)
I used to recommend a project to emphasize Pyramid’s capabilities.
* [Pyramid Auth Demo](https://michael.merickel.org/projects/pyramid_auth_demo/index.html)
My humble opinion: You do not need to understand both concepts entirely and upfront to adopt Pyramid framework for your first projects. Go for URL Dispatch and SQLAlchemy when working with a relational database.
[Excerpt - Pyramid Provides Too Many "Rails"](https://docs.pylonsproject.org/projects/pyramid/en/1.10-branch/designdefense.html#pyramid-provides-too-many-rails)
>
> By design, Pyramid is not a particularly opinionated web framework. Pyramid provides some features that other web frameworks do not. These are features meant for use cases that might not make sense to you if you're building a simple (...) web application.
>
>
>
|
161,971 |
In the lobby there are tags with numbers on against some player names - what are they?
|
2014/03/27
|
[
"https://gaming.stackexchange.com/questions/161971",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/4067/"
] |
These tags show what "Generation" the player has achieved in the game, which is done by leveling up to level 50 and completing specific challenges for each generation, then "regenerating" back to level 1.
|
41,651,107 |
Is it possible to define abstract static methods?
I'm trying:
```
abstract struct MyStruct
abstract def self.myfun # ERR
abstract def MyStruct::myfun # ERR
end
```
|
2017/01/14
|
[
"https://Stackoverflow.com/questions/41651107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2627246/"
] |
Abstract class methods don't appear to be a language feature:
```
abstract class Abstract
abstract self.doit
end
# => Syntax error in /home/bmiller/test.cr:23: unexpected token: self
```
However you could always delegate to an instance:
```
abstract class Parent
def self.instance
@@instance ||= new
end
def self.doit
instance.doit
end
abstract def doit
end
class Child < Parent
def doit
"ok"
end
end
p Parent.doit # => can't instantiate abstract class Parent
p Child.doit # => "ok"
```
|
23,579,341 |
I try to work with trigger here.
I have a relation like this :
```
salary(salaryid, userid, netsalary, reward, totalsalary)
```
So I want to update `totalsalary` everytime I insert and update (`netsalary` or `reward`), it will recount : `totalsalary = netsalary + reward`.
To do that, I made a function and a trigger :
```
CREATE FUNCTION reCount()
RETURNS TRIGGER AS $function$
BEGIN
UPDATE salary SET totalsalary = netsalary + reward;
RETURN NEW;
END;
CREATE TRIGGER updateTotalsalary
AFTER INSERT OR UPDATE
ON salary
FOR EACH ROW
EXECUTE PROCEDURE reCount();
```
Finally, I try to test by a query insert like this :
```
INSERT INTO salary(salaryid,userid,netsalary,reward,totalsalary)
VALUES (1234,123, 30,2,30);
```
but it run for a long time and it seem never stop. So when a try to stop it with, I got many rows of :
>
> SQL statement "UPDATE salary SET totalsalary = netsalary + reward"
>
> PL/pgSQL function "reCount()" line 3 at SQL statement
>
>
>
So what is the problem. Hope you guys can give me some suggestion?
|
2014/05/10
|
[
"https://Stackoverflow.com/questions/23579341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3518193/"
] |
Try running:
```
bundle exec rake assets:clean assets:precompile --trace
```
then spawn it if you are using passenger:
```
touch tmp/restart.txt
```
then check again.
|
52,085,457 |
I am trying to split a name field into three parts into first name, mid name, last name by using UNSTRING DELIMITED BY SPACES as follows
```
UNSTRING WA-NAME DELIMITED BY SPACES
INTO WA-FIRST-NAME
WA-MID-NAME
WA-LAST-NAME
```
But if my name field has more than 2 spaces the remaining words are getting missed
`Example : NAME : M V S PAVAN
It is showing as WA-FIRST-NAME : M
WA-MID-NAME : V
WA-LAST-NAME : S`
But the fourth word `PAVAN` is missing how can i get that included in my third word. i.e, i want to include all the remaining words in `WA-LAST-NAME`
|
2018/08/29
|
[
"https://Stackoverflow.com/questions/52085457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9969111/"
] |
To just solve the question "how can i get that included in my third word. i.e, i want to include all the remaining words in WA-LAST-NAME" (which may not be what you want) you can use different approaches but the best ones likely will use the POINTER (position in source field). It *may* uses an additional counter for the last item, leading to:
```
UNSTRING WA-NAME DELIMITED BY ALL SPACES *> just in case two spaces were used
INTO WA-FIRST-NAME
WA-MID-NAME
WA-LAST-NAME COUNT STRPV *> *MOVE* the amount of target length
WITH POINTER STRPS ON OVERFLOW
ADD 2 TO STRPV *> adding one to be after the text, another for space
MOVE WA-NAME (STRPS:) TO WA-LAST-NAME (STRPV:)
```
Complete test: <http://tpcg.io/BYJXKL>
As donPablo already pointed out you won't get an 100% automated correct name result...
|
9,028,446 |
I know this isn't a direct technical problem but this seems like an ideal place to ask since I know other developers have experience using this service. I was about to ask this on the Amazon AWS forums but realized you need to be a AWS account holder to do that. I don't want to signup with them before getting the following answered:
1. Is Amazon S3 a CDN? or is it just an online storage service meant for personal use? Even if it isn't a CDN are you at least allowed to serve website assets from it to a high traffic site?
2. I have an adult dating site I would like to store assets for in S3? Is this type of site allowed under their tos? What they had to say on the matter in their tos was way too broad. Basically this site has nude images of members but they are all of age and uploaded by the users themselves. The site is targeted only to U.S. users and is legal under U.S. laws.
|
2012/01/27
|
[
"https://Stackoverflow.com/questions/9028446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1128811/"
] |
Amazons S3 service can be used as a CDN if you want depending on the size of your site your might want to look at cloudfront which will allow you to have your content shared across multiple zones, for what your describing s3 will be fine for your needs but as for amazons rules with content im not to sure.
|
64,063,452 |
```
CREATE TABLE IF NOT EXISTS posts (
title VARCHAR ,
post_description TEXT NOT NULL,
time_posted TIMESTAMP,
PRIMARY KEY(title)
);
UPDATE posts SET time_posted = ???? WHERE time_posted IS NULL;
```
I have a table that represents a post (on any social media you like), and that table contains the tile, the description, and the time that the post has been made.
In this example, if a post has a `NULL` date, I have to automatically modify it to a specific date, which is 27 April 2019 21:11:12 UTC (in UNIX format). The question is how can I do that? I have tried to find a way and read plenty of things on the internet.
I also saw a Unix Time Stamp - Epoch Converter and saw that the value for that date is `1556399472`, but I am not sure how that would work in my table and I don't think it will convert correctly (I have tested it and did not work :< )
Another example here to make sure it is clear:
```
The legendary flying stone | Fake news everyone | NULL
```
I must convert it to something like this
```
The legendary flying stone | Fake news everyone | *The date I specified before which is UTC and must be in UNIX format*
```
NOTE: I am working in SQL in the IntelliJ IDE.
|
2020/09/25
|
[
"https://Stackoverflow.com/questions/64063452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13861198/"
] |
>
> then route traffic to my server in the private subnet.
>
>
>
Not without NAT you won't. You either need a NAT gateway or a NAT instance (be it prepackaged or something you've set up yourself). Routing from public subnets to private subnets needs NAT and private subnets by definition *cannot* route to the internet.
|
30,884,197 |
I have a json file from which HTML content is fetched and displayed on the browser
```
"content": "Hello World <h1 class=\"page-title\">H1 Heading HTML tag</h1> <p>Para Tag</p>",
```
This works when HTML content is small.
How should I handle large HTML blocks of content such as a slider or accordian. Is it possible to call a file instead of the content.
Thanks
|
2015/06/17
|
[
"https://Stackoverflow.com/questions/30884197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2043459/"
] |
Try utilizing `html` , [`.load()`](http://api.jquery.com/load)
html
```
// e.g., "/path/to/html/"
<div id="first">Hello World 1 <h1 class="page-title">H1 Heading HTML tag</h1> <p>Para Tag</p></div>
<div class="second">Hello World 2 <h1 class="page-title">H1 Heading HTML tag</h1> <p>Para Tag</p></div>
<img src="image-1">
<img src="image-2">
```
js
```
$("#container1").load("/path/to/html/ #first");
$("#container2").load("/path/to/html/ .second");
$("#container3").load("/path/to/html/ [src=image-1]");
$("#container4").load("/path/to/html/ img:eq(1)");
```
|
5,603,851 |
I need to download images from other websites to my server. Create a ZIP file with those images. automatically start download of created ZIP file. once download is complete the ZIP file and images should be deleted from my server.
Instead of automatic download, a download link is also fine. but other logic remains same.
|
2011/04/09
|
[
"https://Stackoverflow.com/questions/5603851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658659/"
] |
Well, you'll have to first create the zipfile, using the [**`ZipArchive`**](http://fr.php.net/manual/en/class.ziparchive.php) class.
Then, send :
* The right headers, indicating to the browser it should download something as a zip -- see **`header()`** -- there is an example on that manual's page that should help
* The content of the zip file, using [**`readfile()`**](http://fr2.php.net/readfile)
And, finally, delete the zip file from your server, using [**`unlink()`**](http://fr2.php.net/unlink).
Note : as a security precaution, it might be wise to have a PHP script running automatically *(by crontab, typically)*, that would delete the old zip files in your temporary directory.
This just in case your normal PHP script is, sometimes, interrupted, and doesn't delete the temporary file.
|
58,025,873 |
EDIT: It turns out I am just bad at looking for stuff. The war before the changes did not have these libraries, and the original .war (before repackage) already contains them. So the issue lies somewhere else, spring-boot-maven-plugin has nothing to do with it. Still don't know where they are coming from since I've also tried simply deleting the dependency whereever I find it, but oh well, see my first sentence.
I am working on making my firms software run as a spring boot application. Since our war may be deployed in various different environments like the SAP Cloud Platform, logging libraries should not be included in the lib folder to prevent conflicts. However, some logging libraries (specifically jul-to-slf4j, log4j-api and log4j-to-self4j) are always in my lib folder no matter how specific my exclusions get. Other libraries (two of ours that are needed for tests or have to be included in the classes file) are excluded properly.
I have tried setting the tag to the specific libraries as well as to just exclude the whole group. After this, I tried to simply exclude the dependencies themselves, but they still somehow show up after mvn dependency:tree tells me they are no longer present.
This is the plugin configuration:
```xml
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>
repackage
</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>de.firm.integration.BaseSpringConfiguration</mainClass>
<excludes>
<exclude>
<groupId>de.firm.integration</groupId>
<artifactId>eis-generator-odata-api</artifactId>
</exclude>
<exclude>
<groupId>de.firm.integration</groupId>
<artifactId>eis-admin-ui</artifactId>
</exclude>
<exclude>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</exclude>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</exclude>
<exclude>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jul</artifactId>
</exclude>
<exclude>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclude>
<exclude>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
```
I expect the war that I build to no longer include these logging libraries in my WEB-INF/lib folder. Instead, they keep being included.
|
2019/09/20
|
[
"https://Stackoverflow.com/questions/58025873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11369113/"
] |
For overload resolution, a compiler first has to check that an overload can accept the number of arguments that were provided at the call. This is a process that determines which functions are *viable* for this function call expression.
The first overload can only accept exactly two, while the second overload can only accept exactly three. The immediately disqualifies the second overload in both cases. So the overload set contains a single member for both invocations.
Now a compiler has to see if it can form a conversion sequence from every argument to every parameter type. The `"name"` literal gets converted to a `std::string` via constructor, and a `double` has an implicit conversion to `int`. So forming conversion sequences is a success for the one and only overload in the set. As such, it gets called.
|
21,639,810 |
I'm writing a Notes Client application. Web compatibility is a secondary concern. The language is LotusScript.
The specification: a form to enter lines from receipts. The lines are all saved as part of the same document so that they can be signed as an atomic unit.
When a line is added, it is to be formatted into a table for presentation. Ultimately, this architecture is like an input/datastore/presentation split.
I've managed to get the data stored and signed, and I think I've managed to get it deserializing properly (the LotusScript debugger makes it difficult to see, but it looks right). The problem now is the UI.
Looking at the Programmable Table, it is always a tabbed table with only one row shown per tab. I need a programmable table which can dynamically have rows added to it for display, without forcing new tabs to be created.
This suggests that I would need to use a Rich Text field to contain a table, but thus far my attempts to get anything to display when I try to update a Rich Text field in edit mode have failed. I am forced to conclude that it is impossible.
I cannot figure out how I'm supposed to do a dynamically-displayed list of tabular data like this. Any advice?
|
2014/02/07
|
[
"https://Stackoverflow.com/questions/21639810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695902/"
] |
Most people just create a table with one row and N columns, with a multi-valued field in each column, and use code to append values to each of the fields in parallel. You don't get borders between rows this way or the ability to do variable formatting of cells, and you have to be careful to avoid letting data length exceed column widths in order to keep everything aligned properly.
If you truly want a dynamic table for presentation with all the bells and whistles that you can get in terms of cell formatting, then the Midas Rich Text API from Genii Software is a commercial solution that can do the job.
|
19,143,877 |
I have a question regarding icloud store with core data store in iOS7. In the apple WWDC conference, it was mentioned that the core data store can be created in the sandbox and when the app starts receiving responses from icloud, the changes in the core data store will be merged into icloud store.
Now, (I might be wrong), but the conference further mentioned that the local core data store would be deleted once the app has switched over to the icloud store. So, my question is can a local core data store co-exist with the icloud store in iOS7 (so that the user has capability to work offline with data) ? And is there any sample code for this ?
|
2013/10/02
|
[
"https://Stackoverflow.com/questions/19143877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1813400/"
] |
In iOS 7, the Core Data framework takes care of managing the local store until the iCloud store is setup and available. This pattern also works for when the app is offline and it doesn't delete any data when the app goes offline (just double checked on my app in development).
The iCloud store will be deleted in another case. That's in the event the iCloud user account changes in which case the respective iCloud store file will be removed. In such case, there is a new API `NSPersistentStoreCoordinatorStoresWillChangeNotification` that allows you to store unsaved data before the store becomes unavailable. If the user logs in later with that same account, the data will be restored from iCloud (check the WWDC 2013 session 207 video at 15' for more on this).
As for sample code, there isn't any as of today. There is, though, [iCloud sample code shared by AppleSpaceMan](https://devforums.apple.com/thread/201492?tstart=0) on the developer forum, which is what I used as a base and worked nicely.
|
220,520 |
We have several remote, unmanned terminals where I require a VNC server, as using Remote Desktop prevents others using the terminals. Often the connection to one of these is extremely slow, and manually using Remote Desktop to perform the VNC installation is painstaking. What I would like to do is build a package that I could copy onto the remote terminal using Remote Desktop, and then have the package executed to install and configure VNC when the terminal restarts, as they all automatically restart nightly. The terminals are all running Windows XP. Also, out of the many VNC variants out there, which would suit this application?
|
2011/01/10
|
[
"https://serverfault.com/questions/220520",
"https://serverfault.com",
"https://serverfault.com/users/20657/"
] |
Do you have any special authentication requirements? How picky are you about performance? If you want integrated Windows authentication you would want UltraVNC.
Have you done a search for `deploy vnc`? Depending on the version of VNC, in many cases it is as easy as copy files to the system, adding any prefs to the registry, and running the command to add the service. If you need integrated Windows authentication, or higher video performance it gets trickier since you have to install drivers.
* <http://wpkg.org/TightVNC>
* <http://www.waynezim.com/2009/05/how-to-deploy-vnc-using-group-policy/>
|
1,101,482 |
I am a non-mathematician (a physicist) who wants to find a continuous function on $[0,1]$ that satisfies the relation $f(x)=\frac12 x f(x^2)+1$ with $0\le x\le 1$. I need it for one of my models.
This is what I've got sofar.
I want to use [Banach's contraction theorem](https://en.wikipedia.org/wiki/Banach_fixed-point_theorem#Statement).
Define $T:C[0,1]\to C[0,1]: (Tf)(x)=\frac12 x f(x^2)+1$. If $T$ is a contraction, the Banach's contraction theorem yields that $Tf=f$ and that solves my problem. I know that C[0,1] is a complete normed space with regard to $\lVert\cdot\rVert\_{\infty}$
I do not know how to show that $T$ is a contraction. Can someone show me how do do this?
|
2015/01/12
|
[
"https://math.stackexchange.com/questions/1101482",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/207405/"
] |
Define $\|f\|\_\infty := \max\_{x\in [0,1]} |f(x)|$, for all $f\in C[0,1]$. Given $f, g\in C[0,1]$ and $x\in [0,1]$,
$$|Tf(x) - Tg(x)| = \left|\left(\frac{1}{2}xf(x^2) + 1\right) -\left(\frac{1}{2}xg(x^2) + 1\right)\right| = \frac{|x|}{2}|f(x^2) - g(x^2)| \le \frac{1}{2}\|f - g\|\_\infty.$$
Thus $$\|Tf - Tg\|\_\infty \le \frac{1}{2}\|f - g\|.$$ So $T$ is a contraction (with contraction constant $\frac{1}{2}$).
|
27,740 |
[](https://i.stack.imgur.com/pbxJN.jpg)
[](https://i.stack.imgur.com/wmoWK.jpg)
[](https://i.stack.imgur.com/InRGU.jpg)
[](https://i.stack.imgur.com/bK3JK.jpg)
The oil leak is slow and builds up after time. Seems to get worse if driving over 70mph. Car is ford fiesta 1.4 tdci.
The picture where i've highlighted red circle - the oil seems to build up here, wells up. Any idea what that part of the engine is?
It's hard to tell if there's a loss of power as the car is slow anyway and not had very long.
|
2016/03/31
|
[
"https://mechanics.stackexchange.com/questions/27740",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/14540/"
] |
**You have to clean the engine bay first**
When troubleshooting for the source of an oil look you first have to completely clean off all of the old oil, dirt and built up grime.
You can get a citrus based cleaner for oil at an auto parts store. Typically you will heat the engine up enough to make it warm but not hot enough that if you sprayed something on the engine that it would evaporate quickly. Citrus based cleaners are water soluble so you can hose them off. You may want to brush around the bay, especially underneath the motor where most of the gritty grime will be builtup.
**Once clean, do the following**
* Turn the car on, get it good and hot and ensure that all the water is evaporated. You may want to drive it a short distance but not so far that you will dirty it up again.
* Place a large piece of cardboard under the engine. See where drips might be forming and dropping onto the cardboard. When you have a drip you will want to chase it up to it's source. The oil might run along a wire and drip. It may leak down the side of your engine, drop onto a suspension arm, run down it and then finally drop onto the ground. The source can be difficult to find.
* Check areas where two engine surfaces meet. If you have a failing gasket it will be something like this. A valve cover, an oil pan, something like that.
* Check oil lines - You may have an oil line coming loose that is dripping. Take into account the air movement from a fan or driving down the road at a high rate of speed and oil can get sprayed everywhere. Which is why it's important to clean EVERYTHING before you start you hunt.
* You can also try throwing talcum/baby powder all over the place and blowing it off with a leaf blower and see where it has built up. It's a painful way to do it but I've found the leak source doing this before so sometimes it's a good method depending on where the leak is.
|
26,258,477 |
Here's my request and the response from my server:
Request Headers
```
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:512
Content-Type:application/json; charset=UTF-8
DNT:1
Host:192.168.59.103:8080
Origin:http://192.168.59.103:9000
Referer:http://192.168.59.103:9000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
```
Request Payload
```
{"notification":{"status":"testing","date_opened":null,"time_opened":null,"date_closed":null,"time_closed":null,"subsystem_affected":null,"who_resolved_it":null,"who_sent_it":null,"reason":null,"impact":null,"resolution":null,"description_of_problem":"testing","downtime_date_begin":null,"downtime_time_begin":null,"number_of_days":null,"number_of_hours":null,"number_of_minutes":null,"downtime_date_end":null,"downtime_time_end":null,"notification_number":null,"begin_user":null,"end_user":null,"subject":null}}
```
Response Headers
```
Remote Address:192.168.59.103:8080
Request URL:http://192.168.59.103:8080/api/notifications
Request Method:POST
Status Code:201 Created
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, x-requested-with, Accept
Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:*
Content-Length:0
Content-Type:text/plain; charset=utf-8
Date:Tue, 07 Oct 2014 19:58:39 GMT
Location:http://192.168.59.103:8080/api/notifications/11
ConsoleSearchEmulationRendering
```
Here's the function that I'm calling if saving the new record fails:
```
function failure(err) {
console.log("Oops!");
console.log(err);
}
```
This outputs an object on the console, but I can't figure out what the problem is. As you can see from the server response above, the headers and HTTP status code seem to be correct per <http://jsonapi.org/format/> .
And here's the line where I try to save the new "notification" model:
```
notification.save().then(afterSaving, failure);
```
The `err` object looks like this on the console:
>
> Oops! combined-scripts.js:206 Object {readyState: 4,
> getResponseHeader: function, getAllResponseHeaders: function,
> setRequestHeader: function, overrideMimeType: function…}abort:
> function ( statusText ) {always: function () {complete: function ()
> {done: function () {error: function () {fail: function ()
> {getAllResponseHeaders: function () {getResponseHeader: function ( key
> ) {overrideMimeType: function ( type ) {pipe: function ( /\* fnDone,
> fnFail, fnProgress \*/ ) {progress: function () {promise: function (
> obj ) {readyState: 4responseText: ""setRequestHeader: function ( name,
> value ) {state: function () {status: 201statusCode: function ( map )
> {statusText: "Created"success: function () {then: null\_\_proto\_\_:
> Object
>
>
>
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26258477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16609/"
] |
Add `display:inline-block` to `#logo_text`. It's block level by default, which when pushed over will cause the scroll bar to appear.:
```css
html {
width: 100%;
height: 100%;
background: -webkit-linear-gradient(90deg, #73C8A9 10%, #373B44 90%); /* Chrome 10+, Saf5.1+ */
background: -moz-linear-gradient(90deg, #73C8A9 10%, #373B44 90%); /* FF3.6+ */
background: -ms-linear-gradient(90deg, #73C8A9 10%, #373B44 90%); /* IE10 */
background: -o-linear-gradient(90deg, #73C8A9 10%, #373B44 90%); /* Opera 11.10+ */
background: linear-gradient(90deg, #73C8A9 10%, #373B44 90%); /* W3C */
}
ul {
position: absolute;
bottom: 0%;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
width: 500px;
line-height: 120px;
padding-right: 40px;
}
ul li {
list-style-type: none;
color: #fff;
font-family: Arial, "sans-serif";
font-size: 1.2em;
display: inline;
padding-left: 40px;
}
a {
text-decoration: none;
color: #fff;
}
a:hover {
padding-top: 40px;
background: url(images/dot.png) top center no-repeat;
color: lightgrey;
}
.main_logo {
position: absolute;
top: 150px;
right: 20px;
width: 500px;
height: 250px;
color: #fff;
padding: 5px;
font-size: 2em;
font-family: Arial;
}
.largetext {
font-size: 8em;
margin: 0;
padding: 0;
}
#logo_text {
position: relative;
bottom:200px;
left: 150px;
display:inline-block;
}
#logo_text p {
font-size: 0.7em;
line-height: 12px;
}
@media screen and (min-width: 568px) and (max-width: 1024px){
.main_logo {
top: 150px;
position: absolute;
right: 60px;
width: 290px;
height: 150px;
}
#tag {
height: 70px;
top: 0px;
left: -20px;
}
#tag2 {
left: 150px;
top: 0px;
}
#logo_text {
top: 70px;
left: 70px;
font-size: 0.7em;
}
ul li {
font-size: 1.1em;
}
ul {
position: absolute;
bottom: 5%;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
width: 490px;
line-height: 30px;
}
nav a:hover {
padding-top: 20px;
background: url(images/dot_medium.png) top center no-repeat;
}
}
```
```html
<body>
<div class = "main_logo">
<p class = "largetext">< ></p>
<div id = "logo_text">
<p>John Smith</p>
<p>Web Designer/Developer</p>
</div>
</div>
</div>
</body>
</html>
```
|
786,485 |
I can't seem to get nslookup to resolve correctly.
Here is my hosts file:
```
[root@clc-host ge2011.11]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.101 clc-host
192.168.0.101 clc-host.novalocal
```
Here is the results of `nslookup`:
```
[eamorr@clc-host ge2011.11]$ nslookup clc-host
Server: 10.77.254.1
Address: 10.77.254.1#53
** server can't find clc-host: NXDOMAIN
[eamorr@clc-host ge2011.11]$ nslookup clc-host.novalocal
Server: 10.77.254.1
Address: 10.77.254.1#53
** server can't find clc-host.novalocal: NXDOMAIN
```
Do you know how I might fix this issue? All I want to do is have "clc-host" resolve to 192.168.0.101. I need both "clc-host" and "clc-host.novalocal" to resolve to 192.168.0.101!!!
Here is " ifconfig -a"
```
[eamorr@clc-host ge2011.11]$ ifconfig -a
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1450
inet 192.168.0.101 netmask 255.255.255.0 broadcast 192.168.0.255
ether fa:16:3e:xx:xx:xx txqueuelen 1000 (Ethernet)
RX packets 506130 bytes 500159111 (476.9 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 318940 bytes 80431845 (76.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 0 (Local Loopback)
RX packets 251781 bytes 57945811 (55.2 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 251781 bytes 57945811 (55.2 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255
ether 52:54:00:xx:xx:xx txqueuelen 0 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
virbr0-nic: flags=4098<BROADCAST,MULTICAST> mtu 1500
ether 52:54:00:xx:xx:xx txqueuelen 500 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
```
I think there is some internal problem with the DNS and I don't know how to fix it. I don't think it's related to /etc/hosts
Do I need to install a full DNS server locally?
I'm trying to install 3rd party software - the GUI won't accept an IP address and I have to use the machine's hostname, which isn't resolving...
|
2016/06/27
|
[
"https://serverfault.com/questions/786485",
"https://serverfault.com",
"https://serverfault.com/users/362569/"
] |
`nslookup` (**n**ame **s**erver **lookup**) doesn't work with entries in the host file, instead it queries the DNS system, which doesn't know about names defined in your local `hosts` file. Try to just `ping` the name or access it in the web browser.
|
1,783,935 |
I spent a few hours trying to solve this indefinite integral:
$$\int \frac { dx}{x^{2m}+1}, m \in \mathbb R $$
I tried to transform the fraction to partial fractions getting $\int \frac{\imath}{2(x^m+\imath)} {dx} - \int \frac{\imath}{2(x^m-\imath)} {dx}$, but this doesn't help me because we enter in complex analisys, a field that I've no knowledgement and searching for methods that can help me with this make me nuts. I think the solution should involve some sort of induction, so I tried to solve for $ m= 0, 1, 2...$, but this doesn't help me neither. I've no luck looking for some books in the university library that can help me.
Putting the integral in wolframalpha gives me the result:$$ x \space\_2F\_1(1,\frac{1}{2m};1 + \frac{1}{2m}; -x^{2m}) \color{silver} {+constant}$$where $\_2F\_1(1,\frac{1}{2m};1 + \frac{1}{2m}; -x^{2m})$ is the hypergeometric function (I'd never hear about this before) .
This reveals to me that this problem is beyond my capabilities. Can some kind soul make a detailed resolution for me? If possible, not going into deep complex analysis.
|
2016/05/13
|
[
"https://math.stackexchange.com/questions/1783935",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336846/"
] |
The Wolfram Alpha expression of the indefinite integral in terms of the Gauss hypergeometric function is more straightforward than it might seem. We formally expand the integrand in powers of $x$ and integrate term-by-term to obtain
$$\int \frac{dx}{1+x^{2m}} = \int\left[1-x^{2m}+x^{4m}-\cdots\right]dx = x-\frac{x^{2m+1}}{2m+1} +\frac{x^{4m+1}}{m+1}-\cdots.$$ This expression is of the form $x \,f(-x^{2m})$ with $$f(u)=1+\frac{u}{2m+1}+\frac{u^2}{4m+1}+\cdots =\sum\_{k=0}^\infty \frac{u^k}{2km+1}.$$ To compare with Wolfram Alpha, we recall that the Gauss hypergeometric function is *defined* as $\displaystyle \_2F\_1(a,b;c;u)=\sum\_{k=0}^\infty \frac{(a)\_k(b)\_k}{(c)\_k }\frac{u^k}{k!}$ where $(a)\_k = a(a+1)\cdots (a+k-1)$. The particular case of $(a,b,c)=(1,\frac{1}{2m},1+\frac{1}{2m})$ gives
$$\frac{(1)\_k}{k!}\frac{(\frac{1}{2m})\_k}{(1+\frac{1}{2m})\_k }=\frac{k!}{k!}\frac{\frac{1}{2m}(\frac{1}{2m}+1)\cdots (\frac{1}{2m}+k-1)}{(\frac{1}{2m}+1)(\frac{1}{2m}+2)\cdots (\frac{1}{2m}+k)}=\frac{\frac{1}{2m}}{\frac{1}{2m}+k}=\frac{1}{1+2mk}$$ and we conclude that $f(u)={\_2F}\_1(1,\frac{1}{2m},1+\frac{1}{2m};u)$ in agreement with Wolfram Alpha.
Note: For the formal expansion in powers of $x$ to be justified, we need $|x^m|<1$. Hence the above reasoning will be valid near $x=0$ under the assumption $m>0$.
|
70,793,722 |
I am trying to run a playbook if a specific system user does not exist and make it fail and print a message if the user exists. Below the how I do the user check:
```
- name: 'Check system user'
getent:
database: passwd
key: '{{USER}}'
register: result
```
How do I make it fail and print message if user exists and make it continue with the rest of tasks if user does not exist?
THanks in advance.
|
2022/01/20
|
[
"https://Stackoverflow.com/questions/70793722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7784565/"
] |
Q: **"*Fail and print a message if the user exists and continue with the rest of the tasks if the user does not exist.*"**
A: For example, given the variable
```yaml
USER: admin
```
The tasks below
```yaml
- getent:
database: passwd
- assert:
that: "{{ USER in getent_passwd }}"
fail_msg: "User {{ USER }} does not exist."
success_msg: "User {{ USER }} exists."
- debug:
msg: Continue
```
gives
```yaml
TASK [assert] **************************************************************
ok: [localhost] => changed=false
msg: User admin exists.
TASK [debug] ***************************************************************
ok: [localhost] =>
msg: Continue
```
Test a missing user. For example
```yaml
USER: joker
```
The same tasks will fail and print the message
```yaml
TASK [assert] **************************************************************
fatal: [localhost]: FAILED! => changed=false
assertion: false
evaluated_to: false
msg: User joker does not exist.
```
|
2,506,488 |
I need to know when the [`finalize()`](https://docs.oracle.com/javase/10/docs/api/java/lang/Object.html#finalize()) method is called in the `JVM`. I created a test class which writes into a file when the `finalize()` method is called by overriding it. It is not executed. Can anybody tell me the reason why it is not executing?
|
2010/03/24
|
[
"https://Stackoverflow.com/questions/2506488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131565/"
] |
The `finalize` method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.
Note that it's entirely possible that an object never gets garbage collected (and thus `finalize` is never called). This can happen when the object never becomes eligible for gc (because it's reachable through the entire lifetime of the JVM) or when no garbage collection actually runs between the time the object become eligible and the time the JVM stops running (this often occurs with simple test programs).
There are ways to tell the JVM to run `finalize` on objects that it wasn't called on yet, but using them isn't a good idea either (the guarantees of that method aren't very strong either).
If you rely on `finalize` for the correct operation of your application, then you're doing something wrong. `finalize` should **only** be used for cleanup of (usually non-Java) resources. And that's *exactly* because the JVM doesn't guarantee that `finalize` is ever called on any object.
|
102,671 |
I would like to know whether 'I park my car '***on*** the porch' or '***in*** the porch' is correct?
|
2013/02/02
|
[
"https://english.stackexchange.com/questions/102671",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/36955/"
] |
In the UK, it's neither ***on*** nor ***in*** the porch. This is a decent-sized porch:
 [Source](http://www.rogergladwell.co.uk/20dec06/porch.html)
Parking on that is plainly ridiculous; and it's too small to park a car in it.
Andrew Lazarus suggested a carport, and it could look like a porch:
 [[Andreas Hornig](http://commons.wikimedia.org/wiki/File:Carport_In_Front_Of_Garages.jpg)]
In British English, one parks ***under*** a carport; and if this structure were called a porch, it would still be ***under*** the porch. It's *under* because there is simply a supported roof, and no walls to be inside of.
What British English doesn't have is "porch" describing the sort of large covered terrace which fronts some American houses.
|
587,709 |
I'm managing a VPS server (I'm using Debian 10 Buster, the latest **stable** version), and I want to install the latest version of the essential web packages (for example: Apache 2.4.43, Bind 9.16.3), but when I use the default apt-repository, it installs a slightly old version (apache 2.4.38 and bind 9.11.5)..
I've found out that the version 2.4.43 of apache2 is only available for Debian Bullseye (testing version), but I don't want to install a testing version of Debian, I prefer stable versions.
**In a nutshell:** I want to install the "latest" version of apt packages (like apache2, bind9, postfix, etc.) without upgrading to an unstable version of Debian.
|
2020/05/19
|
[
"https://unix.stackexchange.com/questions/587709",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/413392/"
] |
The reason Debian stable is called stable is because the software it contains, or rather, the external interfaces of all the individual pieces of software it contains, don’t change during its lifetime. A consequence of this is that, barring a few exceptions, packaged software isn’t upgraded to newer versions. So you can’t — in general — install packaged versions of newer software while remaining on Debian stable.
Some packages are however made available as backports, and the `apache2` package is one of them. You can install these by enabling backports and selecting that as the source of upgrades:
```
echo deb http://deb.debian.org/debian buster-backports main | sudo tee /etc/apt/sources.list.d/buster-backports.list
sudo apt update
sudo apt install -t buster-backports apache2
```
If other upgrades are already available in testing, and there’s a particularly relevant reason to upgrade, you can try filing bugs requesting a backport.
Note however that you should only upgrade to backports of packages if you have a specific reason to do so: backported packages don’t receive the same security support as packages in the stable repository, and while the stable distribution is tested as a coherent whole, no such testing is done with backports.
|
2,209,563 |
>
> What is $\lim\_{x\to\infty} xe^{-x^2}$?
>
>
>
I am calculating $\int\_0^\infty x^2e^{-x^2}\,dx$. By integration by parts, I have
$$I = -\frac{1}{2}xe^{-x^2} |\_{0}^\infty+\frac{1}{2}\int\_0^\infty e^{-x^2}\,dx$$
The second integration is just $\frac{\sqrt{\pi}}{2}$. Now I want to know how to calculate $\lim\_{x\to \infty} xe^{-x^2}$. It is in the form of $\infty \cdot 0$.
|
2017/03/30
|
[
"https://math.stackexchange.com/questions/2209563",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/412823/"
] |
By L'Hôpital's
$$
\lim\_{x\rightarrow \infty}\frac{x}{e^{x^2}}=\lim\_{x\rightarrow \infty}\frac{1}{2xe^{x^2}}=0
$$
note: the above will evaluate to 0 for any expression of the form
$$
\lim\_{x\rightarrow \infty}\frac{p(x)}{e^{x}}
$$
where $p(x)$ is a polynomial.
|
3,792,817 |
im searching for full directx tutorials i found directxtutorial.com but it only gave me the basic. couldn't find others that were full tutorials.
have you find any or know any?
|
2010/09/25
|
[
"https://Stackoverflow.com/questions/3792817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/401995/"
] |
Last but not least, you must authorize your virtual host or directory to use `.htaccess`.
```
AllowOverride All
```
**Update:**
I can't figure out your exact problem but it's always worth testing that Apache is actually parsing your `.htaccess` file. Make a syntax error on purpose and see if you get a `500 Internal Server Error` message. Also, test `mod_rewrite` with a simple redirection rule that doesn't involve Drupal.
|
78,984 |
If I am writing a study paper and I have given some descriptors as to which systems will be measured (things such as "openness" and "availability" in my case) is it acceptable for me to provide a list of this after with a short sentence expanding on what metrics that word in intended to include?
e.g.
* Openness - Measured by the proportion of the human population has access and the ease of entry for those who meet the requirements
* etc...
|
2016/10/28
|
[
"https://academia.stackexchange.com/questions/78984",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/63967/"
] |
One important thing to keep in mind is that the abstract is typically copied to various article databases, which have varying support for markup. As such, much of the formatting will not necessarily be carried over. That nicely formatted bulleted list which appears in the pages of the journal can turn into a confusing mess in online article databases. (e.g. It might lose the bullets and be smashed into a single paragraph.)
For this reason, it's generally recommended to avoid any special formatting in article abstracts - even things like italics should be kept *de minimis*.
If at all possible, skip the bulleted list, and keep the list in plain text format. If you *do* want to keep the bulleted list, be sure to format the list entries such that things stay readable even if the bullets are removed and everything is collapsed into a single paragraph.
|
262,531 |
```
\begin{equation}
S=\sum\limits_{i=1}^{8}A_i
S=\sum\limits_{i=1}^{8}B_i
S=\sum\limits_{i=1}^{8}C_i
S=\sum\limits_{i=1}^{8}D_i
\end{equation}
```
Considering the above code, I am so interested to know that how it is possible to print these 4 equations, one per line, instead of all followed in one single line.
|
2015/08/21
|
[
"https://tex.stackexchange.com/questions/262531",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/71060/"
] |
Package `amsmath` provides many environments for equations, e.g.:
* `gather` for centering equations by default
* `align`, which allows vertical alignments
Example:
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{gather}
S=\sum_{i=1}^{8}A_i\\
S=\sum_{i=1}^{8}B_i\\
S=\sum_{i=1}^{8}C_i\\
S=\sum_{i=1}^{8}D_i
\end{gather}
\begin{align}
S &= \sum_{i=1}^{8}A_i\\
S &= \sum_{i=1}^{8}B_i\\
S &= \sum_{i=1}^{8}C_i\\
S &= \sum_{i=1}^{8}D_i
\end{align}
\end{document}
```
>
> [](https://i.stack.imgur.com/7wtbJ.png)
>
>
>
Equation number in last line
----------------------------
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{gather}
\nonumber S=\sum_{i=1}^{8}A_i\\
\nonumber S=\sum_{i=1}^{8}B_i\\
\nonumber S=\sum_{i=1}^{8}C_i\\
S=\sum_{i=1}^{8}D_i
\end{gather}
\begin{align}
\nonumber S &= \sum_{i=1}^{8}A_i\\
\nonumber S &= \sum_{i=1}^{8}B_i\\
\nonumber S &= \sum_{i=1}^{8}C_i\\
S &= \sum_{i=1}^{8}D_i
\end{align}
\end{document}
```
>
> [](https://i.stack.imgur.com/2AOeg.png)
>
>
>
Equation number in the middle
-----------------------------
```
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
\begin{gathered}
S=\sum_{i=1}^{8}A_i\\
S=\sum_{i=1}^{8}B_i\\
S=\sum_{i=1}^{8}C_i\\
S=\sum_{i=1}^{8}D_i
\end{gathered}
\end{equation}
\begin{equation}
\begin{aligned}
S &= \sum_{i=1}^{8}A_i\\
S &= \sum_{i=1}^{8}B_i\\
S &= \sum_{i=1}^{8}C_i\\
S &= \sum_{i=1}^{8}D_i
\end{aligned}
\end{equation}
\end{document}
```
>
> [](https://i.stack.imgur.com/tlh5w.png)
>
>
>
Addendum: sign function definition with cases
---------------------------------------------
```
\documentclass{article}
\usepackage{amsmath}
\usepackage{colonequals}
\DeclareMathOperator{\sgn}{sgn}
\begin{document}
\begin{equation}
\sgn(x) \colonequals
\begin{cases}
-1 & \text{if } x < 0 \\
0 & \text{if } x = 0 \\
1 & \text{if } x > 0
\end{cases}
\end{equation}
\end{document}
```
>
> [](https://i.stack.imgur.com/dXFPj.png)
>
>
>
|
26,598 |
Dropbox gives me pop-up errors about not being able to monitor the file system (that quickly disappear) when it starts up but it still seems to work ok, why is that?
|
2012/05/08
|
[
"https://webapps.stackexchange.com/questions/26598",
"https://webapps.stackexchange.com",
"https://webapps.stackexchange.com/users/14814/"
] |
On Linux, the Dropbox client is subject to a default system limit on the number of directories it can monitor for changes. There is a warning regarding this, along the lines of:
>
> Unable to monitor filesystem
>
>
> Please run: echo 100000 | sudo tee
> /proc/sys/fs/inotify/max\_user\_watches and restart Dropbox to correct
> the problem.
>
>
>
This comes up often in the Dropbox Forums, and they have a mention of it in their ["Why aren't certain files on one computer syncing to another?"](https://www.dropbox.com/help/145) document:
>
> Monitoring more than 10000 folders
>
>
> The Linux version of the Dropbox desktop application is limited from
> monitoring more than 10000 folders by default. Anything over that is
> not watched and, therefore, ignored when syncing. There's an easy fix
> for this. Open a terminal and enter the following:
>
>
>
```
> echo fs.inotify.max_user_watches=100000 | sudo tee -a /etc/sysctl.conf; sudo sysctl -p
```
>
> This command will tell your system to
> watch up to 100000 folders. Once the command is entered and you enter
> your password, Dropbox will immediately resume syncing.
>
>
>
|
3,961,448 |
>
> For a positive integer $k$, we have:- $(1 + x)(1 + 2x)(1 + 3x)$ ... $(1 + kx) = a\_0 + a\_1x + a\_2x^2 + $ ... $ + a\_kx^k$. Where $a\_0,a\_1,$ ... $,a\_k$ are the coefficients of the polynomial. Find the sum of the digits of the smallest value of $k$ if $(a\_0 + a\_1 +$ ... $+ a\_{k-1})$ is divisible by $2005$.
>
>
>
**What I Tried**: I have no idea where to start. I was able to guess, that the expression $(1 + x)(1 + 2x)$ ... $(1 + kx)$ consists of a $(+1)$ term and a $(k!x^k)$ term , and I can guess $a\_0 = 1$ , $a\_k = k!$ , and this might given an idea that $a\_1 = 1!$ , $a\_2 = 2!$ and so on, but is this enough.
Suppose, after solving this part, I need to find for which $(k-1)$ I will have that :-
$$\rightarrow 0! + 1! + ... + (k - 1)! = 2005m$$
This is easy, because as far as I can see, $2005 = 5 \* 401$ and $401$ is prime , so $k$ has to be $402$ in order to be minimum.
I have a doubt in the $1$st part, can anyone help me?
|
2020/12/25
|
[
"https://math.stackexchange.com/questions/3961448",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/772237/"
] |
Let $A(ka,0)$ and $B(0,kb)$ be the vertices, where $0<k<1$.
By Pythagoras' theorem, the base is $AB=k\sqrt{a^2+b^2}$ and the height is $\dfrac{ab(1-k)}{\sqrt{a^2+b^2}}$.
Can you proceed with that?
|
22,651,158 |
Please tell me two methods below to catch the `<table>` (line 3) which has no specific attribute like "id" or "class name" and input the first 3 rows `<tr>something1</tr>` `<tr>something2</tr>` `<tr>something3</tr>` with javascript.
**Method 1**: from the Top to the Bottom tag: `div` -> `div` -> `table` (subclass 3)
**Method 2**: from the Bottom to the Top tag: `<table id="Hero-WPQ1">` up to `<table>` (line 3).
```
<div id="content_data">
<div>
<table>
<tbody>
<tr>
<td>
<table>
<tbody>
<tr>something1</tr>
<tr>something2</tr>
<tr>something3</tr>
<tr>something4</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table class="ms-bottompaging">
something
</table>
<table id="Hero-WPQ1">
something
</table>
</div>
```
|
2014/03/26
|
[
"https://Stackoverflow.com/questions/22651158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3440423/"
] |
Instead of single quotes, you have to use back quote in your comparision and you can have if and elif for extracting in between strings. I have modified as below and it's working:
```
with open('file.txt', 'rb') as f:
textfile_temp = f.readlines()
config_found = False
textfile = []
for line in textfile_temp:
if re.match("`show accounting log all`", line):
config_found = False
elif config_found:
i = line.rstrip()
textfile.append(i)
elif re.match("Generating configuration....", line):
config_found = True
print textfile
```
Output:
```
['interested config', 'interested config', 'interested config']
```
Instead you can use split as below:
```
with open('file.txt', 'rb') as f:
textfile_temp = f.read()
print textfile_temp.split('Generating configuration....')[1].split("`show accounting log all`")[0]
```
Output:
```
interested config
interested config
interested config
```
|
11,915,275 |
I'm currently having a major brain fart :).
My plan was to build a simple swing based tic tac toe application in Java. I had planned for the app to allow for one player, two player local and two player remote options. I've got the one and two player local versions working fine but am struggling to get my head around the two player remote option.
Worth noting in the Netbeans project I have the gui in a separate package from the logic.
I've fried my brain thinking about all the options.
1. Like having a client server architecture but then if the client is running on a different pc than the logic this slows down the one player and two player local versions for no reason.
2. I'm thinking the entire application (gui + logic) should be distributed amongst the various pc's on the home wirless network. That way players can play one and two player local games without any unneccesary lag time and see if anyone else is available for a two player remote version. The question if I go this way is who's logic acts as the server - how does that work?
Is option 2 the best / only way of going about this because this isn't just a networked game?
Are there any other ways of going about this?
I know doing a tic tac toe game with just a remote game option would be a simple case of a client server architecture but having one player and then a networked version in the same app is tricky.
Thanks,
Paul.
|
2012/08/11
|
[
"https://Stackoverflow.com/questions/11915275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1592281/"
] |
Technically, you could do this without actual server -- you can make it like client/host.
When user wants to be host, he sends UDP broadcast packet, with information on what ip, and what game he wants to play. everyone who wants to join can catch this packet.
When user wants to join, he listens to broadcast packet, and joins to the one he recieved.
Every player could do his own logic, and send his move to other player -- other side should only check is the move legal -- because maybe someone wants to hack your game :D
|
66,689,798 |
I am receiving a datetime in the following format:
```
Thu, 18 Mar 2021 10:37:31 +0000
```
If I'm correct this if RFC2822.
I can't figure out a way to convert this to a 'normal' datetime that would be used by SQl server.
For example I want it to be:
```
2021-03-18 10:37:31
YYYY-MM-DD hh:mi:ss
```
I have tried things like CONVERT() and found a sketchy way by doing:
```
DECLARE @WeirdDate varchar(50) = 'Thu, 30 Jul 2015 20:00:00 +0000'
SELECT
CONVERT(DATETIME, SUBSTRING(@WeirdDate, CHARINDEX(',', @WeirdDate) + 1, 20))
```
But none of it is working that well.
Is there a way to convert this in a 'proper' way?
**edit:**
To clarify:
The format *should* always be the same as the provided example. Including the day name.
I am **not** sure that it will always be the same timezone. I could be receiving it from a different timezone. This is something to consider.
|
2021/03/18
|
[
"https://Stackoverflow.com/questions/66689798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12712962/"
] |
You *could* achieve this with a "little" string manipulation is seems, and some style codes:
```sql
DECLARE @YourDate varchar(50) = 'Thu, 30 Jul 2015 20:00:00 +0000'
SELECT TRY_CONVERT(datetimeoffset(0),CONVERT(varchar(25),TRY_CONVERT(datetime2(0),STUFF(STUFF(@YourDate,1,5,''),21,6,''),106),126) + STUFF(RIGHT(@YourDate,5),4,0,':'));
```
This will, however, fail if you're using a `LOGIN` with a language setting which isn't an English based one.
If the value is always UTC, you can actually just use the "middle" `TRY_CONVERT` expression.
|
60,333,230 |
I have an array as shown in below picture. How do I add conditional CSS class to - based on the key `sender_id` of the array in VueJS ?
conditions:
1)if `sender_id != sender_id` : add arrived class
2)if `sender_id == sender_id` : add delivered class.
The goal is to add CSS styling as per the arrived or delivered message in a chat application.
[](https://i.stack.imgur.com/bkz9t.png)
|
2020/02/21
|
[
"https://Stackoverflow.com/questions/60333230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8874732/"
] |
I edited your example and I added a `useEffect` hook and if you press a tab 2 is scrolling into this content.
<https://codesandbox.io/s/lingering-voice-y45cg>
|
1,608,110 |
In my application I'm using an external library (Batik 1.7) that is made up of several modules. The modules have multiple cyclic dependencies between themselves. This doesn't influence the build, but some tools (e.g. the M2Eclipse Dependency Graph, or the Dependencies report) will not work anymore.
Is there a good way to diagnose what cycles are there, and an easy way to get rid of them?
**Update:** The problem is with the POMs, as e.g. [`batik-bridge`](http://repo1.maven.org/maven2/org/apache/xmlgraphics/batik-bridge/1.7/batik-bridge-1.7.pom) is dependent on [`batik-gvt`](http://repo1.maven.org/maven2/org/apache/xmlgraphics/batik-gvt/1.7/batik-gvt-1.7.pom), which is in turn depend upon `batik-bridge`.
I think I can solve this by excluding some of the dependencies manually, but I'm not sure what to exclude. What I'd like to have is a clear overview of the cycles in the graph.
|
2009/10/22
|
[
"https://Stackoverflow.com/questions/1608110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/104894/"
] |
Try running this from the command line in the root of your topmost project:
```
mvn dependency:tree
```
|
59,397,389 |
I am using Terraform 0.12. I have a data source that is returning a list of maps. Here is an example:
```
[
{
"name": "abc"
"id": "123"
},
{
"name": "bcd"
"id": "345"
}
]
```
How to iterate over this datasource of list of maps and find if a map with key "name" and value "bcd" exists ?
this is my data source:
```
data "ibm_is_images" "custom_images" {}
locals {
isexists = "return true/false based on above condition"
}
```
If it exists, I want to create a resource of count 0 otherwise 1
```
resource "ibm_is_image" "my_image" {
count = local.isexists == "true" ? 0 : 1
}
```
|
2019/12/18
|
[
"https://Stackoverflow.com/questions/59397389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140971/"
] |
You can use the [`contains` function](https://www.terraform.io/docs/configuration/functions/contains.html) to check whether a value is found in a list.
So now you just need to be able to turn your list of maps into a list of values matching the `name` key. In Terraform 0.12 you can use the [generalised splat operator](https://www.terraform.io/docs/configuration/expressions.html#splat-expressions) like this:
```
variable "foo" {
default = [
{
"name": "abc"
"id": "123"
},
{
"name": "bcd"
"id": "345"
}
]
}
output "names" {
value = var.foo[*].name
}
```
Applying this gives the following output:
```
names = [
"abc",
"bcd",
]
```
So, combining this we can do:
```
variable "foo" {
default = [
{
"name": "abc"
"id": "123"
},
{
"name": "bcd"
"id": "345"
}
]
}
output "names" {
value = var.foo[*].name
}
output "bcd_found" {
value = contains(var.foo[*].name, "bcd")
}
output "xyz_found" {
value = contains(var.foo[*].name, "xyz")
}
```
When this is applied we get the following:
```
bcd_found = true
names = [
"abc",
"bcd",
]
xyz_found = false
```
|
53,003,958 |
I am trying to post form data from angular service to laravel controller store. I am using following code. The url I set is being called but I get following exception error:
```
exception: "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException"
```
These are the codes I am using.
```
private _commentUrl = GlobalVariable.BASE_API_URL + 'comments/store';
postComment(data:any) {
return this.http.post<any>(this._commentUrl, data);
}
```
php
---
```
class CommentsController extends Controller
{
public function store(Request $request)
{
dd($request);
```
|
2018/10/26
|
[
"https://Stackoverflow.com/questions/53003958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1687891/"
] |
No need to mention store in your url
You can simply write your url like:
```
private _commentUrl = GlobalVariable.BASE_API_URL + 'comments';
```
|
21,793,908 |
I can't seem to get this work. I already set popWindow focusable as to what I read on other forums but still no luck.
xml
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:background="@drawable/popbg"
android:orientation="vertical" >
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="10dp"
android:layout_marginTop="30dp"
android:background="@drawable/zcancel" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:text="SSID"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
```
java
```
case(R.id.settings):
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
v.setBackgroundResource(R.drawable.cpanel2);
return true;
case MotionEvent.ACTION_UP:
v.setBackgroundResource(R.drawable.cpanel1);
LayoutInflater layoutInflater =
(LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popSwitchView = layoutInflater.inflate(R.layout.settings_xml, null);
final PopupWindow popWindow = new PopupWindow(popSwitchView);
popWindow.setWidth(LayoutParams.MATCH_PARENT);
popWindow.setHeight(LayoutParams.MATCH_PARENT);
popWindow.showAtLocation(popSwitchView, Gravity.CENTER, 0, 0);
popWindow.setOutsideTouchable(false);
popWindow.setFocusable(true);
Drawable d = getResources().getDrawable(R.drawable.popbg);
popWindow.setBackgroundDrawable(d);
Button CancelButton = (Button)popSwitchView.findViewById(R.id.cancel);
CancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
popWindow.dismiss();
}
});
popWindow.showAsDropDown(v, 50, -30);
return true;
default:
return false;
}
```
I'm planning on creating a popwindow of setting for network configurations. I can't seem to fix my code for a good view for you guys .
|
2014/02/15
|
[
"https://Stackoverflow.com/questions/21793908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753367/"
] |
ha, .found the answer.,
just did
```
popWindow.setFocusable(true);
popWindow.update();
```
thanks for the support!
credits from this topic
[Keyboard not shown when i click on edittextview in android?](https://stackoverflow.com/questions/6977773/keyboard-not-shown-when-i-click-on-edittextview-in-android)
|
209,867 |
I need to connect to my ISP's server using pptp. And then I need to connect to the private network at my office using OpenVPN.
OS: Ubuntu 10.10
How can I make such connection?
Thank you.
|
2010/12/07
|
[
"https://serverfault.com/questions/209867",
"https://serverfault.com",
"https://serverfault.com/users/39020/"
] |
1. Firstly look in the SQL Server Logs in Enterprise Manager(EM). To get there, start EM and drill down from the Database Server … Management … SQL Server Logs. There should be multiple logs starting with Current and then followed by 6 or more archived logs.
2. Review all recent Error Log(s). There WILL be an indication here as to why the database has been marked suspect. You need to fix whatever the problem is first (i.e. missing file, permissions problem, hardware error etc.)
3. Then, when the problem has been fixed and you're either sure that the data is going to be ok, or you have no backup anyway, so you've nothing to lose, then change the database status to normal and restart SQL Server.
4. To change the database status we will us the following store procedure: sp\_resetstatus.
The steps are as follows:
a.
```
USE master
GO
sp_configure 'allow updates', 1
GO
RECONFIGURE WITH OVERRIDE
GO
```
b.
```
sp_resetstatus
GO
-- Example: sp_resetstatus ‘Washington’
```
5. After the procedure is run, immediately disable updates to the system tables:
```
sp_configure 'allow updates', 0
GO
RECONFIGURE WITH OVERRIDE
GO
```
6. Stop and Restart ALL SQL Server Services
7. If the database still goes back into suspect mode, and you can't fix the original problem, and you have no recent backup, then you can get information out of the database by putting it into Emergency Mode. If you do this, extract the data/objects out with DTS and rebuild the database. Note that the data may be corrupt or transactionally inconsistent. You WILL NOT be able to use this instance of the database after it is put in to Emergency Mode besides pulling data out of it !!!
8. Issue the following command to put the database into emergency mode:
a.
```
USE master
GO
sp_configure 'allow updates', 1
GO
RECONFIGURE WITH OVERRIDE
GO
```
b.
```
UPDATE master..sysdatabases
SET status = 32768
WHERE name = 'DatabaseName'
```
9. Stop and Restart ALL SQL Server Services.
10. We are now ready to pull whatever data we can out of the tables in the corrupt database. Remember, some tables may be corrupt, thus you may have to play with various T-SQL statements to get the data out. First try DTS …
11. These are the steps necessary to export data out of the corrupt database into the new:
a. Create a new production DB, or a temp DB, to have a place to export whatever data we can out of the corrupt db.
b. Start a DTS operation by going into EM and drilling down to “Data Transformation Services” … “Local Packages”.
c. Open a NEW DTS package by right-mouse clicking …
d. When DTS opens, choose “Copy SQL Server Objects Task” from the Connection Icons. Enter in a description like “Export Corrupt Data”. Enter in the SA/pass combination as well as the CORRUPT database from the drop-down.
e. Select the “Destination” Tab. ”. Enter in the SA/pass combination as well as the PRODUCTION database from the drop-down.
f. Select the “Copy” Tab. UNCHECK the “Create destination objects” box. UNCHECK the “Copy all objects” box and then Click on the “Select Objects” Button. This brings up the “Select Objects” screen.
g. CHECK ONLY “Show all tables” like shown above. Then check each table that needs to be exported. If ALL tables need to be export, Click on the “Select All” button. Click OK.
\*\* If ALL objects are to be recovered, Select ALL Objects by check marking them and then click on the “Select All” button. This will grab everything possible.
h. Click OK again and we are done creating this task. Now we execute the package by Clicking the green arrow on the menu bar.
12. Restore Data Issue: Restoring the data into the Production database is dependent on what time of day it is. If it is during “Hot” times, high playing times, restore the data during a slow period or close of gaming day!
If Microsoft Tech support is to be called, it is advisable to get the log files ready to be emailed to the tech for review. The process to accomplish this is as follows:
1. Go to the Bin folder located under the SQL Server installation folder. In this folder you will find an application called SQLDIAG.exe.
2. Execute SQLDIAG.exe. This app is “suppose” to zip all the log files into a file called SQLDIAG.txt in the Log folder under the SQL Server installation folder. This operation did NOT work for us.
3. We went directly into the Log folder of SQL Server and used PKZip to zip the files. We then emailed them directly to the tech.
|
24,147,593 |
All right, I've inherited some code and the guy who started writing the code has a bad habit of squelching exceptions, thus making my life difficult. So as I look through the code I'm trying to toss something in the `catch` blocks so I can figure out what's going on. Since this is a Windows Forms application, I cannot write to the console itself, however I can write to the Debug console. I'd like to change the text foreground color when I hit one of these (previously) squelched exceptions so that I can easily pick them out as I debug. Of course, the other reason for writing to the debug console is so that the customer does not see these messages in the final design. Is there any way to do this? I've tried the following code, but it does not quite do it.
```
catch
{
ConsoleColor tempColor = Console.ForegroundColor;
StackTrace stackTrace = new StackTrace();
Console.ForegroundColor = ConsoleColor.Red;
System.Diagnostics.Debug.WriteLine("Exception Thrown: " + stackTrace.GetFrame(0).GetMethod().ToString());
Console.ForegroundColor = tempColor;
}
```
|
2014/06/10
|
[
"https://Stackoverflow.com/questions/24147593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1642677/"
] |
There doesn't seem to be any way to change the color.
However using the category option of the `WriteLine` method will allow you to format a header line and a message line:
```
Debug.WriteLine("\n\tError Message","Error Message 1");
```
The output should be something like this:
```none
Error Message 1:
Error Message
```
|
15,591,619 |
sorry I've spent most of today trying to solve what is probably a simple pointer problem, was wondering if anyone could help.
I want a function that returns a number and an array to main(), therefore requiring the use of pointers for at least one of these. The array must be dynamically allocated inside the function.
I've tried to show my best attempt below in a simplified form. I just get "Segmentation Fault".
```c
double my_func(double **ptr);
int main(int argc, char **argv){
double value;
double *a;
value = my_func(&a);
printf("Value is %f array[1] is %f \n", value, a[1]);
return 0;
}
double my_func(double **ptr){
int i;
/* generate an array */
void *memory = malloc(10*sizeof(double));
if (memory == NULL){
printf("ERROR: out of memory\n");
}
*ptr = (double *) memory;
/* Fill the array with some values */
for (i=0;i<10;i++)
{
**(ptr+i) = 42;
}
return 3.14;
}
```
[The reason for this is that I have a function that reads in a file, and I want to return the number of lines and an array containing the file contents to main(). I want it to dynamically allocate the array, such that the program will operate for any size file.]
Thanks for any help!
|
2013/03/23
|
[
"https://Stackoverflow.com/questions/15591619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1725306/"
] |
The following line you are adding i to the address of the variable a:
```
**(ptr+i) = 42;
```
To add i to the malloced address you need to dereference ptr first:
```
*(*ptr+i) = 42;
```
|
4,559,618 |
Just curious about speed of Python and Java..
Intuitively, Python should be much slower than java, but I want to know more...Could anybody give me more? or introduce some nice post to read?
|
2010/12/30
|
[
"https://Stackoverflow.com/questions/4559618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/435645/"
] |
The current standard implementation of Python (CPython) is slower than Java because the standard CPython implementation doesn't have a powerful [JIT compiler](http://en.wikipedia.org/wiki/Just-in-time_compilation). Yet.
There have been several projects with the aim of producing a faster implement of Python:
* [Psyco](http://psyco.sourceforge.net/)
* [Unladen Swallow](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)
* [PyPy](http://codespeak.net/pypy/dist/pypy/doc/)
From what I've tried some of these projects can give very good speed ups for specific algorithms, but you still won't get it to run as fast as Java for typical application code. Most of the current effort seems now to be directed towards PyPy.
|
11,093,311 |
working on a project using altera DE2-115, the project involves showing output on a screen, i'm having hard time using VGA with verilog, could you please show or link me to a very simple working example so that i could understand the concept and apply it on my project
|
2012/06/19
|
[
"https://Stackoverflow.com/questions/11093311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1465148/"
] |
[FPGA4FUN](http://www.fpga4fun.com/) has some VGA examples [making a pong game](http://www.fpga4fun.com/PongGame.html)
|
126,286 |
In Bach BWV 812 Menuet I bar 6 we have a trill preceding an accidental — the thrust of the bar is to B(natural), therefore in the preceding trill do(would) you trill on B(natural)-A or B(flat)-A?
Similarly at the mordent at the repeat phrase(bar 8), do you use B(flat) or B(natural) as the auxiliary note — presaging the B(natural) in the lower voice (or following on from the B(natural) in the preceding bar.
[](https://i.stack.imgur.com/5eyqs.jpg)
|
2022/12/05
|
[
"https://music.stackexchange.com/questions/126286",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/87060/"
] |
Certainly the entire bar is an E major bar, so every B should be played as a B natural. But you're right that accidentals in the auxiliary notes are supposed to be notated explicitly. I can only imagine that the editor felt a natural immediately followed by another natural at the same pitch would *look* redundant, even though technically it's not (accidentals above ornaments are not supposed to affect the rest of the bar, unlike accidentals on explicit notes).
|
66,911,339 |
I am trying to find the proper syntax to initialize "Map<,<List<List>>>" in kotlin. I am a bit new to kotlin. I have variables initialized in my class as this:
```
var jitterMs: Double = 0.0
```
The way I am trying to initialize is this:
```
val bandMap: Map<Int,<List<List<String>>>> = emptyMap()
```
It gives me an error that a proper getter or setter is expected, and I think that's because it just doesn't understand what I am trying to do. What is wrong with this syntax?
Thanks,
Edit: As Tenfour pointed out, I actually want a mutable map. This is what I have now as an error saying there is a type error:
```
val bandMap: MutableMap<Int,List<List<String>>> = emptyMap()
```
|
2021/04/01
|
[
"https://Stackoverflow.com/questions/66911339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12637353/"
] |
This is how you would do it:
```
val bandMap: Map<Int, List<List<String>>> = emptyMap()
```
For a `MutableMap` write the following:
```
val bandMap: MutableMap<Int, List<List<String>>> = mutableMapOf()
```
Or, for the most idiomatic way to make a `mutableMap` would be:
```
val bandMap = mutableMapOf<Int, List<List<String>>>()
```
|
47,298,625 |
Basically, I have a class for the Player of a game
```
class Player:
def __init__(self,inventory,hp):
self.inventory = []
self.hp = 20
...
...
P = Player()
```
And I simply want to check for an item in the inventory (where items are each a class as well)
```
class Book():
def __init__(self,name,description):
...
...
```
Then do this.
```
if Book() in P.inventory:
print("You have a book.")
else:
print("You don't have a book.")
```
The problem I'm having is that even if the `Book()` object is in the player's inventory, it reads the `if` statement as false and runs the `else` statement.
I'm thinking I could try to use a `for` loop like so
```
for i in P.inventory:
counter = 0
if i == Book():
print("You have a book.")
counter = 1
if counter == 0:
print("You don't have a book.")
```
but I'm hoping I won't have to use that much code for such a simple task.
|
2017/11/15
|
[
"https://Stackoverflow.com/questions/47298625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8842253/"
] |
`Book()` creates a new object everytime so `Book() == Book()` returns `False`. You might want to use `isinstance` instead:
```
a_book = Book()
isinstance(a_book, Book)
```
with something like:
```
def check_for_books(inventory):
for i in inventory:
if isinstance(i, Book):
print("You have a book.")
return
else:
print("You have no books.")
```
|
31,486,897 |
```
echo '<table style="width:100%"> <tr>';
echo '<td>Order</td>';
echo '<td>Destination</td>';
echo '<td>Location</td>';
echo '<td>Status</td>';
echo '<td>TimeStamp</td>';
echo '</tr>';
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr><td>';
echo $row['OrderNumber'] . '';
echo '</td><td>';
echo $row['Destination'] . '';
echo '</td><td>';
echo $row['Location'] . '';
echo '</td><td>';
echo $row['Status'] . '';
echo '</td><td>';
echo $row['TimeStamp'] . '';
echo '</td></tr>';
}
echo '</table>';
```
}
I want to change the background of the row turned a different color is the time stamp is more than 60 minutes past the current time. any help would be much appreciated. i dont even know where to begin.
Thanks
edit: format of my time stamp "2015-07-17 19:17:31"
|
2015/07/18
|
[
"https://Stackoverflow.com/questions/31486897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5124780/"
] |
Do an if to see if time is over 60 minutes and if so assign it a class with a different background color. Since you didn't clarify I'm going to assume you are using unix timestamp `time()`.
```
$currTime = time();
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$calc = $currTime - $row['TimeStamp'];
if($calc > 3600){
$rowClass = "oldOrder";
} else {
$rowClass = "normalOrder";
}
echo '<tr class="'.$rowClass.'"><td>';
echo $row['OrderNumber'] . '';
echo '</td><td>';
echo $row['Destination'] . '';
echo '</td><td>';
echo $row['Location'] . '';
echo '</td><td>';
echo $row['Status'] . '';
echo '</td><td>';
echo $row['TimeStamp'] . '';
echo '</td></tr>';
}
```
Then add CSS to define the two classes
```
.oldOrder{
background-color: #ccc;
}
.normalOrder{
background-color: #fff;
}
```
|
102,150 |
We know students aren't allowed to do magic during the school holidays, but when does that prohibition start and end? Does the journey between Hogwarts and London count as term-time or holiday? **Are students allowed to cast spells on the Hogwarts Express?**
The only canonical example I can think of is Hermione casting spells on the train before the start of her first year, when the ban on magic isn't yet in operation because she hasn't even enrolled at the school yet. I haven't got the books to hand, so can't search for other examples.
|
2015/09/06
|
[
"https://scifi.stackexchange.com/questions/102150",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/31394/"
] |
There are several other canon instances of students casting spells on the Hogwarts train, such as Ginny casting the [Bat-Bogey](http://harrypotter.wikia.com/wiki/Bat-Bogey_Hex) hex, or Draco casting a [Full-Body Bind](http://harrypotter.wikia.com/wiki/Full_Body-Bind_Curse) on Harry Potter. The mere act of casting magic thus doesn't appear to be prohibited on the train, though malicious magic can of course be punished.
The prohibition on students casting magic during the school holidays seems more a function of a). secrecy from Muggles, and b). keeping half-trained wizards and witches from getting themselves into trouble away from the protection of trained professionals.
In that light, though teachers don't [usually](http://harrypotter.wikia.com/wiki/Remus_Lupin) ride the train, prefects do, so there is at least SOME supervision by responsible people. Also, there are no Muggles. Therefore it makes sense for the Hogwarts Express to count as 'safe territory' and be exempt from the underage magic prohibition.
|
24,111,212 |
I have a form which requires 3 steps, 1 is a few details then when the user presses the "Next" button it moves on to the next step without using ajax and without checking if everything is correct.
I moved to angularJS today and would really like to get this to work.
Here is what i have.
```
<form id="mccheckout" method="post" action="{$smarty.server.PHP_SELF}?a=confproduct&i={$i}">
<input type="text" name="namefiled" id="namefiled" value="" required="" ng-maxlength="30" placeholder="Enter the name" ng-model="name" class="ng-valid ng-dirty">
<input type="submit">
</form>
```
When i press next i want to load the next step of the form if the name field is correct.
The next step should be:
```
<input type="text" name="namefiled" id="namefiled" value="" required="" ng-maxlength="30" placeholder="Enter the password" ng-model="password" class="ng-valid ng-dirty">
```
This should be in the same `<form>` I dont want it to be outside the form, the submit button should only check if everything is correct and then call for the next piece of the form.
Im not sure how to go about doing this and im fairly new to ajax. Should i load the form contents from the same page or an external file via ajax request?
Could you guys provide some example code on how you would do this.
Thank you for your time,
|
2014/06/08
|
[
"https://Stackoverflow.com/questions/24111212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446806/"
] |
Here is one potential way of doing it:
```
<html lang="en">
<head>
<meta charset="utf-8">
<title>IrishGeek82 SO Help File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300,400italic,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script>
$(document).ready(function()
{
}
);
</script>
<style type="text/css">
.invalid
{
border:1px solid red;
}
</style>
<script type="text/javascript">
function validateStep1()
{
return true;
}
function validateStep2()
{
return true;
}
function validateStep3()
{
return true;
}
function validateStep4()
{
return false;
}
//Start at step 0
var currStep = 0;
//Each "step" refers to an element in your form that has an ID.
//We include a reference to a validation function in the JSON String
//So we can validate the field.
var steps = [{"stepName":"step1","validationMethod":validateStep1},
{"stepName":"step2","validationMethod":validateStep2},
{"stepName":"step3","validationMethod":validateStep3},
{"stepName":"step4","validationMethod":validateStep4}];
//This function runs the validation routine on the current
//step and advances to the next step on TRUE.
function validateForm(formObj)
{
console.log("Curr Step:"+currStep);
//You can perform your validation in here and only advance to the next step if you can.
//You could just as easily use anonymous functions in the JSON Object above.
if (steps[currStep].validationMethod())
{
currStep++;
if (currStep <= steps.length)
{
$("#"+steps[currStep].stepName).css("display","block");
console.log("Curr Step:"+currStep);
}
else
{
currStep--;
}
}
else
{
$("#"+steps[currStep].stepName).addClass("invalid");
}
}
</script>
</head>
<body>
<form id="someForm" name="someForm" action="#" method="get">
<input type="text" id="step1" name="step1" style="display:block;" value=""/>
<input type="text" id="step2" name="step2" style="display:none;" value=""/>
<input type="text" id="step3" name="step3" style="display:none;" value=""/>
<input type="text" id="step4" name="step4" style="display:none;" value=""/>
<hr>
<button id="navButton" onclick="validateForm('someForm');return false;">Next</button>
</form>
</body>
</html>
```
I created an array of ids that are elements in your form along with a function to validate each step.
The main function validateForm() looks up the validation function for the current step, runs it, and if the result is True, advances to the next step and shows the field.
Please let me know if that helps :)
|
49,601,931 |
I want the below code to return a numerical value as opposed to `<function exp at 0x101c22e18>`:
```
def exp(x,y):
x**y
print(f"exp of {x} to the {y}")
return exp
test1 = 2
test2 = 2
testing = exp(test1, test2)
print(testing)
```
Why isn't my `print` statement returning `4`?
|
2018/04/01
|
[
"https://Stackoverflow.com/questions/49601931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8421707/"
] |
Here is one way using `ast.literal_eval` and list indexing / slicing.
```
from ast import literal_eval
lst = ['(', '1', '1', '1', ')']
res = [literal_eval(lst[0] + ','.join(lst[1:-1]) + lst[-1])]
# [(1, 1, 1)]
```
But, as already mentioned, try and resolve this upstream first.
With updated data:
```
lst = ['(', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ')', ',', ' ', '(', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ',', ' ', '(', '1', ',', ' ', '1', ',', ' ', '1', ')', ')']
res = list(literal_eval(''.join(lst)))
# [((1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)),
# ((1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1))]
```
|
14,860,957 |
```
<?php
include('includes/db.php');
$drinks_cat = $_POST['drinks_cat'];
$drinks_name = $_POST['drinks_name'];
$drinks_shot = $_POST['drinks_shot'];
$drinks_bottle = $_POST['drinks_bottle'];
$drinks_availability = 'AVAILABLE';
$msg = "ERROR: ";
$itemimageload="true";
$itemimage_size=$_FILES['image']['size'];
$iname = $_FILES['image']['name'];
if ($_FILES['image']['size']>250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$itemimageload="false";}
if (!($_FILES['image']['type'] =="image/jpeg" OR $_FILES['image']['type'] =="image/gif" OR $_FILES['image']['type'] =="image/png"))
{$msg=$msg."Your uploaded file must be of JPG , PNG or GIF. Other file types are not allowed<BR>";
$itemimageload="false";}
$file_name=$_FILES['image']['name'];
$add="images"; // the path with the file name where the file will be stored
if($itemimageload=="true")
{
if (file_exists($add) && is_writable($add))
{
if(move_uploaded_file ($_FILES['image']['tmp_name'], $add."/".$_FILES['image']['name']))
{
echo "Image successfully updated!";
}
else
{
echo "Failed to upload file Contact Site admin to fix the problem";
}
}
else
{
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
echo $msg;
}
$dir = $add."/".$iname;
echo "<BR>";
// Connects to your Database
mysql_query("INSERT INTO `product_drinks`(`drinks_id`, `drinks_cat`, `drinks_name`, `drinks_shot`, `drinks_bottle`, `drinks_image`, `drinks_availability`) VALUES (NULL,'".$drinks_cat."', '".$drinks_name."','".$drinks_shot."','".$drinks_bottle."','".$dir."','".$drinks_availability."')") or die("insert error");
Print "Your table has been populated";
?>
```
The code I'm working on works but i have to create a new "image" folder for my admin folder. Is there any way that I could upload the file outside the admin folder and move it to to the original "image" folder". I know it's quite confusing but my directory looks like this.
clubmaru
-admin
-images
-css
-images
-js
|
2013/02/13
|
[
"https://Stackoverflow.com/questions/14860957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1941372/"
] |
You may be looking for PHP's ***rename*** function. <http://php.net/manual/en/function.rename.php>
Set the oldname parameter to the file (with its path) and the newname parameter to where you want it to be (along with the new path, obviously)
Just ensure the "image folder" you want to move the file to has the correct permissions set ensure it's writable. You also may want to consider changing the parameter in your **move\_uploaded\_file** to put the file where you want it in the first place!
|
59,909 |
Went to Alaska and was shooting bald eagles. There so many flying around that my camera kept trying to focus and I missed a lot of shots. What should my settings be on a situation like this? Using a Nikon D7000 with 18-200 mm lens.
|
2015/02/04
|
[
"https://photo.stackexchange.com/questions/59909",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/37502/"
] |
Use a large depth-of-field (DOF) or use the fact that object farther than the half of the hyperfocal distance are "acceptably focused".
You can use a DOF calculator like [this one](http://www.dofmaster.com/dofjs.html) to calculate what aperture to use for a certain DOF or to calculate the hyperfocal distance.
The drawback of large DOF is that you need a small aperture, which limits the amount of incoming light.
Assuming you used Manual mode with shutter=1/250 to avoid camera shake blur and eagle motion blur, and you used the calculated aperture, you would have only one more freedom, ISO, to adjust the level of exposure (that is, if you don't have abundant light, otherwise you would increase the shutter speed, obviously.)
Note that you will need to acquire an inital focus either by using Auto and then switching to Manual focusing mode, or using Manual, the viewfinder and the built-in rangefinder. And you will have to re-focus from time to time (don't forget this otherwise you end up with out-of-focus images after awhile.)
Note also that close to the far end of your lens, using hyperfocal may require you to stop down your lens too much, resulting in hitting the diffraction limit of your lens (= getting more blur).
If you'd like to learn more, please check [this link](http://en.wikipedia.org/wiki/Depth_of_field) out.
|
73,814,567 |
**I am trying to make a simple python script that is not working when it is in the folder: "C:/Users/UserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup" in windows 10**
So I have made a python script without console (.pyw), which is run when the pc starts and the user has logged in. After that, a Tkinter fullscreen topmost window will appear with an image on it. The script has to be in the Startup-folder to run when the user has started the pc and logged in. Inside the startup-folder is also a .jpg image which is the one that should be showing.
The problem is that if I run the script manually from inside the Startup-folder everything works, but when I restart the pc and log in, the Tkinter window doesn't open, and instead the Windows image viewer program opens up showing the desired picture, but not a Tkinter window.
This is probably because if I run this code inside the folder by manually double clicking the script I get this result:
```
from pathlib import Path
Path.cwd() #Should give the file path from C: to the running script
```
>
> C:/Users/UserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup
>
>
>
While if I keep this script in the folder and restart the pc instead I get this result:
>
> C:/WINDOWS/System32
>
>
>
This must mean that when I run the script manually it will run via the first file path, while if I restart the PC it runs it through another file path. This might be somehow interfering with my code.
The reason why the Windows image viewer program shows the image has maybe something to do with .show(), which is the line of code that opens the Windows image viewer program to show the image with the variable name .
**This is the code with added comments:**
```
import tkinter as tk # Importing Tkinter
from PIL import ImageTk, Image # Importing Image functions from PIL
root = tk.Tk() # Making a Tkinter window with the name root
root.attributes('-fullscreen',1) # Making the window fullscreen
root.attributes('-topmost',True) # Making the window topmost
root.title('<irrelevant>')
image = ImageTk.PhotoImage(Image.open('Image.png') # Code line taken from the internet, supposed to turn the image into a variable of the type that Tkinter use, this is the code line that is causing the problem
label = tk.Label(root, image=image) # Placeing the image on the screen
label.image = image
label.place(x=<irrelevant>, y=<irrelevant>)
root.mainloop() # Running the screen
```
Note that this is not copy-pasted code but written by eye so that the spelling errors here might not be in the original script, another note is that this script runs perfectly if you have it anywhere but the startup folder, for example, if you have it on your desktop you can successfully run the script.
I have tried to eliminate this problem for the better part of a day but have been unsuccessful.
I have tried changing
```
ImageTk.PhotoImage(Image.open('Image.png'))
```
to
```
file = 'Image.png'
tk.PhotoImage(file=file)
```
to no avail.
I've tried to change the whole thing from using Tkinter to using Pygame, but it just made things more complex, especially to replace the "topmost" line with Pygame.
I have also looked into other ways to make a script run on Windows startup, but they all have seemed unnecessarily complicated.
I do not need a small fix to the code, I just need a script to fulfill the task mentioned earlier, even if that means using different libraries or solving the problem in another way.
|
2022/09/22
|
[
"https://Stackoverflow.com/questions/73814567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16096769/"
] |
Assuming some sample data on your structures:
```
create table test_table (
stuff text,
property text,
innerProperty text
);
create table base_table (
property text,
id text,
stuff text
);
insert into test_table values
('foot1', 'foot', 'ball'),
('foot2', 'ultimate', 'frisbee'),
('foot3', 'base', 'ball'),
('foot4', 'nix', 'nein');
insert into base_table values
('foot', 'foot', 'feet'),
('flat', 'ball', 'pancake'),
('flit', 'frisbee', 'float');
```
I think in general using left outer joins instead of inner joins is the basis of the solution:
```
select t.stuff, bt.stuff, bt2.stuff
from
test_table t
left join base_table bt on bt.property = t.property
left join base_table bt2 on bt2.id = t.innerProperty
where
bt.property is not null or bt2.id is not null
```
Where the `where` clause mimics basically what you are trying to do -- you want a match from one or the other.
However, this yields these results:
```
foot1 feet pancake <- Bt2.stuff should be empty if BT matches?
foot2 float
foot3 pancake
```
My understanding is that if there is a match on `bt` then you don't want to even evaluate the second join -- make `bt2` conditional on NO match from `bt`. If that is the case you can simply change the join condition on `bt2` from this:
```
left join base_table bt2 on bt2.id = t.innerProperty
```
to this:
```
left join base_table bt2 on bt2.id = t.innerProperty and bt.property is null
```
Meaning, don't do the BT2 join if BT was successful.
Which you can see skips removes bt2.stuff = pancake from the query:
```
foot1 feet
foot2 float
foot3 pancake
```
Let me know if this is what you had in mind.
|
40,642,744 |
As far as I know, `fprintf` takes an pointer to a array of chars as an argument, and prints it. I don't know "when" it stops though. Take the following examples:
Assume: `print_s` is
```
void print_s(const char* s) {
fprintf(stdout,"%s",s);
}
```
Example 1:
```
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
print_s((char*) c);
```
output:
```
abcd // e not printed!
```
Example 2:
```
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
c[5] = 'b';
print_s((char*) c);
```
output:
```
abcdb // works as expected
```
Example 3:
```
char c[6];
c[0] = 'a';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
print_s((char*) c);
```
output:
```
a<someGarbage>cd // works as expected
```
Example 4:
```
char c[6];
c[0] = 'a';
c[1] = 'b';
c[2] = 'c';
c[3] = 'd';
c[4] = 'e';
c[5] = '\0';
print_s((char*) c);
```
output:
```
abcde // works as expected
```
|
2016/11/16
|
[
"https://Stackoverflow.com/questions/40642744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4712455/"
] |
Please note that when you declare character arrays and initialize their elements one-by-one, you need to provide values for the characters continuously starting from the first one, and the last character should be given a null `'\0'` value.
Example:
```
char a[6];
a[0]='a';
a[1]='b';
a[2]='c';
a[3]='d';
a[4]='\0';
```
This would declare the array `a` as the string `"abcd"`.
If you fail to initialize in a similar way, your string is prone to getting garbage character values, which cannot be correctly interpreted by any I/O function, and would give unexpected results.
|
1,248 |
I've always gone with the rule of **1 Broker per website**, the main reasons being for most efficient CCS, cleaner deploying set up, separation of concerns if one 'goes down' etc
We have a new implementation and 3 main websites, where all content is being published to the DB using the DD4T framework.
A new requirement is that the websites will need to use content and component links from each others publications. The team here is going with the rule '**we'll put all sites in the same broker db**'
I don't like this idea, but the content was originally not intended to be shared across the multiple sites and the mvc views are not stored in a correct structure to allow easy consumption from the other site so to do this 'my way' would require some extensive last minute development.
The 'my way' solution would be to have the content stored in separate broker database and:
* Use odata to pull the content we need from each others site
* Write our own logic where we need to pull specific content
I wanted to open this scenario up to the community to see what people's thoughts are, if anyone has encountered a similar situation, or worse gone down the route of a 'single' broker and what issues they have ran into further down the line, what has been done to ensure performance, uptime and is not an issue.
Thanks, John
|
2013/05/09
|
[
"https://tridion.stackexchange.com/questions/1248",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/148/"
] |
We have worked on a Platform (very much famous and has been featured in many of SDL Tridion Shows as a case study) where we had more than 80 websites sharing data from same broker. And this has been implemented in SDL Tridion 2009. The approach was as below:
1. Any data that needs to be fetched from broker is fetched by using a WCF service based on a specific query which in turn uses the SDL Tridion Content Delivery DLLs - In 2011, you may choose for the Content Delivery Web service (aka ODATA service)
2. Where ever there is need to show a collection of data (kind of a list page) - we have indexed that in Search Index - SOLR - and fetches it based on scenario by using a WCF service
(so more or less second option in your question)
This approach worked pretty much good with more than 80 website with decent amount of data publishing and across a wide variety of channels - web, iphone native app, blackberry native app and android native app and few more applications ranging from ASP.NET MVC based website to plain ASP.NET applications.
However, since it was a platform and we try to implement it another scenario where the Publishing amount of data is huge (think of half million publishing activities in a span of 2 ~ 4 hours), the performance was terrible. We then took lot of measures like having a separate publishing server, optimizing deployer extension, CTs and many more measure to make it work decently.
I hope it helps.
|
17,942,726 |
I have an MVC project in which a filter checks for a parameter from the request params.
```
request.Params["Username"]
```
But if the request contains illegal characters then the params property throws a HttpRequestValidationException exception.
So I have to catch this exception then access the params property which works fine.
How do disable the validation on this request which is arriving into a helper class as HttpRequestBase? I don't want to globally do this for every request, just when it arrives into this class.
|
2013/07/30
|
[
"https://Stackoverflow.com/questions/17942726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339268/"
] |
As @Jon-S comments, UnvalidatedRequestValues is how you can bypass validation for a single value. In this example, it would be:
```
request.Unvalidated["Username"]
```
|
192,931 |
What is the meaning of **does** in this sentence?
>
> Whose exhibition **does** “Stars At Dusk” painting belong to?
>
>
>
Thank you very much
|
2019/01/14
|
[
"https://ell.stackexchange.com/questions/192931",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/65340/"
] |
If you wanted to use **such** in that sentence:
>
> The hard drive is destroyed such that it cannot be rebuilt.
>
>
>
There **such** = "in such a manner" and **such that** = "in such a manner as"
P.S. But note the difference in the *as*-clause and the *that*-clause. In the *that*-clause the subject of the main clause can be repeated:
... **hard drive** is destroyed ... such that **it** cannot be rebuilt
whereas with the *as*-clause there is no repetition of subject and the clause is infinitival:
... **hard drive** is destroyed ... in such a manner as *not to allow it to be rebuilt*
... **hard drive** is destroyed ... in such a manner as *to make rebuilding it impossible*
... **hard drive** is destroyed ... in such a manner as *to prevent it from being rebuilt*
In *practical* terms the hard drive is destroyed and cannot be rebuilt in all of those formulations, so if your only concern is that the formulations must ultimately express the same underlying fact, they do indeed.
If your concern is to express that idea as succinctly as possible, I would recommend using the modal verb: **so that|such that it cannot be rebuilt**.
|
43,064,359 |
I'm developing a project with ASP MVC 5, Kendo UI, and some layers. The main idea is that after I chose a value from a dropdown column in a Kendo Grid for example:
```
columns.Bound(b => b.Country).ClientTemplate("#=Country.Name#");
```
It should update a second and third column based on the previous selection:
```
columns.Bound(b => b.Category).ClientTemplate("#=Category.Name#");
columns.Bound(b => b.Client).ClientTemplate("#=Client.Name#");
```
I haven't been able to find any example or idea in the Telerik documentation or forums:
[Grid/Events](http://demos.telerik.com/aspnet-mvc/grid/events)
[Grid / Editing custom editor](http://demos.telerik.com/aspnet-mvc/grid/editing-custom)
[Refresh/Replace DataSource of Foreignkey DropDown List](http://www.telerik.com/forums/refresh-replace-datasource-of-foreignkey-dropdown-list)
I read this example too with a normal dropdown:
[Kendo UI DropDownList on a change to trigger event](https://stackoverflow.com/questions/21284915/kendo-ui-dropdownlist-on-change-to-trigger-event)
Has anyone experienced something like this? My current idea is to create N number of Editor Templates:
```
@model Kendo.Mvc.Examples.Models.CategoryViewModel
@(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
.DataTextField("CategoryName")
.BindTo((System.Collections.IEnumerable)ViewData["categories"])
)
```
With each of the possible Countries, however, it could be really inefficient and I still don't know how to trigger the on Change event.
|
2017/03/28
|
[
"https://Stackoverflow.com/questions/43064359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1928691/"
] |
After a long research, I was able to find a solution in this example:
[Grid InLine and PopUp Editing using Cascading DropDownLists](http://www.telerik.com/support/code-library/grid-inline-and-popup-editing-using-cascading-dropdownlists)
However, it wasn't just copy and paste, I still don't know why this example is not available in the official FAQ Telerik page, but I'd like to provide the key point in order to do it:
1) You must select the **InLine** or **PopUp** edit mode:
```
.Editable(editable => editable.Mode(GridEditMode.InLine))
```
Why? Because when you are going to edit or add the line:
[](https://i.stack.imgur.com/tZCB3.png)
The cascade Drop downs are fully linked to the ID, for example:
[](https://i.stack.imgur.com/gBTL9.png)
2) Next, your new column in the grid is going to look this one:
```
columns.Bound(b => b.CategoryID).ClientTemplate("#=Category.Name#");
```
Be careful, before I we used the class as **Category** instead of the **CategoryID**, the ID is the ***crucial point***.
3) You need to change the previous approach from adding the hint to the class to the ID of the it, for example:
**Non-cascade approach:**
```
[UIHint("ClientStatus")]
public Statuses Status { get; set; }
public int StatusID { get; set; }
```
**Cascade approach:**
```
public Statuses Status { get; set; }
[UIHint("ClientStatus")]
public int StatusID { get; set; }
```
3) The editor template from the cascade approaches should look like this:
**Basic one:**
```
@model int
@(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.DataValueField("CategoriesID")
.DataTextField("Name")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("PopulateCategories", "FullView"))
.ServerFiltering(true);
})
)
@Html.ValidationMessageFor(m => m)
```
**Cascade ones:**
```
@model int
@(Html.Kendo().DropDownListFor(m => m)
.AutoBind(false)
.DataValueField("ID")
.DataTextField("Name")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("PopulateStatuses", "FullView").Data("filterCategories"))
.ServerFiltering(true);
})
.CascadeFrom("CategoriesID")
)
@Html.ValidationMessageFor(m => m)
```
4) The cascade is calling a JavaScript function that looks like this:
```
function filterCategories() {
return {
categoriesID: $("#CategoriesID").data("kendoDropDownList").value()
};
}
```
Where CategoriesID is the ID of the first drop down, which is generated when we edit or add a new line.
4) Finally, we need to share a JSON as a result:
**First drop down:**
```
public JsonResult PopulateCategories()
{
return Json(CategoriesData.GetCategories(), JsonRequestBehavior.AllowGet);
}
```
**Second and further drop downs:**
```
public JsonResult PopulateStatuses(int categoryID)
{
return Json(StatusesData.GetStatuses(categoryID), JsonRequestBehavior.AllowGet);
}
```
|
62,811,803 |
I'm new to pandas dataframe and python.
Currently, I have a pandas dataframe which I'd like to print the values based on conditions set.
My df looks like this:
```
ID Name Price
1 Apple 1
2 Orange 0.5
3 Pear 0.7
```
I'd like to code it such that when I ask the user to input the ID, it will return the price. For example, if the user input 2, it should return 0.5.
```
inputid = input("Please input ID: ")
```
What should I do next to get return Price from df based on the input?
|
2020/07/09
|
[
"https://Stackoverflow.com/questions/62811803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13663727/"
] |
One of possible solutions:
1. Set *ID* column in *df* as its index:
```
df.set_index('ID', inplace=True)
```
2. Define the following function:
```
def getPrice():
inputid = input("Please input ID: ")
try:
return df.loc[int(inputid), 'Price']
except:
return 'No such ID'
```
Then when you call it, executing `getPrice()`:
* An input prompt is displayed.
* The user enters the ID.
* Within *try* block this function attempts to:
+ convert *inputid* to *int* (the index contains *int* values,
but *inputid* is a *string*), so one cause of error can be that
the user just pressed *Enter* without entering any value,
+ even if the user entered a number, it is possible that *df*
does not contain such *ID* (the second cause of error).
* If everything so far is OK, the function returns the price of interest.
* But if any error occurred, the result is an error message.
|
13,098,722 |
I've tried to make A input text box & an output text box with a convert button where, if someone clicks the convert button, the input must be displayed in the output box with some change. but it didn't work.
For example,
If the input is "**something**"
The output should be "**@@:{something}0**"
that is , input value must be present within the characters i specify.
Can someone get me the code for this?
Here's my code so far:
```
function ConvertText() {
document.form1.outstring.value = document.form1.instring.value.to@@{
instring.value}0();
}
<form name="form1" method="post"> <input name="instring" type="text" value="" size="50">
<input type="button" name="Convert" value="Convert" onClick="ConvertText();">
<input name="outstring" type="text" value="" size="50">
</form>
```
|
2012/10/27
|
[
"https://Stackoverflow.com/questions/13098722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690844/"
] |
The reason is you are throwing an exception when the conversion fails inside your `catch` block. The `catch` block technically is outside of the `try` block, so it will not get caught by the same `catch` as you seem to think. This is not really behaving as a loop as you appear to hope it will.
Exceptions are not generally considered the best method for normal (non-exceptional) events in your code. The `TryParse` method and a loop would be much better in this case.
```
static void Main()
{
string input = //get your user input;
short sNum = 0;
while(!short.TryParse(input,out sNum))
{
Console.WriteLine("Input invalid, please try again");
input = //get your user input;
}
Console.WriteLine("output is {0}",sNum);
Console.ReadLine();
}
```
|
64,540,697 |
I am trying to clean data received from an Excel file and transform it using PowerQuery (in PowerBI) into a useable format.
Below a sample table, and what I am trying to do:
```
| Country | Type of location |
|--------- |------------------ |
| A | 1 |
| | 2 |
| | 3 |
| B | 1 |
| | 2 |
| | 3 |
| C | 1 |
| | 2 |
| | 3 |
```
As you can see, I have a list of location types for each country (always constant, always the same number per country, ie each country has 3 rows for 3 location types)
What I am trying to do is to see if there is a way to fill the empty cells in the "Country" column, with the appropriate Country name, which would give something like this:
```
| Country | Type of location |
|--------- |------------------ |
| A | 1 |
| A | 2 |
| A | 3 |
| B | 1 |
| B | 2 |
| B | 3 |
| C | 1 |
| C | 2 |
| C | 3 |
```
For now I thought about using a series of if/else if conditions, but as there are 100+ countries this doesn't seem like the right solution.
**Is there any way to do this more efficiently?**
|
2020/10/26
|
[
"https://Stackoverflow.com/questions/64540697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14523236/"
] |
As Murray mentions, the `Table.FillDown` function works great and is built into the GUI under the Transform tab in the query editor:
[](https://i.stack.imgur.com/RGxuL.png)
Note that it only fills down to replace nulls, so if you have empty strings instead of nulls in those rows, you'll need to do a replacement first. The button for that is just above the Fill button in the GUI and you'd use the dialog box like this
[](https://i.stack.imgur.com/atzKl.png)
or else just use the M code that this generates instead of the GUI:
```
= Table.ReplaceValue(#"Previous Step","",null,Replacer.ReplaceValue,{"Country"})
```
|
27,246,192 |
I'm trying to change current tab on a link click. I have something like this:

So when I click on the next or previous link I want to change active tab.
I guess this can be done in JavaScript, but since I'm complete beginner, I can preform only easiest tasks.
This is the HTML used for building this part of page:
```
<div class="grey-box-wrap">
<div class="top">
<a href="javascript:;" class="prev"><i></i>previous week</a>
<span class="center">February 04 - February 10, 2013 (week 6)</span>
<a href="javascript:;" class="next">next week<i></i></a>
</div>
<div class="bottom">
<ul class="days">
<li>
<a href="javascript:;">
<b>Feb 04</b>
<!-- <i>7.5</i> -->
<span>monday</span>
</a>
</li>
<li>
<a href="javascript:;">
<b>Feb 06</b>
<!-- <i>7.5</i> -->
<span>tuesday</span>
</a>
</li>
<li>
<a href="javascript:;">
<b>Feb 06</b>
<!-- <i>7.5</i> -->
<span>wednesday</span>
</a>
</li>
<li class="active">
<a href="javascript:;">
<b>Feb 07</b>
<!-- <i>7.5</i> -->
<span>thursday</span>
</a>
</li>
<li>
<a href="javascript:;">
<b>Feb 08</b>
<!-- <i>7.5</i> -->
<span>friday</span>
</a>
</li>
<li>
<a href="javascript:;">
<b>Feb 09</b>
<!-- <i>0.0</i> -->
<span>saturday</span>
</a>
</li>
<li class="last">
<a href="javascript:;">
<b>Feb 10</b>
<!-- <i>0.0</i> -->
<span>sunday</span>
</a>
</li>
</ul>
</div>
</div>
<div class="row-wrapper">
```
This is CSS:
```
.grey-box-wrap .bottom .days li.active a, .grey-box-wrap .bottom .days li:hover a {
color: white;
}
.grey-box-wrap .bottom .days li a {
color: #666666;
}
.grey-box-wrap .top {
height: 40px;
line-height: 40px;
padding: 0 10px;
overflow: hidden;
border-bottom: 1px solid white;
margin-bottom: 10px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.grey-box-wrap .top .prev {
float: left;
}
.grey-box-wrap .top .next {
float: right;
text-align: right;
}
.grey-box-wrap .top .prev, .grey-box-wrap .top .next {
width: 25%;
color: #f1592a;
display: inline-block;
font-weight: bold;
}
.grey-box-wrap .bottom .days li.active, .grey-box-wrap .bottom .days li:hover {
border: solid 1px #f1592a;
}
.grey-box-wrap .bottom .days li {
float: left;
margin-right: 2px;
width: 99px;
padding: 5px;
-webkit-border-radius: 5px 5px 0 0;
-moz-border-radius: 5px 5px 0 0;
-ms-border-radius: 5px 5px 0 0;
-o-border-radius: 5px 5px 0 0;
border-radius: 5px 5px 0 0;
border: 1px solid #bdbdbd;
border-bottom: none;
background: white;
}
```
And this is my attempt to get list elements in JS:
Can someone help me with this, or give me a suggestion on what's the easiest or best way to preform this kind of task?
Thanks!
|
2014/12/02
|
[
"https://Stackoverflow.com/questions/27246192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3265282/"
] |
There are many ways to complete this. I've tried to keep it as simple as possible and have added comments so you can understand each line.
Try something like this with jQuery:
```
$(document).ready(function() { // check document is ready
$('li a').click(function() { // catch a click on a list link
$('li').removeClass('active'); // remove all current instances of active
$(this).parent().addClass('active'); // add the class active to the item you clicked
});
});
```
You can view the example here: <http://jsfiddle.net/dbr8dxmu/>
|
21,401,880 |
I'm trying to take a String that and divide it into categories (Books, Food, & Medical Supplies) using Java programming. This is really very confusing to me since there's little automaton to the String. The String is one word only, but there are plenty of words in the English language. Are there any strategies I could take in implementing this?
|
2014/01/28
|
[
"https://Stackoverflow.com/questions/21401880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361174/"
] |
If you haven't done it already, then fix the cause of the warning raised by the compiler. The snippet
```
ichar(tokens(1))
```
passes a character variable of length 20 to `ichar` which expects a variable of length 1.
I don't see how this could cause your later problems but it's generally a good idea to grasp at every straw when trying to fix mysterious bugs.
|
4,890,069 |
Can i pass complex type to converter as parameter? I have created one converter which basically converts byte array to BitmapImage. However when i pass the byte array as parameter in my binding expression, the parameter is passed as string i.e say my parameter name is PhotosByteArr and when i pass it as parameter to converter, i get the parameter name PhotosByteArr and not the byte array.
This is my binding expression :-
```
<Image Source="{Binding ConverterParameter=PhotosByteArr, Converter={StaticResource byteArrToBitmap}}" Margin="0" Stretch="Fill"/>
```
PhotosByteArr is instance of byte[].
Any idea what can be wrong?
Thanks in advance :)
|
2011/02/03
|
[
"https://Stackoverflow.com/questions/4890069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/260594/"
] |
I think this should be
```
{Binding ConverterParameter={Binding PhotosByteArr} ...
```
But I have the question to you. Why are you not writing
```
{Binding Path=PhotosByteArr ...
```
or just
```
{Binding PhotosByteArr ...
```
and then using `value` argument of the [Convert](http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convert.aspx) method?
```
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var array = (byte[])value;
...
}
```
|
9,537,011 |
I am trying to use the Paperclip gem on a Rails project so followed the docs and first installed Imagemagick using the Homebrew recipe.
I added to my model my attachment
```
has_attached_file :screenshot
```
This worked OK and the file uploads functioned as expected
I then wanted to add thumbnails to this, so again followed the docs and added to the model
```
has_attached_file :screenshot,
:styles => { :medium => "300x300>",
:thumb => "100x100>" }
```
At this point the uploads no longer worked
I check the development logs and noticed this:
```
[32mCommand[0m :: identify -format %wx%h '/var/folders/ky/r5gsdhbn6yggbglsg727cc900000gn/T/stream20120302-60051-eh17n7.png[0]'
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError:
/var/folders/ky/r5gsdhbn6yggbglsg727cc900000gn/T/stream20120302-60051-eh17n7.png is not recognized by the 'identify' command.>
```
At which point after some googling I thought it might be a problem with setting the default path as an environment variable
```
Paperclip.options[:command_path] = "/usr/local/bin/"
```
But I checked that this was correct using
```
which identify
```
And it returned this path
```
/usr/local/bin/identify
```
As expected
I then tried to run identify from the command line as a test and got this error
```
dyld: Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /usr/local/bin/identify
Reason: Incompatible library version: identify requires version 14.0.0 or later, but libfreetype.6.dylib provides version 13.0.0
Trace/BPT trap: 5
```
So I think my problem is not with paperclip, but rather the install of imageMagick via homebrew
I've tried everything suggested including
```
brew update
brew remove imagemagick
brew install imagemagick
```
But it hasn't helped i'm running Lion 10.7.2 and have installed the developer tools.
Any suggestions would be very much appreciated.
|
2012/03/02
|
[
"https://Stackoverflow.com/questions/9537011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638079/"
] |
I ran into the same issue. Running a software update on the operating system resolved it for me. The version of libfree is out of date. Paperclip, ImageMagick and Homebrew were all working fine.
|
15,086,126 |
In our project we are using IntelliJ IDEA. There is an option to test RESTful web services (Tools -> Web Services -> RESTful Web Service -> Test RESTful Web Service). How would I pass in request XML if I choose request header data content-type as `application/xml`?
|
2013/02/26
|
[
"https://Stackoverflow.com/questions/15086126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919581/"
] |
Well, ok. This is still more thought than advice:
According your comment, that application has frames. And I think that this link will be inside frame. And this frame should have its name:
```
<frame name="main"> //my guess
//...
<a href="read_body.php?mailbox=INBOX&passed_id=2&startMessage=1">Complete Registration Request- My WebSite</a>
//...
</frame>
```
So, first thing you need to do to **switch driver to this frame**
```
driver.switchTo.frame("main");
```
And then you can perform the search
```
driver.findElement(By.partialLinkText("Complete Registration Request- My WebSite")).click();
```
**NOTE** The frame name is my own guess, so please do not copypaste my code. Use it as a guide ;)
|
16,911,793 |
I have a table called `konkurrencer` with column `slutter`, which datatype is `datetime`.
*How can I select all from that table where the rows "ends in" 1 hour?*
Let's say I have a prize into that table. It ends in 1 hour, therefore it has to output the row. If the row ends in 2 hours it should not output it. Only if 1 hour.
But how?
|
2013/06/04
|
[
"https://Stackoverflow.com/questions/16911793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079016/"
] |
use this query.
>
>
> ```
> SELECT *
> FROM konkurrencer
> WHERE slutter < DATE_ADD(NOW(), INTERVAL 1 HOUR)
> AND slutter >= NOW()
>
> ```
>
>
|
51,302 |
>
> I want to preface this by saying I am software engineer so each part of this robot build has been a lesson on its own. From welding, to CAD design, pillow block bearings, etc, etc....
>
>
>
I am working on a DIY Rover using the following components:
* [4 DC Motors](https://rads.stackoverflow.com/amzn/click/com/B07KVVL1NM) from electric scooters: 24V, 250W. Connected to axle with #40 roller chains and sprockets.
* [4 Lawn Mower Wheels](https://lawnmowertirestore.com/wheels/lawn-mower-wheels/16x6-50-8-turf-tire-and-rim-for-lawn-and-garden-mower-75-bearing-3.html). They are 16x6.50-8 for a 3/4" axle with a keyway
* [A Pair of 12 Volt - 60Ah GEL Batteries](https://www.ezmobilitybattery.com/mk-battery-m34-sld-g-m34sldg-gel.html) : I pulled them from a discarded electric wheel chair. They are fully charged, and they show **26V** when connected in series
* I replaced the stock sprockets on the motors with [these](https://rads.stackoverflow.com/amzn/click/com/B00VI4S1LC) #40 chain 12 teeth, 1/2" pitch.
* I put the same sprockets on the axles
[](https://i.stack.imgur.com/XdiuO.jpg)
[](https://i.stack.imgur.com/kAMyM.jpg)
[](https://i.stack.imgur.com/vn42I.jpg)
The problem is that the robot does not begin to move. When I lift the wheel off the ground, they move fine, and spin fast depending on how much throttle I give them.
However on the ground they don't move, which is typically a **torque problem**.
However I am not so convinced because these motors are supposed to be for electric scooters and each one capable of moving an adult person, weighing 175+ lbs.
Here are my diagnostic steps:
1. Using a FLYSKY controller and [12x2 Sabertooth](https://www.dimensionengineering.com/products/sabertooth2x12rc) motor controller. Unfortunately this controller has an over current protection, and those batteries are massive, so it just shuts itself down whenever I move throttle just a little bit. But again, when the wheels are off the ground they are spinning fine, so the connections are fine.
2. To avoid the over-current protection problem, I purchased this [60Amp DC Motor Controller](https://rads.stackoverflow.com/amzn/click/com/B089273KVZ). I connected it to just one wheel so far, and spliced a Multimeter into the connection to measure voltage. I can see the motor will get up to 20V when I turn the Potentiometer dial, and I can see the car begin to try to move.
Another question is: what's a good way to measure how many Amps the motor is trying to pull?
**My conclusions are:**
* The chains are just too heavy for this motor. It's a #40 chain which is way overkill. The sprocket on the motor shaft and the axle are also too heavy
* The tires maybe too heavy. But again, it's 4 x 250W motor that's getting 24V and probably up to 10Amps
**What is your advice?**
What would you do to fix this problem with minimal changes to the design? I.e. just replacing the sprockets? Or are the tires also too heavy?
How would I keep the tires and motors as is? Replace the sprockets and chains? Figure out a way to give a higher initial Amperage?
|
2022/06/09
|
[
"https://engineering.stackexchange.com/questions/51302",
"https://engineering.stackexchange.com",
"https://engineering.stackexchange.com/users/21402/"
] |
The motors have a rated speed of 2750rpm. It doesn't look like there's much of a gear ratio, so at the moment the motors spin at the same speed as the wheels. With 16" wheels, 2750rpm is about 130mph (rpm\*diameter\*pi, then converting inches/minute to mph). I'm guessing you don't want it to go that fast, and that speed wouldn't be possible with a total power of 1kw, or 1.3hp.
So you want to gear the motors down a lot, which increases the wheel torque. If you want a design speed of say 20mph, that's a gear ratio of $\frac{130}{20}=6.5$, so the wheel sprocket should have 6.5 times as many teeth as the motor sprocket and be 6.5 times the diameter.
That will also give you 6.5 times as much torque at the wheels
|
24,767,994 |
I was just trying out this method .pop() and it says in the docs it is supposed to "Remove the item at the given position in the list, and return it."
So I tried the following code:
```
def lao(li, i):
guess=input('Have a guess: ')
if guess == li[i]:
li.pop(i)
ho=list('abcde')
```
I wanted to see if lao(ho, 0) returned and removed 'a' as I thought it would, and this is how it went:
```
>>> print(lao(ho, 0))
Have a guess: a
None
>>> ho
['b', 'c', 'd', 'e']
```
So clearly the .pop() method was executed since 'a' was removed but the method didn't return 'a', instead it returned None.
I don't understand why?
|
2014/07/15
|
[
"https://Stackoverflow.com/questions/24767994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3815466/"
] |
Change `li.pop(i)` to `return li.pop(i)`. Python functions return `None` by default (when no `return` statement is present/reached). To return something from the function you must use the `return` keyword. See a [demo on Ideone](http://ideone.com/inhE5c).
|
51,808,420 |
This seems to be so easy to do. But, I can't make it work....! So frustrated...
I googled this problem and tried to solve it for a few hours. (I read a number of posts on StackOverflow.) But, I still can't solve this problem...
The following posts cover similar issues. So, I tried to solve my problem by trying answers in the posts. But, nothing worked for me...
* After reading this([jquery fadeIn not working](https://stackoverflow.com/questions/3398882/jquery-fadein-not-working)), I tried `.hide()`.
: didn't work...
* After reading this([jQuery animations: fadeIn() hidden div, not showing content](https://stackoverflow.com/questions/16006100)), I tried `fadeIn().removeId('tutorialPages')`
: didn't work...
* Also, I tried `display:none` in `CSS` instead of `.hide()` in `JS`.
: didn't work...
**Please keep in mind:**
If you think it's a duplicate of another question, please let me know which one and how I can apply solution(s) in that question to my problem. I am new to JavaScript and it is still difficult for me to apply solutions that worked for same/similar issues to my problem. Thanks in advance! :-)
I am using `Bootstrap 4.1.2.` & `jQuery 3.3.1`.
(\* you can't see the part I used Bootstrap in the following code snippet.)
**Error Message**:
I didn't see this error message when I wrote this code in `JSFiddle`. But, in this code snippet, the following code shows up when `Press this!` is clicked: `"message": "Uncaught TypeError: $(...).fadein is not a function"`.
**What I'm trying to do:**
1. When the page loads up, only `Press this!` is shown.
2. Show the 1st sentence when clicking `Press this!`.
3. Show the 2nd sentence when clicking the 1st sentence.
4. Show the 3rd sentence when clicking the 2nd sentence.
5. Show the 4th sentence when clicking the 3rd sentence.
```js
$(document).ready(function(){
$("#tutorialPages").hide();
$('#test').click(function(){
$("#tutorialFirst").fadein();
});
$('#tutorialFirst').click(function(){
$("#tutorialSecond").fadein();
});
$('#tutorialSecond').click(function(){
$("#tutorialThird").fadein();
});
$('#tutorialThird').click(function(){
$("#tutorialFourth").fadein();
});
});
```
```css
/* #tutorialPages{
display: none;
}
*/
#tutorialGreen{
color:black;
font-weight: bold;
font-size: 30px;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap 4.1.x -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<!-- Bootstrap 4.0 : jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<p id="test">Press this!</p>
<div id="tutorialPages">
<p id="tutorialFirst">This is 1st sentence.</p>
<p id="tutorialSecond">This is 2nd sentence.</p>
<p id="tutorialThird">This is 3rd sentence.</p>
<p id="tutorialFourth">This is 4th sentence.</p>
</div>
</body>
```
|
2018/08/12
|
[
"https://Stackoverflow.com/questions/51808420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10021131/"
] |
You Hide the parent element - `$("#tutorialPages")`, so it doesn't matter what will happen to its child elements, they won't be shown.
`$("#tutorialPages")` should always be shown, and show/hide only the children elements, or add `$("#tutorialPages").show()` to the first click event.
|
1,273,404 |
How to solve an inequality of the form $$f(x)=(x-a)(x-b)(x-c)\ge 0$$ for $$ a,b,c,x,f(x) \in \mathbb R $$ **WITHOUT** testing if an $f(x)$ within an interval between the roots is actually bigger or lesser than $0$?
|
2015/05/08
|
[
"https://math.stackexchange.com/questions/1273404",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/238587/"
] |
Apply root test
$$\lim\_{n \to \infty}\sqrt[n]{|a^n|\over n^{\sqrt{n}}} = \lim\_{n \to \infty}\frac{|a|}{n^{(\sqrt{n})^{-1}}}$$
Consider the denominator. Take $\log$ and you can get
$$\lim\_{n \to \infty} \frac{\log n}{\sqrt{n}}\stackrel{\text{L'H}}=\lim\_{n \to \infty} \frac{2\sqrt{n}}{n} =0$$
Therefore the denominator is $\lim\_{n \to \infty} n^{(\sqrt{n})^{-1}} =e^0 =1$. When $|a| > 1$, the root test shows the series diverges.
|
8,602,948 |
For instance : -78\_base10 on 8 bits is 0xB2
The pseudo-algorithm says : "-A =/A+1"
For instance :
* -78 => 78 => 01001110
* Then apply 'bar' : 01001110 => 10110001
* Then '+1' : 10110001 + 1 = 10110010
* convert in hexa : 0xB2
How to get the result nicely in Ruby (with or without this 'algorithm').
|
2011/12/22
|
[
"https://Stackoverflow.com/questions/8602948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178925/"
] |
How about something like
```
def signed_int_to_hex(n)
"0x%X" % (n % 2 ** 8)
end
signed_int_to_hex(-78) #=> "0xB2"
```
|
37,935,729 |
I have a string series containing multiples words. I want to extract the first character of each word per row in a vectorized fashion.
So far, I have been able to split the words into a list, but haven't found a vectorized way of getting the first characters.
```
s = pd.Series(['aa bb cc', 'cc dd ee', 'ff ga', '0w'])
>>> s. str.split()
0 [aa, bb, cc]
1 [cc, dd, ee]
2 [ff, ga]
3 [0w]
```
Eventually, I want something like this:
```
0 [a, b, c]
1 [c, d, e]
2 [f, g]
3 [0]
```
|
2016/06/21
|
[
"https://Stackoverflow.com/questions/37935729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3886109/"
] |
Another faster solution is nested list comprehension:
```
s2 = pd.Series([[y[0] for y in x.split()] for x in s.tolist()])
print (s2)
0 [a, b, c]
1 [c, d, e]
2 [f, g]
3 [0]
dtype: object
```
Thank you [clocker](https://stackoverflow.com/questions/37935729/extract-first-characters-from-list-series-pandas/37936260#comment63326032_37936260) for improvement - you can remove `tolist()`:
```
print (pd.Series([[y[0] for y in x.split()] for x in s]))
```
**Timings**:
```
import pandas as pd
s = pd.Series(['aa bb cc', 'cc dd ee', 'ff ga', '0w'])
s = pd.concat([s]*10000).reset_index(drop=True)
print(s)
In [42]: %timeit pd.Series([[y[0] for y in x.split()] for x in s.tolist()])
10 loops, best of 3: 28.6 ms per loop
In [43]: %timeit (s.str.split().map(lambda lst : [string[0] for string in lst]))
10 loops, best of 3: 50.4 ms per loop
In [44]: %timeit (s.str.split().apply(lambda lst: [list(elt)[0] for elt in lst]))
10 loops, best of 3: 76.1 ms per loop
In [59]: %timeit (pd.Series([[y[0] for y in x.split()] for x in s]))
10 loops, best of 3: 28.8 ms per loop
```
|
418 |
Currently, a magnet link containing a 40-digits long SHA-hash value, is assigned to every torrent which is created. Therefore, this hash should be unique to identify a torrent and send the right bytes (packages) to the right people. So therefore, there are $16^{40}$ (1461501637330902918203684832716283019655932542976) possible hashes to uniqueliy identify a torrent. What happens after this number has been reached or two torrents with different content have the same hash? (Although this practically never happens, there is a chance of $\frac{x+1}{16^{40}}$ where $x$ is the number of public torrents aka. assigned hashes, that your hashes collide.)
So to make long things short: What happens if two magnet-link-hashes are equal for different contents? What happens after every magnet-link has been used?
|
2011/08/16
|
[
"https://crypto.stackexchange.com/questions/418",
"https://crypto.stackexchange.com",
"https://crypto.stackexchange.com/users/543/"
] |
$16^{40}$ is a huge number. For instance, if you consider each torrent to consist in a single byte each (so they are quite uninteresting torrents), and you pack them all on 10 TB hard disks (for a torrent to exist, it must exist on at least one hard disk on the planet), and if each such disk weighs about 100g, then the total weight of the disks is about 24 billions of times the mass of the whole Earth.
So I am quite confident in stating that this number will not be reached.
Risks of collisions are actually higher. If you accumulate 160-bit hash values (outputs of SHA-1) then, on average, the first collisions should appear after about $2^{80}$ values (this is known as the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_problem)). So the situation you describe may occur much earlier than after exhaustion of the $16^{40}$ space. But $2^{80}$ is still huge, and cannot be practically achieved ($2^{80}$ torrents mean more than one hundred thousand *billions* of torrents *per human being on Earth*).
If a hash collision occurred, then streaming either of the two colliding files would most probably cease to work; downloaders would obtain a mixture of both files. Other torrents would remain totally unaffected.
An interesting question is whether you could, given an existing torrent $T$, handcraft another $T'$ which hashes to the same value -- it would be used as a weapon to prevent usage of $T$. To do that, you would have to break **second preimage resistance** of the hash function. SHA-1 has a few known weaknesses, but for now there is no known method for obtaining a second preimage, except luck (try random values until one matches). Luck (aka "brute force") has average cost $2^{160}$, which is completely out of reach of today's (and tomorrow's and next decade's) technology.
|
47,883,701 |
[](https://i.stack.imgur.com/wmQ1s.png)
Not able to click on submenu in our application. As per the attached picture. I am trying to achieve below scenario steps:
1. Click on `Menu 1`
2. MouseOver on `<Item 3>`
3. Click on `Sub Item 2`
I have tried below code and not able to click on Sub Item 2, Because the issue is when selenium is trying to click on Sub Item 2, the focus/cursor/mouseover changed from Item 3 to Item 1. And 2nd sub item present in Item 1 got clicked.
```
driver.findElement(By.linkText("Menu 1")).click();
WebElement item3 = driver.findElement(By.linkText("<Item 3>"));
Actions action = new Actions(driver);
action.moveToElement(item3).pause(Duration.ofSeconds(1)).build().perform();
action.moveToElement(driver.findElement(By.linkText("<sub Item2>")))
.click().build().perform();`
```
Please help me with the solution to handle this situation.
|
2017/12/19
|
[
"https://Stackoverflow.com/questions/47883701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4609206/"
] |
You can make it as chained actions. It may work for you.
```
WebElement menu1 = driver.findElement(By.linkText("Menu 1"));
WebElement item3 = driver.findElement(By.linkText("<Item 3>"));
Actions action = new Actions(driver);
action.click(menu1).moveToElement(item3).click(driver.findElement(By.linkText("<sub Item2>"))).build.perform();
```
|
22,763,455 |
Consider the following english phrase
```
FRIEND AND COLLEAGUE AND (FRIEND OR COLLEAGUE AND (COLLEAGUE AND FRIEND AND FRIEND))
```
I want to be able to programmatically change arbitrary phrases, such as above, to something like:
```
SELECT * FROM RelationTable R1 JOIN RelationTable R2 ON R2.RelationName etc etc WHERE
R2.RelationName = FRIEND AND R2.RelationName = Colleague AND (R3.RelationName = FRIENd,
etc. etc.
```
My question is. How do I take the initial string, strip it of the following words and symbols : AND, OR, (, ),
Then change each word, and create a new string.
I can do most of it, but my main problem is that if I do a string.split and only get the words I care for, I can't really replace them in the original string because I lack their original index. Let me explain in a smaller example:
```
string input = "A AND (B AND C)"
Split the string for space, parenthesies, etc, gives: A,B,C
input.Replace("A", "MyRandomPhrase")
```
But there is an A in AND.
So I moved into trying to create a regular expression that matches exact words, post split, and replaces. It started to look like this:
```
"(\(|\s|\))*" + itemOfInterest + "(\(|\s|\))+"
```
Am I on the right track or am I overcomplicating things..Thanks !
|
2014/03/31
|
[
"https://Stackoverflow.com/questions/22763455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2804164/"
] |
You can try using `Regex.Replace`, with `\b` word boundary regex
```
string input = "A AND B AND (A OR B AND (B AND A AND A))";
string pattern = "\\bA\\b";
string replacement = "MyRandomPhrase";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
```
|
65,996,165 |
I tried to create a registration using MVVM + Repository pattern with DI, and I used @ViewModelInject and everything was OK, but now @ViewModelInject is deprecated and I changed @ViewModelInject to @HiltViewModel + @Inject constructor() and faced with the `error: [Dagger/MissingBinding] *.AuthRepository cannot be provided without an @Provides-annotated method.` I tried to add a @Provides annotation for the register function in the interface but faced with another error
>
> Execution failed for task ':app:kaptDebugKotlin'.
>
>
>
> >
> > A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> > java.lang.reflect.InvocationTargetException (no error message)
> >
> >
> >
>
>
>
AuthViewModel
```
@HiltViewModel
class AuthViewModel @Inject constructor(
private val repository: AuthRepository,
private val applicationContext: Context,
private val dispatcher: CoroutineDispatcher = Dispatchers.Main
) : ViewModel() {
private val _registerStatus = MutableLiveData<Event<Resource<AuthResult>>>()
val registerStatus: LiveData<Event<Resource<AuthResult>>> = _registerStatus
private val _loginStatus = MutableLiveData<Event<Resource<AuthResult>>>()
val loginStatus: LiveData<Event<Resource<AuthResult>>> = _loginStatus
fun login(email: String, password: String) {
if(email.isEmpty() || password.isEmpty()) {
val error = applicationContext.getString(R.string.error_input_empty)
_loginStatus.postValue(Event(Resource.Error(error)))
} else {
_loginStatus.postValue(Event(Resource.Loading()))
viewModelScope.launch(dispatcher) {
val result = repository.login(email, password)
_loginStatus.postValue(Event(result))
}
}
}
fun register(email: String, username: String, password: String, repeatedPassword: String) {
val error = if(email.isEmpty() || username.isEmpty() || password.isEmpty()) {
applicationContext.getString(R.string.error_input_empty)
} else if(password != repeatedPassword) {
applicationContext.getString(R.string.error_incorrectly_repeated_password)
} else if(username.length < MIN_USERNAME_LENGTH) {
applicationContext.getString(R.string.error_username_too_short, MIN_USERNAME_LENGTH)
} else if(username.length > MAX_USERNAME_LENGTH) {
applicationContext.getString(R.string.error_username_too_long, MAX_USERNAME_LENGTH)
} else if(password.length < MIN_PASSWORD_LENGTH) {
applicationContext.getString(R.string.error_password_too_short, MIN_PASSWORD_LENGTH)
} else if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
applicationContext.getString(R.string.error_not_a_valid_email)
} else null
error?.let {
_registerStatus.postValue(Event(Resource.Error(it)))
return
}
_registerStatus.postValue(Event(Resource.Loading()))
viewModelScope.launch(dispatcher) {
val result = repository.register(email, username, password)
_registerStatus.postValue(Event(result))
}
}
}
```
AppModule
```
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideMainDispatcher() = Dispatchers.Main as CoroutineDispatcher
@Singleton
@Provides
fun provideApplicationContext(@ApplicationContext context: Context) = context
@Singleton
@Provides
fun provideGlideInstance(@ApplicationContext context: Context) =
Glide.with(context).setDefaultRequestOptions(
RequestOptions()
.placeholder(R.drawable.ic_image)
.error(R.drawable.ic_error)
.diskCacheStrategy(DiskCacheStrategy.DATA)
)
}
```
AuthModule
```
@Module
@InstallIn(ActivityComponent::class)
object AuthModule {
@ActivityScoped
@Provides
fun provideAuthRepository() = DefaultAuthRepository() as AuthRepository
}
```
AuthRepository
```
interface AuthRepository {
suspend fun register(email: String, username: String, password: String): Resource<AuthResult>
suspend fun login(email: String, password: String): Resource<AuthResult>
}
```
DefaultAuthRepository
```
class DefaultAuthRepository : AuthRepository {
val auth = FirebaseAuth.getInstance()
val users = FirebaseFirestore.getInstance().collection("users")
override suspend fun register(
email: String,
username: String,
password: String
): Resource<AuthResult> {
return withContext(Dispatchers.IO) {
safeCall {
val result = auth.createUserWithEmailAndPassword(email, password).await()
val uid = result.user?.uid!!
val user = User(uid, username)
users.document(uid).set(user).await()
Resource.Success(result)
}
}
}
override suspend fun login(email: String, password: String): Resource<AuthResult> {
TODO("Not yet implemented")
}
}
//Dagger - Hilt
implementation 'com.google.dagger:hilt-android:2.31.2-alpha'
kapt 'com.google.dagger:hilt-android-compiler:2.31.2-alpha'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha03'
```
[enter image description here](https://i.stack.imgur.com/Zj5U6.png)
|
2021/02/01
|
[
"https://Stackoverflow.com/questions/65996165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11002602/"
] |
You can try to use middleware,check the context.request.path,if it contains "foo",change path to what you want.Here is a working demo:
Startup.cs(put the middleware at the top of Configure method):
```
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.Contains("foo"))
{
context.Request.Path = "/Test2/TestUrl";
}
// Do work that doesn't write to the Response.
await next();
// Do logging or other work that doesn't write to the Response.
});
...
}
```
Test2Controller:
```
public IActionResult TestUrl()
{
return Ok();
}
```
result:
[](https://i.stack.imgur.com/YCqIn.gif)
|
33,782,069 |
modelData has 100,000 items in the list.
I am doing 2 "Selects" within 2 loops.
Could it be structured differently - as it take a long time - 10 mins
```
public class ModelData
{
public string name;
public DateTime DT;
public int real;
public int trade;
public int position;
public int dayPnl;
}
List<ModelData> modelData;
var dates = modelData.Select(x => x.DT.Date).Distinct();
var names = modelData.Select(x => x.name).Distinct();
foreach (var aDate in dates)
{
var dateRealTrades = modelData.Select(x => x)
.Where(x => x.DT.Date.Equals(aDate) && x.real.Equals(1));
foreach (var aName in names)
{
var namesRealTrades = dateRealTrades.Select(x => x)
.Where(x => x.name.Equals(aName));
// DO MY PROCESSING
}
}
```
|
2015/11/18
|
[
"https://Stackoverflow.com/questions/33782069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/439497/"
] |
I believe what you want can be achieved with two queries using group by. One to create a lookup by the date and the other to give you the name-date grouped items.
```
var data = modelData.Where(x => x.real.Equals(1))
.GroupBy(x => new { x.DT.Date, x.name });
var byDate = modelData.Where(x => x.real.Equals(1))
.ToLookup(x => x.DT.Date);
foreach(var item in data)
{
var aDate = item.Key.Date;
var aName = item.Key.name;
var namesRealTrades = item.ToList();
var dateRealTrades = byDate[aDate].ToList();
// DO MY PROCESSING
}
```
The first query will give you items grouped by the name and date to iterate over and the second will give you a lookup to get all the items associated with a given date. The second uses a lookup so that the list is iterated once and gives you fast access to the resulting list of items.
This should greatly reduce the number of times you iterate over `modelData` from what you currently have.
|
668,415 |
[](https://i.stack.imgur.com/ZFaUB.png)Hi all I am using Kali Linux. It is working okay but logs in `dmesg` show that I have this error. I have googled it but not having any luck and before you say anything look at the screenshot yes it can run on hardware Bare Metal that enables you to have access to GPU for hash cat. I have installed NVIDIA drivers from Kali walk through the OS is running fine and has been since I installed it but the error displays before I get login splash screen and its annoying but don't affect the running of Kali or that I can notice.
```
ACPI BIOS Error (bug): Could not resolve symbol [\_SB.PCI0.GFX0.DD02._BCL], AE_NOT_FOUND (20200925/psargs-330)
[ 2.114652] ACPI Error: Aborting method \_SB.PCI0.RP05.PEGP.DD02._BCL due to previous error (AE_NOT_FOUND) (20200925/psparse-529)
```
|
2021/09/10
|
[
"https://unix.stackexchange.com/questions/668415",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/491743/"
] |
The error messages seem to be about [ACPI extensions for display adapters](https://uefi.org/specs/ACPI/6.4/Apx_B_Video_Extensions/acpi-extensions-for-display-adapters-introduction.html).
In the ACPI specification (linked above) the `_BCL` method is described as "Query list of brightness control levels supported". Apparently your ACPI BIOS has declared that it supports this extension method, but when the Linux ACPI interpreter is parsing the ACPI tables provided by the BIOS, it cannot find this method.
In plain English: your system BIOS/UEFI firmware has told the Linux kernel that there is an ACPI-based method for controlling the brightness of the backlight of the laptop's display, but it turns out the actual code to implement it seems to be missing. This is usually not a problem, as the GPU drivers often have alternative methods for controlling the backlight brightness without involving ACPI.
The scary error messages are generated because the same code that checks the validity of ACPI methods is used with all ACPI methods: both the important and the less important methods are checked before use, and all ACPI implementation errors (firmware bugs) detected by the kernel will be reported in the same way. I think some very common nuisance errors have received special treatment, but the backlight-related messages might be important for someone troubleshooting why their laptop's backlight adjustment does not work.
Unfortunately, your choices for fixing these messages are limited to:
* installing a BIOS update and hoping it will fix the issue
* trying various display-related BIOS settings and hoping some combination of them will not have this issue (particularly if you have a dual-GPU laptop)
* setting the kernel console log level so high that the message won't be displayed (but this might cause you not see other important error messages, if your system e.g. develops a hardware fault)
* developing a kernel patch to selectively silence those particular messages in your specific hardware model (requires some programming skills, but might be easier than you think)
|
49,291,723 |
I have a issue. I have a string that contains a pattern and if string contains that pattern then it should be stored inside an variable.
```
var pattern = new RegExp(/@([0-9]+)/i);
if(pattern.test('@2 ajshfd @32 asd')
// here i need to store the matched string inside a variable and replace it with another string.
```
for eg:- input:- @2 ajs @32 hfdasd output:- Hi ajs hello hfdasd
Need help. Thanks in advance.
|
2018/03/15
|
[
"https://Stackoverflow.com/questions/49291723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9180333/"
] |
Edit: updated based on question changes
You can try in 2 steps, first [`exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) and then [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
```js
let pattern = new RegExp(/@(\d+)/i)
let str = '@2 ajshfd @32 asd'
let arrOld = []
let arrNew = ['Hi', 'hello']
let m
do {
m = pattern.exec(str)
if (m) {
arrOld.push(m[1])
str = str.replace(pattern, arrNew.shift())
}
} while (m)
console.log(arrOld)
console.log(str)
```
|
46,356,566 |
I am trying to make a script to check if an argument was entered. If an argument was entered it uses that number for the timer, if no argument was entered, then by default, the timer should equal 3.
This while loop will count down from the given number & print each value as it counts down. When it gets to the end it will output 'blast off!'
```
#!/usr/bin/env python3
import sys
timer = int(sys.argv[1])
while timer != 0:
if len(sys.argv[1]) == 0:
timer = 3
elif len(sys.argv[1]) == int(sys.argv[1]):
timer = int(sys.argv[1])
print (timer)
timer = timer - 1
print ('blast off!')
```
My homework checking script gives me an error of IndexError: list index out of range - related to the first timer = int(sys.argv[1])
I am not sure how exactly I am supposed to "convert an empty string into an integer"
Thank you
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46356566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8616896/"
] |
Check that you actually have an argument:
```
timer = int(sys.argv[1]) if len(sys.argv) >= 2 else 3
```
|
11,235,638 |
I'm writing a client to access a SOAP webservice, that will be hosted by a third party. I have the WSDL and XSD that define the interface and the data.
I've had no problem in creating a service reference from the WSDL, but I'm having a problem in building a simple web service that implements it, that I can use to test against. (The third party's service isn't ready, yet, but even were it running, I'd still like to do my initial testing against my own test server, not against theirs.)
I've browsed around, and apparently I can use svcutil to generate an interface for the service:
```
svcutil.exe thewsdl.wsdl thexsd.xsd /language:c# /out:ITestService.cs
```
This generates a file containing the service interface definition. But now what?
I figured the easiest way to go would be to build a self-hosted service, so I created a new console app, and in it I implemented a class derived from the service interface definition, and fired it up with a ServiceHost.
It runs, and while it was running I was able to create a Service Reference in my client app. But when I try to call it, from the client app, I get an error:
```
The provided URI scheme 'http' is invalid; expected 'https'.
```
What is the easiest way to get around this? Is there a simple way to simply turn off authentication and authorization, and simply allow unrestricted access?
EDITED:
I'm adding a bounty to this, as the original question seems to have attracted no attention.
But let's get to the crux. I am trying to write a client against a customer's SOAP service. As a part of the development, I want to create my own test WCF service, that implements the same WSDL.
So I have a downloaded .wsdl file, and an associated .xsd file, and with them I want to create a service that I can test against, with VS2010's debugger.
It's not important to me whether this service runs standalone, or within IIS, or that it be production stable. All I want is a service that accepts the requests that the customer's site would accept, and return the responses to my client that I need it to return, in order to test my handling of them.
How do I get there? I've tried adding a WCF Service Library, and then using svcutil.exe within it to add my new service, but it doesn't seem to populate the app.config with the server-side boilerplate, and my attempts to reconstruct it haven't worked.
|
2012/06/27
|
[
"https://Stackoverflow.com/questions/11235638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243563/"
] |
Since you want a full fledged service to call instead of mocking it.
Follow these steps:
1. Create new "WCF Service Application" project
2. Copy wsdl and xsd into project
3. select your wsdl file and look in the properties section and copy location from full path
4. Right click on the project in solution explorer and select "Add Service Reference..."
5. For the service address, paste the location of your wsdl that was copied in previous step and hit go. It should show the operations you are expecting for the service.
6. hit ok
7. It should generate all the objects for you including the interface and config file (although at this point is client side in the config- we will have to switch this to be the service)
8. Now you should add the service config section in the system.serviceModel section. Since I don't know the specifics of your wsdl what you should do is create the services node inside the system.serviceModel section and copy the endpoint node from the client node generated. For example below of services node, you can blank out the address for now:
>
>
> ```
> <system.serviceModel>
> <services>
> <service name="YourService">
> <endpoint address=""
> binding="basicHttpBinding" bindingConfiguration="WeatherSoap"
> contract="ServiceReference1.WeatherSoap" name="WeatherSoap" />
> </service>
>
> ```
>
>
1. delete the client node in the config
2. In the service, it is implementing a different interface when it generated the project so you will want to replace the interface implemented with the one listed in the contract attribute in the endpoint above. Then implement its members and it should explode out the operations available. You can fill in whatever you want the service operations to return.
3. depending on what the wsdl has in it, we may need to do a few more things to allow the necessary bindings to run - like setting up for wsHttpbinding, netTCPbinding, etc.
|
14,825,745 |
I had a look for this question before I asked, but sorry if it's a repeat.
In a spreadsheet, I want to employ a date sequence.
eg. Stock Arrives - Friday 22nd February 2013
then, on the 22nd of Feb, that date CHANGES to the next 7 days.
eg. Stock Arrives - 1st March 2013
and then repeats this indefinitely.
Is there any way to do this?
|
2013/02/12
|
[
"https://Stackoverflow.com/questions/14825745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1664882/"
] |
If you want to always show the next Friday you can use this formula
`=TODAY()+8-WEEKDAY(TODAY()+2)`
That will show Friday 15th Feb 2013 right now.....but on 15th feb it will change to showing 22nd Feb
For other days just change the +2 at the end, e.g. +3 will give you next Thursday, +4 will give you next Wednesday, +5 will give you next Tuesday etc.
|
41,448,927 |
Why does .split create an empty character when its argument is the first letter of the string, and it doesn't do the same when the argument is the last letter of the string? In the second example, doesn't it "say", since nothing is on my right I'll output "" ? (Is there a 'nil' at the end of the string?)
I know this is not a very relevant question, however, I'd like to understand why the method behaves this way. Thank you!
```
string = "aware"
string.split("a") --> # outputs: ["", "w", "re"]
string.split("e") --> # outputs: ["awar"]
```
|
2017/01/03
|
[
"https://Stackoverflow.com/questions/41448927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7337500/"
] |
Below is a simple example of behavioral oddity that String#split may seem to have:
```
"1234".split(/1/) # => ["", "234"]
```
It seems like the expected result of the above example would be [“234”] since it is splitting on the 1, but instead we’re getting an unexpected empty string.
\*\*
>
> How String#split works
>
>
>
\*\*
Internally String#split only uses regular expression delimiters. If you pass in a string delimiter it will be escaped for a regular expression and then turned into a regular expression:
```
1 2 3 4
"1234".split("1") # is really the same as "1234".split( Regexp.new( Regexp.escape("1") ) )
```
For the remainder of this article when I refer to delimiter I am referring to a regular expression delimiter since internally that is what String#split uses.
String#split keeps track the track of five important pieces of information:
* the string itself
a results array which is returned
the position marking where to start matching the string against the
delimiter. This is the start position and is initialized to 0.
the position marking where the string matched the delimiter. This is
the matched position and is initialized to 0.
the position marking the offset immediately following where the
string matched the delimiter
String#split operates in a loop. It continues to match the string against the delimiter until there are no more matches that can be found. It performs the following steps on each iteration:
* from the start position match the delimiter against the string
* set the matchedposition to where the delimiter matched the string
* if the delimiter didn’t match the string then break the loop
* create a substring using the start and matched positions of the
string being matched. Push this substring onto the results array
* set the start position for the next iteration
With this knowledge let’s discuss how String#split handles the previous example of:
```
"1234".split(/1/) # => ["", "234"]
```
* the first loop
* the start position is initialized to 0
* the delimiter is matched against the string “1234”
* the first match occurs with the first character, “1” which is at
position 0. This sets the matched position to 0.
* a substring is created using the start and matched positions and
pushed onto our result array. This gives us string[start,end] which
translates to “1234”[0,0] which returns an empty string.
* the start position is reset to position 1
* The second loop
* start is now 1
* The delimiter is matched against the remainder of our string, “234”
* No match is found so the loop is finished.
* A substring is created using the start position and remainder of the
string and pushed onto the results array
* the results array is returned
Given how String#split works it is easy to see why we have that unexpected empty string in our results array. You should note that this only occurred because the regular expression matched our string at the first character. Below is an example where the delimiter doesn’t match the first character and there is no empty string:
```
"1234".split(/2/) # => ["1", "34"]
```
|
11,112 |
I am looking for a relatively large PGN-formatted database (with at least 500k+ games), that is downloadable, with possibly the following properties:
* Simple formatted (no time indication after moves, etc), i.e. game info headers on top, followed by the moves, an example: *(it doesn't have to contain all the headers of this example)* [](https://i.stack.imgur.com/v0WsW.png)
* Few such, but very small (2-3 thousand games) databases can be found [here](http://chessproblem.my-free-games.com/chess/games/Download-PGN.php).
* It would be preferential if the database was diverse, for example not being only composed of man vs. machine games or somesuch. No real constraint on the ratings, whether the levels (amateur to super grandmaster) are fairly balanced or whether it's a 2000+ rating database.
* Although a single-file database would be easiest to work with, say for parsing purposes, one that is divided onto multiple PGN files would also be perfectly fine, as long as they were formatted similarly and did not contain too many duplicates.
In other posts, one mentioned database with similar properties to the above is the ICOFY database, but unfortunately it does not seem to be maintained any longer, nor can a trustworthy download link for it be found.
|
2015/08/23
|
[
"https://chess.stackexchange.com/questions/11112",
"https://chess.stackexchange.com",
"https://chess.stackexchange.com/users/3594/"
] |
Do not know if it really suits you but on <http://www.theweekinchess.com/twic> you can download a lot of PGN files. I once saw an explanation how somebody used this to create an opening book out of it. I could not find one big file with all games but there are quite a lot of files that date back to 25/06/2012. You can always make 1 big file out of it.
|
5,171,520 |
What is the problem with my code
```
var str = "[356] Hello World";
var patt = new RegExp("(?!\[)\d+(?<!\])","");
var result = patt.exec(str);
```
**Result Should Be = 356**
|
2011/03/02
|
[
"https://Stackoverflow.com/questions/5171520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/423903/"
] |
The problem is that you can't do negative lookbehinds in Javascript.
---
Something like this should work:
```
var str = '[356] Hello World',
patt = /\[(\d+)\]/,
result = patt.exec(str)[1];
```
This creates a matching group and selects the match with `[1]`.
|
7,858,173 |
I use a browser - Opera version 11.52.
I use version of the node.js - v0.4.12 and socket.io version 0.8.5.
I tried this example - <https://github.com/LearnBoost/socket.io/tree/master/examples/chat>
This page starts up and displays only the message - Connecting to socket.io server = **In opera**.
Other browsers work properly - Firefox, IE, Chrome.
I tried to debug node.js - No errors.
Thank you for your help and advice!
|
2011/10/22
|
[
"https://Stackoverflow.com/questions/7858173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/943403/"
] |
Try following this guide: <https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO> and configuring the transports setting to something that prioritizes xhr-polling over websockets and see if that resolves the issue. My experience with using socket.io on production web apps has been that the websocket transport is not as reliable as xhr-polling.
|
93,036 |
I am programmatically creating customers and adding billing and shipping addresses to their accounts.
I have put in `$customer->loadByEmail($email)` so when this script runs a second time it updates a customer instead of saving them again.
At the moment I can not work out how to check if a customer has a specific billing or shipping address (or other additional address) when I want to add an address, so I am re-adding the same addresses when the script runs again.
How do I check if a customer has a specific address?
e.g.
```
$address_details = array(
'firstname' => $firstname,
'lastname' => $lastname,
'street' => array(
'0' => $line1,
'1' => $line2,
)
'city' => $city,
'postcode' => $postcode,
'country_id' => 'GB',
'telephone' => $tel,
'parent_id' => $customer->getId(),
);
if(!$customer->hasAddress($address_details)) {
//add address
}
```
I would prefer to steer away from a massive `foreach` such as:
```
$customer = Mage::getSingleton('customer/session')->getCustomer();
$hasAddress=false;
foreach ($customer->getAddresses() as $address) {
if($address->getCity() !== $city) {
$hasAddress = true;
}
//...
}
```
|
2015/12/08
|
[
"https://magento.stackexchange.com/questions/93036",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2310/"
] |
`$customer->getAddresses()` should return all customer addresses **so** `count($customer->getAddresses())` should return quantity of addresses of customer.
you can check like
```
if(count($customer->getAddresses()) >= 0)
{
//Customer has one or more addresses. Your code here
}
```
|
51,989,866 |
I have a df that looks like this:
```
Id field value
0 1 first_name a
1 1 number 123
2 1 last_name aa
0 2 first_name b
1 2 number 456
2 2 last_name bb
3 2 type p
```
Each Id has a different length of index and roughly the same field types but some have more some have less.
How do I flip the df so that fields are columns and values are underneath them?
Like so:
```
Id first_name number last_name type
0 1 a 123 aa
1 2 b 456 bb p
```
|
2018/08/23
|
[
"https://Stackoverflow.com/questions/51989866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3277133/"
] |
This is also just `.pivot`
```
df.pivot(index='Id', columns='field', values='value').reset_index()
#field Id first_name last_name number type
#0 1 a aa 123 NaN
#1 2 b bb 456 p
```
If you get ValueError, this likely means that you have a row duplicated on `['Id', 'field']`. This will make it work, but will chose the value as whichever row appears first in your `DataFrame`.
```
pd.pivot_table(df, index='Id', columns='field', values='value', aggfunc='first')
```
|
46,845,641 |
need to somehow get these two txt files to serve as my key and values, i got the first one in the list working but need to get all the words mapped from both txt files.. I think whats happening is im not parsing through the files correctly. I am able to System.out.println(..) the contents but im recieving null for values so I am missing something big here. anyways new programmer here this is my first post. hi! =)
```
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
//Create map structure **must have import
Map engJapDictionary = new HashMap<String,String>();
//user input
Scanner in = new Scanner(System.in);
System.out.print("Enter phrase for translation: ");
//name the user input
String name = in.next();
System.out.println( "You wrote: " + name );
//Load Eng and Jap
String fileName = "word.txt";
String fileName1 = "word2.txt";
String line = null;
String line2= null;
try {
FileReader fileReader = new FileReader(fileName);
FileReader fileReader1 = new FileReader(fileName1);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while ((line = bufferedReader.readLine()) != null) {
String parts[] = line.split("\t");
while ((line2 = bufferedReader1.readLine()) != null) {
String parts2[] = line2.split("\t");
engJapDictionary.put(parts[0], parts2[0]);
//for each entry in both txt files iterate through i think here. the .put works only for the first entry in both txt files.. =(
continue;
//System.out.println(engJapDictionary +"\n");
//System.out.println(line);
}
}
}catch (IOException e){}
//Size of the Dictionary!
System.out.println("The number of entries is: " + engJapDictionary.size());
// English to Japanese Dictionary
//Building dictionary the long way
engJapDictionary.put("me", "Watashi");
engJapDictionary.put("you", "anata");
engJapDictionary.put("hat", "boshi");
engJapDictionary.put("cat", "neko");
engJapDictionary.put("dream", "yume");
engJapDictionary.put("house", "uchi");
engJapDictionary.put("dog", "inu");
// System.out.println(engJapDictionary.get("you"));
// System.out.println(engJapDictionary.get("hat"));
// System.out.println(engJapDictionary.get("cat"));
// System.out.println(engJapDictionary.get("dream"));
// System.out.println(engJapDictionary.get("house"));
// System.out.println(engJapDictionary.get("dog"));
System.out.println( "Japanese word: " + engJapDictionary.get(name ) );
System.out.println(engJapDictionary.get(name));
System.out.println(engJapDictionary.containsKey(name));
//Print the keys!!
//System.out.println("\n" + engJapDictionary.keySet());
//Print the values!!
//System.out.println(engJapDictionary.values());
}
}
```
|
2017/10/20
|
[
"https://Stackoverflow.com/questions/46845641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8723020/"
] |
You are calling `engJapDictionary.put(parts[0], parts2[0]);` for the first word of the first file with all the words of the second file. Then, you don't put any other words of the first file in the `Map`, since you finished iterating over the second file in the first run of the inner loop, so `line2 = bufferedReader1.readLine()` returns `null`.
You don't need a nested loop, just a single loop that reads a line from both files in each iteration:
```
while ((line = bufferedReader.readLine()) != null && (line2 = bufferedReader1.readLine()) != null) {
String parts[] = line.split("\t");
String parts2[] = line2.split("\t");
engJapDictionary.put(parts[0], parts2[0]);
}
```
|
3,404,783 |
I need to check if given date is after today 23:59:59, how can I create date object that is today 23:59:59?
|
2010/08/04
|
[
"https://Stackoverflow.com/questions/3404783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159793/"
] |
Use [java.util.Calendar](http://download-llnw.oracle.com/javase/6/docs/api/java/util/Calendar.html):
```
Calendar cal = Calendar.getInstance(); // represents right now, i.e. today's date
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999); // credit to f1sh
Date date = cal.getTime();
```
I think you might be approaching this from slightly the wrong angle, though. Instead of trying to create a Date instance that's one atom before midnight, a better approach might be to create the Date that represents midnight and testing whether the current time is *strictly* less than it. I believe this would be slightly clearer in terms of your intentions to someone else reading the code too.
---
Alternatively, you could use a third-party Date API that knows how to convert back to date. Java's built-in date API is generally considered to be deficient in many ways. I wouldn't recommend using another library just to do this, but if you have to do lots of date manipulation and/or are already using a library like [Joda Time](http://joda-time.sourceforge.net/) you could express this concept more simply. For example, Joda Time has a `DateMidnight` class that allows much easier comparison against "raw" dates of the type you're doing, without the possibility for subtle problems (like not setting the milliseconds in my first cut).
|
12,843,063 |
I was following the <http://tour.golang.org/> untill I got to the third step about that tells you that you can install the gotour on your system.
After that I've installed the go language with brew by:
```
brew install hg
brew install go
```
Then I downloaded the gotour by:
```
go get code.google.com/p/go-tour/gotour
```
When I tried to launch the gotour it didnt recognise the command:
```
$ gotour
-bash: gotour: command not found
```
and
```
$ go gotour
```
and
```
$ ./gotour
```
So I tried to see the go path and it was empty,
```
echo $GOPATH
```
so I defined the GOPATH:
```
GOPATH=/usr/local/Cellar/go/1.0.2/src/pkg/code.google.com/p/
export GOPATH
```
Now I can run the gotour by runing
```
./gotour
```
But I'm insecure about my go enviroment.. wasn't I suposed to be able to run gotour by
```
go run gotour
```
or just by typing (like is described on this website <http://www.moncefbelyamani.com/how-to-install-the-go-tour-on-your-mac/>):
```
gotour
```
I would like to know if i'm doing things the right way since I'm new to the go programing language.
|
2012/10/11
|
[
"https://Stackoverflow.com/questions/12843063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079609/"
] |
Installing go 1.4 with homebrew on OSX:
---------------------------------------
### 1) Create Directories
```
mkdir $HOME/Go
mkdir -p $HOME/Go/src/github.com/user
```
### 2) Setup your paths
```
export GOPATH=$HOME/Go
export GOROOT=/usr/local/opt/go/libexec
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:$GOROOT/bin
```
### 3) Install Go
```
brew install go
```
### 4) "go get" the basics
```
go get golang.org/x/tools/cmd/godoc
```
### 5) Start here: <https://golang.org/doc/code.html> at "your first program"
|
35,796,381 |
I have this RDD (showing two elements):
```
[['a', [1, 2]], ['b', [3, 0]]]
```
and I'd like to add up elements in the list based on the index, so to have
a final result
```
[4, 2]
```
how would I achieve this? I know the presence of first element ('a'/'b') is irrelevant as I could strip it out with a map so the question becomes how to sum column values.
|
2016/03/04
|
[
"https://Stackoverflow.com/questions/35796381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2352319/"
] |
You can strip the keys as you said, and then reduce your RDD as follows (given that you have 2 columns):
```
myRDD.reduce(lambda x,y:[x[0]+y[0], x[1]+y[1]])
```
This will give you the sum of all the columns
|
2,851,399 |
I would like to programmatically change content of button via style change. I created a style, added setter for `Button.ContentProperty`, set new style to button, but content was not changed.
I know that I can set button content directly, but now I would like to know why this does not work:
```
Style aStyle = new Style();
Setter bSetter = new Setter();
bSetter.Property = Button.ContentProperty;
bSetter.Value = "Some Text";
aStyle.Setters.Add(bSetter);
aButton.Style = aStyle;
```
XAML:
```
<Button x:Name="aButton" Style="{x:Null}" Click="Button_Click" />
```
I could change appearance of a button this way, but I couldn't change content. Btw, I found example in MCTS book on WPF.
Any idea?
|
2010/05/17
|
[
"https://Stackoverflow.com/questions/2851399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25732/"
] |
1. `priority_queue` has template parameters that specify the container type and the comparison to use for ordering. By default, the comparison is `less<T>`; to get the opposite ordering, use `priority_queue<T, vector<T>, greater<T>>`.
2. Insertion into a priority queue takes logarithmic time, so building a queue of `N` items has complexity `O(N logN)`, the same as building and sorting a vector. But once it's built, insertion into the priority queue is still logarithmic, while insertion into a sorted vector is linear.
|
46,355,446 |
I just wanted to know when is neccessary for me to place a div.cssclass when using two css classes together in my stylesheet. I normally troubleshoot by using with and without it until it works which obviously is fine and quick enough but I would be good to know the best practice.
Example:
```
.cssclass1 .cssclass2 { }
```
VS
```
.cssclass1 div.cssclass2 { }
```
Is it when its not a direct sibling to it, i.e the next class nested in there?
|
2017/09/22
|
[
"https://Stackoverflow.com/questions/46355446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7985277/"
] |
If both those elements are divs, then there is **no difference**, except that
```
.cssclass1 .cssclass2 {
```
is faster than
```
.cssclass1 div.cssclass2 {
```
If you'd have let's say:
```
<div class="cssclass1">
<div class="cssclass2"></div>
<a class="cssclass2"></a>
</div>
```
then `.cssclass1 .cssclass2 {` would select both `div` and `a`, while `.cssclass1 div.cssclass2 {` would select only the div.
|
24,745,675 |
I wish to switch between browser tabs for a feature I am testing. However I have not been able to do this. Have tried using the following:
```
page.driver.browser.switch_to.window(page.driver.browser.window_handles.first)
```
The idea been that when I am on the second tab the above code should bring it back to the first tab. However this is not working.
I also just tried to close the second tab using this:
```
page.execute_script "window.close();"
```
but this does do anything, the tab is not closed nor is the overall browser window so appears that it is not doing anything.
Had anybody else had problems like this and how did you figure out a solution? I am using FireFox.
|
2014/07/14
|
[
"https://Stackoverflow.com/questions/24745675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1523236/"
] |
Here's my method for closing new tabs.
```
def close_new_tabs
window = page.driver.browser.window_handles
if window.size > 1
page.driver.browser.switch_to.window(window.last)
page.driver.browser.close
page.driver.browser.switch_to.window(window.first)
end
end
```
I call this method anytime a new tab may need to be closed.
|
15,446,893 |
I'm trying to figure out how I can have a class listen to another. So this is the idea.
I have a `MainFrame` class, which is simply a container class, JFrame container, that takes an argument of type JPanel. Basically I want this container class to be able to switch between frames depending on what my other class, `FrameSwitcher`, will tell it to do.
The other classes are: `FrameSwitcher, MainMenu and ScoreBoards`.
The idea is that, let's say `MainMenu`, will contain 4 buttons, each one will listen, BUT will NOT change the frames. Rather it will somehow - and this is the part I need help with - send to the `FrameSwitcher` what button was clicked, and this information will then be sent to `MainFrame` to switch to the appropriate frames.
|
2013/03/16
|
[
"https://Stackoverflow.com/questions/15446893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2162251/"
] |
`FrameSwitcher` should keep `ActionListeners` added to the menu. On click it changes it's state and call MainFrame's method `switchTo(argumentWhereToSwitch);`
|
27,206,238 |
PROBLEM:
Accept a number and display the message "PRIME" if the number is a prime, otherwise display the message "COMPOSITE".
I cant sleep to think how could i write a code for this. I was thinking that it could be easy if i get the logic here. Sorry guys, Im just a beginner
So could you help me how to solve this problem.
My professor told me that i can get the logic in these code, but I'm still confuse :D
here's my last code for getting the factor that my prof told me that i could get the logic here.
(i dont know how :D)
```
import java.util.Scanner;
public class Factors {
public static void main(String[] args) {
Scanner n = new Scanner(System.in);
int num;
int ctr = 1;
System.out.print("Enter a number : ");
num = n.nextInt();
while(ctr <= num) {
if(num % ctr == 0) {
System.out.print(ctr + "\t");
}
ctr++;
}
System.out.println();
}
}
```
}
|
2014/11/29
|
[
"https://Stackoverflow.com/questions/27206238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4040724/"
] |
Not necessarily the fastest way, but it's simple.
```
# Make a set of of the values
prey = set(relationship.values())
# Find the intersection of predators and prey (elements that are both keys and values)
both = prey.intersection(relationship)
```
|
36,563,269 |
Once I execute the query I am getting the following error:
>
> Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1
> value. This is not permitted when the subquery follows =, !=, <, <= ,
>
>
>
> >
> > , >= or when the subquery is used as an expression.
> >
> >
> >
>
>
>
```
SELECT MAX(IL.INSLEND),n.ACTIONED, N.LEASID,n.BLDGID
FROM note n
INNER JOIN dbo.INSL il ON n.SEQNO=il.RECNUM
INNER JOIN dbo.LEAS l ON l.BLDGID = n.BLDGID AND l.LEASID = n.LEASID
AND n.REF1 = 'INSURAN' AND n.REF2= 'REMIND' OR n.ACTIONED <> 'C'
AND il.TABLEKEY = n.LEASID
WHERE il.TABLEID='LEAS' AND il.TABLEKEY = L.LEASID
GROUP BY n.LEASID, N.BLDGID, n.ACTIONED, IL.TABLEKEY, IL.TABLEID, L.LEASID
HAVING N.LEASID='083468' AND
(SELECT MAX(il.INSLEND) FROM dbo.INSL WHERE IL.TABLEKEY=L.LEASID AND IL.TABLEID='LEAS') < '2016-04-11'
```
|
2016/04/12
|
[
"https://Stackoverflow.com/questions/36563269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5996185/"
] |
try this...
```
SELECT MAX(IL.INSLEND),n.ACTIONED, N.LEASID,n.BLDGID FROM note n INNER JOIN dbo.INSL il ON n.SEQNO=il.RECNUM INNER JOIN dbo.LEAS l ON l.BLDGID = n.BLDGID AND l.LEASID = n.LEASID AND n.REF1 = 'INSURAN' AND n.REF2= 'REMIND' OR n.ACTIONED <> 'C' AND il.TABLEKEY = n.LEASID WHERE il.TABLEID='LEAS' AND il.TABLEKEY = L.LEASID GROUP BY n.LEASID, N.BLDGID, n.ACTIONED, IL.TABLEKEY, IL.TABLEID, L.LEASID HAVING N.LEASID='083468' AND MAX(il.INSLEND)< '2016-04-11'
```
|
20,794,104 |
I'm currently going through some programs to learn Ruby. I've been playing around with a palindrome program for a bit, though no matter the input (a palindrome) I end up on `else`.
Here is some of the code I've been trying:
```
print "enter a string:\n"
string = gets
if string.reverse == string
print "it's a palindrome"
else
print "not a palindrome.\n"
end
```
Any help/advice is greatly appreciated.
|
2013/12/27
|
[
"https://Stackoverflow.com/questions/20794104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You're not showing enough code to validate this, but I suspect you are making one of several common mistakes.
Common Problem #1: Not setting up your Managed Object Model Correctly
I can't demonstrate this in code, but your managed object model must contain each property you want. Just adding a new `@property` declaration in the object subclass does not add it to the model. It must exist in both places.
Common Problem #2: Implementing a Getter/Setter and calling Super
```
- (void)setCommandName:(NSString *)commandName
{
// Do "willUpdateCommandName" logic here
//Call Super
[super setCommandName:commandName];
// Do "didUpdateCommandName" logic here
}
```
This is a fairly common construction outside CoreData, but within Core Data, it is a common problem. Instead, you should call the primitive setter.
```
- (void)setCommandName:(NSString *)commandName
{
// Do "willUpdateCommandName" logic here
//Call Super
[self setPrimitiveCommandName:commandName];
// Do "didUpdateCommandName" logic here
}
```
Common Problem #3: You are initializing your object with `-init`, rather than `-initWithEntity:insertIntoManagedObjectContext:`.
You are definitely making this mistake in your code sample, but possibly others too. [According to the documentation](https://developer.apple.com/library/mac/documentation/cocoa/reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html#//apple_ref/occ/instm/NSManagedObject/setPrimitiveValue%3aforKey%3a), you should not use `-init`. Internally, I suspect that it requires the NSEntityDescription to dynamically generate the getters/setters for your object.
If you don't want the object inserted immediately, you can pass `nil` as the `NSManagedObjectContext`, but you must pass in the `NSEntityDescription`, acquired from your `NSManagedObjectModel`. Doing this correctly looks like this.
```
// Macro for easy reading/writing
#define SOClass(x) NSStringFromClass([x class])
// It is important to note that the entity name *CAN* be different from the class name, but generally it is not
NSString *entityName = SOClass(SOCommand);
NSDictionary *entities = self.managedObjectModel.entitiesByName;
NSEntityDescription *entityDescription = entities[entityName];
SOCommand *newCommand = [[SOCommand alloc] initWithEntity:entityDescription
insertIntoManagedObjectContext:nil];
```
If you know the context you want to use, you may also use this syntax:
```
// Macro for easy reading/writing
#define SOClass(x) NSStringFromClass([x class])
// It is important to note that the entity name *CAN* be different from the class name, but generally it is not
NSString *entityName = SOClass(SOCommand);
SOCommand *newCommand = [NSEntityDescription entityForName:entityName
inManagedObjectContext:self.managedObjectContext];
```
|
2,470,760 |
I wold like to have in my model a CharField with fixed length. In other words I want that only a specified length is valid.
I tried to do something like
```
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
```
but it gives me an error (it seems that I can use both max\_length and min\_length at the same time).
Is there another quick way?
My model is this:
```
class Volume(models.Model):
vid = models.AutoField(primary_key=True)
jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volumenumber = models.CharField('Volume Number')
date_publication = models.CharField('Date of Publication', max_length=6, blank=True)
class Meta:
db_table = u'volume'
verbose_name = "Volume"
ordering = ['jid', 'volumenumber']
unique_together = ('jid', 'volumenumber')
def __unicode__(self):
return (str(self.jid) + ' - ' + str(self.volumenumber))
```
What I want is that the `volumenumber` must be exactly 4 characters.
I.E.
if someone insert '4b' django gives an error because it expects a string of 4 characters.
So I tried with
```
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
```
but it gives me this error:
```
Validating models...
Unhandled exception in thread started by <function inner_run at 0x70feb0>
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors
self._populate()
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate
self.load_app(app_name, True)
File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app
models = import_module('.models', app_name)
File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module>
class Volume(models.Model):
File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume
volumenumber = models.CharField('Volume Number', max_length=4, min_length=4)
TypeError: __init__() got an unexpected keyword argument 'min_length'
```
That obviously doesn't appear if I use only "max\_length" OR "min\_length".
I read the documentation on the django web site and it seems that I'm right (I cannot use both together) so I'm asking if there is another way to solve the problem.
|
2010/03/18
|
[
"https://Stackoverflow.com/questions/2470760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257092/"
] |
CharField database model field instances only have a `max_length` parameter, as indicated in the [docs](http://docs.djangoproject.com/en/dev/ref/models/fields/#charfield). This is probably because there is only a max character length contraint equivalent in SQL.
[Form Field CharField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#charfield) objects, on the other hand, do have a `min_length` parameter. So you'd have to write a custom ModelForm for this specific model and override the default admin model form with the custom one.
Something like that:
```
# admin.py
from django import forms
...
class VolumeForm(forms.ModelForm):
volumenumber = forms.CharField(max_length=4, min_length=4)
class Meta:
model = Volume
class VolumeAdmin(admin.ModelAdmin):
form = VolumeForm
...
admin.site.register(Volume, VolumeAdmin)
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.