qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
45,880,127 |
Let's say we have a fake data source which will return data it holds in batch
```
class DataSource(size: Int) {
private var s = 0
implicit val g = scala.concurrent.ExecutionContext.global
def getData(): Future[List[Int]] = {
s = s + 1
Future {
Thread.sleep(Random.nextInt(s * 100))
if (s <= size) {
List.fill(100)(s)
} else {
List()
}
}
}
object Test extends App {
val source = new DataSource(100)
implicit val g = scala.concurrent.ExecutionContext.global
def process(v: List[Int]): Unit = {
println(v)
}
def next(f: (List[Int]) => Unit): Unit = {
val fut = source.getData()
fut.onComplete {
case Success(v) => {
f(v)
v match {
case h :: t => next(f)
}
}
}
}
next(process)
Thread.sleep(1000000000)
}
```
I have mine, the problem here is some portion is more not pure. Ideally, I would like to wrap the Future for each batch into a big future, and the wrapper future success when last batch returned 0 size list? My situation is a little from [this](https://stackoverflow.com/questions/30737955/asynchronous-iterable-over-remote-data) post, the `next()` there is synchronous call while my is also async.
Or is it ever possible to do what I want? Next batch will only be fetched when the previous one is resolved in the end whether to fetch the next batch depends on the size returned?
What's the best way to walk through this type of data sources? Are there any existing Scala frameworks that provide the feature I am looking for? Is play's **Iteratee, Enumerator, Enumeratee** the right tool? If so, can anyone provide an example on how to use those facilities to implement what I am looking for?
Edit----
With help from chunjef, I had just tried out. And it actually did work out for me. However, there was some small change I made based on his answer.
```
Source.fromIterator(()=>Iterator.continually(source.getData())).mapAsync(1) (f=>f.filter(_.size > 0))
.via(Flow[List[Int]].takeWhile(_.nonEmpty))
.runForeach(println)
```
However, can someone give comparison between Akka Stream and Play Iteratee? Does it worth me also try out Iteratee?
---
Code snip 1:
```
Source.fromIterator(() => Iterator.continually(ds.getData)) // line 1
.mapAsync(1)(identity) // line 2
.takeWhile(_.nonEmpty) // line 3
.runForeach(println) // line 4
```
Code snip 2: Assuming the getData depends on some other output of another flow, and I would like to concat it with the below flow. However, it yield too many files open error. Not sure what would cause this error, the mapAsync has been limited to 1 as its throughput if I understood correctly.
```
Flow[Int].mapConcat[Future[List[Int]]](c => {
Iterator.continually(ds.getData(c)).to[collection.immutable.Iterable]
}).mapAsync(1)(identity).takeWhile(_.nonEmpty).runForeach(println)
```
|
2017/08/25
|
[
"https://Stackoverflow.com/questions/45880127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6273735/"
] |
The following is one way to achieve the same behavior with Akka Streams, using your `DataSource` class:
```
import scala.concurrent.Future
import scala.util.Random
import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl._
object StreamsExample extends App {
implicit val system = ActorSystem("Sandbox")
implicit val materializer = ActorMaterializer()
val ds = new DataSource(100)
Source.fromIterator(() => Iterator.continually(ds.getData)) // line 1
.mapAsync(1)(identity) // line 2
.takeWhile(_.nonEmpty) // line 3
.runForeach(println) // line 4
}
class DataSource(size: Int) {
...
}
```
A simplified line-by-line overview:
* **`line 1`**: Creates a stream source that continually calls `ds.getData` if there is downstream demand.
* **`line 2`**: `mapAsync` is a way to deal with stream elements that are `Future`s. In this case, the stream elements are of type `Future[List[Int]]`. The argument `1` is the level of parallelism: we specify `1` here because `DataSource` internally uses a mutable variable, and a parallelism level greater than one could produce unexpected results. `identity` is shorthand for `x => x`, which basically means that for each `Future`, we pass its result downstream without transforming it.
* **`line 3`**: Essentially, `ds.getData` is called as long as the result of the `Future` is a non-empty `List[Int]`. If an empty `List` is encountered, processing is terminated.
* **`line 4`**: `runForeach` here takes a function `List[Int] => Unit` and invokes that function for each stream element.
|
I just figured out that by using flatMapConcat can achieve what I wanted to achieve. There is no point to start another question as I have had the answer already. Put my sample code here just in case someone is looking for similar answer.
This type of API is very common for some integration between traditional Enterprise applications. The DataSource is to mock the API while the object App is to demonstrate how the client code can utilize Akka Stream to consume the APIs.
In my small project the API was provided in SOAP, and I used [scalaxb](http://scalaxb.org) to transform the SOAP to Scala async style. And with the client calls demonstrated in the object App, we can consume the API with AKKA Stream. Thanks for all for the help.
```
class DataSource(size: Int) {
private var transactionId: Long = 0
private val transactionCursorMap: mutable.HashMap[TransactionId, Set[ReadCursorId]] = mutable.HashMap.empty
private val cursorIteratorMap: mutable.HashMap[ReadCursorId, Iterator[List[Int]]] = mutable.HashMap.empty
implicit val g = scala.concurrent.ExecutionContext.global
case class TransactionId(id: Long)
case class ReadCursorId(id: Long)
def startTransaction(): Future[TransactionId] = {
Future {
synchronized {
transactionId += transactionId
}
val t = TransactionId(transactionId)
transactionCursorMap.update(t, Set(ReadCursorId(0)))
t
}
}
def createCursorId(t: TransactionId): ReadCursorId = {
synchronized {
val c = transactionCursorMap.getOrElseUpdate(t, Set(ReadCursorId(0)))
val currentId = c.foldLeft(0l) { (acc, a) => acc.max(a.id) }
val cId = ReadCursorId(currentId + 1)
transactionCursorMap.update(t, c + cId)
cursorIteratorMap.put(cId, createIterator)
cId
}
}
def createIterator(): Iterator[List[Int]] = {
(for {i <- 1 to 100} yield List.fill(100)(i)).toIterator
}
def startRead(t: TransactionId): Future[ReadCursorId] = {
Future {
createCursorId(t)
}
}
def getData(cursorId: ReadCursorId): Future[List[Int]] = {
synchronized {
Future {
Thread.sleep(Random.nextInt(100))
cursorIteratorMap.get(cursorId) match {
case Some(i) => i.next()
case _ => List()
}
}
}
}
}
object Test extends App {
val source = new DataSource(10)
implicit val system = ActorSystem("Sandbox")
implicit val materializer = ActorMaterializer()
implicit val g = scala.concurrent.ExecutionContext.global
//
// def process(v: List[Int]): Unit = {
// println(v)
// }
//
// def next(f: (List[Int]) => Unit): Unit = {
// val fut = source.getData()
// fut.onComplete {
// case Success(v) => {
// f(v)
// v match {
//
// case h :: t => next(f)
//
// }
// }
//
// }
//
// }
//
// next(process)
//
// Thread.sleep(1000000000)
val s = Source.fromFuture(source.startTransaction())
.map { e =>
source.startRead(e)
}
.mapAsync(1)(identity)
.flatMapConcat(
e => {
Source.fromIterator(() => Iterator.continually(source.getData(e)))
})
.mapAsync(5)(identity)
.via(Flow[List[Int]].takeWhile(_.nonEmpty))
.runForeach(println)
/*
val done = Source.fromIterator(() => Iterator.continually(source.getData())).mapAsync(1)(identity)
.via(Flow[List[Int]].takeWhile(_.nonEmpty))
.runFold(List[List[Int]]()) { (acc, r) =>
// println("=======" + acc + r)
r :: acc
}
done.onSuccess {
case e => {
e.foreach(println)
}
}
done.onComplete(_ => system.terminate())
*/
}
```
|
5,923,078 |
I need to add my own data type to a list which is in a function, here's my code:
```
type Car = (String, String, Int, String)
testDatabase :: [Car]
testDatabase = [("Ford", "Petrol", 2006, "Sport")]
addNewCar :: Car
addNewCar newCar = newCar:testDatabase
```
Here's the error I get:
```
ERROR file:.\template.hs:20 - Type error in explicitly typed binding
*** Term : addNewCar
*** Type : ([Char],[Char],Int,[Char]) -> [([Char],[Char],Int,[Char])]
*** Does not match : Car
```
(sorry its a rubbish explanation im just struggling a tad with Haskell). Thank you in advance!!
Ash!
|
2011/05/07
|
[
"https://Stackoverflow.com/questions/5923078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84546/"
] |
The inferred type of `addNewCar` is `([Char],[Char],Int,[Char]) -> [([Char],[Char],Int,[Char])`, which is the same as `Car -> [Car]`. This type says that `addNewCar` is a function which takes a car and returns a list of cars. This is exactly the type you want.
However your type signature says that `addNewCar` is simply a value of type `Car`. This is wrong and clashes with the inferred type. That's why you get the error. So to fix this, simply remove the type signature or change it to `addNewCar :: Car -> [Car]`.
|
You have a type error in your code. `addNewCar` is a function that takes a car and returns a list of cars, so it should have the type
```
addNewCar :: Car -> [Car]
```
You could also just remove the type signature, and the compiler will infer it automatically.
|
68,561,708 |
I'm trying to use Tesseract-OCR to get the readings on below images but having issues getting consistent results with the spotted background. I have below configuration on my pytesseract
`CONFIG = f"—psm 6 -c tessedit_char_whitelist=01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄabcdefghijklmnopqrstuvwxyzåäö.,-"`
I have also tried below image pre-processing with some good results, but still not perfect results
```py
blur = cv2.blur(img,(4,4))
(T, threshInv) = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
```
What I want is to consistently be able to identify the numbers and the decimal separator. What image pre-processing could help in getting consistent results on images as below?
[](https://i.stack.imgur.com/QhM4Q.jpg)
[](https://i.stack.imgur.com/Qylzp.jpg)
[](https://i.stack.imgur.com/dfymA.jpg)
[](https://i.stack.imgur.com/ejUJp.jpg)
[](https://i.stack.imgur.com/BMn5B.jpg)
[](https://i.stack.imgur.com/nNMLr.jpg)
[](https://i.stack.imgur.com/mkZ4l.jpg)
|
2021/07/28
|
[
"https://Stackoverflow.com/questions/68561708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10833061/"
] |
The problem is that `$newdir` contains `/` characters, so your `sed` command ends up looking like `s/'MyDir'//dir/to/my/file/g`, which won't work -- the first `/` effectively terminates your `sed` expression, and everything else is garbage.
Fortunately, `sed` let's you use *any* character as a delimiter to the `s` command, so you could write instead:
```
sed -i "s|'MyDir'|${newdir}|g" myconf.conf
```
|
One way to get around the "does my data contain the delimiter" problem is to use shell variable expansion to escape the delimiter character:
```sh
sed -i "s|'MyDir'|${newdir//|/\\|}|g" myconf.conf
```
Demo:
```sh
$ newdir="/a/dir/with|a/pipe"
$ sed "s|'MyDir'|${newdir}|g" <<< "this is 'MyDir' here"
sed: 1: "s|'MyDir'|/a/dir/with|a ...": bad flag in substitute command: 'a'
$ sed "s|'MyDir'|${newdir//|/\\|}|g" <<< "this is 'MyDir' here"
this is /a/dir/with|a/pipe here
```
You can do this with the default slash delimiter, with more escapes
```sh
sed -i "s/'MyDir'/${newdir//\//\\\/}/g" myconf.conf
```
|
66,197,785 |
In Google Sheets, from one sheet I am trying to lookup the game info for the next game based on a game schedule that is maintained on a second sheet. The game dates and times in the schedule are maintained in separate columns as displayed below.
For example, since it's now 11:55am on 2/14, I'm looking for a function that will return row # 8 based on the schedule below.
[Game Schedule](https://i.stack.imgur.com/CRkpr.png)
Thank you!
|
2021/02/14
|
[
"https://Stackoverflow.com/questions/66197785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5008312/"
] |
You can try
```
=ARRAYFORMULA(TRANSPOSE(
INDEX(Schedule!A3:C15, MATCH(NOW(),Schedule!A3:A15+Schedule!B3:B15,1)+1)
))
```
[](https://i.stack.imgur.com/cFfuT.png)
`MATCH` to assume that the range `A3:A16+B3:B16` is sorted in ascending order and return the largest value less than or equal to search\_key `NOW()`. We're using `ARRAYFORMULA` for corect summing `A3:A16+B3:B16` as row by row. The one is added to move the pointer of `INDEX` to the line below.
[My sample sheet](https://docs.google.com/spreadsheets/d/1vHs5nf2NRKd9qzXwEh9gba62OTvTg0VwBjwoc1c1eIs/edit?usp=sharing)
|
B2:
```
=TODAY()
```
B3:
```
=INDEX(SPLIT(NOW(), " "),,2)
```
B4:
```
=INDEX(INDIRECT("Schedule!"&ADDRESS(MATCH(B2+B3, Schedule!A1:A+Schedule!B1:B, 1)+1, 3)))
```
[](https://i.stack.imgur.com/D4gxq.png)
|
73,359,729 |
I have a dataframe which contains post and comments.
Every comment has an id and a parent id (identifies the comment or post which the comment was a response to).
Posts only have an id, since they don't answer to anything.
| submission | id | parent id |
| --- | --- | --- |
| post1 | 1 | |
| comment1 | 2 | 1 |
| comment2 | 3 | 1 |
| comment3 | 4 | 2 |
| comment4 | 5 | 4 |
| post2 | 6 | |
| comment5 | 7 | 6 |
I would like to retrieve the id of the original post for every comment and obtain something like that:
| submission | id | parent id | ancestor id |
| --- | --- | --- | --- |
| post1 | 1 | | |
| comment1 | 2 | 1 | 1 |
| comment2 | 3 | 1 | 1 |
| comment3 | 4 | 2 | 1 |
| comment4 | 5 | 4 | 1 |
| post2 | 6 | | |
| comment5 | 7 | 6 | 2 |
to do so I tried to loop from the end of the dataframe to the beginning, iteratively tracing back the parent\_id of the parent\_id until I found an empty parent\_id cell.
On the test dataframe it works, but on the main one is too slow. Is there a way to make it more efficient?
Here my original code:
```
#creating a column for the id of the original post
df["ancestor"] = df.id
#obtaining the id of the original post for every comment
for i in reversed(range(len(df.id))): #looping trough the comments
id = df["parent_id"][i] #variable to initialize the future loop
parent = id
while parent != "": #only looping trough comments
df.ancestor[i] = id
parent = df.parent_id[df.id == id].values[0]
id = parent
```
|
2022/08/15
|
[
"https://Stackoverflow.com/questions/73359729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18694315/"
] |
You can use placehoders on prepare statements, this is why we use them to prevent sql injection
One other thing never use column names as variables names, databases can not differentiate
```
DROP procedure IF EXISTS `sp_insurance_contract_get`;
DELIMITER $$
CREATE PROCEDURE `sp_insurance_contract_get` (enquiryCode_ VARCHAR(20), contractCode_ VARCHAR(20))
BEGIN
SET @t1 = "SELECT * FROM InsuranceContract
WHERE enquiryCode = ?
AND contractCode = ?;";
PREPARE param_stmt FROM @t1;
SET @a = enquiryCode_;
SET @b = contractCode_;
EXECUTE param_stmt USING @a, @b;
DEALLOCATE PREPARE param_stmt;
END$$
DELIMITER ;
```
|
When you say
```
WHERE enquiryCode = enquiryCode
```
you compare that named column to itself. The result is true always (unless the column value is NULL).
Change the names of your SP's parameters, so you can say something like
```
WHERE enquiryCode_param = enquiryCode
```
and things should work.
Notice that you have no need of a MySql "prepared statement" here. In the MySql / MariaDb world prepared statements are used for dynamic SQL. That's for constructing statements within the server from text strings. You don't need to do that here.
|
73,972,845 |
```
class Employee:
def __init__(self, name, salary, increment):
self.name = name
self.salary = salary
self.increment = increment
@property
def salaryafterIncre(self):
return self.salary * (1+self.increment)
@salaryafterIncre.setter
def salaryafterIncre(self):
self.salary = self.salary * (1+self.increment)
e1 = Employee("shubh", 10000, 0.1)
print(e1.salaryafterIncre)
e1.salaryafterIncre()
print(e1.salary)
```
|
2022/10/06
|
[
"https://Stackoverflow.com/questions/73972845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20174942/"
] |
What about
```java
@Configuration
public class Config {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ModelMapper modelMapper(final CurrencyConverterService currencyConverter) {
ModelMapper modelMapper = new ModelMapper();
...
}
...
}
```
when you create a bean you can pass other beans as parameter
|
Solution 1: use javax.inject.Provider
-------------------------------------
Assuming you are using Maven you can add the following dependency:
```xml
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
```
And then in CurrencyConverterService inject an instance of `javax.inject.Provider` of `RestTemplate`:
```java
import javax.inject.Provider;
...
@Service
@RequiredArgsConstructor
public class CurrencyConverterService {
...
private final Provider<RestTemplate> restTemplate;
```
And retrieve the instance with `restTemplate.get()`.
However this will still fail during runtime in case of circular usage.
Solution 2: resolve cyclic dependency
-------------------------------------
Assuming you do *not* need the `CurrencyConverterService` for constructing `RestTemplate` the more stable solution is to create a second class producing the `RestTemaplate` (you can have as many classes annotated with `@Configuration` or `@Component` as you want):
```java
@Configuration
public class RestTemplateProducer {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
```
|
73,972,845 |
```
class Employee:
def __init__(self, name, salary, increment):
self.name = name
self.salary = salary
self.increment = increment
@property
def salaryafterIncre(self):
return self.salary * (1+self.increment)
@salaryafterIncre.setter
def salaryafterIncre(self):
self.salary = self.salary * (1+self.increment)
e1 = Employee("shubh", 10000, 0.1)
print(e1.salaryafterIncre)
e1.salaryafterIncre()
print(e1.salary)
```
|
2022/10/06
|
[
"https://Stackoverflow.com/questions/73972845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20174942/"
] |
What about
```java
@Configuration
public class Config {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ModelMapper modelMapper(final CurrencyConverterService currencyConverter) {
ModelMapper modelMapper = new ModelMapper();
...
}
...
}
```
when you create a bean you can pass other beans as parameter
|
You can write @Lazy at the top of the @Autowired in of the class where you are injecting dependencies.
As that will break the cycle.
However you have to write it on the top of @Autowired
|
57,323,676 |
I'm adding new UIWindow to show passcode view controller when the app is entering foreground.
Before iOS 13 in AppDelegate I had property `var passcodeWindow = UIWindow(frame: UIScreen.main.bounds)` where my `rootViewController` was the passcode view controller and in `applicationWillEnterForeground` method I was doing `passcodeWindow.makeKeyAndVisible()` to place it on the top.
Now when I want to implement the passcode functionality in iOS 13 there is a problem with this approach. I moved it to the `sceneWillEnterForeground` method in SceneDelegate, but it seems like I can't show `passcodeWindow` on top of the actual window in this scene.
I do it exactly the same as in AppDelegate and the `passcodeWindow` is not shown.
The way I do it in `sceneWillEnterForeground` in AppDelegate and in SceneDelegate:
```
passcodeWindow.rootViewController = passcodeViewController(type: .unlock)
passcodeWindow.makeKeyAndVisible()
```
I expect `passcodeWindow` to show on the top of current window in the scene.
|
2019/08/02
|
[
"https://Stackoverflow.com/questions/57323676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7661368/"
] |
You can try this:
```
if #available(iOS 13.0, *) {
if let currentWindowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
passcodeWindow.windowScene = currentWindowScene
}
}
```
|
You need a strong reference for your UIWindow instance, and the most important thing is that you need to set "isHidden" property false.
```
newWindow = UIWindow.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
newWindow?.backgroundColor = UIColor.systemBlue
newWindow?.windowScene = (scene as? UIWindowScene)
newWindow?.isHidden = false
```
|
19,612,822 |
I know that there are different ways to do this, but I just want to know why my regex isn't working. This isn't actually something that I need to do, I just wanted to see if I could do this with a regex, and I have no idea why my code isn't working.
Given a string S, I want to find all non-overlapping substrings that contain a subsequence Q that obeys certain rules. Now, let's suppose that I am searching for the subsequence `"abc"`. I want to match a substring of S that contains `'a'` followed at some point by `'b'` followed at some point by `'c'` with the restriction that no `'a'` follows `'a'`, and no `'a'` or `'b'` follows `'b'`. The regex I am using is as follows (in python):
```
regex = re.compile(r'a[^a]*?b[^ab]*?c')
match = re.finditer(regex, string)
for m in match:
print m.group(0)
```
To me this breaks down and reads as follows:
`a[^a]*?b`: `'a'` followed the smallest # of characters not including `'a'` and terminating with a `'b'`
`[^ab]*?c`: the smallest # of characters not including `'a'` or `'b'` and terminating with a `'c'`
So putting this all together, I assumed that I would match non-overlapping substrings of S that contain the subsequence "abc" that obeys my rules of exclusion.
This **works fine** for something like:
`S = "aqwertybwertcaabcc"`, which gives me `"aqwertybwertc"` and `"abc"`,
but it **fails** to work for `S = "abbc"`, as in it matches to `"abbc"`.
|
2013/10/26
|
[
"https://Stackoverflow.com/questions/19612822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2073001/"
] |
Assuming what you actually want is for the subsequence Q to contain no `a`s between the first `a` and the first `b` and no `a`s or `b`s between the first `b` and the first `c` after the first `b`, the correct regex to use is:
```
r'a[^ab]*b[^abc]*c'
```
The regex that you're currently using will do everything that it can to succeed on a string, including matching the literal `b` to a `b` after the first `b`, which is why `"abbc"` is matched. Only by specifically excluding `b` in the first character class can this be avoided and the `b` be made to match only the first `b` after the `a`.
|
It could help if you look at the inverse class.
In all cases `abc` is the trivial solution.
And, in this case non-greedy probably doesn't apply because
there are fixed sets of characters used in the example inverse classes.
```
# Type 1 :
# ( b or c can be between A,B )
# ( a or b can be between B,C )
# ------------------------------
a # 'a'
[b-z]*? # [^a]
b # 'b'
[abd-z]*? # [^c]
c # 'c'
# Type 2, yours :
# ( b or c can be between A,B )
# ( c can be between B,C )
# ------------------------------
a # 'a'
[b-z]*? # [^a]
b # 'b'
[c-z]*? # [^ab]
c # 'c'
# Type 3 :
# ( c can be between A,B )
# ------------------------------
a # 'a'
[c-z]*? # [^ab]
b # 'b'
[d-z]*? # [^abc]
c # 'c'
# Type 4 :
# ( distinct A,B,C ) :
# ------------------------------
a # 'a'
[d-z]*? # [^abc]
b # 'b'
[d-z]*? # [^abc]
c # 'c'
```
|
44,144 |
I wonder what the following violin technique is called it happens in the following video at ar 4;50. It seems that it is some sort of slapping motion with the bow and also something that resembles pull offs.
|
2016/05/04
|
[
"https://music.stackexchange.com/questions/44144",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/7306/"
] |
Looks to me like the player is interspersing conventionally bowed notes with left-hand pizzicato notes. This is similar to the pull-off (*ligado*) technique on guitar, but has a quite different sound.
I only watched the clip once, but it appears that the passages that combine bowed and L.H. pizzicato are executed as follows: a note is fingered with the little finger on the L.H. and bowed conventionally; then, the L.H. little finger plucks the string it is on, sounding a note fingered by another L.H. finger, which then plucks the string again, sounding either another fingered note or an open string. This is then repeated on different strings.
Of course, this is all executed very rapidly, giving a unique sound not achievable using a conventional pizzicato.
There are violin techniques that involve "slapping" the bow against the strings, but I can't see them in the passage you give the time of. These techniques include:
* *spiccato*, where the bow bounces on the string.
* *col legno battuto*, where the wooden side of the bow is "tapped" against the string.
|
It's a combination of spiccato bowing (bouncing the bow off the strings) alternating with left-hand pizzicato.
Of course the *real* Paganini did this sort of party trick having slashed three of the violin strings with a knife, and then holding the violin upside down, if some of the stories about him are to be believed.
|
44,144 |
I wonder what the following violin technique is called it happens in the following video at ar 4;50. It seems that it is some sort of slapping motion with the bow and also something that resembles pull offs.
|
2016/05/04
|
[
"https://music.stackexchange.com/questions/44144",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/7306/"
] |
Looks to me like the player is interspersing conventionally bowed notes with left-hand pizzicato notes. This is similar to the pull-off (*ligado*) technique on guitar, but has a quite different sound.
I only watched the clip once, but it appears that the passages that combine bowed and L.H. pizzicato are executed as follows: a note is fingered with the little finger on the L.H. and bowed conventionally; then, the L.H. little finger plucks the string it is on, sounding a note fingered by another L.H. finger, which then plucks the string again, sounding either another fingered note or an open string. This is then repeated on different strings.
Of course, this is all executed very rapidly, giving a unique sound not achievable using a conventional pizzicato.
There are violin techniques that involve "slapping" the bow against the strings, but I can't see them in the passage you give the time of. These techniques include:
* *spiccato*, where the bow bounces on the string.
* *col legno battuto*, where the wooden side of the bow is "tapped" against the string.
|
While I didn't notice the col legno battuto anywhere the rest of the above information is correct. Also noteworthy is the incorporation of ricochet bowing in the phrasing of the beginning of this piece. The spiccato that appears in other parts of the piece you will notice uses the middle and lower half of the bow. The spiccato used to facilitate and shape the left hand pizzicato motives uses the upper fourth of the bow helping to match its attack and dynamics with the relatively weak sound produced by left hand pizz on the violin. While the stronger spiccato allowed the bow to draw more life for each note the upper bow spiccato resulted in little slaps with the end of the bow breathing just enough life into the string for the left hand technique to continue the phrase and manage the wave in the string.
|
125,050 |
I like to add users to an [OG group](https://www.drupal.org/project/og) using [vbo](https://www.drupal.org/project/views_bulk_operations), a custom action and [og\_group()](http://drupalcontrib.org/api/drupal/contributions!og!og.module/function/og_group/7).
I build up a page with a [view](https://www.drupal.org/project/views) of users to add (/node/%nid/add\_user).
On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).
In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)
So here is my code to subscribe the user to the group:
```
function mymodule_vbo_actions_users_woform(&$user_node, $context) {
global $user;
//dpm($node); dpm($context);return;
switch ($context['settings']['action_type']) {
case 'add_user_to_group':
$nid_page = menu_get_object();
if (!isset($nid_page)) $nid_page = arg(1);
$nid_page = $context['page_nid'];
$account = user_load($user_node->uid);
//dpm($nid_page);
$node_page = node_load($nid_page);
dpm($user_node);
dpm($account);
dpm($node_page);
$aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
$og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
$og_membership->save();
dpm($og_membership);
// get member roles id for selected group bundle
$result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
$role_id = NULL;
foreach ($result_roles as $key_roles => $value_roles) {
$role_id = $value_roles->rid;
break;
}
dpm($role_id);
og_role_grant('node',$node_page->nid,$account->uid,$role_id);
break;
}
}
```
This code seems to be correct. I watched the `og_membership` table and the record for the selected user is inserted, but then DELETED immediately!?
So the question is of course: Why is the record deleted?
|
2014/07/29
|
[
"https://drupal.stackexchange.com/questions/125050",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/23004/"
] |
I would use a db\_query to find all nodes that that field appears on and then update them with a node\_load here is the code:
```
$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
$node = node_load($record->entity_id);
// update node
}
```
|
You can either do it programmatically or using views.
Using Views : Create a view page and under the fields section add the following fields:
Node id and the specific field you would like to update.
Update the filter condition as follows:
Node type = 'YOUR NODE TYPE'
AND
"Your required field" = NOT NULL
The output of this view will be the node ids of all those node which will be having a values assigned to the specific field.
If this didn't helped you, please let me know, will solve it in a different way
Thanks
|
125,050 |
I like to add users to an [OG group](https://www.drupal.org/project/og) using [vbo](https://www.drupal.org/project/views_bulk_operations), a custom action and [og\_group()](http://drupalcontrib.org/api/drupal/contributions!og!og.module/function/og_group/7).
I build up a page with a [view](https://www.drupal.org/project/views) of users to add (/node/%nid/add\_user).
On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).
In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)
So here is my code to subscribe the user to the group:
```
function mymodule_vbo_actions_users_woform(&$user_node, $context) {
global $user;
//dpm($node); dpm($context);return;
switch ($context['settings']['action_type']) {
case 'add_user_to_group':
$nid_page = menu_get_object();
if (!isset($nid_page)) $nid_page = arg(1);
$nid_page = $context['page_nid'];
$account = user_load($user_node->uid);
//dpm($nid_page);
$node_page = node_load($nid_page);
dpm($user_node);
dpm($account);
dpm($node_page);
$aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
$og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
$og_membership->save();
dpm($og_membership);
// get member roles id for selected group bundle
$result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
$role_id = NULL;
foreach ($result_roles as $key_roles => $value_roles) {
$role_id = $value_roles->rid;
break;
}
dpm($role_id);
og_role_grant('node',$node_page->nid,$account->uid,$role_id);
break;
}
}
```
This code seems to be correct. I watched the `og_membership` table and the record for the selected user is inserted, but then DELETED immediately!?
So the question is of course: Why is the record deleted?
|
2014/07/29
|
[
"https://drupal.stackexchange.com/questions/125050",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/23004/"
] |
I would use a db\_query to find all nodes that that field appears on and then update them with a node\_load here is the code:
```
$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
$node = node_load($record->entity_id);
// update node
}
```
|
```
$nid = 1;
$thefield = db_select('field_data_field_thefield', 'f');
->fields('f',array('entity_id'))
->condition('f.entity_id', $nid, '=');
->execute()
->fetchField();
if($thefield){
Do Something...
}
```
You could use a db\_query instead of db\_select to make it even quicker
|
125,050 |
I like to add users to an [OG group](https://www.drupal.org/project/og) using [vbo](https://www.drupal.org/project/views_bulk_operations), a custom action and [og\_group()](http://drupalcontrib.org/api/drupal/contributions!og!og.module/function/og_group/7).
I build up a page with a [view](https://www.drupal.org/project/views) of users to add (/node/%nid/add\_user).
On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).
In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)
So here is my code to subscribe the user to the group:
```
function mymodule_vbo_actions_users_woform(&$user_node, $context) {
global $user;
//dpm($node); dpm($context);return;
switch ($context['settings']['action_type']) {
case 'add_user_to_group':
$nid_page = menu_get_object();
if (!isset($nid_page)) $nid_page = arg(1);
$nid_page = $context['page_nid'];
$account = user_load($user_node->uid);
//dpm($nid_page);
$node_page = node_load($nid_page);
dpm($user_node);
dpm($account);
dpm($node_page);
$aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
$og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
$og_membership->save();
dpm($og_membership);
// get member roles id for selected group bundle
$result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
$role_id = NULL;
foreach ($result_roles as $key_roles => $value_roles) {
$role_id = $value_roles->rid;
break;
}
dpm($role_id);
og_role_grant('node',$node_page->nid,$account->uid,$role_id);
break;
}
}
```
This code seems to be correct. I watched the `og_membership` table and the record for the selected user is inserted, but then DELETED immediately!?
So the question is of course: Why is the record deleted?
|
2014/07/29
|
[
"https://drupal.stackexchange.com/questions/125050",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/23004/"
] |
I would use a db\_query to find all nodes that that field appears on and then update them with a node\_load here is the code:
```
$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
$node = node_load($record->entity_id);
// update node
}
```
|
If you want to update any field in node , then better to use `node_load()` function.
Because if you use any custom **select** or **update** query then
* first thing you need to update it in all the tables (main and revision tables).
* Second thing, drupal events will not trigger that is attached with updation.
If you still want to do it manually by `db_select()` and `db_query()`
Hope it will help!
|
125,050 |
I like to add users to an [OG group](https://www.drupal.org/project/og) using [vbo](https://www.drupal.org/project/views_bulk_operations), a custom action and [og\_group()](http://drupalcontrib.org/api/drupal/contributions!og!og.module/function/og_group/7).
I build up a page with a [view](https://www.drupal.org/project/views) of users to add (/node/%nid/add\_user).
On this view I added a views bulk operations field with the "skip batch" option. (I skipped the batch to get the current %nid from the url).
In the custom code I like to add the selected user to the page shown. I know I can do this also with the standard group forms, but I want to do it this way :-)
So here is my code to subscribe the user to the group:
```
function mymodule_vbo_actions_users_woform(&$user_node, $context) {
global $user;
//dpm($node); dpm($context);return;
switch ($context['settings']['action_type']) {
case 'add_user_to_group':
$nid_page = menu_get_object();
if (!isset($nid_page)) $nid_page = arg(1);
$nid_page = $context['page_nid'];
$account = user_load($user_node->uid);
//dpm($nid_page);
$node_page = node_load($nid_page);
dpm($user_node);
dpm($account);
dpm($node_page);
$aValues = array('entity_type'=>'user','entity'=>$account,'membership type' => 'OG_MEMBERSHIP_TYPE_DEFAULT',);
$og_membership = og_group('node',$node_page->nid,$aValues,FALSE);
$og_membership->save();
dpm($og_membership);
// get member roles id for selected group bundle
$result_roles = db_query("SELECT rid FROM og_role o where group_bundle = :bundle and name=:name and gid=:gid;",array(':bundle'=>$node_page->type,':name'=>'bidder', ':gid'=>$node_page->nid));
$role_id = NULL;
foreach ($result_roles as $key_roles => $value_roles) {
$role_id = $value_roles->rid;
break;
}
dpm($role_id);
og_role_grant('node',$node_page->nid,$account->uid,$role_id);
break;
}
}
```
This code seems to be correct. I watched the `og_membership` table and the record for the selected user is inserted, but then DELETED immediately!?
So the question is of course: Why is the record deleted?
|
2014/07/29
|
[
"https://drupal.stackexchange.com/questions/125050",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/23004/"
] |
I would use a db\_query to find all nodes that that field appears on and then update them with a node\_load here is the code:
```
$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
$node = node_load($record->entity_id);
// update node
}
```
|
The field API allows you to load/attach just one field in a list of entities with [`field_attach_load()`](https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_load/7). This approach is field storage agnostic, invokes field-level hooks, and reads from the field cache if possible.
|
70,682,557 |
I'm trying to display a static image located in the same folder as my Html file but it seems I can't get the right path for it to display correctly. The application I'm developing is an atlassian plugin that also includes a java backend to get Data from the Database and I'm displaying it on the frontend using HTML and javascript, the whole application runs on a webserver as a Plugin. Both the image and the Html file are located in here: `D:\clone4\project\src\main\resources\templates\scheduleraction`
The URL path for the web application is:
`https://staging.com/jira/secure/SchedulerAction!default.jspa`
I tried many ways and this is the last one :
`<img src="/SchedulerAction!default.jspa/piechart.jpg" alt="pie-chart">`
I need to add the correct path in the "src" so the client can retrieve the image from my Files on the webserver. I would love any hint or help!
[](https://i.stack.imgur.com/kdOj9.png)
|
2022/01/12
|
[
"https://Stackoverflow.com/questions/70682557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12995281/"
] |
```
s=df.mask((df-df.apply(lambda x: x.std() )).gt(5))#mask where condition applies
s=s.assign(A=s.A.fillna(s.A.max()),B=s.B.fillna(s.B.max())).sort_index(axis = 0)#fill with max per column and resort frame
A B
0 1.0 2.0
1 1.0 6.0
2 2.0 8.0
3 1.0 8.0
4 2.0 1.0
```
|
Calculate a column-wise z-score (if you deem something an outlier if it lies outside a given number of standard deviations of the column) and then calculate a boolean mask of values outside your desired range
```
def calc_zscore(col):
return (col - col.mean()) / col.std()
zscores = df.apply(calc_zscore, axis=0)
outlier_mask = zscores > 5
```
After that it's up to you to fill the values marked with the boolean mask.
```
df[outlier_mask] = something
```
|
70,682,557 |
I'm trying to display a static image located in the same folder as my Html file but it seems I can't get the right path for it to display correctly. The application I'm developing is an atlassian plugin that also includes a java backend to get Data from the Database and I'm displaying it on the frontend using HTML and javascript, the whole application runs on a webserver as a Plugin. Both the image and the Html file are located in here: `D:\clone4\project\src\main\resources\templates\scheduleraction`
The URL path for the web application is:
`https://staging.com/jira/secure/SchedulerAction!default.jspa`
I tried many ways and this is the last one :
`<img src="/SchedulerAction!default.jspa/piechart.jpg" alt="pie-chart">`
I need to add the correct path in the "src" so the client can retrieve the image from my Files on the webserver. I would love any hint or help!
[](https://i.stack.imgur.com/kdOj9.png)
|
2022/01/12
|
[
"https://Stackoverflow.com/questions/70682557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12995281/"
] |
```
s=df.mask((df-df.apply(lambda x: x.std() )).gt(5))#mask where condition applies
s=s.assign(A=s.A.fillna(s.A.max()),B=s.B.fillna(s.B.max())).sort_index(axis = 0)#fill with max per column and resort frame
A B
0 1.0 2.0
1 1.0 6.0
2 2.0 8.0
3 1.0 8.0
4 2.0 1.0
```
|
Per the discussion in the comments you need to decide what your threshold is. say it is q=100, then you can do
```
q = 100
df.loc[df['A'] > q,'A'] = max(df.loc[df['A'] < q,'A'] )
df
```
this fixes column A:
```
A B
0 1 2
1 1 6
2 2 8
3 1 115
4 2 1
```
do the same for B
|
53,455 |
I'm running Raspbian Jessie on my Raspberry Pi 3 and I'm doing a little house alarm project. When the alarm is activated the Pi should transmit FM signal of an alarm sound on a frequency that a few radios in the house will be tuned at. The program I use for transmiting FM is [here](http://www.icrobotics.co.uk/wiki/index.php/Turning_the_Raspberry_Pi_Into_an_FM_Transmitter) and it uses PWM (on GPIO 4) to transmit FM.
Transmiting audio works as expected but the problem is present on my LCD 16x2 display (it's connected to I2C). Whenever I run the LCD and transmit in the same time the LCD starts displaying gibberish (first couple of times it even raised an I/O Error 5, but I can't reproduce it anymore). All other functions of the alarm such as arming, disarming or disabling the siren are working as expected while transmiting.
The reason I think PWM conflicts with I2C is because on [this post](https://raspberrypi.stackexchange.com/questions/45567/rpio-pwm-causes-i2c-to-stop-working-solved?newreg=81767faa3cbf4c98be97db90e4f9b8e4) an I2C clock is mentioned, it's on GPIO 3, but that still makes me believe there are more I2C connections between the pins (even though I didn't find them in [this reference](http://elinux.org/RPi_Low-level_peripherals))
---
**The question:**
How would I use the I2C LCD and transmit FM using the PWM method in the same time?
---
Extra tehnical info:
* LCD is I2C LCD1602 from [this kit](http://rads.stackoverflow.com/amzn/click/B014PF05ZA)
* LCD module source can be found [here](https://github.com/sunfounder/SunFounder_SensorKit_for_RPi2/blob/master/Python/LCD1602.py). It's rather high level so it's simpler for me and my week of experience with a Raspberry Pi.
* Last time the I/O Error was raised was at the `BUS.write_byte` function in the LCD module source (can't remember what line, the error doesn't occur anymore but is surely linked with the LCD problem)
---
**EDIT:**
The Error 5 happened again (file at the github link above):
```
Traceback (most recent call last):
File "alarm.py", line 432, in <module>
setup()
File "alarm.py", line 133, in setup
LCD1602.clear()
File "/home/pi/alarm/LCD1602.py", line 75, in clear
send_command(0x01) # Clear Screen
File "/home/pi/alarm/LCD1602.py", line 21, in send_command
write_word(LCD_ADDR ,buf)
File "/home/pi/alarm/LCD1602.py", line 15, in write_word
BUS.write_byte(addr ,temp)
IOError: [Errno 5] Input/output error
```
---
**EDIT 2:**
[](https://i.stack.imgur.com/js8SO.jpg)
[](https://i.stack.imgur.com/inN1m.jpg)
[](https://i.stack.imgur.com/hvQ3w.jpg)
There are the pictures. I don't think anything is incorrectly connected. (Sorry about the pictures being blurry, I don't have a good camera)
|
2016/08/13
|
[
"https://raspberrypi.stackexchange.com/questions/53455",
"https://raspberrypi.stackexchange.com",
"https://raspberrypi.stackexchange.com/users/51879/"
] |
PWM should not conflict with I2C.
Everything below presumes the (predominant) Broadcom pin numbering scheme, which does not correlate to the physical arrangement of the pins.
I've never used GPIO 4 for PWM; the normal PWM pins used are 12, 13, 18, and 19, making use of two separate PWM channels derived from one clock.
Have a look at the [chart here](http://elinux.org/RPi_BCM2835_GPIOs#GPIO0). Note that the crossed out pins simply indicate those which aren't available on 26-pin models. Although it contains additional information, the parts we are concerned with here are pretty much lifted directly from section 6.2 of the [BCM2835 Peripherals datasheet](https://www.raspberrypi.org/documentation/hardware/raspberrypi/bcm2835/BCM2835-ARM-Peripherals.pdf), so they are authoritative.
Notice that the normal PWM pins I've referred to have as either their default, or include as an ALT function, PWM0 or PWM1; this refers to the two channels just mentioned. The default purpose of one of them, pin 18, is access to the PCM clock, which is used for the timing of digital audio but may be turned to other purposes.
Pin 4, which you have said you are using, is not connected to any of the above. Instead, it uses "general purpose clock 0". However, I can't fine any reason to believe this affects the I2C clock, and looking around at documentation for libraries which can make use of general purpose clock 0 via GPIO 4 and the I2C bus, there is no indication that this should be problematic.
Put another way, it sounds like you have a eccentric issue. Whether this is due to a mistake in your code or connections, some physical defect in something, or the code written by someone else you are making use of (e.g., for the FM transmission) is impossible to say, but there is thus is **no meaningful answer to your question** because the problem you have is *not reproducible in the general sense* -- the "general sense" being that if you want to use PWM and I2C simultaneously there is not a problem and the "how to do it" is to just do it.
|
You can also create aditional i2c busses on the raspberry pi to solve i2c conflicts
<https://www.instructables.com/id/Raspberry-PI-Multiple-I2c-Devices/>
|
19,717,124 |
I have this enumeration:
```
Enum Lame_Bitrate
kbps_8 = 8
kbps_16 = 16
kbps_24 = 24
kbps_32 = 32
kbps_40 = 40
kbps_48 = 48
kbps_56 = 56
kbps_64 = 64
kbps_80 = 80
kbps_96 = 96
kbps_112 = 112
kbps_128 = 128
kbps_144 = 144
kbps_160 = 160
kbps_192 = 192
kbps_224 = 224
kbps_256 = 256
kbps_320 = 320
End Enum
```
And I would like to return the approximated value of the Enum given a number.
For example, if I have the number `190` then I expect to find the more approximated value in the Enum to return the `192` (kbps\_192 value of the Enum), if I have the number `196` then again I expect to return the value `192` (not return the next value `224` because is less approximated).
Something like this:
```
Private Sub Test()
Dim wma_file As String = "C:\windows media audio file.wma"
Dim wma_file_Bitrate As Integer = 172
Dim mp3_bitrate_approximated As Integer
mp3_bitrate_approximated = Return_Approximated_Value_Of_Enum(wma_file_Bitrate)
End Sub
private function Return_Approximated_Value_Of_Enum(byval value as integer) as integer
return... enum.find(value).approximated...
end function
```
Exist any framework method to find the more approximated number given other number in a Enum?
I hope you can understand my question, thank you.
PS: I prefer a solution using LINQ extensions if can be.
|
2013/10/31
|
[
"https://Stackoverflow.com/questions/19717124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1248295/"
] |
If you want to find the nearest enum:
```
Dim number = 190
Dim allBitrates() As Lame_Bitrate = DirectCast([Enum].GetValues(GetType(Lame_Bitrate)), Lame_Bitrate())
Dim nearestBitrate = allBitrates.OrderBy(Function(br) Math.Abs(number - br)).First()
```
If you want to find all nearest enums (in case of multiple with the same min-distance):
```
number = 120 ' two with the same distance
Dim nearestBitrates As IEnumerable(Of Lame_Bitrate) = allBitrates.
GroupBy(Function(br) Math.Abs(number - br)).
OrderBy(Function(grp) grp.Key).
First()
Console.Write(String.Join(",", nearestBitrates))
```
Output:
```
kbps_112,kbps_128
```
|
I've adapted @Tim Schmelter solution and I've did 3 generic functions.
Just I want to share this.
· Get Nearest Enum Value:
```
' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
' MsgBox(Get_Nearest_Enum_Value(Of Bitrate)(133).ToString) ' Result: kbps_128
' MsgBox(Get_Nearest_Enum_Value(Of KnownColor)(1000)) ' Result: 174
Private Function Get_Nearest_Enum_Value(Of T)(ByVal value As Long) As T
Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)) _
.Cast(Of Object) _
.OrderBy(Function(br) Math.Abs(value - br)) _
.First)
End Function
```
· Get Nearest Lower Enum Value:
```
' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
' MsgBox(Get_Nearest_Lower_Enum_Value(Of Bitrate)(190).ToString) ' Result: kbps_128
' MsgBox(Get_Nearest_Lower_Enum_Value(Of Bitrate)(196).ToString) ' Result: kbps_192
Private Function Get_Nearest_Lower_Enum_Value(Of T)(ByVal value As Integer) As T
Select Case value
Case Is < [Enum].GetValues(GetType(T)).Cast(Of Object).First
Return Nothing
Case Else
Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)) _
.Cast(Of Object) _
.Where(Function(enum_value) enum_value <= value) _
.Last)
End Select
End Function
```
· Get Nearest Higher Enum Value:
```
' Enum Bitrate As Short : kbps_128 = 128 : kbps_192 = 192 : kbps_256 = 256 : kbps_320 = 320 : End Enum
' MsgBox(Get_Nearest_Higher_Enum_Value(Of Bitrate)(196).ToString) ' Result: kbps_256
' MsgBox(Get_Nearest_Higher_Enum_Value(Of KnownColor)(1000)) ' Result: 0
Private Function Get_Nearest_Higher_Enum_Value(Of T)(ByVal value As Integer) As T
Select Case value
Case Is > [Enum].GetValues(GetType(T)).Cast(Of Object).Last
Return Nothing
Case Else
Return [Enum].Parse(GetType(T), [Enum].GetValues(GetType(T)) _
.Cast(Of Object) _
.Where(Function(enum_value) enum_value >= value) _
.First)
End Select
End Function
```
|
4,094,297 |
How can I find the limit of series $\sum\_{k=1}^{n-1} \frac{1}{nk}$?
I need to show that this series converges to $0$ as $n\to \infty$ in order to prove that the Cauchy Product of two non-absolutely convergent series can converge. I multiplied $\sum a\_k=\sum \frac{(-1)^k}{k}$, where $a\_0=0,$ by itself. And I got $b\_n=\sum\_{k=1}^{n}a\_{n-k} \cdot a\_k= \frac{2 \cdot (-1)^n}{n} \cdot \sum\_{k=1}^{n-1} \frac{1}{k}$. My plan is proving that $\sum b\_n$ is convergent by Leibniz Criterion. However I could not do anything in order to prove as $n \to \infty$ $\sum\_{k=1}^{n-1} \frac{1}{nk} \to 0$ . I would be glad if someone point out what should I do.
EDIT: I guess I've proved without using any "too strong" theorem or tool.
Let us say $c\_n = \sum\_{k=1}^{n-1} \frac{1}{nk}= \frac{1}{n} \cdot [\frac{1}{1}+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}+\frac{1}{5}+\frac{1}{6}+\frac{1}{7}+\frac{1}{8}+ \ldots +\frac{1}{n-1}]$.
Then there exist $l \in \mathbb{N}$ such that $2^{l}<n-1$, but $2^{l+1} \ge n-1$.
Thus, $c\_n< \frac{1}{n} \cdot [\frac{1}{1}+\frac{1}{2}+\frac{1}{2}+\frac{1}{4}+\frac{1}{4}+\frac{1}{4}+\frac{1}{4}+ \ldots +\frac{1}{2^l}+\frac{1}{2^l}+ \ldots+\frac{1}{2^l}]$, where there are $2^l$ many $\frac{1}{2^l}$ terms.
Hence, $c\_n < \frac{1}{n} \cdot(l+1)$. Moreover since $2^l<n-1$, we have $l<\log\_{2}{(n-1)}$.
Thus, $c\_n<\frac{1}{n} \cdot(1+\log\_{2}{(n-1)})$. If we consider $0<c\_n$ for any $n\in \mathbb{N}$ and use the associated funciton of $\frac{(1+\log\_{2}{(n-1)})}{n}$ we get; $0 \le c\_n \le \frac{(1+\log\_{2}{(x-1)})}{x}$. After that taking the limit as $x \to \infty$ we can easily see $c\_n \to 0$, by using L'Hospital rule and squeeze theorem.
|
2021/04/08
|
[
"https://math.stackexchange.com/questions/4094297",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/746652/"
] |
Let $S\_n=\sum\_{k=1}^{n-1}\frac1k$. By [Stolz's formula](https://en.wikipedia.org/wiki/Stolz%E2%80%93Ces%C3%A0ro_theorem)($\cdot/\infty$ case),
$$\lim\_{n\to\infty}\frac{S\_n}n=\lim\_{n\to\infty}\frac{S\_{n+1}-S\_{n}}{(n+1)-n}=\lim\_{n\to\infty}\frac1n=0.$$
|
**Hint**
$$\sum\_{k=1}^{n-1} \frac{1}{nk}=\frac{1}{n}\sum\_{k=1}^{n-1} \frac{1}{k}=\frac{H\_{n-1}}{n}$$
Now, use the asymptotics
$$H\_p=\gamma+\log(p)+\frac 1{2p}+O\left(\frac{1}{p^2}\right)$$ and continue with Taylor series.
|
1,596,611 |
I am working on preparing for JEE and was working on this math problem.
We have the sum, $$\sum\_{n=1}^{120}n!=1!+2!+3!+\ldots+120!$$
Now I am given the question, which says that what happens when this sum is divided by $120$. Does it divide evenly? If not, then what is its remainder?
|
2016/01/02
|
[
"https://math.stackexchange.com/questions/1596611",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/302159/"
] |
Note that $5!=120$, and all terms after $n=5$ are also divisible by $120$. Therefore, we can conclude that $120$ does not divide evenly and our remainder is the sum of the terms before $n=5$: $$\sum\_{n=1}^4{n!}=1!+2!+3!+4!=33$$
|
Since every term after the first one is even, the whole sum is odd. But $120$ is even, hence it does not divide the sum.
|
22,975,258 |
```
mysql> USE bitcoin;
Database changed
mysql> CREATE TABLE btc ( uuid VARCHAR(36) NOT NULL, ign VARCHAR(20) NOT NULL, btc DOUBLE(30) NOT NULL, ) ENGINE=InnoDB;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') NOT NULL, ) ENGINE=InnoDB' at line 1
mysql> CREATE TABLE btc ( uuid VARCHAR(36) NOT NULL, ign VARCHAR(20) NOT NULL, btc DOUBLE(30) NOT NULL, );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') NOT NULL, )' at line 1
mysql> CREATE TABLE btc ( uuid VARCHAR(36) NOT NULL, ign VARCHAR(20) NOT NULL, btc DOUBLE(30) NOT NULL, );
```
This error is being thrown when using MYSQL Command Line on Debian. I am trying to create a table with the given values.
```
mysql> CREATE TABLE btc ( uuid VARCHAR(36) NOT NULL, ign VARCHAR(20) NOT NULL, btc DOUBLE(30) NOT NULL);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') NOT NULL)' at line 1
mysql>
```
Doesnt work either.
|
2014/04/09
|
[
"https://Stackoverflow.com/questions/22975258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123121/"
] |
The issue was with the hash formatting. I changed it:
```
sign_in_and_redirect(:user, authentication.user.user_id)
```
and that solved it.
|
Change
```
sign_in_and_redirect(:user, authentication.user)
```
To
```
sign_in_and_redirect(authentication.user)
```
|
30,782,662 |
This is allowed by the Java compiler, what is it doing?
```
int x = x = 1;
```
I realize that x is assigned to x, but how can it have two `=`s?
|
2015/06/11
|
[
"https://Stackoverflow.com/questions/30782662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171100/"
] |
x = 1 both assigns the value 1 to x and also 'returns' 1, it allows for things like this:
```
while ((line = reader.readLine()) != null)
```
|
`int x` puts `x` on the stack.
The right hand part `x = 1` assigns 1 to `x`. But this is an *expression* with value 1.
Finally this is re-assigned to `x`.
|
30,782,662 |
This is allowed by the Java compiler, what is it doing?
```
int x = x = 1;
```
I realize that x is assigned to x, but how can it have two `=`s?
|
2015/06/11
|
[
"https://Stackoverflow.com/questions/30782662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171100/"
] |
x = 1 both assigns the value 1 to x and also 'returns' 1, it allows for things like this:
```
while ((line = reader.readLine()) != null)
```
|
Read assignment statement from right to left:
Acording to [Assignment Operators](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26)
>
> There are 12 assignment operators; all are syntactically
> right-associative (they group right-to-left). Thus, a=b=c means
> a=(b=c), which assigns the value of c to b and then assigns the value
> of b to a.
>
>
>
So,
```
int x = x = 1;
```
is the same as
```
x = (x = 1);
```
then
```
x = 1; x = x;
```
|
30,782,662 |
This is allowed by the Java compiler, what is it doing?
```
int x = x = 1;
```
I realize that x is assigned to x, but how can it have two `=`s?
|
2015/06/11
|
[
"https://Stackoverflow.com/questions/30782662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171100/"
] |
Read assignment statement from right to left:
Acording to [Assignment Operators](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26)
>
> There are 12 assignment operators; all are syntactically
> right-associative (they group right-to-left). Thus, a=b=c means
> a=(b=c), which assigns the value of c to b and then assigns the value
> of b to a.
>
>
>
So,
```
int x = x = 1;
```
is the same as
```
x = (x = 1);
```
then
```
x = 1; x = x;
```
|
`int x` puts `x` on the stack.
The right hand part `x = 1` assigns 1 to `x`. But this is an *expression* with value 1.
Finally this is re-assigned to `x`.
|
18,533,563 |
I have created the wordpress folder inside the root. Now I wanna to set it main domain.
for example. my site url is <http://www.example.com>
wordpress url is <http://www.example.com/wordpress>
Now I wanna set wordpress as site url , it open with the main url
when I enter the <http://www.example.com> then it show me the wordrpess site that I have created, Please let me know how I can do it?
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18533563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734190/"
] |
As you didn't post the Java code you wrote, so I can't point out what went wrong exactly.
However, I don't think same id matters anyway. (But that's really bad, you should change it though)
Remember, `switchTo().frame()` has three overloads, you shouldn't be using index or name/id, but pass in the frame element itself. See [source code here](https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/WebDriver.java#306).
>
> WebDriver frame(int index); // unstable
>
>
> WebDriver frame(String nameOrId); // not working in your case, as they identical
>
>
> WebDriver frame(WebElement frameElement); // the one you want
>
>
>
Even `driver.findElements(By.name("content")).get(N)` is bad, as it depends on the order of elements, working but not elegant.
You can locate the frames either by parent `<div>` id attribute or by frame `src` attribute.
```java
// switch out of all frames, just in case, you might not need this line here
driver.switchTo().defaultContent();
// switch to customer frame
WebElement customerFrame = driver.findElement(By.cssSelector("#folderCustomer iframe"));
// alternative css locator: By.cssSelector("iframe[src*='customerSearch']")
driver.switchTo().frame(customerFrame);
// now inside customer frame, you can do stuff
// when you done, switch out of it
driver.switchTo().defaultContent();
// switch to producer frame now
WebElement producerFrame = driver.findElement(By.cssSelector("#folderProducer iframe"));
// alternative css locator: By.cssSelector("iframe[src*='producerSearch']")
driver.switchTo().frame(producerFrame);
// now inside producer frame, you can do stuff
```
|
The problem is not that the elements have the same name, but rather that they are identical (even their parents have the same ID).
I would definitely bring this up with the developers of the site (the fact that two elements have the same ID...which is a big no-no on websites).
Regardless, you can do `driver.findElements(By.name("content")).get(N)` to get the Nth Iframe, and then switch to it.
|
18,533,563 |
I have created the wordpress folder inside the root. Now I wanna to set it main domain.
for example. my site url is <http://www.example.com>
wordpress url is <http://www.example.com/wordpress>
Now I wanna set wordpress as site url , it open with the main url
when I enter the <http://www.example.com> then it show me the wordrpess site that I have created, Please let me know how I can do it?
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18533563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734190/"
] |
The problem is not that the elements have the same name, but rather that they are identical (even their parents have the same ID).
I would definitely bring this up with the developers of the site (the fact that two elements have the same ID...which is a big no-no on websites).
Regardless, you can do `driver.findElements(By.name("content")).get(N)` to get the Nth Iframe, and then switch to it.
|
In this kind of case Xpath is a bast way to find an element. You can differentiate both element by their Xpath.
|
18,533,563 |
I have created the wordpress folder inside the root. Now I wanna to set it main domain.
for example. my site url is <http://www.example.com>
wordpress url is <http://www.example.com/wordpress>
Now I wanna set wordpress as site url , it open with the main url
when I enter the <http://www.example.com> then it show me the wordrpess site that I have created, Please let me know how I can do it?
|
2013/08/30
|
[
"https://Stackoverflow.com/questions/18533563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734190/"
] |
As you didn't post the Java code you wrote, so I can't point out what went wrong exactly.
However, I don't think same id matters anyway. (But that's really bad, you should change it though)
Remember, `switchTo().frame()` has three overloads, you shouldn't be using index or name/id, but pass in the frame element itself. See [source code here](https://code.google.com/p/selenium/source/browse/java/client/src/org/openqa/selenium/WebDriver.java#306).
>
> WebDriver frame(int index); // unstable
>
>
> WebDriver frame(String nameOrId); // not working in your case, as they identical
>
>
> WebDriver frame(WebElement frameElement); // the one you want
>
>
>
Even `driver.findElements(By.name("content")).get(N)` is bad, as it depends on the order of elements, working but not elegant.
You can locate the frames either by parent `<div>` id attribute or by frame `src` attribute.
```java
// switch out of all frames, just in case, you might not need this line here
driver.switchTo().defaultContent();
// switch to customer frame
WebElement customerFrame = driver.findElement(By.cssSelector("#folderCustomer iframe"));
// alternative css locator: By.cssSelector("iframe[src*='customerSearch']")
driver.switchTo().frame(customerFrame);
// now inside customer frame, you can do stuff
// when you done, switch out of it
driver.switchTo().defaultContent();
// switch to producer frame now
WebElement producerFrame = driver.findElement(By.cssSelector("#folderProducer iframe"));
// alternative css locator: By.cssSelector("iframe[src*='producerSearch']")
driver.switchTo().frame(producerFrame);
// now inside producer frame, you can do stuff
```
|
In this kind of case Xpath is a bast way to find an element. You can differentiate both element by their Xpath.
|
7,853,736 |
Leaks is telling me that the following is a memory leak, but I'm not sure why.
TitledArray.h
```
@interface TitledArray : NSObject {
NSMutableArray *realArray;
BOOL uniqueTitles;
BOOL uniqueIDs;
}
@property (nonatomic) BOOL uniqueTitles;
@property (nonatomic) BOOL uniqueIDs;
@property (nonatomic, retain) NSMutableArray *realArray;
```
TitledArray.m
```
-(id)init {
return [self initWithUniqueTitles:FALSE uniqueIDs:FALSE];
}
-(id)initWithUniqueTitles:(BOOL)titles uniqueIDs:(BOOL)IDs {
if ( self = [super init] ) {
//self.realArray = [[NSMutableArray alloc] init];
self.realArray = [NSMutableArray array];
self.uniqueTitles = titles;
self.uniqueIDs = IDs;
}
return self;
}
```
MissionLoading.h
```
@interface MissionLoading : TitledObject {
TitledArray *storageWeights;
TitledArray *passengerWeights;
}
@property (nonatomic, retain) FloatArray *storageWeights;
@property (nonatomic, retain) FloatArray *passengerWeights;
```
MissionLoading.m
```
@synthesize storageWeights;
@synthesize passengerWeights;
-(id)init {
if ( self = [super init]) {
self.storageWeights = [[TitledArray alloc] initWithUniqueTitles:FALSE uniqueIDs:TRUE];
self.passengerWeights = [[TitledArray alloc] initWithUniqueTitles:FALSE uniqueIDs:TRUE];
}
return self;
}
-(void)dealloc{
[storageWeights release];
[passengerWeights release];
[super dealloc];
}
```
Code:
```
for (int i = 0; i < recordCount; i++)
{
loading = [[MissionLoading alloc] init];
// add to array
[loading release];
}
```
The root leak is in the TitledArray object with self.realArray = [NSMutableArray array];
I'm still quite new to iOS development, but this looks good to me. Any thoughts would be helpful. I can provide more information if needed.
Thanks!
|
2011/10/21
|
[
"https://Stackoverflow.com/questions/7853736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1001482/"
] |
When assigning to a property that has `retain` in the `@property` declaration, the synthesized setter retains the value already, so autorelease the thing that you are assigning to the property, like so:
```
-(id)init {
if ( self = [super init]) {
self.storageWeights = [[[TitledArray alloc] initWithUniqueTitles:FALSE uniqueIDs:TRUE] autorelease];
self.passengerWeights = [[[TitledArray alloc] initWithUniqueTitles:FALSE uniqueIDs:TRUE] autorelease];
}
// ....
}
```
|
Looks like you had a //self.realArray = [[NSMutableArray alloc] init]; in the init. Do a clean build and then run the tools again. That old code might have been in there for some reason and would certainly be flagged as a leak.
One other thing, put `self.realArray = nil` in the `dealloc` of TitledArray.
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
I would suggest implementing a custom HandleErrorAttribute action filter.
See this link for more details:
<http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx>
Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.
Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.
**UPDATE:**
Per some questions below, here is an example of a `HandleJsonErrorAttribute` that I use:
```
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as ServiceException;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };
filterContext.ExceptionHandled = true;
}
}
```
And here is the jQuery that I use to handle these unhanded exceptions:
```
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
showPopdown($.parseJSON(jqXHR.responseText).message);
});
```
This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.
Also, in my implementation, I have a custom `ServiceException` that I throw from services, and this sends the message from the service layer instead of a generic message.
|
The easiest way I think you can do that is using the elmah library.
Take a look at this: <http://code.google.com/p/elmah/wiki/MVC> and this
<http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx>
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
I would suggest implementing a custom HandleErrorAttribute action filter.
See this link for more details:
<http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx>
Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.
Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.
**UPDATE:**
Per some questions below, here is an example of a `HandleJsonErrorAttribute` that I use:
```
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as ServiceException;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };
filterContext.ExceptionHandled = true;
}
}
```
And here is the jQuery that I use to handle these unhanded exceptions:
```
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
showPopdown($.parseJSON(jqXHR.responseText).message);
});
```
This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.
Also, in my implementation, I have a custom `ServiceException` that I throw from services, and this sends the message from the service layer instead of a generic message.
|
I think the easiest way is using ExceptionHandler attribute since it's ready to use anytime you create a new ASP.NET MVC 3 project. You can still configure Web.config to use a custom error page and handling exceptions in global Application\_Error method as usual but when an exception occurs the URL is not displayed as nice as the new MVC 3's way.
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
**For Global Error Handling**
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.
*Make sure that Error.cshtml Layout is not null*.
[It sould be something like: @{ Layout = "~/Views/Shared/\_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-
```
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<p>Controller Name: @Model.ControllerName</p>
<p>Action Name : @Model.ActionName</p>
<p>Message: @Model.Exception.Message</p>
</body>
</html>
```
**For Specific Error Handling**
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:
```
public class MyController: Controller
{
[HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException("This method is not implemented.");
return View();
}
}
```
|
I would suggest implementing a custom HandleErrorAttribute action filter.
See this link for more details:
<http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx>
Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.
Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.
**UPDATE:**
Per some questions below, here is an example of a `HandleJsonErrorAttribute` that I use:
```
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as ServiceException;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };
filterContext.ExceptionHandled = true;
}
}
```
And here is the jQuery that I use to handle these unhanded exceptions:
```
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
showPopdown($.parseJSON(jqXHR.responseText).message);
});
```
This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.
Also, in my implementation, I have a custom `ServiceException` that I throw from services, and this sends the message from the service layer instead of a generic message.
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
I would suggest implementing a custom HandleErrorAttribute action filter.
See this link for more details:
<http://msdn.microsoft.com/en-us/library/dd410203%28v=vs.90%29.aspx>
Setting up a HandleErrorAttribute action filter gives you complete control over which actions are handled by the filter, and it's easy to set at the controller level, or even at the site level by setting it up on a custom base controller, and having all of your controllers inherit from the base controller.
Something else I do with this, is I have a separate HandleJsonErrorAttribute that responds to Ajax calls by returning a Json response, rather than the custom page.
**UPDATE:**
Per some questions below, here is an example of a `HandleJsonErrorAttribute` that I use:
```
public class HandleJsonErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
var serviceException = filterContext.Exception as ServiceException;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult { Data = new { message = serviceException == null ? "There was a problem with that request." : serviceException.Message } };
filterContext.ExceptionHandled = true;
}
}
```
And here is the jQuery that I use to handle these unhanded exceptions:
```
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
showPopdown($.parseJSON(jqXHR.responseText).message);
});
```
This allows my Ajax methods to be very lightweight -- they just handle returning normal Json, and in the event of an unhanded exception, a message w/ an error status code gets wrapped in Json and returned.
Also, in my implementation, I have a custom `ServiceException` that I throw from services, and this sends the message from the service layer instead of a generic message.
|
you can create custom exception in MVC if you want to customize a way of exception handling.
you can find useful post here .
<http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html>
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
**For Global Error Handling**
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.
*Make sure that Error.cshtml Layout is not null*.
[It sould be something like: @{ Layout = "~/Views/Shared/\_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-
```
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<p>Controller Name: @Model.ControllerName</p>
<p>Action Name : @Model.ActionName</p>
<p>Message: @Model.Exception.Message</p>
</body>
</html>
```
**For Specific Error Handling**
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:
```
public class MyController: Controller
{
[HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException("This method is not implemented.");
return View();
}
}
```
|
The easiest way I think you can do that is using the elmah library.
Take a look at this: <http://code.google.com/p/elmah/wiki/MVC> and this
<http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx>
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
The easiest way I think you can do that is using the elmah library.
Take a look at this: <http://code.google.com/p/elmah/wiki/MVC> and this
<http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx>
|
you can create custom exception in MVC if you want to customize a way of exception handling.
you can find useful post here .
<http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html>
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
**For Global Error Handling**
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.
*Make sure that Error.cshtml Layout is not null*.
[It sould be something like: @{ Layout = "~/Views/Shared/\_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-
```
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<p>Controller Name: @Model.ControllerName</p>
<p>Action Name : @Model.ActionName</p>
<p>Message: @Model.Exception.Message</p>
</body>
</html>
```
**For Specific Error Handling**
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:
```
public class MyController: Controller
{
[HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException("This method is not implemented.");
return View();
}
}
```
|
I think the easiest way is using ExceptionHandler attribute since it's ready to use anytime you create a new ASP.NET MVC 3 project. You can still configure Web.config to use a custom error page and handling exceptions in global Application\_Error method as usual but when an exception occurs the URL is not displayed as nice as the new MVC 3's way.
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
I think the easiest way is using ExceptionHandler attribute since it's ready to use anytime you create a new ASP.NET MVC 3 project. You can still configure Web.config to use a custom error page and handling exceptions in global Application\_Error method as usual but when an exception occurs the URL is not displayed as nice as the new MVC 3's way.
|
you can create custom exception in MVC if you want to customize a way of exception handling.
you can find useful post here .
<http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html>
|
5,995,781 |
I'm new in mysql and I'm currently having an issue with a query. I need to get an average duration for each activity each day within a week. The date format is like: '2000-01-01 01:01:01', but I want to get rid of the 01:01:01 thing and only care about the date. How do I do that?
The table is something like this:
```
record_id int(10) NOT NULL,
activity_id varchar(100) NOT NULL,
start_time datetime NOT NUll,
end_time datetime NOT NULL,
duration int(10) NOT NULL;
```
Thanks.
|
2011/05/13
|
[
"https://Stackoverflow.com/questions/5995781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636625/"
] |
**For Global Error Handling**
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.
*Make sure that Error.cshtml Layout is not null*.
[It sould be something like: @{ Layout = "~/Views/Shared/\_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-
```
@{ Layout = "~/Views/Shared/_Layout.cshtml"; }
@model System.Web.Mvc.HandleErrorInfo
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>
Sorry, an error occurred while processing your request.
</h2>
<p>Controller Name: @Model.ControllerName</p>
<p>Action Name : @Model.ActionName</p>
<p>Message: @Model.Exception.Message</p>
</body>
</html>
```
**For Specific Error Handling**
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:
```
public class MyController: Controller
{
[HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
public ActionResult Index()
{
throw new NotImplementedException("This method is not implemented.");
return View();
}
}
```
|
you can create custom exception in MVC if you want to customize a way of exception handling.
you can find useful post here .
<http://www.professionals-helpdesk.com/2012/07/creating-custom-exception-filter-in-mvc.html>
|
36,242 |
[Yebamoth 61b](http://halakhah.com/yebamoth/yebamoth_61.html#PARTb) discusses the positive commandment of being fruitful and multiplying. As far as I am aware, one makes no blessing before intercourse. Why not?
Please cite sources!
|
2014/03/12
|
[
"https://judaism.stackexchange.com/questions/36242",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/4682/"
] |
UPDATE FOUND THIS:
>
> The גליוני הש"ס to Berachos 35a discusses that there should be a
> blessing on marital relations, and concludes that Birkas Ha'erusin
> accomplishes that. It would seem he held this concept can extend to
> other pleasures, although this could still be in the realm of "a need
> of the body.
> <https://judaism.stackexchange.com/a/34856/1857>
>
>
>
|
The Shulchan Aruch ([EH 63:2](http://beta.hebrewbooks.org/tursa.aspx?a=eh_x7690)) actually does quote a beracha from the Bahag, to be made after the first bi'ah with a Betula. The Aruch HaShulchan says that we are not noheg to say this beracha anymore.
However, that beracha is not a beracha on the mitzva, but it appears to be a birkas hashevach. The reason we don't make a beracha on bi'ah is because it is contingent on another party. If she says no, you are not supposed to have bi'ah.
|
36,242 |
[Yebamoth 61b](http://halakhah.com/yebamoth/yebamoth_61.html#PARTb) discusses the positive commandment of being fruitful and multiplying. As far as I am aware, one makes no blessing before intercourse. Why not?
Please cite sources!
|
2014/03/12
|
[
"https://judaism.stackexchange.com/questions/36242",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/4682/"
] |
The Maggid Ta'alumos to the Rif on Maseches Berachos, daf 35a (25a in pages of the Rif) says that we do not make the blessing because she may not get pregnant and then the mitzvah was not fulfilled. He also addresses that Onah is a negative commandment and therefore has no blessing.
However, he does indicate that the blessings under the Chuppah do constitute a general birkas hamitzvah.
|
UPDATE FOUND THIS:
>
> The גליוני הש"ס to Berachos 35a discusses that there should be a
> blessing on marital relations, and concludes that Birkas Ha'erusin
> accomplishes that. It would seem he held this concept can extend to
> other pleasures, although this could still be in the realm of "a need
> of the body.
> <https://judaism.stackexchange.com/a/34856/1857>
>
>
>
|
36,242 |
[Yebamoth 61b](http://halakhah.com/yebamoth/yebamoth_61.html#PARTb) discusses the positive commandment of being fruitful and multiplying. As far as I am aware, one makes no blessing before intercourse. Why not?
Please cite sources!
|
2014/03/12
|
[
"https://judaism.stackexchange.com/questions/36242",
"https://judaism.stackexchange.com",
"https://judaism.stackexchange.com/users/4682/"
] |
The Maggid Ta'alumos to the Rif on Maseches Berachos, daf 35a (25a in pages of the Rif) says that we do not make the blessing because she may not get pregnant and then the mitzvah was not fulfilled. He also addresses that Onah is a negative commandment and therefore has no blessing.
However, he does indicate that the blessings under the Chuppah do constitute a general birkas hamitzvah.
|
The Shulchan Aruch ([EH 63:2](http://beta.hebrewbooks.org/tursa.aspx?a=eh_x7690)) actually does quote a beracha from the Bahag, to be made after the first bi'ah with a Betula. The Aruch HaShulchan says that we are not noheg to say this beracha anymore.
However, that beracha is not a beracha on the mitzva, but it appears to be a birkas hashevach. The reason we don't make a beracha on bi'ah is because it is contingent on another party. If she says no, you are not supposed to have bi'ah.
|
4,312,729 |
Having a bit of trouble trying to get an xsd to match two documents:
XML Document 1:
```
<?xml version="1.0" encoding="UTF-8"?>
<video contenttype="asf" fileextension=".wmv" hascontent="no" lang="en-GB" length="1800" pid="3678738364972" sid="">
<lastmodified timestamp="1282678200000">
Tue, 24 Aug 2010 19:30:00 +0000
</lastmodified>
<links/>
<keywords/>
<slides/>
<copyright>
Copyright owned by original broadcaster
</copyright>
<title>
Friends
</title>
<comment>
The One Where the Monkey Gets Away: Rachel accidentally lets Ross's pet monkey escape, then learns that her former best friend is engaged to marry her ex-fiancé. [AD,S]
</comment>
<author>
E4
</author>
<email/>
<captioning/>
<extendeddata>
<data name="keepOriginal">
0
</data>
<data name="keepTranscoded">
0
</data>
<data name="realStartTime">
1282677909
</data>
<data name="scheduledStartTime">
1282678200
</data>
<data name="broadcastLength">
1800
</data>
<data name="broadcastChannel">
E4
</data>
<data name="paddingUsed">
300000
</data>
<data name="transcodingSpec">
-b 2.35M -a 128k --debug --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
</data>
<data name="transcoding">
succeeded
</data>
<data name="transcodingProfile">
-b 2.35M -a 128k --debug --primary-format mp4 --podcast "-l 270 -b 600 -R 48 -B 64" --keep-files true
</data>
<data name="transcoderDetails">
ver 1.58.2.1, 2010-08-24 21:31:33 up 5 days, 11:24, 0 users, load average: 3.08, 3.38, 2.67, OS20031 212.70.69.26
</data>
<data name="originalFilename">
/var/lib/etvd/mpegts/E4/Friends (24-Aug-2010 20.30).emcast
</data>
<data name="originalRecordingTime">
created 2010-08-24 , last modified 2010-08-24 : recording lasted 0s
</data>
<data name="primaryFormat">
mp4
</data>
<data name="doXml">
True
</data>
<data name="doFiles">
True
</data>
</extendeddata>
<categories>
<category name="em:podcast">
mp4
</category>
</categories>
</video>
```
XML Document 2:
```
<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
<title>
A vid with Pete
</title>
<description>
Petes vid
</description>
<contributor>
Pete
</contributor>
<subject>
Cat 2
</subject>
</video>
```
Proposed XSD:
```
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="UploadXSD"
targetNamespace="UploadXSD"
elementFormDefault="qualified"
xmlns="http://tempuri.org/UploadXSD.xsd"
xmlns:mstns="http://tempuri.org/UploadXSD.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="video">
<xs:complexType>
<xs:sequence>
<xs:element name="title" minOccurs="1" type="xs:string"></xs:element>
<xs:element name="description" type="xs:string"></xs:element>
<xs:element name="contributor" type="xs:string"></xs:element>
<xs:element name="subject" type="xs:string"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
```
Is it possible to use c# to validate against both of the xml documents and NOT use a namespace? Because with the XML Document 1 (above) it is created by a third party system and it cannot generate the namespace...
Asked a few questions about xml in the last few days appreciate help am very new to this...
|
2010/11/30
|
[
"https://Stackoverflow.com/questions/4312729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223863/"
] |
I believe you do need to match namespace. I once faced a similar issue, where the XML document was out of my control (Adobe Smart Forms), and I wanted to validate it against my XSD.
To do this I **cleaned** the XML document before I validated, adjusting the namespace, and in my case removing alot of garbage that Adobe added. Sorry I don't have any code with me on how I did it.
|
As far as I'm aware, you don't need a namespace. I've never used one in any of my XSD schemas.
Here's Microsoft's documentation on the feature:
<http://msdn.microsoft.com/en-us/library/aa258639%28SQL.80%29.aspx>
|
109,381 |
I have a content type that has a mix of user-editable fields and auto-populated fields (from an external source). I would like to mark those fields as disabled right when I create them so the user cannot overwrite them. I know there are readonly modules and ways to do this in hook\_form\_alter but I'm curious if I can short circuit having to do this on the fly and just have it disabled by default. Thanks.
|
2014/04/07
|
[
"https://drupal.stackexchange.com/questions/109381",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/25639/"
] |
The simple bulk action support in Drupal 8 core does not currently support this feature.
|
The issue about [Port Views Bulk Operations to Drupal 8](https://www.drupal.org/project/views_bulk_operations/issues/1823572) is closed (completed) now.
If somebody has problem with it, try to use /admin/yourpath in views, then you use admin theme and select/deselect all button should work.
|
109,381 |
I have a content type that has a mix of user-editable fields and auto-populated fields (from an external source). I would like to mark those fields as disabled right when I create them so the user cannot overwrite them. I know there are readonly modules and ways to do this in hook\_form\_alter but I'm curious if I can short circuit having to do this on the fly and just have it disabled by default. Thanks.
|
2014/04/07
|
[
"https://drupal.stackexchange.com/questions/109381",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/25639/"
] |
The simple bulk action support in Drupal 8 core does not currently support this feature.
|
If you need "select all" you can use the module [VBO](https://www.drupal.org/project/views_bulk_operations).
Then you can replace the field "Node: Views bulk operation" with the "Global: Views bulk operations" which supports selecting all rows.
|
74,553,190 |
Im trying to make a complex queryset and I want to include my `ForeignKeys` names instead of pk. I'm using ajax to get a live feed from user inputs and print the results on a `DataTable` but I want to print the names instead of the pk. Im getting a queryset and when I `console.log` it, `sensor_name` is not in there.
My models are like this:
```
class TreeSensor(models.Model):
class Meta:
verbose_name_plural = "Tree Sensors"
field = models.ForeignKey(Field, on_delete=models.CASCADE)
sensor_name = models.CharField(max_length=200, blank=True)
datetime = models.DateTimeField(blank=True, null=True, default=now)
longitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
latitude = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
class TreeSensorMeasurement(models.Model):
class Meta:
verbose_name_plural = "Tree Sensor Measurements"
sensor = models.ForeignKey(TreeSensor, on_delete=models.CASCADE)
datetime = models.DateTimeField(blank=True, null=True, default=None)
soil_moisture_depth_1 = models.DecimalField(max_digits=15, decimal_places=2)
soil_moisture_depth_2 = models.DecimalField(max_digits=15, decimal_places=2)
soil_moisture_depth_1_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
soil_moisture_depth_2_filtered = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
soil_temperature = models.DecimalField(max_digits=15, decimal_places=2)
```
And my view looks like this(I've omitted the non-essential code):
```
field_list = Field.objects.filter(user=request.user)
tree_sensors = TreeSensor.objects.filter(field_id__in=field_list.values_list('id', flat=True))
statSensors = (TreeSensorMeasurement.objects
.filter(sensor_id__in=tree_sensors.values_list('id', flat=True))
.filter(datetime__date__lte=To_T[0]).filter(datetime__date__gte=From_T[0])
.filter(soil_moisture_depth_1__lte=To_T[1]).filter(soil_moisture_depth_1__gte=From_T[1])
.filter(soil_moisture_depth_2__lte=To_T[2]).filter(soil_moisture_depth_2__gte=From_T[2])
.filter(soil_temperature__lte=To_T[3]).filter(soil_temperature__gte=From_T[3])
.order_by('sensor', 'datetime'))
TreeData = serializers.serialize('json', statSensors)
```
The code above works correctly but I cant figure out the twist I need to do to get the `TreeSensors` name instead of pk in the frontend. An example of how I receive one instance in the frontend:
```
datetime: "2022-11-20T13:28:45.901Z"
sensor: 2
soil_moisture_depth_1: "166.00"
soil_moisture_depth_1_filtered: "31.00"
soil_moisture_depth_2: "171.00"
soil_moisture_depth_2_filtered: "197.00"
soil_temperature: "11.00"
```
|
2022/11/23
|
[
"https://Stackoverflow.com/questions/74553190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Use parameter expansion to strip prefix and suffix.
```
for f in /root/Desktop/match/jars/44a65820/*; do
link="${f%-44a65820.jar}.jar";
ln -s "$f" "/root/Desktop/match/jars/${link##*/}";
done
```
|
Given the simplified tree for testing
```bash
shell> tree /tmp/match
/tmp/match
└── jars
└── 44a65820
├── one.jar
├── three.jar
└── two.jar
```
In Ansible, declare the variable
```yaml
match_files: "{{ st.files|map(attribute='path')|list }}"
```
and [find](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/find_module.html#ansible-builtin-find-module-return-a-list-of-files-based-on-specific-criteria) the files
```yaml
- find:
path: /tmp/match
file_type: file
patterns: '*.jar'
recurse: true
register: st
```
gives
```yaml
match_files:
- /tmp/match/jars/44a65820/two.jar
- /tmp/match/jars/44a65820/one.jar
- /tmp/match/jars/44a65820/three.jar
```
Create the [links](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html#parameter-state) in the loop
```yaml
- file:
state: link
src: "{{ item }}"
dest: "{{ path }}/{{ file }}"
loop: "{{ match_files }}"
vars:
arr: "{{ item.split('/') }}"
path: "{{ arr[:-2]|join('/') }}"
file: "{{ arr[-1] }}"
```
gives
```bash
shell> tree /tmp/match
/tmp/match
└── jars
├── 44a65820
│ ├── one.jar
│ ├── three.jar
│ └── two.jar
├── one.jar -> /tmp/match/jars/44a65820/one.jar
├── three.jar -> /tmp/match/jars/44a65820/three.jar
└── two.jar -> /tmp/match/jars/44a65820/two.jar
```
---
Example of a complete playbook for testing
```yaml
- hosts: localhost
vars:
match_files: "{{ st.files|map(attribute='path')|list }}"
tasks:
- find:
path: /tmp/match
file_type: file
patterns: '*.jar'
recurse: true
register: st
- debug:
var: match_files
- file:
state: link
src: "{{ item }}"
dest: "{{ path }}/{{ file }}"
loop: "{{ match_files }}"
vars:
arr: "{{ item.split('/') }}"
path: "{{ arr[:-2]|join('/') }}"
file: "{{ arr[-1] }}"
```
|
42,304,119 |
I'm building a robot for a school project. I am currently using an Arduino Uno, two DC motors and an ultrasonic sensor. The two motors are being controlled via the [Arduino Motor Shield v3](https://store.arduino.cc/usa/arduino-motor-shield-rev3). I want the robot to be autonomous so it has to be able to move around on its own using the ultrasonic sensor.
This is the latest version of my source code:
```cpp
#include <Servo.h> // include Servo library
#include <AFMotor.h> // include DC motor Library
#define trigPin 12 // define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);
void setup() {
Serial.begin(9600); // begin serial communication
Serial.println("Motor test!");
pinMode(trigPin, OUTPUT); // set the trig pin to output to send sound waves
pinMode(echoPin, INPUT); // set the echo pin to input to receive sound waves
motor1.setSpeed(105); // set the speed of the motors, between 0-255
motor2.setSpeed (105);
}
void loop() {
long duration, distance; // start the scan
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // delays are required for a successful sensor operation.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // this delay is required as well!
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // convert the distance to centimetres.
// if there's an obstacle ahead at less than 25 centimetres, do the following:
if (distance < 25) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print(" CM!"); // print out the distance in centimeters.
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run (BACKWARD);
} else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); // if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
```
The current issue is that the wheels are rotating as expected but after a few turns they stop.
I suspect that the issue is software related, but I am not completely sure. Moreover, I believe that the motors are correctly connected to the motor shield, but I might not handle them properly in the code.
Could anyone please help me solving this issue?
|
2017/02/17
|
[
"https://Stackoverflow.com/questions/42304119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7564671/"
] |
There are a few different ways to do this.
```
library(data.table)
dt = data.table("Group" = c(rep("A",4),rep("B",4)), "value" = rep(1:4, each = 2))
knitr::kable(dt)
> dt
Group value
1: A 1
2: A 1
3: A 2
4: A 2
5: B 3
6: B 3
7: B 4
8: B 4
```
We can remove duplicates across all rows
```
knitr::kable(dt[!duplicated(dt),])
|Group | value|
|:-----|-----:|
|A | 1|
|A | 2|
|B | 3|
|B | 4|
```
Or, we can remove duplicates according to specific rows
```
knitr::kable(unique(dt,by = c("Group")))
|Group | value|
|:-----|-----:|
|A | 1|
|B | 3|
```
Then, since that can match to multiple options we can specify which one we want to grab
```
knitr::kable(dt[unique(dt,by = c("Group")),.(Group, value), mult = "first"])
|Group | value|
|:-----|-----:|
|A | 1|
|B | 3|
knitr::kable(dt[unique(dt,by = c("Group")),.(Group, value), mult = "last"])
|Group | value|
|:-----|-----:|
|A | 2|
|B | 4|
```
**EDIT**
To not print values in a specific group that have been duplicated
```
dt$Group = ifelse(duplicated(dt$Group),"",dt$Group)
knitr::kable(dt)
|Group | value|
|:-----|-----:|
|A | 1|
| | 1|
| | 2|
| | 2|
|B | 3|
| | 3|
| | 4|
| | 4|
```
|
You can use `duplicated` function with negation (`!`) to retain values of "group" only at transitions but be careful that is does
not result in loss of information from other columns (if they are important). In the demo datset we retain only transitions of `cyl` variable.
```
mtcarsSubset = mtcars[,1:5]
knitr::kable(mtcarsSubset)
#| | mpg| cyl| disp| hp| drat|
#|:-------------------|----:|---:|-----:|---:|----:|
#|Mazda RX4 | 21.0| 6| 160.0| 110| 3.90|
#|Mazda RX4 Wag | 21.0| 6| 160.0| 110| 3.90|
#|Datsun 710 | 22.8| 4| 108.0| 93| 3.85|
#|Hornet 4 Drive | 21.4| 6| 258.0| 110| 3.08|
#|Hornet Sportabout | 18.7| 8| 360.0| 175| 3.15|
#|Valiant | 18.1| 6| 225.0| 105| 2.76|
#|Duster 360 | 14.3| 8| 360.0| 245| 3.21|
#|Merc 240D | 24.4| 4| 146.7| 62| 3.69|
#|Merc 230 | 22.8| 4| 140.8| 95| 3.92|
#|Merc 280 | 19.2| 6| 167.6| 123| 3.92|
#|Merc 280C | 17.8| 6| 167.6| 123| 3.92|
#|Merc 450SE | 16.4| 8| 275.8| 180| 3.07|
#|Merc 450SL | 17.3| 8| 275.8| 180| 3.07|
#|Merc 450SLC | 15.2| 8| 275.8| 180| 3.07|
#|Cadillac Fleetwood | 10.4| 8| 472.0| 205| 2.93|
#|Lincoln Continental | 10.4| 8| 460.0| 215| 3.00|
#|Chrysler Imperial | 14.7| 8| 440.0| 230| 3.23|
#|Fiat 128 | 32.4| 4| 78.7| 66| 4.08|
#|Honda Civic | 30.4| 4| 75.7| 52| 4.93|
#|Toyota Corolla | 33.9| 4| 71.1| 65| 4.22|
#|Toyota Corona | 21.5| 4| 120.1| 97| 3.70|
#|Dodge Challenger | 15.5| 8| 318.0| 150| 2.76|
#|AMC Javelin | 15.2| 8| 304.0| 150| 3.15|
#|Camaro Z28 | 13.3| 8| 350.0| 245| 3.73|
#|Pontiac Firebird | 19.2| 8| 400.0| 175| 3.08|
#|Fiat X1-9 | 27.3| 4| 79.0| 66| 4.08|
#|Porsche 914-2 | 26.0| 4| 120.3| 91| 4.43|
#|Lotus Europa | 30.4| 4| 95.1| 113| 3.77|
#|Ford Pantera L | 15.8| 8| 351.0| 264| 4.22|
#|Ferrari Dino | 19.7| 6| 145.0| 175| 3.62|
#|Maserati Bora | 15.0| 8| 301.0| 335| 3.54|
#|Volvo 142E | 21.4| 4| 121.0| 109| 4.11|
knitr::kable(mtcarsSubset[!duplicated(mtcarsSubset$cyl),])
#| | mpg| cyl| disp| hp| drat|
#|:-----------------|----:|---:|----:|---:|----:|
#|Mazda RX4 | 21.0| 6| 160| 110| 3.90|
#|Datsun 710 | 22.8| 4| 108| 93| 3.85|
#|Hornet Sportabout | 18.7| 8| 360| 175| 3.15|
```
|
42,304,119 |
I'm building a robot for a school project. I am currently using an Arduino Uno, two DC motors and an ultrasonic sensor. The two motors are being controlled via the [Arduino Motor Shield v3](https://store.arduino.cc/usa/arduino-motor-shield-rev3). I want the robot to be autonomous so it has to be able to move around on its own using the ultrasonic sensor.
This is the latest version of my source code:
```cpp
#include <Servo.h> // include Servo library
#include <AFMotor.h> // include DC motor Library
#define trigPin 12 // define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);
void setup() {
Serial.begin(9600); // begin serial communication
Serial.println("Motor test!");
pinMode(trigPin, OUTPUT); // set the trig pin to output to send sound waves
pinMode(echoPin, INPUT); // set the echo pin to input to receive sound waves
motor1.setSpeed(105); // set the speed of the motors, between 0-255
motor2.setSpeed (105);
}
void loop() {
long duration, distance; // start the scan
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // delays are required for a successful sensor operation.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // this delay is required as well!
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // convert the distance to centimetres.
// if there's an obstacle ahead at less than 25 centimetres, do the following:
if (distance < 25) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print(" CM!"); // print out the distance in centimeters.
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run (BACKWARD);
} else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); // if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
```
The current issue is that the wheels are rotating as expected but after a few turns they stop.
I suspect that the issue is software related, but I am not completely sure. Moreover, I believe that the motors are correctly connected to the motor shield, but I might not handle them properly in the code.
Could anyone please help me solving this issue?
|
2017/02/17
|
[
"https://Stackoverflow.com/questions/42304119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7564671/"
] |
Finally, I changed the data-frame that then is converted into a table.
`ReplicationTable %>% mutate(dependent_variable = ifelse(duplicated(dependent_variable), "", dependent_variable)`
This replaces all entries with an empty string after the first unique entry in `dependent_variable`. This also works in grouped data-frames.
|
You can use `duplicated` function with negation (`!`) to retain values of "group" only at transitions but be careful that is does
not result in loss of information from other columns (if they are important). In the demo datset we retain only transitions of `cyl` variable.
```
mtcarsSubset = mtcars[,1:5]
knitr::kable(mtcarsSubset)
#| | mpg| cyl| disp| hp| drat|
#|:-------------------|----:|---:|-----:|---:|----:|
#|Mazda RX4 | 21.0| 6| 160.0| 110| 3.90|
#|Mazda RX4 Wag | 21.0| 6| 160.0| 110| 3.90|
#|Datsun 710 | 22.8| 4| 108.0| 93| 3.85|
#|Hornet 4 Drive | 21.4| 6| 258.0| 110| 3.08|
#|Hornet Sportabout | 18.7| 8| 360.0| 175| 3.15|
#|Valiant | 18.1| 6| 225.0| 105| 2.76|
#|Duster 360 | 14.3| 8| 360.0| 245| 3.21|
#|Merc 240D | 24.4| 4| 146.7| 62| 3.69|
#|Merc 230 | 22.8| 4| 140.8| 95| 3.92|
#|Merc 280 | 19.2| 6| 167.6| 123| 3.92|
#|Merc 280C | 17.8| 6| 167.6| 123| 3.92|
#|Merc 450SE | 16.4| 8| 275.8| 180| 3.07|
#|Merc 450SL | 17.3| 8| 275.8| 180| 3.07|
#|Merc 450SLC | 15.2| 8| 275.8| 180| 3.07|
#|Cadillac Fleetwood | 10.4| 8| 472.0| 205| 2.93|
#|Lincoln Continental | 10.4| 8| 460.0| 215| 3.00|
#|Chrysler Imperial | 14.7| 8| 440.0| 230| 3.23|
#|Fiat 128 | 32.4| 4| 78.7| 66| 4.08|
#|Honda Civic | 30.4| 4| 75.7| 52| 4.93|
#|Toyota Corolla | 33.9| 4| 71.1| 65| 4.22|
#|Toyota Corona | 21.5| 4| 120.1| 97| 3.70|
#|Dodge Challenger | 15.5| 8| 318.0| 150| 2.76|
#|AMC Javelin | 15.2| 8| 304.0| 150| 3.15|
#|Camaro Z28 | 13.3| 8| 350.0| 245| 3.73|
#|Pontiac Firebird | 19.2| 8| 400.0| 175| 3.08|
#|Fiat X1-9 | 27.3| 4| 79.0| 66| 4.08|
#|Porsche 914-2 | 26.0| 4| 120.3| 91| 4.43|
#|Lotus Europa | 30.4| 4| 95.1| 113| 3.77|
#|Ford Pantera L | 15.8| 8| 351.0| 264| 4.22|
#|Ferrari Dino | 19.7| 6| 145.0| 175| 3.62|
#|Maserati Bora | 15.0| 8| 301.0| 335| 3.54|
#|Volvo 142E | 21.4| 4| 121.0| 109| 4.11|
knitr::kable(mtcarsSubset[!duplicated(mtcarsSubset$cyl),])
#| | mpg| cyl| disp| hp| drat|
#|:-----------------|----:|---:|----:|---:|----:|
#|Mazda RX4 | 21.0| 6| 160| 110| 3.90|
#|Datsun 710 | 22.8| 4| 108| 93| 3.85|
#|Hornet Sportabout | 18.7| 8| 360| 175| 3.15|
```
|
42,304,119 |
I'm building a robot for a school project. I am currently using an Arduino Uno, two DC motors and an ultrasonic sensor. The two motors are being controlled via the [Arduino Motor Shield v3](https://store.arduino.cc/usa/arduino-motor-shield-rev3). I want the robot to be autonomous so it has to be able to move around on its own using the ultrasonic sensor.
This is the latest version of my source code:
```cpp
#include <Servo.h> // include Servo library
#include <AFMotor.h> // include DC motor Library
#define trigPin 12 // define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);
void setup() {
Serial.begin(9600); // begin serial communication
Serial.println("Motor test!");
pinMode(trigPin, OUTPUT); // set the trig pin to output to send sound waves
pinMode(echoPin, INPUT); // set the echo pin to input to receive sound waves
motor1.setSpeed(105); // set the speed of the motors, between 0-255
motor2.setSpeed (105);
}
void loop() {
long duration, distance; // start the scan
digitalWrite(trigPin, LOW);
delayMicroseconds(2); // delays are required for a successful sensor operation.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // this delay is required as well!
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1; // convert the distance to centimetres.
// if there's an obstacle ahead at less than 25 centimetres, do the following:
if (distance < 25) {
Serial.println("Close Obstacle detected!" );
Serial.println("Obstacle Details:");
Serial.print("Distance From Robot is " );
Serial.print(distance);
Serial.print(" CM!"); // print out the distance in centimeters.
Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
motor1.run(FORWARD); // Turn as long as there's an obstacle ahead.
motor2.run (BACKWARD);
} else {
Serial.println("No obstacle detected. going forward");
delay(15);
motor1.run(FORWARD); // if there's no obstacle ahead, Go Forward!
motor2.run(FORWARD);
}
}
```
The current issue is that the wheels are rotating as expected but after a few turns they stop.
I suspect that the issue is software related, but I am not completely sure. Moreover, I believe that the motors are correctly connected to the motor shield, but I might not handle them properly in the code.
Could anyone please help me solving this issue?
|
2017/02/17
|
[
"https://Stackoverflow.com/questions/42304119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7564671/"
] |
There are a few different ways to do this.
```
library(data.table)
dt = data.table("Group" = c(rep("A",4),rep("B",4)), "value" = rep(1:4, each = 2))
knitr::kable(dt)
> dt
Group value
1: A 1
2: A 1
3: A 2
4: A 2
5: B 3
6: B 3
7: B 4
8: B 4
```
We can remove duplicates across all rows
```
knitr::kable(dt[!duplicated(dt),])
|Group | value|
|:-----|-----:|
|A | 1|
|A | 2|
|B | 3|
|B | 4|
```
Or, we can remove duplicates according to specific rows
```
knitr::kable(unique(dt,by = c("Group")))
|Group | value|
|:-----|-----:|
|A | 1|
|B | 3|
```
Then, since that can match to multiple options we can specify which one we want to grab
```
knitr::kable(dt[unique(dt,by = c("Group")),.(Group, value), mult = "first"])
|Group | value|
|:-----|-----:|
|A | 1|
|B | 3|
knitr::kable(dt[unique(dt,by = c("Group")),.(Group, value), mult = "last"])
|Group | value|
|:-----|-----:|
|A | 2|
|B | 4|
```
**EDIT**
To not print values in a specific group that have been duplicated
```
dt$Group = ifelse(duplicated(dt$Group),"",dt$Group)
knitr::kable(dt)
|Group | value|
|:-----|-----:|
|A | 1|
| | 1|
| | 2|
| | 2|
|B | 3|
| | 3|
| | 4|
| | 4|
```
|
Finally, I changed the data-frame that then is converted into a table.
`ReplicationTable %>% mutate(dependent_variable = ifelse(duplicated(dependent_variable), "", dependent_variable)`
This replaces all entries with an empty string after the first unique entry in `dependent_variable`. This also works in grouped data-frames.
|
162,767 |
When generating a matrix barcode, it takes 1 minute per 10000 files .That's how to generating a matrix barcode for big quantities in less time.
[Here](http://www.mediafire.com/file/ciadoloynverba7/library_used_for_datamatrix.txt) is the library used to encoder data.
My code for button generating:
```
Class1 CLS = new Class1();
DataTable dt = CLS.ShowalldataSerial(textBox4.Text);
for (int i = 0; i <= Convert.ToInt32(textBox1.Text); i++)
{
Serial = SRL.Rnd().ToString();
txt = "UserID" + dt.Rows[0][0] + "FirmName" + dt.Rows[0][1] + "OrderNo" + dt.Rows[0][2] + "BtachNo" + dt.Rows[0][3] + "Quantity" + dt.Rows[0][4] + "ProductName" + dt.Rows[0][5] + "SerialNo" + Serial;
dm.DM(txt, Color.FromName(comboBox1.SelectedItem.ToString()), Color.White).Save(root + "\\" + Serial + ".emf", System.Drawing.Imaging.ImageFormat.Emf);
}
MessageBox.Show("Records generated success ");
```
When creating 10000 in `textbox1` it take 1 minute. If I write 200000 in `textbox1` it takes 20 minutes.
The code is working without any problems and gives me results that I need, but it is slow. Can someone help me speed it up?
|
2017/05/07
|
[
"https://codereview.stackexchange.com/questions/162767",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/138262/"
] |
1. Strings are immutable so whenever you're concatenating them you're effectively creating new instances every time, this can slow down performance a lot, instead use `StringBuilder` and it's method `Append()` to build strings.
2. Avoid duplicate operations per each cycle unless it's necessary, such as `Convert.ToInt32(textBox1.Text)` convert the value to `int` before the for loop and save the value in variable, than later use the variable instead of converting the value every time. Another example is `comboBox1.SelectedItem.ToString()`.
|
I totally agree with Denis' answer, here. On top of that, I'd add:
1. It's just 6 milliseconds for each barcode, including save to disk: it's not that slow at the end of day, and you have a custom library doing most of the job, so that means that you really have to squeeze every single possible fraction of millisecond.
2. In every loop you already know the size of the final string (just add the length of each single part of if), so when instancing the StringBuilder use that number to set the initial capacity. Or, just in case, set it to the maximum possible string length and see what's faster.
3. Use a parallel for. If this thing is running on an average working PC, let's say an 8 cores, going from 6ms to 1ms could be a plausible scenario. Even taking into account that you need to instance a new encoder for each barcode, I'd say that it's realistic to at least expect the final time to go down to an half, even a third.
4. Give proper names to loop variables.
---
**Edit**
Sorry, I was again thinking about point 4 above, got struck by a doubt, checked again, and here you are doing something that make no sense at all:
```
txt = "UserID" + dt.Rows[0][0] + "FirmName" + dt.Rows[0][1] + "OrderNo" + dt.Rows[0][2] + "BtachNo" + dt.Rows[0][3] + "Quantity" + dt.Rows[0][4] + "ProductName" + dt.Rows[0][5] + "SerialNo" + Serial;
```
You are rebuilding at every loop exactly the same base string, over and over and over again, what's the point of that? Your string is the same except for the serial number, so build it **once** outside the for loop and the reuse it. You don't even need to use a StringBuilder here, as in general it begins to be faster when you are concatenating more than 3 strings, otherwise plain normal string concatenation is better.
---
**Edit 2, on OP request**
Something like this should do:
```
Class1 CLS = new Class1();
DataTable dt = CLS.ShowalldataSerial(textBox4.Text);
string baseText = "UserID" + dt.Rows[0][0] + "FirmName" + dt.Rows[0][1] + "OrderNo" + dt.Rows[0][2] + "BtachNo" + dt.Rows[0][3] + "Quantity" + dt.Rows[0][4] + "ProductName" + dt.Rows[0][5] + "SerialNo";
Color foregroundColor = Color.FromName(comboBox1.SelectedItem.ToString());
int serialsToGenerate = Convert.ToInt32(textBox1.Text);
Parallel.For(0, serialsToGenerate, index=>
{
string Serial = SRL.Rnd().ToString();
string txt = baseText + Serial;
// WARNING HERE
DM_Encoder dm = new DM_Encoder();
dm.DM(txt, foregroundColor, Color.White).Save(root + "\\" + Serial + ".emf", System.Drawing.Imaging.ImageFormat.Emf);
});
```
The content of the Parallel.For will be executed in multithread, so you need a unique instance of every variable you modify and for every class you call a method of, so keep an eye on the
```
// WARNING HERE
```
because I have no idea how you instanced and set the dm object before, and you need to do the same here; I just added a generic call to the constructor to help you understand.
Another big warning: you need to understand multithread programming, otherwise this code will sooner or later blow up in your face. Usually in the worst possible moment.
|
162,767 |
When generating a matrix barcode, it takes 1 minute per 10000 files .That's how to generating a matrix barcode for big quantities in less time.
[Here](http://www.mediafire.com/file/ciadoloynverba7/library_used_for_datamatrix.txt) is the library used to encoder data.
My code for button generating:
```
Class1 CLS = new Class1();
DataTable dt = CLS.ShowalldataSerial(textBox4.Text);
for (int i = 0; i <= Convert.ToInt32(textBox1.Text); i++)
{
Serial = SRL.Rnd().ToString();
txt = "UserID" + dt.Rows[0][0] + "FirmName" + dt.Rows[0][1] + "OrderNo" + dt.Rows[0][2] + "BtachNo" + dt.Rows[0][3] + "Quantity" + dt.Rows[0][4] + "ProductName" + dt.Rows[0][5] + "SerialNo" + Serial;
dm.DM(txt, Color.FromName(comboBox1.SelectedItem.ToString()), Color.White).Save(root + "\\" + Serial + ".emf", System.Drawing.Imaging.ImageFormat.Emf);
}
MessageBox.Show("Records generated success ");
```
When creating 10000 in `textbox1` it take 1 minute. If I write 200000 in `textbox1` it takes 20 minutes.
The code is working without any problems and gives me results that I need, but it is slow. Can someone help me speed it up?
|
2017/05/07
|
[
"https://codereview.stackexchange.com/questions/162767",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/138262/"
] |
1. Strings are immutable so whenever you're concatenating them you're effectively creating new instances every time, this can slow down performance a lot, instead use `StringBuilder` and it's method `Append()` to build strings.
2. Avoid duplicate operations per each cycle unless it's necessary, such as `Convert.ToInt32(textBox1.Text)` convert the value to `int` before the for loop and save the value in variable, than later use the variable instead of converting the value every time. Another example is `comboBox1.SelectedItem.ToString()`.
|
I don't see you using the `i` variable inside your loop? If it's just for counting you could perhaps rewrite the loop to:
```
var counter = Convert.ToInt32(textBox1.Text);
while(counter-- >= 0)
{
//Code goes here...
}
```
I also see you always use the row at index `0`, is this intended or is that where you meant to take the "i-th" row?
* Always use `0`: place the row in a variable to reuse, and not re-access it every time
```
while(counter-- >= 0)
{
var row = dt.Rows[0];
//Access the row:
var cell = row[0];
}
```
* Take i-th row: use the for-loop and the indexer
```
var counter = Convert.ToInt32(textBox1.Text);
for (int i = 0; i <= counter; i++)
{
var row = dt.Rows[i];
}
```
Another tip is to use a formatted string to build the result:
```
while(counter-- >= 0)
{
Serial = SRL.Rnd().ToString();
var row = dt.Rows[0];
var formatted = $"UserID{row[0]}FirmName{row[1]}OrderNo{row[2]}BtachNo{row[3]}Quantity{row[4]}ProductName{row[5]}SerialNo{Serial}";
}
```
With all tips, including from other answers your code would look like this:
```
var CLS = new Class1();
var dt = CLS.ShowalldataSerial(textBox4.Text);
var counter = Convert.ToInt32(textBox1.Text);
var selectedColor = Color.FromName(comboBox1.SelectedItem.ToString());
while(counter-- >= 0)
{
Serial = SRL.Rnd().ToString();
var row = dt.Rows[0];
var txt = $"UserID{row[0]}FirmName{row[1]}OrderNo{row[2]}BtachNo{row[3]}Quantity{row[4]}ProductName{row[5]}SerialNo{Serial}";
dm.DM(txt, selectedColor, Color.White).Save($"{root}\\{Serial}.emf", System.Drawing.Imaging.ImageFormat.Emf);
}
```
|
10,772,530 |
I am curious about this. I must learn Prolog for my course, but the applications that I seen mostly are written using C++, C# or Java. Applications written by Prolog, to me is very very rare application.
So, I wonder how Prolog is used and implement the real-world application?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326261/"
] |
I once asked my supervisor a similar question, when he is giving us a Prological lecture.
And he told me that people do not really use prolog to implement a whole huge system. Instead, people write the main part with other language(which is more sane and trivial), and link it to a "decision procedure" or something written in Prolog.
Not sure about other Prolog implementation, we were using BProlog and it provides C/Java interface.
|
According to the Tiobe Software Index, Prolog is currently #36: between Haskell and FoxPro:
<http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html>
What's it used for?
I first heard of it with respect to Japan's (now defunct) "Fifth Generation" project:
<http://en.wikipedia.org/wiki/Fifth_generation_computer>
Frankly, I'm not really aware of anybody using Prolog for any serious commercial development.
|
10,772,530 |
I am curious about this. I must learn Prolog for my course, but the applications that I seen mostly are written using C++, C# or Java. Applications written by Prolog, to me is very very rare application.
So, I wonder how Prolog is used and implement the real-world application?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326261/"
] |
* **Microsoft Windows NT Networking Installation and Configuration applet**
One of the notorious and in a way notable examples is Microsoft Windows NT OS network interface configuration code that involved a Small Prolog interpreter built in. Here is a [link](http://www.drdobbs.com/cpp/184409294) to the story written by David Hovel for Dr. Dobbs. (*The often cited Microsoft Research link seems to be gone.*)
* **Expert systems**
Once Prolog was considered as THE language for a class of software systems called *Expert Systems*. These were interactive knowledge management systems often with a relational database backend.
* **Beyond Prolog**
In general rule-based programming, resolution and different automated reasoning systems are widely used beyond Prolog.
|
According to the Tiobe Software Index, Prolog is currently #36: between Haskell and FoxPro:
<http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html>
What's it used for?
I first heard of it with respect to Japan's (now defunct) "Fifth Generation" project:
<http://en.wikipedia.org/wiki/Fifth_generation_computer>
Frankly, I'm not really aware of anybody using Prolog for any serious commercial development.
|
10,772,530 |
I am curious about this. I must learn Prolog for my course, but the applications that I seen mostly are written using C++, C# or Java. Applications written by Prolog, to me is very very rare application.
So, I wonder how Prolog is used and implement the real-world application?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326261/"
] |
SWI-Prolog website is served from... SWI-prolog, using just a small subset of the libraries available.
Well, it's not a commercial application, but it's rather [real world](http://www.swi-prolog.org/).
Much effort was required to make the runtime able to perform 24x7 service (mainly garbage collection) and required performance scalability (among other multithreading).
Several libraries were developed driven by real world applications needs.
|
According to the Tiobe Software Index, Prolog is currently #36: between Haskell and FoxPro:
<http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html>
What's it used for?
I first heard of it with respect to Japan's (now defunct) "Fifth Generation" project:
<http://en.wikipedia.org/wiki/Fifth_generation_computer>
Frankly, I'm not really aware of anybody using Prolog for any serious commercial development.
|
10,772,530 |
I am curious about this. I must learn Prolog for my course, but the applications that I seen mostly are written using C++, C# or Java. Applications written by Prolog, to me is very very rare application.
So, I wonder how Prolog is used and implement the real-world application?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326261/"
] |
SWI-Prolog website is served from... SWI-prolog, using just a small subset of the libraries available.
Well, it's not a commercial application, but it's rather [real world](http://www.swi-prolog.org/).
Much effort was required to make the runtime able to perform 24x7 service (mainly garbage collection) and required performance scalability (among other multithreading).
Several libraries were developed driven by real world applications needs.
|
I once asked my supervisor a similar question, when he is giving us a Prological lecture.
And he told me that people do not really use prolog to implement a whole huge system. Instead, people write the main part with other language(which is more sane and trivial), and link it to a "decision procedure" or something written in Prolog.
Not sure about other Prolog implementation, we were using BProlog and it provides C/Java interface.
|
10,772,530 |
I am curious about this. I must learn Prolog for my course, but the applications that I seen mostly are written using C++, C# or Java. Applications written by Prolog, to me is very very rare application.
So, I wonder how Prolog is used and implement the real-world application?
|
2012/05/27
|
[
"https://Stackoverflow.com/questions/10772530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326261/"
] |
SWI-Prolog website is served from... SWI-prolog, using just a small subset of the libraries available.
Well, it's not a commercial application, but it's rather [real world](http://www.swi-prolog.org/).
Much effort was required to make the runtime able to perform 24x7 service (mainly garbage collection) and required performance scalability (among other multithreading).
Several libraries were developed driven by real world applications needs.
|
* **Microsoft Windows NT Networking Installation and Configuration applet**
One of the notorious and in a way notable examples is Microsoft Windows NT OS network interface configuration code that involved a Small Prolog interpreter built in. Here is a [link](http://www.drdobbs.com/cpp/184409294) to the story written by David Hovel for Dr. Dobbs. (*The often cited Microsoft Research link seems to be gone.*)
* **Expert systems**
Once Prolog was considered as THE language for a class of software systems called *Expert Systems*. These were interactive knowledge management systems often with a relational database backend.
* **Beyond Prolog**
In general rule-based programming, resolution and different automated reasoning systems are widely used beyond Prolog.
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
```
|
You could use a filtering join:
```
update m
set BitField = 1
from MailSubscription m
join #temp t1
on t1.Service_id = m.Service_id
join #temp2 t2
on t2.UserProfile_Id= m.UserProfile_Id
and t1.EmailAddress = t2.EmailAddress
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE MailSubscription SET BitField=1
FROM #temp2
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress
WHERE MailSubscription.Service_id = #temp.ServiceId
AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id
```
|
Another option with EXISTS operator
```
UPDATE MailSubscription
SET BitField = 1
WHERE EXISTS (
SELECT 1
FROM #temp2 t2 JOIN #temp t ON t2.EmailAddress = t.EmailAddress
WHERE t2.UserProfile_Id = MailSubscription.UserProfile_Id
AND t.Service_Id = MailSubscription.Service_Id
)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
```
|
```
UPDATE MailSubscription SET BitField=1
FROM #temp2
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress
WHERE MailSubscription.Service_id = #temp.ServiceId
AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
You could use a filtering join:
```
update m
set BitField = 1
from MailSubscription m
join #temp t1
on t1.Service_id = m.Service_id
join #temp2 t2
on t2.UserProfile_Id= m.UserProfile_Id
and t1.EmailAddress = t2.EmailAddress
```
|
I think this should help u find the answer.
```
Update 'Tablename'
SET Mailsubscription = 1
WHERE concat(UserProfile_Id ,".", Service_Id) IN (
SELECT concat(t.UserProfile_Id , "." , t2,Service_Id)
FROM #temp t INNER JOIN #temp2 t2
ON t2.EmailAddress = t.EmailAddress)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE MailSubscription SET BitField=1
FROM #temp2
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress
WHERE MailSubscription.Service_id = #temp.ServiceId
AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id
```
|
I think this should help u find the answer.
```
Update 'Tablename'
SET Mailsubscription = 1
WHERE concat(UserProfile_Id ,".", Service_Id) IN (
SELECT concat(t.UserProfile_Id , "." , t2,Service_Id)
FROM #temp t INNER JOIN #temp2 t2
ON t2.EmailAddress = t.EmailAddress)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
You could use a filtering join:
```
update m
set BitField = 1
from MailSubscription m
join #temp t1
on t1.Service_id = m.Service_id
join #temp2 t2
on t2.UserProfile_Id= m.UserProfile_Id
and t1.EmailAddress = t2.EmailAddress
```
|
```
update MailSubscription set
BitField = 1
from MailSubscription as MS
where
exists
(
select *
from #temp2 as T2
inner join #temp as T on T.EmailAddress = T2.EmailAddress
where
T2.UserProfile_Id = MS.UserProfile_Id and
T.Service_Id = MS.Service_Id
)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
```
|
I think this should help u find the answer.
```
Update 'Tablename'
SET Mailsubscription = 1
WHERE concat(UserProfile_Id ,".", Service_Id) IN (
SELECT concat(t.UserProfile_Id , "." , t2,Service_Id)
FROM #temp t INNER JOIN #temp2 t2
ON t2.EmailAddress = t.EmailAddress)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
```
|
```
update MailSubscription set
BitField = 1
from MailSubscription as MS
where
exists
(
select *
from #temp2 as T2
inner join #temp as T on T.EmailAddress = T2.EmailAddress
where
T2.UserProfile_Id = MS.UserProfile_Id and
T.Service_Id = MS.Service_Id
)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE M
SET M.BitField=1
from MailSubscription M
inner join #temp2 t2 on M.UserProfile_id=t2.UserProfile_Id
inner join #temp t on M.Service_id=t.ServiceId
and t.EmailAddress=t2.EmailAddress
```
|
Another option with EXISTS operator
```
UPDATE MailSubscription
SET BitField = 1
WHERE EXISTS (
SELECT 1
FROM #temp2 t2 JOIN #temp t ON t2.EmailAddress = t.EmailAddress
WHERE t2.UserProfile_Id = MailSubscription.UserProfile_Id
AND t.Service_Id = MailSubscription.Service_Id
)
```
|
17,922,077 |
I have table with two FK `UserProfile_Id` and `Service_Id`. This table contains bit field which value I need to change.
I have two temporary tables:
First table **#temp2**:
```
EmailAddress,
UserProfile_Id
```
Second table **#temp**:
```
EmailAddress,
Service_Id
```
This statement does not work:
```
UPDATE MailSubscription SET BitField=1
where UserProfile_id IN ( SELECT UserProfile_Id from #temp2 )
and Service_id IN ( SELECT ServiceId from #temp)
```
I know why it does not work, but have no idea how to fix it to work fine.
I need to change `bitField` for `MailSubscription` where **tuple**(UserProfile\_Id,Service\_Id) is in joined #temp and #temp2, but I can not write it like this in mssql.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17922077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714342/"
] |
```
UPDATE MailSubscription SET BitField=1
FROM #temp2
JOIN #temp on #temp2.EmailAddress=#temp.EmailAddress
WHERE MailSubscription.Service_id = #temp.ServiceId
AND MailSubscription.UserProfile_id = #temp2.UserProfile_Id
```
|
```
update MailSubscription set
BitField = 1
from MailSubscription as MS
where
exists
(
select *
from #temp2 as T2
inner join #temp as T on T.EmailAddress = T2.EmailAddress
where
T2.UserProfile_Id = MS.UserProfile_Id and
T.Service_Id = MS.Service_Id
)
```
|
52,485,689 |
I am new in Android, I have finished some Android app development courses and now I am trying to apply what I learned. I've chosen a news app for it. It will extract news' from 5-10 source and display them in recyclerview.
I recognized that the course materials I used is outdated. I've used AsynctaskLoader to handle internet connection issues but now in official Android documentation it says *"Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData."*
My question is should I convert my code to comply with ViewModels and LiveData or would Asynctask handle my task (or any other suggestion)? As I mentioned I only want to extract news data from a couple of source and display them in the app. It seems I don't need data storage feature. But, for now I have added two news source and the app seems to load news data a little bit late. Does this latency has something to do with using loaders? Would using viewmodels speed up news loading task (especially when there are lots of news source)?
|
2018/09/24
|
[
"https://Stackoverflow.com/questions/52485689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10392737/"
] |
If you've already written it with Loaders there's no reason to rush to change it. Deprecated doesn't mean gone. And no, Loaders don't add significant performance penalty- any perf issues would be elsewhere in your app.
|
Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData. ViewModels survive configuration changes like Loaders but with less boilerplate. LiveData provides a lifecycle-aware way of loading data that you can reuse in multiple ViewModels. You can also combine LiveData using MediatorLiveData , and any observable queries, such as those from a Room database, can be used to observe changes to the data. ViewModels and LiveData are also available in situations where you do not have access to the LoaderManager, such as in a Service. Using the two in tandem provides an easy way to access the data your app needs without having to deal with the UI lifecycle.
|
52,485,689 |
I am new in Android, I have finished some Android app development courses and now I am trying to apply what I learned. I've chosen a news app for it. It will extract news' from 5-10 source and display them in recyclerview.
I recognized that the course materials I used is outdated. I've used AsynctaskLoader to handle internet connection issues but now in official Android documentation it says *"Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData."*
My question is should I convert my code to comply with ViewModels and LiveData or would Asynctask handle my task (or any other suggestion)? As I mentioned I only want to extract news data from a couple of source and display them in the app. It seems I don't need data storage feature. But, for now I have added two news source and the app seems to load news data a little bit late. Does this latency has something to do with using loaders? Would using viewmodels speed up news loading task (especially when there are lots of news source)?
|
2018/09/24
|
[
"https://Stackoverflow.com/questions/52485689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10392737/"
] |
Loaders are good because of its ability to handle life cycle, but it is not as efficient as LiveData and ViewModel. If you care about performance, speed and being latest, use Android Architecture Components (LiveData, ViewModel), also, you don't have to stick to the old system of doing things, you can write a simple AsyncTask and wrap it with ViewModel and LiveData. It works like a magic and better than Loaders. For information on how to wrap AsyncTask in LiveData and ViewModel, visit <https://medium.com/androiddevelopers/lifecycle-aware-data-loading-with-android-architecture-components-f95484159de4>
|
Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData. ViewModels survive configuration changes like Loaders but with less boilerplate. LiveData provides a lifecycle-aware way of loading data that you can reuse in multiple ViewModels. You can also combine LiveData using MediatorLiveData , and any observable queries, such as those from a Room database, can be used to observe changes to the data. ViewModels and LiveData are also available in situations where you do not have access to the LoaderManager, such as in a Service. Using the two in tandem provides an easy way to access the data your app needs without having to deal with the UI lifecycle.
|
30,299,397 |
I'm trying to show `UIActionSheet` on iPad from button on `UITableViewCell`. It works fine on iOS 7, but not working properly on iOS 8. `UIActionSheet` containts some visual artifacts and I'm getting this warning in console:
```
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSLayoutConstraint:0x79793de0 H:[UIView:0x797a7630(304)]>",
"<NSLayoutConstraint:0x7a16ae00 UIView:0x7a16ab60.width == _UIAlertControllerView:0x797a9230.width>",
"<NSAutoresizingMaskLayoutConstraint:0x7a66f2a0 h=--& v=--& H:[UIView:0x7a16ab60(298)]>",
"<NSLayoutConstraint:0x797a49e0 _UIAlertControllerView:0x797a9230.width >= UIView:0x797a7630.width>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x79793de0 H:[UIView:0x797a7630(304)]>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
```
My code:
```
- (void)onFavoriteBtn:(id)sender {
CGPoint btnPosition = [sender convertPoint:CGPointZero toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:btnPosition];
if (indexPath) {
UIButton *favoriteBtn = (UIButton *)sender;
CGRect favoriteBtnRect = favoriteBtn.frame;
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Remove from Favorites" otherButtonTitles:nil];
[sheet showFromRect:favoriteBtnRect inView:favoriteBtn.superview animated:true];
}
}
```
|
2015/05/18
|
[
"https://Stackoverflow.com/questions/30299397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1561346/"
] |
`UIActionSheet` is deprecated, so you can use `UIAlertViewController` available in iOS 8.0 or later.
```
- (IBAction)onFavoriteBtn:(id)sender {
CGPoint btnPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:btnPosition];
if (indexPath) {
[self showActionSheet:sender];
}
}
- (void)showActionSheet:(UIView *)sender
{
NSString *alertTitle = NSLocalizedString(@"ActionTitle", @"Archive or Delete Data");
NSString *alertMessage = NSLocalizedString(@"ActionMessage", @"Deleted data cannot be undone");
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
message:alertMessage
preferredStyle:UIAlertControllerStyleActionSheet];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction *action)
{
NSLog(@"Cancel action");
}];
UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Delete", @"Delete action")
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *action)
{
NSLog(@"Delete action");
}];
UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Archive", @"Archive action")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action)
{
NSLog(@"Archive action");
}];
[alertController addAction:cancelAction];
[alertController addAction:deleteAction];
[alertController addAction:archiveAction];
UIPopoverPresentationController *popover = alertController.popoverPresentationController;
if (popover)
{
popover.sourceView = sender;
popover.sourceRect = sender.bounds;
popover.permittedArrowDirections = UIPopoverArrowDirectionAny;
}
[self presentViewController:alertController animated:YES completion:nil];
}
```
|
Looks like your favorite button superview is too small to embed action sheet. Try to use window to display action sheet, just don't forget convert coordinates of favorites button:
```
- (void)onFavoriteBtn:(id)sender {
CGPoint btnPosition = [sender convertPoint:CGPointZero toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:btnPosition];
if (indexPath) {
UIButton *favoriteBtn = (UIButton *)sender;
CGRect frame = [self.window convertRect:favoriteBtn.bounds fromView:favoriteBtn];
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Remove from Favorites" otherButtonTitles:nil];
[sheet showFromRect:frame inView:self.window animated:true];
}
}
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
### `Using ES6:`
```js
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
```
OR
```js
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
```
|
Here a function which solves your problem.
```js
const minMaxSum = (arr) => {
const orderedAr = arr.sort((a, b) => a - b);
const min = orderedAr
.slice(0, 4)
.reduce((val, acc) => acc + val, 0);
const max = orderedAr
.slice(-4)
.reduce((val, acc) => acc + val, 0);
return `${min} ${max}`;
};
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
### `Using ES6:`
```js
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
```
OR
```js
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
```
|
My approach considering Optimal time/space complexity:
* find min/max values from input array with Infinity/-Infinity
* calculate totalSum of input array
* print out (totalSum - max, totalSum - min)
##### Time: O(n) where n is # elements in input array
##### Space: O(1) no extra memory needed
```
function miniMaxSum(array) {
let min = Infinity; // any number lesser than Infinity becomes min
let max = -Infinity; // any number greater than -Infinity becomes max
let totalSum = 0;
for(let i = 0; i < array.length; i++) {
if(array[i] < min) min = array[i];
if(array[i] > max) max = array[i];
totalSum += array[i];
};
// sum - max gets us MINSUM
// sum - min gets us MAXSUM
console.log(totalSum - max, totalSum - min);
};
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
### `Using ES6:`
```js
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
```
OR
```js
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
```
|
Here's the full code with more optimized and cleaned with all test cases working-
Using Arrays.sort()
```
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr)
{
int min=0;
int max=0;
Arrays.sort(arr);
for(int i=0; i<arr.length;i++)
{
if(i>0)
{
max+=arr[i];
}
if(i<4)
{
min+=arr[i];
}
}
System.out.println(min + " " + max);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] arr = new int[5];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < 5; i++)
{
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
miniMaxSum(arr);
scanner.close();
}
}
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
### `Using ES6:`
```js
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
```
OR
```js
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
```
|
**New Answer**
```js
const arr = [5,5,5,5,7]
const min = (arr) => {
const max = Math.max(...arr)
const min = Math.min(...arr)
let maxIndexValue
let minIndexValue
let maxResult = 0
let minResult = 0
if(arr.reduce((val, c) => val + c) / arr.length === arr[0]){
const arrayFilter = arr.slice(1);
let maxResult = arrayFilter.reduce((val, c) => val + c)
let minResult = arrayFilter.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}else{
for(let i = 0; i < arr.length; i++){
if(arr[i] === max){
maxIndexValue = i
}
if(arr[i] === min){
minIndexValue = i
}
}
const maxArray = arr.filter((element, index, num)=> num[index] !== num[maxIndexValue])
const minArray = arr.filter((element, index, num)=> num[index] !== num[minIndexValue])
const maxResult = maxArray.reduce((val, c) => val + c)
const minResult = minArray.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}
}
min(arr)
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
You could take the first value as start value for `sum`, `min` and `max` value and iterate from the second item. Then add the actual value and check `min` and `max` values and take adjustments.
At the end return the delta of `sum` and `max` and `sum` and `min`.
```js
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
```
|
**New Answer**
```js
const arr = [5,5,5,5,7]
const min = (arr) => {
const max = Math.max(...arr)
const min = Math.min(...arr)
let maxIndexValue
let minIndexValue
let maxResult = 0
let minResult = 0
if(arr.reduce((val, c) => val + c) / arr.length === arr[0]){
const arrayFilter = arr.slice(1);
let maxResult = arrayFilter.reduce((val, c) => val + c)
let minResult = arrayFilter.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}else{
for(let i = 0; i < arr.length; i++){
if(arr[i] === max){
maxIndexValue = i
}
if(arr[i] === min){
minIndexValue = i
}
}
const maxArray = arr.filter((element, index, num)=> num[index] !== num[maxIndexValue])
const minArray = arr.filter((element, index, num)=> num[index] !== num[minIndexValue])
const maxResult = maxArray.reduce((val, c) => val + c)
const minResult = minArray.reduce((val, c) => val + c)
console.log(maxResult, minResult)
}
}
min(arr)
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
### `Using ES6:`
```js
let numbers = [3,1,5,9,7]
let ascending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => a - b)
ascending.pop()
let min = ascending.reduce((a, b) => a + b)
let descending = JSON.parse(JSON.stringify(numbers)).sort((a, b) => b - a)
descending.pop()
let max = descending.reduce((a, b) => a + b)
console.log(`${min} ${max}`)
```
OR
```js
let numbers = [3,1,5,9,7]
let sum = numbers.reduce((a, b) => a + b)
let maxNumber = Math.max(...numbers)
let minNumber = Math.min(...numbers)
console.log(`${sum - maxNumber} ${sum - minNumber}`)
```
|
Have a look at this code.
```js
function miniMaxSum(arr) {
// Write your code here
const MaxValue = Math.max(...arr)
const MinValue = Math.min(...arr)
const MaxSum = arr.reduce((a,b) => a+b) - MinValue
const MinSum = arr.reduce((a,b) => a+b) - MaxValue
return `${MinSum} ${MaxSum}`
}
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
You could take the first value as start value for `sum`, `min` and `max` value and iterate from the second item. Then add the actual value and check `min` and `max` values and take adjustments.
At the end return the delta of `sum` and `max` and `sum` and `min`.
```js
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
```
|
Have a look at this code.
```js
function miniMaxSum(arr) {
// Write your code here
const MaxValue = Math.max(...arr)
const MinValue = Math.min(...arr)
const MaxSum = arr.reduce((a,b) => a+b) - MinValue
const MinSum = arr.reduce((a,b) => a+b) - MaxValue
return `${MinSum} ${MaxSum}`
}
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
You could take the first value as start value for `sum`, `min` and `max` value and iterate from the second item. Then add the actual value and check `min` and `max` values and take adjustments.
At the end return the delta of `sum` and `max` and `sum` and `min`.
```js
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
```
|
Here's the full code with more optimized and cleaned with all test cases working-
Using Arrays.sort()
```
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr)
{
int min=0;
int max=0;
Arrays.sort(arr);
for(int i=0; i<arr.length;i++)
{
if(i>0)
{
max+=arr[i];
}
if(i<4)
{
min+=arr[i];
}
}
System.out.println(min + " " + max);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args)
{
int[] arr = new int[5];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < 5; i++)
{
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
miniMaxSum(arr);
scanner.close();
}
}
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
You could take the first value as start value for `sum`, `min` and `max` value and iterate from the second item. Then add the actual value and check `min` and `max` values and take adjustments.
At the end return the delta of `sum` and `max` and `sum` and `min`.
```js
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
```
|
My approach considering Optimal time/space complexity:
* find min/max values from input array with Infinity/-Infinity
* calculate totalSum of input array
* print out (totalSum - max, totalSum - min)
##### Time: O(n) where n is # elements in input array
##### Space: O(1) no extra memory needed
```
function miniMaxSum(array) {
let min = Infinity; // any number lesser than Infinity becomes min
let max = -Infinity; // any number greater than -Infinity becomes max
let totalSum = 0;
for(let i = 0; i < array.length; i++) {
if(array[i] < min) min = array[i];
if(array[i] > max) max = array[i];
totalSum += array[i];
};
// sum - max gets us MINSUM
// sum - min gets us MAXSUM
console.log(totalSum - max, totalSum - min);
};
```
|
60,362,680 |
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
For example `var arr = [1,3,5,7,9]` the output will be 16 24.
Here is my solution.everything works except one case.When all element in the arr are equal my solutions returns error. How I can fix it?
```
function miniMaxSum(arr) {
let largest = arr[0];
let smallest = arr[0];
let largestSum = 0;
let smallestSum = 0;
for(let i = 0; i < arr.length; i ++){
if(arr[i] > largest){
largest = arr[i];
}
if (arr[i] < smallest){
smallest = arr[i];
}
}
for(let j = 0; j < arr.length; j ++){
if(arr[j] < largest){
smallestSum = smallestSum + arr[j];
}
if(arr[j] > smallest){
largestSum = largestSum + arr[j];
}
}
console.log(smallestSum + " " + largestSum)
}
```
|
2020/02/23
|
[
"https://Stackoverflow.com/questions/60362680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11213856/"
] |
You could take the first value as start value for `sum`, `min` and `max` value and iterate from the second item. Then add the actual value and check `min` and `max` values and take adjustments.
At the end return the delta of `sum` and `max` and `sum` and `min`.
```js
function minMaxSum(array) {
var sum = array[0],
min = array[0],
max = array[0];
for (let i = 1; i < array.length; i++) {
sum += array[i];
if (min > array[i]) min = array[i];
if (max < array[i]) max = array[i];
}
return [sum - max, sum - min];
}
console.log(minMaxSum([1, 3, 5, 7, 9]));
```
|
The solution is simple, just get the min and max value, sum the array and extract min or max in order to get the max sum or min sum.
As pseudocede:
```
min_value = find_min_value(arr)
max_value = find_max_value(arr)
max_sum = sum_array(arr) - min_value
min_sum = sum_array(arr) - max_value
```
:)
|
39,277,227 |
I have the following :
```
$data = [
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 31.25, treatment : 'Pressure' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 31.25, treatment : 'Gas' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 33.12, treatment : 'Temp' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 25.87, treatment : 'Current' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 26.63, treatment : 'Pressure' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 26.00, treatment : 'Gas' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 23.75, treatment : 'Temp' }
];
```
and i would like to end up with something like this:
```
var data=[{model_num : "ABC", revision : "AA", "testRecipeID":85, "Pressure":31.25, "Gas":31.25, "Temp": 33.12,"Current":25.87 },{model_num : "ABC", revision : "AB", "testRecipeID":86, "Gas":26.00,"Temp":23.75}]
```
I know how to do this in JS but not on PHP and it turns out I need to do it in my php so that I can process the large amounts of data that I have. I have this based on another question that I found but It doesn't work it returns a 0
```
$table = array();
$round_names = array();
$total = array();
foreach ($data as $score)
{
$round_names[] = $score->treatment;
$table[$score->testRecipeID][$score->treatment] = $score->value;
$total[$score->testRecipeID] += $score->value;
print_r($round_names);
}
$round_names = array_unique($round_names);
foreach ($table as $player => $rounds)
{
echo "$player\t";
foreach ($round_names as $round)
echo "$rounds[$round]\t";
echo "$total[$player]\n";
}
```
any help will be greatly appreciated!
this is how i do it in JS
```
var result = [];
data.forEach(function(e) {
var a = e.model_num + '|' + e.revision+ '|'e.recipeID;
if(!this[a]) {
this[a] = {model_num: e.model_num, revision: e.revision, recipeID: e.recipeID}
result.push(this[a]);
}
this[a][e.treatment] = e.value;
}, {});
```
|
2016/09/01
|
[
"https://Stackoverflow.com/questions/39277227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5636625/"
] |
If you need the structure, you can try with [JSON Encode](http://php.net/manual/en/function.json-encode.php):
```
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
```
Which outputs:
```
{"a":1,"b":2,"c":3,"d":4,"e":5}
```
If you need it to be an array, use:
```
echo json_encode(array($arr));
```
|
Because neither of the previous answers managed to provide the desired output, I am compelled to answer this pivot question.
1. Create a temporary string from the 3 identifying column values.
2. Use that string as the first level key while grouping related row data.
3. The null coalescing assignment operator spares you needing to call `isset()` to check if the group has been encountered before. If it is the first encounter, save the three core elements to the row.
4. Unconditionally push the dynamically keyed value into the group's row.
5 When finished iterating clear away the temporary keys with `array_values()`.
Code: ([Demo](https://3v4l.org/2PPl6))
```
$data = [
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 31.25, 'treatment' => 'Pressure'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 31.25, 'treatment' => 'Gas'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 33.12, 'treatment' => 'Temp'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 25.87, 'treatment' => 'Current'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 26.63, 'treatment' => 'Pressure'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 26.0, 'treatment' => 'Gas'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 23.75, 'treatment' => 'Temp']
];
$result = [];
foreach ($data as $row) {
$compositeKey = "{$row['model_num']}-{$row['revision']}-{$row['testRecipeID']}";
$result[$compositeKey] ??= [
'model_num' => $row['model_num'],
'revision' => $row['revision'],
'testRecipeID' => $row['testRecipeID']
];
$result[$compositeKey][$row['treatment']] = $row['value'];
}
var_export(array_values($result));
```
Output:
```
array (
0 =>
array (
'model_num' => 'ABC',
'revision' => 'AA',
'testRecipeID' => 85,
'Pressure' => 31.25,
'Gas' => 31.25,
'Temp' => 33.12,
'Current' => 25.87,
),
1 =>
array (
'model_num' => 'ABC',
'revision' => 'AB',
'testRecipeID' => 86,
'Pressure' => 26.63,
'Gas' => 26.0,
'Temp' => 23.75,
),
)
```
|
39,277,227 |
I have the following :
```
$data = [
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 31.25, treatment : 'Pressure' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 31.25, treatment : 'Gas' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 33.12, treatment : 'Temp' },
{model_num : "ABC", revision : "AA", "testRecipeID":85, value : 25.87, treatment : 'Current' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 26.63, treatment : 'Pressure' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 26.00, treatment : 'Gas' },
{model_num : "ABC", revision : "AB", "testRecipeID":86, value : 23.75, treatment : 'Temp' }
];
```
and i would like to end up with something like this:
```
var data=[{model_num : "ABC", revision : "AA", "testRecipeID":85, "Pressure":31.25, "Gas":31.25, "Temp": 33.12,"Current":25.87 },{model_num : "ABC", revision : "AB", "testRecipeID":86, "Gas":26.00,"Temp":23.75}]
```
I know how to do this in JS but not on PHP and it turns out I need to do it in my php so that I can process the large amounts of data that I have. I have this based on another question that I found but It doesn't work it returns a 0
```
$table = array();
$round_names = array();
$total = array();
foreach ($data as $score)
{
$round_names[] = $score->treatment;
$table[$score->testRecipeID][$score->treatment] = $score->value;
$total[$score->testRecipeID] += $score->value;
print_r($round_names);
}
$round_names = array_unique($round_names);
foreach ($table as $player => $rounds)
{
echo "$player\t";
foreach ($round_names as $round)
echo "$rounds[$round]\t";
echo "$total[$player]\n";
}
```
any help will be greatly appreciated!
this is how i do it in JS
```
var result = [];
data.forEach(function(e) {
var a = e.model_num + '|' + e.revision+ '|'e.recipeID;
if(!this[a]) {
this[a] = {model_num: e.model_num, revision: e.revision, recipeID: e.recipeID}
result.push(this[a]);
}
this[a][e.treatment] = e.value;
}, {});
```
|
2016/09/01
|
[
"https://Stackoverflow.com/questions/39277227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5636625/"
] |
This is your JS function in PHP
```
<?php
$data = '[
{"model_num" : "ABC", "revision" : "AA", "testRecipeID":85, "value" : 31.25, "treatment" : "Pressure" },
{"model_num" : "ABC", "revision" : "AA", "testRecipeID":85, "value" : 31.25, "treatment" : "Gas" },
{"model_num" : "ABC", "revision" : "AA", "testRecipeID":85, "value" : 33.12, "treatment" : "Temp" },
{"model_num" : "ABC", "revision" : "AA", "testRecipeID":85, "value" : 25.87, "treatment" : "Current" },
{"model_num" : "ABC", "revision" : "AB", "testRecipeID":86, "value" : 26.63, "treatment" : "Pressure" },
{"model_num" : "ABC", "revision" : "AB", "testRecipeID":86, "value" : 26.00, "treatment" : "Gas" },
{"model_num" : "ABC", "revision" : "AB", "testRecipeID":86, "value" : 23.75, "treatment" : "Temp" }
]';
$data = json_decode($data);
$result = [];
foreach ($data as $row) {
$a = $row->model_num . '|' . $row->revision . '|' . $row->testRecipeID;
if (! array_key_exists($a, $result)) {
$result[$a] = [
'model_num' => $row->model_num,
'revision' => $row->revision,
'testRecipeID' => $row->testRecipeID
];
}
}
```
|
Because neither of the previous answers managed to provide the desired output, I am compelled to answer this pivot question.
1. Create a temporary string from the 3 identifying column values.
2. Use that string as the first level key while grouping related row data.
3. The null coalescing assignment operator spares you needing to call `isset()` to check if the group has been encountered before. If it is the first encounter, save the three core elements to the row.
4. Unconditionally push the dynamically keyed value into the group's row.
5 When finished iterating clear away the temporary keys with `array_values()`.
Code: ([Demo](https://3v4l.org/2PPl6))
```
$data = [
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 31.25, 'treatment' => 'Pressure'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 31.25, 'treatment' => 'Gas'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 33.12, 'treatment' => 'Temp'],
['model_num' => 'ABC', 'revision' => 'AA', 'testRecipeID' => 85, 'value' => 25.87, 'treatment' => 'Current'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 26.63, 'treatment' => 'Pressure'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 26.0, 'treatment' => 'Gas'],
['model_num' => 'ABC', 'revision' => 'AB', 'testRecipeID' => 86, 'value' => 23.75, 'treatment' => 'Temp']
];
$result = [];
foreach ($data as $row) {
$compositeKey = "{$row['model_num']}-{$row['revision']}-{$row['testRecipeID']}";
$result[$compositeKey] ??= [
'model_num' => $row['model_num'],
'revision' => $row['revision'],
'testRecipeID' => $row['testRecipeID']
];
$result[$compositeKey][$row['treatment']] = $row['value'];
}
var_export(array_values($result));
```
Output:
```
array (
0 =>
array (
'model_num' => 'ABC',
'revision' => 'AA',
'testRecipeID' => 85,
'Pressure' => 31.25,
'Gas' => 31.25,
'Temp' => 33.12,
'Current' => 25.87,
),
1 =>
array (
'model_num' => 'ABC',
'revision' => 'AB',
'testRecipeID' => 86,
'Pressure' => 26.63,
'Gas' => 26.0,
'Temp' => 23.75,
),
)
```
|
72,047 |
I would like to build a electronic flatulence (fart) detector. I was thinking of methane because detectors are readily available, but I read <http://en.wikipedia.org/wiki/Flatulence> and it says:
>
> However, not all humans produce flatus that contains methane. For example, in one study of the feces of nine adults, only five of the samples contained archaea capable of producing methane.
>
>
>
Oxygen, nitrogen, carbon dioxide are listed but I think they would be too common in normal air. That seems to leave:
* Hydrogen
* Hydrogen sulfide
* Methyl mercaptan
* Dimethyl sulfide
* Dimethyl trisulfide
Does anyone know if practical sensors are available that detect those gases or have other ideas? I think somewhere around the $20 or less mark would be good, so I wasn't really seeking a full professional solution like gas chromatography that may normally be used.
The application is for under office type chairs, so maybe heat detection could be used although I'm not sure it would be posible to tell the difference between the desired event and someone just sitting down on a cold chair, although maybe a pressure sensor could be used along with some filtering to not trigger until the temperature had stabilized a bit.
|
2013/06/08
|
[
"https://electronics.stackexchange.com/questions/72047",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/24932/"
] |
It looks like Hydrogen is the major component: [Normal Flatus](http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1378885/). 360mL perday. How much per fart will take some closer reading.
Here is an Arduino flamable gas detector, it probably can sense Hydrogen:
[LM393 MQ-9](http://dx.com/p/lm393-mq-9-flammable-gas-detection-sensor-module-for-arduino-red-black-151069), say, at 10ppm. (Some shopping legwork for a Hydrogen leak detector or flammable gas sensor is in order.) So a 36mL bolus of Hydrogen (I just guessed what volumes are emitted throughout the day to make up that 360ml, and guessed 1/10 of the total) must diffuse into a volume of 3600 Liters before it is below detection level of 10ppm. Your 10ppm sensor must be within about 100 centimeters. Looks like the under-the-seat location is the right spot.
|
Weird project. Chairs that detect farts? No thanks.
Anyway I would suggest you look at an off-the-shelf propane sensor. Propane (C3H8) and methane (CH4) are very similar. In fact many of them are described as Propane Methane sensors. They are cheap and made in the thousands for RV's and Boats. A friend of mine always said if he was too close the the sensor the alarm would go off.
|
72,047 |
I would like to build a electronic flatulence (fart) detector. I was thinking of methane because detectors are readily available, but I read <http://en.wikipedia.org/wiki/Flatulence> and it says:
>
> However, not all humans produce flatus that contains methane. For example, in one study of the feces of nine adults, only five of the samples contained archaea capable of producing methane.
>
>
>
Oxygen, nitrogen, carbon dioxide are listed but I think they would be too common in normal air. That seems to leave:
* Hydrogen
* Hydrogen sulfide
* Methyl mercaptan
* Dimethyl sulfide
* Dimethyl trisulfide
Does anyone know if practical sensors are available that detect those gases or have other ideas? I think somewhere around the $20 or less mark would be good, so I wasn't really seeking a full professional solution like gas chromatography that may normally be used.
The application is for under office type chairs, so maybe heat detection could be used although I'm not sure it would be posible to tell the difference between the desired event and someone just sitting down on a cold chair, although maybe a pressure sensor could be used along with some filtering to not trigger until the temperature had stabilized a bit.
|
2013/06/08
|
[
"https://electronics.stackexchange.com/questions/72047",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/24932/"
] |
Methane was used by another guy used in his office chair to detect his own flatus, but if that source is real, Futurlec seems to offer [dozens of gas sensors](http://www.futurlec.com/Gas_Sensors.shtml) for whatever gas you like.
As an example: [The Twittering Office Chair](http://www.instructables.com/id/The-Twittering-Office-Chair/) and [it's Twitter account](https://twitter.com/officechair) (apparently died of asphyxiation back in '09).
|
Weird project. Chairs that detect farts? No thanks.
Anyway I would suggest you look at an off-the-shelf propane sensor. Propane (C3H8) and methane (CH4) are very similar. In fact many of them are described as Propane Methane sensors. They are cheap and made in the thousands for RV's and Boats. A friend of mine always said if he was too close the the sensor the alarm would go off.
|
41,077,180 |
I'm attempting to nest an arc generated using `d3.arc` perfectly inside another arc.
I can do this by drawing "on my own":
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
function arc_position(x, y, radius, angle) {
return {
x: x + (radius * Math.cos(angle)),
y: y + (radius * Math.sin(angle))
};
}
function describe_arc(x, y, radius, startAngle, endAngle) {
var s = arc_position(x, y, radius, endAngle);
var e = arc_position(x, y, radius, startAngle);
var sweep = e - s <= 180 ? '0' : '1';
var d = [
'M', s.x, s.y,
'A', radius, radius, 0, sweep, 0, e.x, e.y
].join(' ');
return d;
}
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g");
var s = arc_position(250, 250, 200, Math.PI/2);
var e = arc_position(250, 250, 200, (Math.PI * 3)/2);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,180,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 30) + "," + s.y + "L" + (e.x + 30) + "," + e.y);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,200,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 10) + "," + s.y + "L" + (e.x + 10) + "," + e.y);
</script>
</body>
</html>
```
But I can't figure out a methodology using `d3.arc`:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(200)
.startAngle(0)
.endAngle(Math.PI);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", arc());
arc.outerRadius(200 - 40);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", arc())
.attr("transform", "translate(20,0)")
</script>
</body>
</html>
```
Any ideas?
|
2016/12/10
|
[
"https://Stackoverflow.com/questions/41077180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] |
I don't think that there is a good way to do this just using `d3.arc` because that is meant for drawing sections of circles and you're trying to draw a partial ellipse.
You can get close by generating the angle offset using the stroke width and the radius of the inner arc as `offsetAngle = sin(stroke width / inner radius)`. The arc's `startAngle` is the `offsetAngle` and the `endAngle` is `Math.PI - offsetAngle`.
Unfortunately, that will generate a path which includes the center point of the circle. You can hack together something that works by just removing the `L0,0` from the generated path (`innerArc().replace("L0,0","")`) and this will give you what you want, albeit in an ugly fashion.
Because it is a fairly simple path, it is probably best to use your own path generator to do this instead.
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var outerRadius = 200;
var stroke = 20;
var innerRadius = outerRadius - stroke;
var innerAngle = Math.sin(stroke/innerRadius);
var outerArc = d3.arc()
.innerRadius(0)
.outerRadius(outerRadius)
.startAngle(0)
.endAngle(Math.PI);
var innerArc = d3.arc()
.innerRadius(0)
.outerRadius(innerRadius)
.startAngle(innerAngle)
.endAngle(Math.PI - innerAngle);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", stroke)
.attr("d", outerArc());
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", stroke)
.attr("d", innerArc().replace("L0,0",""));
</script>
</body>
</html>
```
|
You draw second arc with outer radius `R - 2 * strokewidth` and center shifted by `strokewidth`.
But smaller arc should have **the same center** as larger one and outer radius `R - strokewidth`
|
41,077,180 |
I'm attempting to nest an arc generated using `d3.arc` perfectly inside another arc.
I can do this by drawing "on my own":
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
function arc_position(x, y, radius, angle) {
return {
x: x + (radius * Math.cos(angle)),
y: y + (radius * Math.sin(angle))
};
}
function describe_arc(x, y, radius, startAngle, endAngle) {
var s = arc_position(x, y, radius, endAngle);
var e = arc_position(x, y, radius, startAngle);
var sweep = e - s <= 180 ? '0' : '1';
var d = [
'M', s.x, s.y,
'A', radius, radius, 0, sweep, 0, e.x, e.y
].join(' ');
return d;
}
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g");
var s = arc_position(250, 250, 200, Math.PI/2);
var e = arc_position(250, 250, 200, (Math.PI * 3)/2);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,180,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 30) + "," + s.y + "L" + (e.x + 30) + "," + e.y);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,200,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 10) + "," + s.y + "L" + (e.x + 10) + "," + e.y);
</script>
</body>
</html>
```
But I can't figure out a methodology using `d3.arc`:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(200)
.startAngle(0)
.endAngle(Math.PI);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", arc());
arc.outerRadius(200 - 40);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", arc())
.attr("transform", "translate(20,0)")
</script>
</body>
</html>
```
Any ideas?
|
2016/12/10
|
[
"https://Stackoverflow.com/questions/41077180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] |
*(This is not an answer, but just a comment, which I chose to disguise as an answer because I need the S.O. snippet)*
I believe that [Paul S](https://stackoverflow.com/a/41082900/5768908) is right, and he deserves the *big prize* of the green tick: what you're trying to paint in the inner (orange) path is **not** an arc of a circumference, but an *ellipse* instead. And, as the docs say,
>
> The arc generator produces a circular or annular sector
>
>
>
, which will not work for creating an elliptic sector.
You can easily see that in the following demo: using a for loop, we draw arcs with decreasing outer radius. The only way to perfectly fill the internal space of each arc is if the next, smaller arch has **the same center** of the precedent, bigger one:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(200)
.startAngle(0)
.endAngle(Math.PI);
var color = d3.scaleOrdinal(d3.schemeCategory10);
for(var i = 0; i<11; i++){
svg.append("path")
.style("stroke", color(i))
.style("fill", "none")
.style("stroke-width", "20px")
.attr("d", arc());
arc.outerRadius(200 - 20*i);
};
</script>
</body>
</html>
```
There is an even easier way to visualize that. Let's create a single arc, with a huge stroke:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(150)
.startAngle(0)
.endAngle(Math.PI);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "100px")
.attr("d", arc());
</script>
</body>
</html>
```
Look at the blue arc: it is a semicircle. Now look at the white space inside it: it's clearly **not** a semicircle. The blue thing is a semicircle, but the space inside it is not.
So, as `d3.arc()` right now doesn't have the option to set **two different focal points**, the options are creating your own function (as you did) or hacking the path (as Paul S did).
|
You draw second arc with outer radius `R - 2 * strokewidth` and center shifted by `strokewidth`.
But smaller arc should have **the same center** as larger one and outer radius `R - strokewidth`
|
41,077,180 |
I'm attempting to nest an arc generated using `d3.arc` perfectly inside another arc.
I can do this by drawing "on my own":
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
function arc_position(x, y, radius, angle) {
return {
x: x + (radius * Math.cos(angle)),
y: y + (radius * Math.sin(angle))
};
}
function describe_arc(x, y, radius, startAngle, endAngle) {
var s = arc_position(x, y, radius, endAngle);
var e = arc_position(x, y, radius, startAngle);
var sweep = e - s <= 180 ? '0' : '1';
var d = [
'M', s.x, s.y,
'A', radius, radius, 0, sweep, 0, e.x, e.y
].join(' ');
return d;
}
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g");
var s = arc_position(250, 250, 200, Math.PI/2);
var e = arc_position(250, 250, 200, (Math.PI * 3)/2);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,180,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 30) + "," + s.y + "L" + (e.x + 30) + "," + e.y);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", describe_arc(250,250,200,(Math.PI * 3)/2, Math.PI/2));
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", "M" + (s.x + 10) + "," + s.y + "L" + (e.x + 10) + "," + e.y);
</script>
</body>
</html>
```
But I can't figure out a methodology using `d3.arc`:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(200)
.startAngle(0)
.endAngle(Math.PI);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "20px")
.attr("d", arc());
arc.outerRadius(200 - 40);
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", "20px")
.attr("d", arc())
.attr("transform", "translate(20,0)")
</script>
</body>
</html>
```
Any ideas?
|
2016/12/10
|
[
"https://Stackoverflow.com/questions/41077180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] |
I don't think that there is a good way to do this just using `d3.arc` because that is meant for drawing sections of circles and you're trying to draw a partial ellipse.
You can get close by generating the angle offset using the stroke width and the radius of the inner arc as `offsetAngle = sin(stroke width / inner radius)`. The arc's `startAngle` is the `offsetAngle` and the `endAngle` is `Math.PI - offsetAngle`.
Unfortunately, that will generate a path which includes the center point of the circle. You can hack together something that works by just removing the `L0,0` from the generated path (`innerArc().replace("L0,0","")`) and this will give you what you want, albeit in an ugly fashion.
Because it is a fairly simple path, it is probably best to use your own path generator to do this instead.
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var outerRadius = 200;
var stroke = 20;
var innerRadius = outerRadius - stroke;
var innerAngle = Math.sin(stroke/innerRadius);
var outerArc = d3.arc()
.innerRadius(0)
.outerRadius(outerRadius)
.startAngle(0)
.endAngle(Math.PI);
var innerArc = d3.arc()
.innerRadius(0)
.outerRadius(innerRadius)
.startAngle(innerAngle)
.endAngle(Math.PI - innerAngle);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", stroke)
.attr("d", outerArc());
svg.append("path")
.style("fill", "none")
.style("stroke", "orange")
.style("stroke-width", stroke)
.attr("d", innerArc().replace("L0,0",""));
</script>
</body>
</html>
```
|
*(This is not an answer, but just a comment, which I chose to disguise as an answer because I need the S.O. snippet)*
I believe that [Paul S](https://stackoverflow.com/a/41082900/5768908) is right, and he deserves the *big prize* of the green tick: what you're trying to paint in the inner (orange) path is **not** an arc of a circumference, but an *ellipse* instead. And, as the docs say,
>
> The arc generator produces a circular or annular sector
>
>
>
, which will not work for creating an elliptic sector.
You can easily see that in the following demo: using a for loop, we draw arcs with decreasing outer radius. The only way to perfectly fill the internal space of each arc is if the next, smaller arch has **the same center** of the precedent, bigger one:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(200)
.startAngle(0)
.endAngle(Math.PI);
var color = d3.scaleOrdinal(d3.schemeCategory10);
for(var i = 0; i<11; i++){
svg.append("path")
.style("stroke", color(i))
.style("fill", "none")
.style("stroke-width", "20px")
.attr("d", arc());
arc.outerRadius(200 - 20*i);
};
</script>
</body>
</html>
```
There is an even easier way to visualize that. Let's create a single arc, with a huge stroke:
```html
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform","translate(250,250)");
var arc = d3.arc()
.innerRadius(0)
.outerRadius(150)
.startAngle(0)
.endAngle(Math.PI);
svg.append("path")
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "100px")
.attr("d", arc());
</script>
</body>
</html>
```
Look at the blue arc: it is a semicircle. Now look at the white space inside it: it's clearly **not** a semicircle. The blue thing is a semicircle, but the space inside it is not.
So, as `d3.arc()` right now doesn't have the option to set **two different focal points**, the options are creating your own function (as you did) or hacking the path (as Paul S did).
|
2,522,609 |
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
**EDIT**
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
|
2010/03/26
|
[
"https://Stackoverflow.com/questions/2522609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179855/"
] |
using `ob_*` functions such as `ob_get_contents()`, a php script can catch it's output.
|
probably with ob\_start and output\_callback see <http://php.net/manual/en/function.ob-start.php>
|
2,522,609 |
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
**EDIT**
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
|
2010/03/26
|
[
"https://Stackoverflow.com/questions/2522609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179855/"
] |
Try something like this:
```
// Start output buffering
ob_start();
// run code in x.php file
// ...
// saving captured output to file
file_put_contents('filename.htm', ob_get_contents());
// end buffering and displaying page
ob_end_flush();
```
If you cannot use the [ob\_\* functions](http://de3.php.net/manual/en/ref.outcontrol.php), you can also write the form to a variable and then save that variable.
|
using `ob_*` functions such as `ob_get_contents()`, a php script can catch it's output.
|
2,522,609 |
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
**EDIT**
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
|
2010/03/26
|
[
"https://Stackoverflow.com/questions/2522609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179855/"
] |
Try something like this:
```
// Start output buffering
ob_start();
// run code in x.php file
// ...
// saving captured output to file
file_put_contents('filename.htm', ob_get_contents());
// end buffering and displaying page
ob_end_flush();
```
If you cannot use the [ob\_\* functions](http://de3.php.net/manual/en/ref.outcontrol.php), you can also write the form to a variable and then save that variable.
|
probably with ob\_start and output\_callback see <http://php.net/manual/en/function.ob-start.php>
|
2,522,609 |
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
**EDIT**
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
|
2010/03/26
|
[
"https://Stackoverflow.com/questions/2522609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179855/"
] |
Look at ob functions (see <http://php.net/manual/en/function.ob-start.php>) that allows you to capture every output (echo, print, etc...) from the page.
|
probably with ob\_start and output\_callback see <http://php.net/manual/en/function.ob-start.php>
|
2,522,609 |
I am having a php file which executes some code to generate a html file.Its like I m having a form from which some data will be posted to x.php file, which gives a output(a webpage). I want to save that output in a html file.What the most efficient way of doing this.?
**EDIT**
I want to save it on sever side. Actually the thing is i want to create pdf file for that.. I wrote everything else.Now the thing is i want to save the output in a html page.So that i can convert it into pdf file..
|
2010/03/26
|
[
"https://Stackoverflow.com/questions/2522609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179855/"
] |
Try something like this:
```
// Start output buffering
ob_start();
// run code in x.php file
// ...
// saving captured output to file
file_put_contents('filename.htm', ob_get_contents());
// end buffering and displaying page
ob_end_flush();
```
If you cannot use the [ob\_\* functions](http://de3.php.net/manual/en/ref.outcontrol.php), you can also write the form to a variable and then save that variable.
|
Look at ob functions (see <http://php.net/manual/en/function.ob-start.php>) that allows you to capture every output (echo, print, etc...) from the page.
|
27,906,479 |
I have an application that I developed standalone and now am trying to integrate into a much larger model. Currently, on the server side, there are 11 tables and an average of three navigation properties per table. This is working well and stable.
The larger model has 55 entities and 180+ relationships and includes most of my model (less the relationships to tables in the larger model). Once integrated, a very strange thing happens: the server sends the same data, the same number of entities are returned, but the exportEntities function returns a string of about 150KB (rather than the 1.48 MB it was returning before) and all queries show a tenth of the data they were showing before.
I followed the troubleshooting information on the Breeze website. I looked through the Breeze metadata and the entities and relationships seem defined correctly. I looked at the data that was returned and 9 out of ten entities did not appear as an object, but as a function: `function (){return e.refMap[t]}` which, when I expand it, has an 'arguments' property: `Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them`.
For reference, here are the two entities involved in the breaking change.
The Repayments Entity
```
public class Repayment
{
[Key, Column(Order = 0)]
public int DistrictId { get; set; }
[Key, Column(Order = 1)]
public int RepaymentId { get; set; }
public int ClientId { get; set; }
public int SeasonId { get; set; }
...
#region Navigation Properties
[InverseProperty("Repayments")]
[ForeignKey("DistrictId")]
public virtual District District { get; set; }
// The three lines below are the lines I added to break the results
// If I remove them again, the results are correct again
[InverseProperty("Repayments")]
[ForeignKey("DistrictId,ClientId")]
public virtual Client Client { get; set; }
[InverseProperty("Repayments")]
[ForeignKey("DistrictId,SeasonId,ClientId")]
public virtual SeasonClient SeasonClient { get; set; }
```
The Client Entity
```
public class Client : IClient
{
[Key, Column(Order = 0)]
public int DistrictId { get; set; }
[Key, Column(Order = 1)]
public int ClientId { get; set; }
....
// This Line lines were in the original (working) model
[InverseProperty("Client")]
public virtual ICollection<Repayment> Repayments { get; set; }
....
}
```
The relationship that I restored was simply the inverse of a relationship that was already there, which is one of the really weird things about it. I'm sure I'm doing something terribly wrong, but I'm not even sure at this point what information might be helpful in debugging this.
For defining foreign keys and inverse properties, I assume I must use either data annotations or the FluentAPI even if the tables follow all the EF conventions. Is either one better than the other? Is it necessary to consistently choose one approach and stay with it? Does the error above provide any insight as to what I might be doing wrong? Is there any other information I could post that might be helpful?
Breeze is an excellent framework and has the potential to really increase our reach providing assistance to small farmers in rural East Africa, and I'd love to get this prototype working.
THanks
|
2015/01/12
|
[
"https://Stackoverflow.com/questions/27906479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2719246/"
] |
Ok, some of what you are describing can be explained by breeze's default behavior of compressing the payload of any query results that return multiple instances of the same entity. If you are using something like the default 'json.net' assembly for serialization, then each entity is sent with an extra '$id' property and if the same entity is seen again it gets serialized via a simple '$ref' property with the value of the previously mentioned '$id'.
On the breeze client during deserialization these '$refs' get resolved back into full entities. However, because the order in which deserialization is performed may not be the same as the order that serialization might have been performed, breeze internally creates deferred closure functions ( with no arguments) that allow for the deferred resolution of the compressed results regardless of the order of serialization. This is the
```
function (){return e.refMap[t]}
```
that you are seeing.
If you are seeing this value as part of the actual top level query result, then we have a bug, but if you are seeing this value while debugging the results returned from your server, before they have been returned to the calling function, then this is completely expected ( especially if you are viewing the contents of the closure before it should be executed.)
So a couple of questions and suggestions
* Are you are actually seeing an error processing the result of your query or are simply surprised that the results are so small? If it's just a size issue, check and see if you can identify data that should have been sent to the client and is missing. It is possible that the reference compression is simply very effective in your case.
* take a look at the 'raw' data returned from your web service. It should look something like this, with '$id' and '$ref' properties.
```
[{
'$id': '1',
'Name': 'James',
'BirthDate': '1983-03-08T00:00Z',
},
{
'$ref': '1'
}]
```
if so, then look at the data and make sure that an '$'id' exists that correspond to each of your '$refs'. If not, something is wrong with your server side serialization code. If the data does not look like this, then please post back with a small example of what the 'raw' data does look like.
|
After looking at your Gist, I think I see the issue. Your metadata is out of sync with the actual results returned by your query. In particular, if you look for the '$id' value of "17" in your actual results you'll notice that it is first found in the 'Client' property of the 'Repayment' type, but your metadata doesn't have 'Client' navigation property defined for the 'Repayment' type ( there is a 'ClientId' ). My guess is that you are reusing an 'older' version of your metadata.
The reason that this results in incomplete results is that once breeze determines that it is deserializing an 'entity' ( i.e. a json object that has $type property that maps to an actual entityType), it only attempts to deserialize the 'known' properties of this type, i.e. those found in the metadata. In your case, the 'Client' navigation property on the 'Repayment' type was never being deserialized, and any refs to the '$id' defined there are therefore not available.
|
6,646,509 |
What are the datatypes available in asterisk server dial plan?
how to check the date type?
|
2011/07/11
|
[
"https://Stackoverflow.com/questions/6646509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809719/"
] |
Asterisk dial plan language is weakly-typed (has no 'types' as such). All values are strings, but can be treated as numbers in some context (e.g. arithmetic expressions). The only way to check 'the type' is to use a regular expression to check the value.
There are some functions like [HASH](http://www.voip-info.org/wiki/view/Asterisk+func+hash) or [SORT](http://www.voip-info.org/wiki/view/Asterisk+func+sort) which seem to operate on some complex data types, but these are not main features of the language, but rather helpers for specific use cases.
|
No, in dialplan everything is a string. You can use AGI to check date or compare various things.
What exactly do you need? I'm guessing but maybe this will be useful: [How to include contexts based on time and date](http://www.voip-info.org/wiki/view/Asterisk+tips+openhours)
|
6,646,509 |
What are the datatypes available in asterisk server dial plan?
how to check the date type?
|
2011/07/11
|
[
"https://Stackoverflow.com/questions/6646509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809719/"
] |
Asterisk dial plan language is weakly-typed (has no 'types' as such). All values are strings, but can be treated as numbers in some context (e.g. arithmetic expressions). The only way to check 'the type' is to use a regular expression to check the value.
There are some functions like [HASH](http://www.voip-info.org/wiki/view/Asterisk+func+hash) or [SORT](http://www.voip-info.org/wiki/view/Asterisk+func+sort) which seem to operate on some complex data types, but these are not main features of the language, but rather helpers for specific use cases.
|
There is no type in dialplan, everything can be treated string variable.
But if required, you can always use your favorite programming language using AGI.
|
6,646,509 |
What are the datatypes available in asterisk server dial plan?
how to check the date type?
|
2011/07/11
|
[
"https://Stackoverflow.com/questions/6646509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/809719/"
] |
No, in dialplan everything is a string. You can use AGI to check date or compare various things.
What exactly do you need? I'm guessing but maybe this will be useful: [How to include contexts based on time and date](http://www.voip-info.org/wiki/view/Asterisk+tips+openhours)
|
There is no type in dialplan, everything can be treated string variable.
But if required, you can always use your favorite programming language using AGI.
|
38,682,341 |
I want to have three images on a row, if the total width of these three images doesn't fit the browser window then all three images should be below each other. So it's "all or nothing", there should never be only two images beside each other and one below (this happens then you gradually decrease browser window width using `float:left;` on all three images)
All this should be centered in the browser window, no matter the size of the window.
I know limited CSS and HTML but am using the following code to get current data centered in the window:
```css
* {
padding: 0;
margin: 0;
}
html, body {
height: 100%;
}
table {
vertical-align: middle;
height: 100%;
margin: 0 auto;
}
```
```html
<table>
<tr>
<td>
<table width="280" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
"images and text"
</td>
</tr>
</table>
</td>
</tr>
</table>
```
|
2016/07/31
|
[
"https://Stackoverflow.com/questions/38682341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6659536/"
] |
The parent of your `<a>` element is a `td` element, and the `td` element doesn't have a following-sibling - certainly not a following sibling that is a `tr`. If you want the next row in the table, use
```
.//a[@class="..."]/ancestor::tr[1]/following-sibling::tr[1]
```
or
```
.//tr[descendant::a/@class="..."]/following-sibling::tr[1]
```
|
If you want to select just next `tr` after `<a class="productnamecolor colors_productname">` simply use following two ways :-
* using [`following`](https://developer.mozilla.org/en-US/docs/Web/XPath/Axes/following) axis :
```
(.//a[@class="productnamecolor colors_productname"]/following::tr)[1]
```
* using [`preceding`](https://developer.mozilla.org/en-US/docs/Web/XPath/Axes/preceding) axis :
```
(.//tr[preceding::a[@class="productnamecolor colors_productname"])[1]
```
Hope it helps...:)
|
2,070,906 |
How to keep session alive for 1week without logout PHP, overwriting default server values?
I need to do this in the PHP code.
|
2010/01/15
|
[
"https://Stackoverflow.com/questions/2070906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] |
You can set the session lifetime in your script by using the session\_set\_cookie\_params -function call before the session is started. The first argument of the function call defines the session lifetime in seconds relative to the server time (so make sure the server clock is correct):
For example, to make a session last a week:
```
session_set_cookie_params(3600 * 24 * 7);
session_start();
```
This will override the setting in the php.ini -file.
Make sure to check up on the function documentation on the PHP -site: <http://www.php.net/manual/en/function.session-set-cookie-params.php>
|
Just wanted to add this even though it's an old thread for the sake of completeness for future googlers:
>
> Beware if you are on a Debian system.
>
>
>
The `/etc/cron.d/php5` script will still clean your `/var/lib/php5/` directory containing your sessions based on the `php.ini` value `session.gc_maxlifetime`.
|
2,070,906 |
How to keep session alive for 1week without logout PHP, overwriting default server values?
I need to do this in the PHP code.
|
2010/01/15
|
[
"https://Stackoverflow.com/questions/2070906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] |
You can set the session lifetime in your script by using the session\_set\_cookie\_params -function call before the session is started. The first argument of the function call defines the session lifetime in seconds relative to the server time (so make sure the server clock is correct):
For example, to make a session last a week:
```
session_set_cookie_params(3600 * 24 * 7);
session_start();
```
This will override the setting in the php.ini -file.
Make sure to check up on the function documentation on the PHP -site: <http://www.php.net/manual/en/function.session-set-cookie-params.php>
|
Alternative solution:
You say people are leaving open their browsers for days and complain that session expire. Simple solution: don't let session expire by sending an keep-alive request using eg. XMLHttpRequest every 10 minutes.
|
2,070,906 |
How to keep session alive for 1week without logout PHP, overwriting default server values?
I need to do this in the PHP code.
|
2010/01/15
|
[
"https://Stackoverflow.com/questions/2070906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131637/"
] |
Just wanted to add this even though it's an old thread for the sake of completeness for future googlers:
>
> Beware if you are on a Debian system.
>
>
>
The `/etc/cron.d/php5` script will still clean your `/var/lib/php5/` directory containing your sessions based on the `php.ini` value `session.gc_maxlifetime`.
|
Alternative solution:
You say people are leaving open their browsers for days and complain that session expire. Simple solution: don't let session expire by sending an keep-alive request using eg. XMLHttpRequest every 10 minutes.
|
11,941,257 |
Last days as a result of some customer complains and discussion with our marketing guys I've got a request to change the default behavior of the configurable products options. They asked me to remove the + $xx.xx from the options drop-down as it is confusing the customers/visitors and just leave the available options without displaying the price change. Fair enough from their point of view, but it is a bit tricky from developers point of view I think. The site is running Magento CE 1.6.2, and the file which we need to override/change is /public\_html/js/varien/configurable.js. We need to change the getOptionLabel function in it so that it does not display the price change.
So my question is: what is the right Magento way to change this file and not touch the core javascript file?
Thanks in advance.
|
2012/08/13
|
[
"https://Stackoverflow.com/questions/11941257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1177078/"
] |
See this from prototype manual <http://prototypejs.org/doc/latest/language/Function/prototype/wrap/> you can wrap whatever object method and even call "parent" if needed and here's a pseudo sample:
```
//where Product.Config is the object/class you need to "override"
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod){
//replace the original method here with your own stuff
//or call parentMethod(); if conditions don't match
});
```
|
Just to add to @anton-s's absolutely correct answer, you can also do "full" class rewrites:
```
// Create the original class
var ClassA = Class.create();
ClassA.prototype = {
initialize: function(config) {
this.config = config;
},
test: function(msg) {
console.log('Hi from class A with message ' + msg);
}
};
// Create new class extending the original class
var ClassB = Class.create(ClassA, {
// $super is a reference to the original method
test: function($super, msg) {
console.log('Hi from class B');
console.log('this.config is accessible in class B: ' + this.config);
$super(msg + ' ...')
}
});
// To make the extend an override, you can do this:
ClassA = ClassB;
// ClassA now is ClassB overriding the original ClassA
var a = new ClassA('some config data');
a.test('Call A 1');
```
Since all this only works on prototype classes, not on already instantiated objects, I'll also throw in this hack, which is pretty much what wrap() does, too:
```
// Overriding a method of an already instantiated object
// There are many ways to do this more elegantly thanks to the amazing JS scoping magic
a.origTest = a.test;
a.test = function(msg) {
console.log('Hi from the patched method');
this.origTest(msg);
}
a.test('Call A 2');
```
Keep in mind though that the `wrap()` method is nicer, and can also be used on on class definitions or on concrete instances.
```
// Wrap method of concrete instance
spConfig.getOptionLabel = spConfig.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
// Wrap method of class declaration
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
```
|
11,941,257 |
Last days as a result of some customer complains and discussion with our marketing guys I've got a request to change the default behavior of the configurable products options. They asked me to remove the + $xx.xx from the options drop-down as it is confusing the customers/visitors and just leave the available options without displaying the price change. Fair enough from their point of view, but it is a bit tricky from developers point of view I think. The site is running Magento CE 1.6.2, and the file which we need to override/change is /public\_html/js/varien/configurable.js. We need to change the getOptionLabel function in it so that it does not display the price change.
So my question is: what is the right Magento way to change this file and not touch the core javascript file?
Thanks in advance.
|
2012/08/13
|
[
"https://Stackoverflow.com/questions/11941257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1177078/"
] |
See this from prototype manual <http://prototypejs.org/doc/latest/language/Function/prototype/wrap/> you can wrap whatever object method and even call "parent" if needed and here's a pseudo sample:
```
//where Product.Config is the object/class you need to "override"
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod){
//replace the original method here with your own stuff
//or call parentMethod(); if conditions don't match
});
```
|
**How to override \js\varien\configurable.js in Magento 1.9 EE and add new data attribute**
Create file \js\jsoverride\configurable.js:
```
Product.Config.prototype.reloadOptionLabels = Product.Config.prototype.reloadOptionLabels.wrap(function (parentMethod, element) {
var selectedPrice;
if (element.options[element.selectedIndex].config && !this.config.stablePrices) {
selectedPrice = parseFloat(element.options[element.selectedIndex].config.price);
} else {
selectedPrice = 0;
}
for (var i = 0; i < element.options.length; i++) {
if (element.options[i].config) {
element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price - selectedPrice);
element.options[i].setAttribute('data-in-stock', element.options[i].config.in_stock);
}
}
});
```
Create or use file: \app\design\frontend\enterprise\YOUR\_THEME\layout\local.xml and add next rows:
```
<?xml version="1.0"?>
<layout version="0.1.0">
<catalog_product_view>
<reference name="head">
<action method="addJs"><script>jsoverride/configurable.js</script></action>
</reference>
</catalog_product_view>
</layout>
```
Note, filling data to element.options[i].config.in\_stock in file
>
> app\design\frontend\enterprise\YOUR\_THEME\template\catalog\product\view\type\options\configurable.phtml
>
>
>
with next row
```
var spConfig = new Product.Config(UPDATED JSON WITH NEW ATTRIBUTE);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.