date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/18
| 342 | 1,294 |
<issue_start>username_0: I have to following map in scala
```
mutable.Map[String, mutable.Map[String, App]]()
```
Assuming App contains a field called Token which is not the key for the inner map.
What is the best practice to extract a map of from this nested map.
I did
```
val result = mutable.Map[String, AppKey]()
myMap foreach(x=>x._2 foreach(y=>result.put(y._2.token, y._2)))
```<issue_comment>username_1: Cracked it!
Needed to concatenate the namespace url with the class and set it as a variable before I could create the new $controller object with it. So it was passing the class\_exists check when feeding it with the namespaced url, but failing on the new object as it was out of scope.
```
$controller = 'Project\\Controllers\\' . $controller;
if (class_exists($controller)) {
$controller_object = new $controller();
.......
```
Upvotes: 3 <issue_comment>username_2: I think I found where you missed something . You got this piece of code correctly and your code gets inside this if condition however when you are instantiating the object you forgot to use the full namespaced path . So PHP looks for a class called "Posts" that doesn't exist in the same namespace with the script .
```
if (class_exists('Project\\Controllers\\' . $controller))
```
Upvotes: 1
|
2018/03/18
| 246 | 593 |
<issue_start>username_0: I have a hash:
```
a = {b: {c: {d: e}}}
```
How can I save `d` from `a`? Should I write like:
```
x = [:b][:c]
a(x) = "foo"
```
`a`
output `{b:{c:"foo"}}`<issue_comment>username_1: As mu points out in the comments you probably want to use `dig`:
```
a = {b: {c: {d: :e}}}
keys = [:b, :c]
d_and_e = a.dig(*keys)
```
This will return `{d: :e}`.
Upvotes: 0 <issue_comment>username_2: ```
a[:b][:c].keys.first # => :d
a[:b][:c].keys.first.to_s # => "d"
```
Upvotes: 0 <issue_comment>username_3: hash.keys.join or hash.keys(if there is only one key)
Upvotes: -1
|
2018/03/18
| 472 | 1,547 |
<issue_start>username_0: I'm trying to format a dataset for use in some survival analysis models. Each row is a school, and the time-varying columns are the total number of students enrolled in the school that year. Say the data frame looks like this (there are time invariate columns as well).
```
Name total.89 total.90 total.91 total.92
a 8 6 4 0
b 1 2 4 9
c 7 9 0 0
d 2 0 0 0
```
I'd like to create a new column indicating when the school "died," i.e., the first column in which a zero appears. Ultimately I'd like to have this column be "years since 1989" and can re-name columns accordingly.
A more general version of the question, for a series of time ordered columns, how do I identify the first column in which a given value occurs?<issue_comment>username_1: Here's a base R approach to get a column with the first zero (`x = 0`) or `NA` if there isn't one:
```
data$died <- apply(data[, -1], 1, match, x = 0)
data
# Name total.89 total.90 total.91 total.92 died
# 1 a 8 6 4 0 4
# 2 b 1 2 4 9 NA
# 3 c 7 9 0 0 3
# 4 d 2 0 0 0 2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is an option using `max.col` with `rowSums`
```
df1$died <- max.col(!df1[-1], "first") * NA^!rowSums(!df1[-1])
df1$died
#[1] 4 NA 3 2
```
Upvotes: 1
|
2018/03/18
| 285 | 1,005 |
<issue_start>username_0: I really need to know how to clear the screen in Ruby. I've already looked all over and haven't found anything that can help.
I've already tried using cls in several formats and it NEVER worked (I am on Windows, btw).
All that happens is an arrow keeps showing up in the IRB console.<issue_comment>username_1: To clear the terminal window on multiple operational systems, you could use:
```
def clear
if Gem.win_platform?
system 'cls'
else
system 'clear'
end
end
```
>
> [Documentation for **Gem#win\_platform?**](https://apidock.com/ruby/v1_9_3_125/Gem/win_platform%3F/class)
>
> Is this a windows platform?
>
>
>
Upvotes: 2 <issue_comment>username_2: on terminal type 'clear' and hit enter button it will clear your screen .
Upvotes: -1 <issue_comment>username_3: I found out earlier today that 'cls' doesn't work in RubyMine but it will work if I run the app in command prompt. It would've been nice if I had been told about that earlier.
Upvotes: 0
|
2018/03/18
| 486 | 1,964 |
<issue_start>username_0: We're developing a connector that creates actionable outlook messages for external users. I.E. This is a service. Can anyone please help with the below example? We're getting an error for the external users when they try to action the message by clicking on one of the action buttons.
Example:
User A is on the tenant that registered the connector - Tenant A,
User B is on another Office 365 tenant, Tenant B.
We've created an Office 365 connector targeting the user's "Inbox"
[](https://i.stack.imgur.com/uYDUr.png)
The connector has **not** been published to the store but is still in dev.
So to be clear we're not implementing our solution using "Actionable Email".
We can create the actionable message for both User A and B, no problems so both users get the email. But only User A ( on the tenant that registered the connector ) can click an Action button from Outlook. User B gets the error message:
"Target URL '<https://nameomitted.com/method>' is not allowed"
We are not receiving anything at our web server end from the call. The console error from the browser when clicking the action button is:
[](https://i.stack.imgur.com/XhPWP.png)
So the error is generated from Microsoft internally.
Can we only send to users in the same tenant as the one that registered the connector until we've published to the store? That seems restrictive for development.
Any help is greatly appreciated.<issue_comment>username_1: Is your connector's registration pending or approved?
Pending connector's functionality is limited. Most cross tenant operations are blocked.
Upvotes: 3 [selected_answer]<issue_comment>username_2: In my case, I was using a different URL which was not registered in the Provider. If both the end points (in the provider & in the Adaptive Card JSON) match, then only it will work.
Upvotes: 0
|
2018/03/18
| 366 | 1,135 |
<issue_start>username_0: I am trying to create 46 variables, indexed from 0-45 dependent on 3 other variables, each of which is indexed from 0-45. It seems as though the array approach would be the most straightforward but I can't get it to work. So i have variables a\_0,...,a\_45,b\_0,...,b\_45,c\_0,...,c\_45 and i want to create d\_i=a\_i+b\_i+c\_i but I'm having some difficulty.
Attempt:
```
data test;
set test;
array d [0:45];
array a [0:45] a_0-a_45;
array b [0:45] b_0-b_45;
array c [0:45] c_0-c_45;
do i=0 to 45;
d[i]=a[i]+b[i]+c[i];
end;
run;
```
1) I can't seem to get the index from 0.
2) Whenever I run checks, the variables never add up in the intended way.<issue_comment>username_1: Is your connector's registration pending or approved?
Pending connector's functionality is limited. Most cross tenant operations are blocked.
Upvotes: 3 [selected_answer]<issue_comment>username_2: In my case, I was using a different URL which was not registered in the Provider. If both the end points (in the provider & in the Adaptive Card JSON) match, then only it will work.
Upvotes: 0
|
2018/03/18
| 765 | 2,469 |
<issue_start>username_0: I have a dataframe with lots of key/value columns whereas the keys and values are separated columns.
```
import pandas as pd
values = [['John', 'somekey1', 'somevalue1', 'somekey2', 'somevalue2']]
df = pd.DataFrame(values, columns=['name', 'key1', 'value1', 'key2', 'value2'])
```
**Remark:** The original data would have more preceding columns and not just the name. And it has more than just two key/value columns.
What I want to achieve is having a result like this:
```
values = [
['John', 'somekey1', 'somevalue1'],
['John', 'somekey2', 'somevalue2']
]
df = pd.DataFrame(values, columns=['name', 'key', 'value'])
```
There I was thinking to join all key/value columns into a list or dictionary and than explode that list/dict. I found [this nice posting](https://stackoverflow.com/questions/32468402/how-to-explode-a-list-inside-a-dataframe-cell-into-separate-rows) on **pd.melt** but my problem is, that I don't know the exact id\_var columns upfront. Therefore I tried **pd.Series.stack**, which gave me the correct result for the key/value column, but missing the other columns from the original data. Any idea? Here's what I tried:
```
# generates: [(somekey1, somevalue1), (somekey2, somevalue2)]
df['pairs'] = df.apply(lambda row: [(row['key1'],row['value1']), (row['key2'], row['value2'])], axis=1)
# unstacks the list, but drops all other columns
df['pairs'].apply(pd.Series).stack().reset_index(drop=True).to_frame('pairs')
```<issue_comment>username_1: IIUC `wide_to_long`
```
pd.wide_to_long(df,['key','value'],i='name',j='drop').reset_index().drop('drop',1)
Out[199]:
name key value
0 John somekey1 somevalue1
1 John somekey2 somevalue2
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Here's what comes to my mind:
```
common = ['name'] # Add more columns, if needed
# Alternatively:
common = df.loc[:, :'name'].columns # Everything up to 'name'
result = pd.concat([df.loc[:, common + ['key1', 'value1']],
df.loc[:, common + ['key2', 'value2']]])
result['key'] = np.where(result['key1'].isnull(),
result['key2'], result['key1'])
result['value'] = np.where(result['value1'].isnull(),
result['value2'], result['value1'])
result.drop(['value1', 'value2', 'key1', 'key2'], axis=1, inplace=True)
# name key value
#0 John somekey1 somevalue1
#0 John somekey2 somevalue2
```
Upvotes: 2
|
2018/03/18
| 848 | 3,337 |
<issue_start>username_0: This question might be a duplicate, in that case I would love to get a reading on it, but please check if the duplicate question fits mine. I have tried looking for answers, but have not found any that fits my question correctly.
I have a website built with React served from a .NET Core 2.0 project with a regular Web API generated from the regular Controller web api that is built in to the project. The Web API is set up like this:
```
[Produces("application/json")]
[Route("api/File")]
public class FileController : Controller
{
// POST: api/File
[HttpPost]
public ActionResult Post()
{
Console.WriteLine(Request);
return null;
}
```
I want to upload Images / PDF files and other file types from a regular `input type="file"` field.
The code for that can be seen below:
```js
export class Home extends Component {
render() {
return
}
handleFileUpload = (event) => {
var file = event.target.files[0];
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", 'api/File', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status == 200) {
// Every thing ok, file uploaded
console.log(xhr.responseText); // handle response.
}
};
fd.append("upload_file", file);
xhr.send(fd);
}
}
```
What needs to be implemented in the Post-file-controller part for the correct handling of the file? If I want the file to be uploaded as, say a `uint8` array (to be stored).
Every bit of help is appreciated as I am stuck.<issue_comment>username_1: I will assume you meant `byte[]` by saying `uint8 array`. You can try using the new `IFormFile` interface.
```
[Route("api/File")]
public class FileController : Controller
{
// POST: api/file
[HttpPost]
public ActionResult Post(IFormFile file)
{
var uploadPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
if (file.Length > 0) {
var filePath = Path.Combine(uploads, file.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create)) {
//You can do anything with the stream e.g convert it to byte[]
byte[] fileBytes = new byte[fileStream.Length];
//Read the stream and write bytes to fileBytes
fileStream.Read(fileBytes, 0, fileBytes.Length);
//fileBytes will contain the file byte[] at this point
//Persist the file to disk
await file.CopyToAsync(fileStream);
}
}
//....
}
```
**Edit**: Make sure the parameter name `IFormFile file*` matches the name you are sending from the client, in your case it should be `IFormFile upload_file`
Upvotes: 1 <issue_comment>username_2: I'm a bit late to the party but if anybody else struggles with this problem: The reason the backend parameter `file` was null in my case, was because the input name in the frontend must be the same as the method parameter name in the backend.
In your example you chose the input name `upload_file`
```js
fd.append("upload_file", file);
```
so the parameter in the backend must have the same name:
```
[HttpPost]
public void PostFile(IFormFile upload_file)
{
_fileService.Add(upload_file);
}
```
Upvotes: 2
|
2018/03/18
| 3,029 | 8,652 |
<issue_start>username_0: If I have the list `[1,2,3,4,5,6,7]` and I want to group 3 (or any other number) adjacent values so I end up with the list: `[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7]]`
How would I go about doing this in Haskell?<issue_comment>username_1: ```
Data.List> f n xs = zipWith const (take n <$> tails xs) (drop (n-1) xs)
Data.List> f 3 [1..7]
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7]]
```
Some brief explanations: `tails` gives us the lists that start at each position in the original. We only want the first few elements of each of these, so we run `take n` on each. This gets us most of the way there, but leaves a few extra dangling lists at the end; in your example they would be the ones starting from `6`, `7`, and beyond, so `[[6,7],[7],[]]`. We could do this by computing the length of the input list and taking only that many final lists, but this doesn't work well for infinite input lists or partially defined input lists. Instead, since the output should always be `n` elements shorter than the input, we use a standard-ish `zipWith` trick to cut off the extra elements.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Alternative to Daniel's [very clever answer](https://stackoverflow.com/a/49353736/3058609), you can use `take` and explicit recursion.
```
f n (x:xs) | length xs < (n-1) = []
| otherwise = (x : take (n-1) xs) : f n xs
```
However this will end up being substantially slower since it's necessary to force `length xs` so many times.
Upvotes: 0 <issue_comment>username_3: An alternative explanation of @DanielWagner's solution from a slightly higher level of abstraction:
>
> Original solution:
>
>
>
> ```
> f n xs = zipWith const (take n <$> tails xs) (drop (n-1) xs)
>
> ```
>
>
>
> ---
>
>
> `take n <$> tails xs` uses the nondeterminism monad:
>
>
>
> ```
> type NonDet a = [a]
> -- instance Monad NonDet
> tails :: [a] -> NonDet [a]
>
> ```
>
> `tails` nondeterministically "chooses" where the sublist begins, and then the pure function
>
>
>
> ```
> take n :: [a] -> [a]
>
> ```
>
> is `fmap`'d under the `NonDet`erminism layer to chop the tail off. This leaves some flab at the result's end, so we go into the plumbing of `NonDet`/`[]` with `zipWith` fix it.
>
>
>
This new explanation also opens up an optimization. The `[]` monad has a concept of failure, which is the empty list. If we had a version of `take` that would fail monadically when it had a too-short argument, we could use it and not worry about removing the short sublists at the end of the result. So:
```
import Control.Monad((<=<))
import Data.Maybe(maybeToList)
-- Maybe is the simplest failure monad.
-- Doesn't return [[a]] because this could conceivably be used in other
-- contexts and Maybe [a] is "smaller" and clearer than [[a]].
-- "safe" because, in the context of (do xs <- safeTake n ys),
-- length xs == n, definitely.
safeTake :: Int -> [a] -> Maybe [a]
safeTake 0 _ = return []
safeTake n [] = Nothing
safeTake n (x:xs) = (x:) <$> (safeTake $ n - 1) xs
-- maybeToList :: Maybe a -> [a]
-- maybeToList (return x) = return x / maybeToList (Just x) = [x]
-- maybeToList empty = empty / maybeToList Nothing = [ ]
-- (.) :: (b -> c) -> (a -> b) -> (a -> c)
-- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
f n = maybeToList . safeTake n <=< tails
```
`f` no longer digs through the nondeterminism abstraction with something that is outside the monad. It can also be written in terms of Kliesli composition, which certainly gives it points in the beauty category. A `criterion` benchmark also shows a 15-20% speedup (under `-O2`). Personally, I think it's cool that seeing something more abstractly and making the code "prettier" can also confer performance.
Upvotes: 2 <issue_comment>username_4: ```
let x:y:ls = [1,2,3,4,5,6,7] in zip3 (x:y:ls) (y:ls) ls
```
Will give
```
[(1,2,3),(2,3,4),(3,4,5),(4,5,6),(5,6,7)]
```
Tuples instead of lists. If you want lists then apply `\(a, b, c) -> [a, b, c]`. Or do
```
let x:y:ls = [1,2,3,4,5,6,7] in [[a, b, c] | (a, b, c) <- zip3 (x:y:ls) (y:ls) ls]
```
Upvotes: 2 <issue_comment>username_5: It doesn't appear Haskell will iterate over a list 3 at a time. list comprehensions won't either. Without iteration, it seems, there is no way to handle infinite lists. IDK, I'm too new to Haskell. All I could come up with is a recursive function. ugh. A feature of the function is that it can be parameterized, it can produce arbitrary size sub-lists. Using Haskell pattern matching requires specifying the number of elements in each sub list, like for 3, (x:y:z:xs) and Haskell will reduce xs by 3 on each iteration. Four at a time would be (w:x:y:z:xs). This introduced bad hard coding into the function. So this function has to reduce xs using drop 3 but 3 can be parameter as take 3 can also. A helper function to take the size of each sub-list and to pass the constant [] (null list) to the primary function as the first parmeter would be helpful.
```
fl2 (ys) (xs) = if null xs then ys else (fl2 (ys ++ [take 3 xs]) (drop 3 xs))
```
fl2 [] [1..12] ......... [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
What is interesting is the function pair [take 3 l, drop 3 l] when used in a function is good for one [[1,2,3],[4,5,6,7,8,9,10,11,12]]. This is basically what the fl2 function uses but the sub-lists must accumulate.
Edit 3/19/18
Messing around with this I found, to my surprise, that this works. I could probable clean it up a lot but, for now ...
```
f7 ls = (take 3 ls, drop 3 ls)
f8 (a,b) = if null b then [a] else a : (f8 (f7 b))
```
How this is run is not pretty, but...
```
f8 $ f7 [1..12]
```
produces [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
This IMO is still better that passing a [] as a parameter.
This last function and probably the previous handles [] with [], [1] with [1] and odd numbered lists, truncating the very last list accordingly. None of this were a consideration of writing of the function but is is a result.
**Edit 3/23/2018**
Well thanks to dfeuer, I tried splitAt instead of (\xs -> (take 3 xs, drop 3 xs). I also changed the syntax of the single line function to not use if-then-else. Calling the function is still the same. A third wrapper function might well be in order.
```
f7 = (splitAt 3)
f8 (a,b) | null b = [a] | True = a : (f8 $ f7 b)
```
I am smitten by the use of pattern matching guards in single line functions. If-then-else is so ugly. I agree that 'if' should be a function like it is in lisp-like languages.
**Edit 3/26/2018**
Errrr. I don't know how I got the specification wrong. The result list is [1,2,3],[2,3,4],[3,4,5] not [1,2,3],[4,5,6],[7,8,9]
I feel dumber than normal.
Here are two revised function to produce the correct result list.
The first function generates all possible triples in range because the sub-lists of the result are triples.
```
lt = [[a,b,c] | a <- [1..10], b <- [2..11], c <- [3..12]]
```
The second function picks out the correct elements of 'lt' by a calculated index value. For the 12 element input list the index values are 1,111,222,...999 so are multiples of 111. So here for an input list of [1..12]
```
[lt!!(x*111) | x <- [0..9]]
```
Produces
```
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9],[8,9,10],[9,10,11],[10,11,12]]
```
**Edit 3/27/2018**
Well, the list generated to pick values from had as the last value of a set the next needed in any list. I was recently taught to look closely and together at the lists generated. I generated a few lists from the lt generating function above. The last element of each list were the exact values for any size list. lt is no longer needed. This single line does everything.
```
grp3 n = map (\x -> [(x-2),(x-1),x]) [3..n]
```
The following is most general. It will group by any amount and it will include sublists of groups less than the group size specified for completeness.
```
grp n ls = [take n.drop x $ ls)|x<-[0,n..]]
```
**5/7/2018**
I do this too often. I find relatively quickly that some of my functions can change character with only minor changes in the code. I am careless about versions. This last version generates the wrong type list.
```
take 6 $ grp 3 [1..]
```
[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15],[16,17,18]]
Take the `n` out of the enumeration
```
grp n ls = [(take n.drop i$ls)| (i,x) <- zip [0..] ls]
```
and
```
take 6 $ grp 3 [1..]
```
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8]]
I added the zip to both now to limit the output.
```
grp 3 [1..10]
```
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9],[8,9,10],[9,10],[10]]
Upvotes: 0
|
2018/03/18
| 1,031 | 3,093 |
<issue_start>username_0: I have a CSS grid and in this grid articles that could be blog posts. They consist of an image on the left and text on the right.
I need the articles to start at the bottom, so that newer articles appear above them. But I just can't get them to start at the bottom whatever I try it's not working. `align-items: end;` should do the trick but it doesn't … So what am I missing here?
```css
.blog-Grid {
display: grid;
}
.post {
display: grid;
grid-template-columns: repeat(2, 1fr);
width: 50%;
margin: 0 0 10% 15%;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```<issue_comment>username_1: You can use flexbox with the main grid and keep CSS grid only for posts.
```css
.blog-Grid {
display: flex;
min-height:200vh;
flex-direction:column;
justify-content:flex-end;
}
.post {
display: grid;
grid-template-columns: repeat(2, 1fr);
width: 50%;
margin: 0 0 10% 15%;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
Upvotes: 1 <issue_comment>username_2: >
> *So what am I missing here?*
>
>
>
You're overlooking the fact that HTML elements are, by default, `height: auto` (see reference below). This means they are the height of their content. This means there is no extra space for vertical alignment.
Here is a simplified version of your code. I added a border around the container. Note how the height is automatically "shrink-to-fit".
```css
.blog-Grid {
display: grid;
border: 2px solid red;
}
.post {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
* {
margin: 0;
box-sizing: border-box;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
So, very simply, add height to your container in order to create extra space.
```css
.blog-Grid {
display: grid;
height: 100vh;
align-content: end;
border: 2px solid red;
}
.post {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
}
* {
margin: 0;
box-sizing: border-box;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
[jsFiddle demo](https://jsfiddle.net/kr3w7162/)
-----------------------------------------------
Also see:
* [Block elements consume the full width of their parent, by default. This behavior does not extend to height.](https://stackoverflow.com/a/46546152/3597276)
* [What is the difference between align-items vs. align-content in Grid Layout?](https://stackoverflow.com/q/40740553/3597276)
* [The difference between justify-self, justify-items and justify-content in CSS Grid](https://stackoverflow.com/q/48535585/3597276) (more details about `align-items` vs `align-content`)
Upvotes: 0
|
2018/03/18
| 1,481 | 4,974 |
<issue_start>username_0: <https://i.imgur.com/El9iCsP.gifv>
Above is a gif of what is happening. The game is resetting fine when ever I'm just pressing the reset button however when the player actually dies (collides with a wall) the game doesn't re-initiate. Basically I'm making a kind of speed runner game for a college project (really quick hack together) but it is also my first time using Unity. From what I gather the issue is due to me creating a GameControl class to access the gameOver variable from the player class however I'm not entirely sure how to fix this.
**GameControl:**
```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameControl : MonoBehaviour
{
public static GameControl instance;
public bool gameOver = false;
public float scrollSpeed;
public float scrollIncrease;
public float startTime;
public Text timerText;
public void resetGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
void Awake()
{
if(instance == null)
{
instance = this;
}
else if(instance != null)
{
Destroy(gameObject);
}
startTime = Time.time;
}
void Update()
{
if (gameOver == false)
{
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
scrollSpeed -= scrollIncrease;
}
else
{
Time.timeScale = 0;
}
}
}
```
**Player:**
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class player : MonoBehaviour {
Rigidbody2D rb;
public float moveSpeed;
public float jump;
public float jumps = 0;
void Start () {
rb = GetComponent();
}
void Update()
{
if (GameControl.instance.gameOver == false)
{
float moveHorizontal = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveHorizontal \* moveSpeed, rb.velocity.y);
if (Input.GetKeyDown(KeyCode.Space) && jumps < 2)
{
jumps++;
rb.velocity = Vector2.zero;
rb.AddForce(new Vector2(0, jump));
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == "obstacle" || collision.gameObject.name == "Left Boundry")
{
GameControl.instance.gameOver = true;
}
else if(collision.gameObject.tag == "floor")
{
jumps = 0;
}
}
}
```<issue_comment>username_1: You can use flexbox with the main grid and keep CSS grid only for posts.
```css
.blog-Grid {
display: flex;
min-height:200vh;
flex-direction:column;
justify-content:flex-end;
}
.post {
display: grid;
grid-template-columns: repeat(2, 1fr);
width: 50%;
margin: 0 0 10% 15%;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
Upvotes: 1 <issue_comment>username_2: >
> *So what am I missing here?*
>
>
>
You're overlooking the fact that HTML elements are, by default, `height: auto` (see reference below). This means they are the height of their content. This means there is no extra space for vertical alignment.
Here is a simplified version of your code. I added a border around the container. Note how the height is automatically "shrink-to-fit".
```css
.blog-Grid {
display: grid;
border: 2px solid red;
}
.post {
display: grid;
grid-template-columns: repeat(2, 1fr);
}
* {
margin: 0;
box-sizing: border-box;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
So, very simply, add height to your container in order to create extra space.
```css
.blog-Grid {
display: grid;
height: 100vh;
align-content: end;
border: 2px solid red;
}
.post {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
}
* {
margin: 0;
box-sizing: border-box;
}
```
```html

### I'm a header
Lorem ipsum text.

### I'm a header
Lorem ipsum text.
```
[jsFiddle demo](https://jsfiddle.net/kr3w7162/)
-----------------------------------------------
Also see:
* [Block elements consume the full width of their parent, by default. This behavior does not extend to height.](https://stackoverflow.com/a/46546152/3597276)
* [What is the difference between align-items vs. align-content in Grid Layout?](https://stackoverflow.com/q/40740553/3597276)
* [The difference between justify-self, justify-items and justify-content in CSS Grid](https://stackoverflow.com/q/48535585/3597276) (more details about `align-items` vs `align-content`)
Upvotes: 0
|
2018/03/18
| 1,309 | 4,229 |
<issue_start>username_0: I'm trying to have three of divs side by side with spacing in between the div's in the middle.
Here is the image of what I need: [](https://i.stack.imgur.com/tmPr6.png)
Here is my current code:
```
.box {
float: left;
width: 33%;
background-color: red;
text-align: center;
color: #fff;
}
Div 1
Div 2
Div 3
```
The problem with my current code is that it does not have the spacing I need in the middle of div 1 and 2, and div 2 and 3.<issue_comment>username_1: The gap between would be variable, or width can't be always 33% (3x33% + 2x10px can be more/less then viewport).
Then the code is simple:
```css
#wrapper {background: red;}
.inner {width: 33%; margin: 0 auto; background: green;}
.left {float: left;}
.right {float: right;}
```
```html
inner left
inner right
inner middle
```
If width should be variable and the gap between divs always 10px, change `width: 33%` for `width: calc((100% - 20px) / 3);`.
Upvotes: 2 <issue_comment>username_2: You might be better using a flexbox to achieve what you need. Create a container for the three .box divs, and style it with the following:
```
display:flex;
justify-content:space-between;
```
Keep in mind that the width of your .box divs will need to be lowered to achieve the space you want and that you would not require the float:left; in the css.
For more info on flexboxes, click here: <https://css-tricks.com/snippets/css/a-guide-to-flexbox/>
Upvotes: 4 [selected_answer]<issue_comment>username_3: Here's a [plunker](https://plnkr.co/edit/GpuNXAM8uLs6zQEZ5EZz?p=preview) I made with the solution you're looking for. The code that makes it work is below. I'm sure there might be an easier solution with flexbox, but this works with older browsers that don't support flexbox (looking at you, IE <= 9). Notice how I included the comments between the .box elements. This is because without them the whitespace is included when doing the inline-block width calculations and the last element ends up wrapping to the next line. Hopefully this helps!
```
.box {
width:calc(33.3333333% - 10px);
display:inline-block;
background:#777;
margin:0 10px;
text-align:center;
}
.box:first-child, .box:last-child {
margin:0;
width:calc(33.333333% - 5px);
}
```
Upvotes: 2 <issue_comment>username_4: What about an **easy** CSS grid solution:
```css
.container {
display: grid;
grid-gap: 10px; /* Simply adjust this value !*/
grid-template-columns: repeat(3, 1fr); /* OR grid-template-columns: 1fr 1fr 1fr;*/
grid-auto-rows: 1fr;
border:1px solid green
}
.container>div {
border: 1px solid red;
height: 20px;
}
```
```html
```
Upvotes: 3 <issue_comment>username_5: I think **Correct answer is only half correct**, the *default behaviour of flex items* is set to flex-grow 1, so if items needed they will take extra space if they need it.
Need to remove that behaviour so the items do not grow or shrink.
See snippet bellow.
```css
.grid {
display: flex;
justify-content: space-betwen;
}
.grid .item {
border: 2px solid tomato;
}
.grid .item2 {
color: red;
border: 2px solid blue;
flex: 0 0 33%;
}
```
```html
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque itaque id unde rerum et, ipsa iusto placeat, tempora cupiditate cumque sapiente nostrum, suscipit quidem consectetur totam commodi qui quis doloremque? Lorem, ipsum dolor sit amet consectetur
adipisicing elit. Laudantium quos error voluptatum atque veniam earum culpa, odio impedit minima quis quia id! Consequuntur adipisci id distinctio! Voluptas pariatur quasi accusamus!
Same Content
Same Content
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque itaque id unde rerum et, ipsa iusto placeat, tempora cupiditate cumque sapiente nostrum, suscipit quidem consectetur totam commodi qui quis doloremque? Lorem, ipsum dolor sit amet consectetur
adipisicing elit. Laudantium quos error voluptatum atque veniam earum culpa, odio impedit minima quis quia id! Consequuntur adipisci id distinctio! Voluptas pariatur quasi accusamus!
Same Content
Same Content
```
Upvotes: 2
|
2018/03/18
| 1,410 | 4,701 |
<issue_start>username_0: I'm trying to find the complementary rotary "gear" shape to any input polygon shape. For example this polygon, is rotated around so that the complementary gear becomes apparent. Both shapes would be able to rotate without interferences.
I'm having issues defining the second polygon, which is the edge of the white inner region. One method I can think of is "sampling" the input shape along its circumference, and rotating like before to generate a pointcloud. A concave hull algorithm (Alpha shape) could be used to obtain the edge.
While this would work, I feel there must be a more elegant solution to this problem.
Thanks
[](https://i.stack.imgur.com/qkWwF.jpg)
Polygon and its rotated image
[](https://i.stack.imgur.com/toozg.png)
Sampled polygon and resulting pointcloud
[](https://i.stack.imgur.com/ehDMv.jpg)
close up of edge<issue_comment>username_1: The gap between would be variable, or width can't be always 33% (3x33% + 2x10px can be more/less then viewport).
Then the code is simple:
```css
#wrapper {background: red;}
.inner {width: 33%; margin: 0 auto; background: green;}
.left {float: left;}
.right {float: right;}
```
```html
inner left
inner right
inner middle
```
If width should be variable and the gap between divs always 10px, change `width: 33%` for `width: calc((100% - 20px) / 3);`.
Upvotes: 2 <issue_comment>username_2: You might be better using a flexbox to achieve what you need. Create a container for the three .box divs, and style it with the following:
```
display:flex;
justify-content:space-between;
```
Keep in mind that the width of your .box divs will need to be lowered to achieve the space you want and that you would not require the float:left; in the css.
For more info on flexboxes, click here: <https://css-tricks.com/snippets/css/a-guide-to-flexbox/>
Upvotes: 4 [selected_answer]<issue_comment>username_3: Here's a [plunker](https://plnkr.co/edit/GpuNXAM8uLs6zQEZ5EZz?p=preview) I made with the solution you're looking for. The code that makes it work is below. I'm sure there might be an easier solution with flexbox, but this works with older browsers that don't support flexbox (looking at you, IE <= 9). Notice how I included the comments between the .box elements. This is because without them the whitespace is included when doing the inline-block width calculations and the last element ends up wrapping to the next line. Hopefully this helps!
```
.box {
width:calc(33.3333333% - 10px);
display:inline-block;
background:#777;
margin:0 10px;
text-align:center;
}
.box:first-child, .box:last-child {
margin:0;
width:calc(33.333333% - 5px);
}
```
Upvotes: 2 <issue_comment>username_4: What about an **easy** CSS grid solution:
```css
.container {
display: grid;
grid-gap: 10px; /* Simply adjust this value !*/
grid-template-columns: repeat(3, 1fr); /* OR grid-template-columns: 1fr 1fr 1fr;*/
grid-auto-rows: 1fr;
border:1px solid green
}
.container>div {
border: 1px solid red;
height: 20px;
}
```
```html
```
Upvotes: 3 <issue_comment>username_5: I think **Correct answer is only half correct**, the *default behaviour of flex items* is set to flex-grow 1, so if items needed they will take extra space if they need it.
Need to remove that behaviour so the items do not grow or shrink.
See snippet bellow.
```css
.grid {
display: flex;
justify-content: space-betwen;
}
.grid .item {
border: 2px solid tomato;
}
.grid .item2 {
color: red;
border: 2px solid blue;
flex: 0 0 33%;
}
```
```html
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque itaque id unde rerum et, ipsa iusto placeat, tempora cupiditate cumque sapiente nostrum, suscipit quidem consectetur totam commodi qui quis doloremque? Lorem, ipsum dolor sit amet consectetur
adipisicing elit. Laudantium quos error voluptatum atque veniam earum culpa, odio impedit minima quis quia id! Consequuntur adipisci id distinctio! Voluptas pariatur quasi accusamus!
Same Content
Same Content
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque itaque id unde rerum et, ipsa iusto placeat, tempora cupiditate cumque sapiente nostrum, suscipit quidem consectetur totam commodi qui quis doloremque? Lorem, ipsum dolor sit amet consectetur
adipisicing elit. Laudantium quos error voluptatum atque veniam earum culpa, odio impedit minima quis quia id! Consequuntur adipisci id distinctio! Voluptas pariatur quasi accusamus!
Same Content
Same Content
```
Upvotes: 2
|
2018/03/18
| 238 | 931 |
<issue_start>username_0: I want to build a button that when clicked will refresh the page (i.e. command+r shortcut on your keyboard). Is there a reload() (JavaScript) equivalent function in Elm. If not, how should I go about creating this button?<issue_comment>username_1: The easiest way is to use a port like
reload -> Cmd msg
and having it call the JS yourself, see above post about using elm lang navigation package.
Upvotes: -1 <issue_comment>username_2: <https://package.elm-lang.org/packages/elm/browser/latest/Browser-Navigation#reload>
There are two commands in the Navigation package to achieve exactly this.
```
Browser.Navigation.reload : Cmd msg
Browser.Navigation.reloadAndSkipCache : Cmd msg
```
Just use them in your update function
```
import Browser.Navigation as Navigation
[...]
update msg model = case msg of
[...]
ReloadBtnClicked -> (model, Navigation.reload)
[...]
```
Upvotes: 3
|
2018/03/18
| 696 | 2,489 |
<issue_start>username_0: ***Senario:***
So I am trying to simplify the usage of setting a lot of `TextViews` invisible by making a lot a lines of code into one, so decided to make a method that gets `List` and turns them all invisible. I made a test Class to show the error. (Problem bellow)
**Method:**
```
private void makeTextViewsInvisible(List listOfTextViews){
int i= 0;
while(i < listOfTextViews.size()){
listOfTextViews.get(i).setVisibility(View.INVISIBLE);
i++;
}
}
```
**Using the method:**
```
makeTextViewsInvisible(new List()) ;
//Dose'nt work?
//I don't want to define : (List a = new ...) And add TextViews manually (a.add(TextView1)...)
//I want to add all three TextViews in one line of code inside the brackets
```
Problem is, that I cannot make a `new List` inside the brackets, I need to make a whole new `List` and add all the `TextViews` *manually* (By using `List.add();`), witch dosent simplify my code. Any way to make a new List inside the bracket it self?<issue_comment>username_1: You could do something like that if you would use this library...
[org.apache.commons](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html)
Then it should be possible to call your method like this.
```
List newList = ListUtils.union(list1,list2);
makeTextViewsInvisible(ListUtils.union(t1,t2,t3));
```
Upvotes: 0 <issue_comment>username_2: The syntax
>
> makeTextViewsInvisible(new List())
>
>
>
is incorrect.
You clearly do not understand the syntax of List initialization.
If you want to insert three elements to the list of a given type (in your case it'll be `List` I believe) you have to initialize it (the list of type `TextViews`). Note that you probably don't want to instantiate a List, because it is an interface and you would have to implement every method of List interface, such as `add(), get(), indexOf()` etc. I suggest that you pass the `ArrayList` as your function argument. Let's say that `t1,t2,t3` are already defined objects of type `TextViews`. To instantiate `ArrayList` you need the following syntax:
```
ArrayList exampleList= new ArrayList<>(Arrays.asList(t1,t2,t3));
```
You have to pass an array as a constructor of a list, which you can easily do with `Arrays.asList()` static method. With that said, syntax of your method invocation would look like this:
```
makeTextViewsInvisible(new ArrayList(Arrays.asList(t1,t2,t3));
```
Upvotes: 2 [selected_answer]
|
2018/03/18
| 1,981 | 8,237 |
<issue_start>username_0: I read this documentation: <https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics>
There are many different API method to track exceptions, track trace etc..
I have a ASP.NET MVC 5 application.
For example, I have the following controller method (called by ajax):
```
[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
if ([condition])
{
// some actions here
try
{
driver.VistrackId = await _vistracksService.AddNewDriverToVistrackAsync(domain);
await db.SaveChangesAsync();
}
catch (VistracksApiException api_ex)
{
// external service throws exception type VistracksApiException
throw new AjaxException("vistracksApiClient", api_ex.Response.Message);
}
catch (VistracksApiCommonException common_ex)
{
// external service throws exception type VistracksApiCommonException
throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
}
catch (Exception ex)
{
// something wrong at all
throw new AjaxException("General", ex.Message);
}
}
else
{
// condition is not valid
throw new AjaxException("General", "AccountId is not found");
}
}
```
this method throws AjaxException if something wrong (which catch by AjaxErrorHandling and then return something json response to client).
Now I want to add telemetry for logging, analyzing exceptions and observe on client events.
So, I added the following:
```
[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
telemetryClient.TrackEvent("Sync driver", new Dictionary { { "ChangedBy", User.Identity.Name }, { "DriverID", DriverID.ToString() } }, null);
if ([condition])
{
// some actions here
try
{
driver.VistrackId = await \_vistracksService.AddNewDriverToVistrackAsync(domain);
await db.SaveChangesAsync();
}
catch (VistracksApiException api\_ex)
{
// external service throws exception type VistracksApiException
telemetryClient.TrackTrace("VistracksApiException", new Dictionary {
{ "ChangedBy", User.Identity.Name },
{ "DriverID", DriverID.ToString() },
{ "ResponseCode", api\_ex.Response.Code.ToString() },
{ "ResponseMessage", api\_ex.Response.Message },
{ "ResponseDescription", api\_ex.Response.Description }
});
telemetryClient.TrackException(api\_ex);
throw new AjaxException("vistracksApiClient", api\_ex.Response.Message);
}
catch (VistracksApiCommonException common\_ex)
{
// external service throws exception type VistracksApiCommonException
telemetryClient.TrackTrace("VistracksApiCommonException", new Dictionary {
{ "ChangedBy", User.Identity.Name },
{ "DriverID", DriverID.ToString() },
{ "Message", common\_ex.Message },
});
telemetryClient.TrackException(common\_ex);
throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
}
catch (Exception ex)
{
// something wrong at all
telemetryClient.TrackTrace("Exception", new Dictionary {
{ "ChangedBy", User.Identity.Name },
{ "DriverID", DriverID.ToString() },
{ "Message", ex.Message },
});
telemetryClient.TrackException(ex);
throw new AjaxException("General", ex.Message);
}
}
else
{
telemetryClient.TrackTrace("ConditionWrong", new Dictionary {
{ "ChangedBy", User.Identity.Name },
{ "DriverID", DriverID.ToString() },
{ "Message", "AccountId is not found" },
});
// condition is not valid
throw new AjaxException("General", "AccountId is not found");
}
}
```
by the following line:
```
telemetryClient.TrackEvent("Sync driver", new Dictionary { { "ChangedBy", User.Identity.Name }, { "DriverID", DriverID.ToString() } }, null);
```
I just "log" client event, that the method was called. Just for statistics.
In each "catch" block I try to write trace with different parameters and write exception:
```
telemetryClient.TrackTrace("trace name", new Dictionary {
{ "ChangedBy", User.Identity.Name },
....
});
telemetryClient.TrackException(ex);
```
Is it necessary? Or just need to track only exception? Then I lose different info, like who try to add these changes etc... When each of these methods should be used?<issue_comment>username_1: You can track all metrics/exceptions/traces/events independently. To make information events related to each others use [TelemetryContext](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#telemetrycontext)
>
> Is it necessary? Or just need to track only exception? Then I lose
> different info, like who try to add these changes etc... When each of
> these methods should be used?
>
>
>
It only depends on your needs. If you need that information - send it.
Upvotes: 0 <issue_comment>username_2: This is the best practice for 2.5.1 AI SDK. Will highlight parts which might not be required in upcoming AI SDK releases.
The right way to do end-to-end tracing is to rely on new Activity class in .NET framework. Until AI supports Activity.Tags (<https://github.com/Microsoft/ApplicationInsights-dotnet/issues/562>) you need to propagate them manually using [TelemetryInitializer](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling#itelemetryprocessor-and-itelemetryinitializer):
```
public class ActvityTagsTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
Activity current = Activity.Current;
if (current == null)
{
current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
}
while (current != null)
{
foreach (var tag in current.Tags)
{
if (!telemetry.Context.Properties.ContainsKey(tag.Key))
{
telemetry.Context.Properties.Add(tag.Key, tag.Value);
}
}
current = current.Parent;
}
}
}
```
Then register it in ApplicationInsights.config:
```
...
```
Then you can populate proper tags:
```
[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
Activity.Current.AddTag("DriverID", DriverID.ToString());
Activity.Current.AddTag("UserID", User.Identity.Name);
try
{
if ([condition])
{
// some actions here
try
{
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("AddNewDriverToVistrackAsync"))
{
driver.VistrackId = await \_vistracksService.AddNewDriverToVistrackAsync(domain);
}
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("SaveChanges"))
{
await db.SaveChangesAsync();
}
}
catch (VistracksApiException api\_ex)
{
// external service throws exception type VistracksApiException
throw new AjaxException("vistracksApiClient", api\_ex.Response.Message);
}
catch (VistracksApiCommonException common\_ex)
{
// external service throws exception type VistracksApiCommonException
throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
}
catch (Exception ex)
{
// something wrong at all
throw new AjaxException("General", ex.Message);
}
}
else
{
// condition is not valid
throw new AjaxException("General", "AccountId is not found");
}
}
catch (Exception ex)
{
// Upcoming 2.6 AI SDK will track exceptions for MVC apps automatically.
telemetryClient.TrackException(ex);
throw;
}
}
```
You should have the following telemetry:
1. Incoming request
2. Outgoing requests (dependencies)
3. Exceptions for failed requests
All telemetry will be stamped with ChangedBy and DriverID
Upvotes: 4 [selected_answer]
|
2018/03/18
| 1,076 | 4,320 |
<issue_start>username_0: I am hosting a website on aws, and I am writing it using jekyll. I want to post a video that I have created (not embedding from youtube). Right now I have a separate layout for video posting, in which I have:
In the frontmatter of my actual post I include the following line: video\_source: "simvids/10-mites-random-shades-5x5.webm"
The simvids directory is in the same folder as the \_site, \_layouts, and \_posts directory. The framework for the video loads, but the video itself does not. This leads me to think that the video tag is not the problem, but that I'm not directing properly to the video. Is my simvids directory in the wrong place? Is the error more subtle?
```
```
Thanks a bunch.<issue_comment>username_1: You can track all metrics/exceptions/traces/events independently. To make information events related to each others use [TelemetryContext](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#telemetrycontext)
>
> Is it necessary? Or just need to track only exception? Then I lose
> different info, like who try to add these changes etc... When each of
> these methods should be used?
>
>
>
It only depends on your needs. If you need that information - send it.
Upvotes: 0 <issue_comment>username_2: This is the best practice for 2.5.1 AI SDK. Will highlight parts which might not be required in upcoming AI SDK releases.
The right way to do end-to-end tracing is to rely on new Activity class in .NET framework. Until AI supports Activity.Tags (<https://github.com/Microsoft/ApplicationInsights-dotnet/issues/562>) you need to propagate them manually using [TelemetryInitializer](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling#itelemetryprocessor-and-itelemetryinitializer):
```
public class ActvityTagsTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
Activity current = Activity.Current;
if (current == null)
{
current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
}
while (current != null)
{
foreach (var tag in current.Tags)
{
if (!telemetry.Context.Properties.ContainsKey(tag.Key))
{
telemetry.Context.Properties.Add(tag.Key, tag.Value);
}
}
current = current.Parent;
}
}
}
```
Then register it in ApplicationInsights.config:
```
...
```
Then you can populate proper tags:
```
[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
Activity.Current.AddTag("DriverID", DriverID.ToString());
Activity.Current.AddTag("UserID", User.Identity.Name);
try
{
if ([condition])
{
// some actions here
try
{
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("AddNewDriverToVistrackAsync"))
{
driver.VistrackId = await \_vistracksService.AddNewDriverToVistrackAsync(domain);
}
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("SaveChanges"))
{
await db.SaveChangesAsync();
}
}
catch (VistracksApiException api\_ex)
{
// external service throws exception type VistracksApiException
throw new AjaxException("vistracksApiClient", api\_ex.Response.Message);
}
catch (VistracksApiCommonException common\_ex)
{
// external service throws exception type VistracksApiCommonException
throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
}
catch (Exception ex)
{
// something wrong at all
throw new AjaxException("General", ex.Message);
}
}
else
{
// condition is not valid
throw new AjaxException("General", "AccountId is not found");
}
}
catch (Exception ex)
{
// Upcoming 2.6 AI SDK will track exceptions for MVC apps automatically.
telemetryClient.TrackException(ex);
throw;
}
}
```
You should have the following telemetry:
1. Incoming request
2. Outgoing requests (dependencies)
3. Exceptions for failed requests
All telemetry will be stamped with ChangedBy and DriverID
Upvotes: 4 [selected_answer]
|
2018/03/18
| 1,085 | 4,301 |
<issue_start>username_0: Using while loops in Python, I have been asked to complete this task for university but I cannot seem to figure out how to do it:
>
> Ask for a number, and if the response is actually NOT a number (e.g. "cow", "six", "8!") then throw it out and ask for an actual number. When you do get a number, return it.
>
>
>
If anyone could show me how to do this that would be great!
I started out with this, although I'm not sure if it is the right starting point:
```
while () #not sure what to put in here
number_a = input("Enter an actual number:")
number_b = int(num_string)
return (
```
I'm not sure what to type after the `while` to make it work for numbers not words.<issue_comment>username_1: You can track all metrics/exceptions/traces/events independently. To make information events related to each others use [TelemetryContext](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics#telemetrycontext)
>
> Is it necessary? Or just need to track only exception? Then I lose
> different info, like who try to add these changes etc... When each of
> these methods should be used?
>
>
>
It only depends on your needs. If you need that information - send it.
Upvotes: 0 <issue_comment>username_2: This is the best practice for 2.5.1 AI SDK. Will highlight parts which might not be required in upcoming AI SDK releases.
The right way to do end-to-end tracing is to rely on new Activity class in .NET framework. Until AI supports Activity.Tags (<https://github.com/Microsoft/ApplicationInsights-dotnet/issues/562>) you need to propagate them manually using [TelemetryInitializer](https://learn.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling#itelemetryprocessor-and-itelemetryinitializer):
```
public class ActvityTagsTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
Activity current = Activity.Current;
if (current == null)
{
current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
}
while (current != null)
{
foreach (var tag in current.Tags)
{
if (!telemetry.Context.Properties.ContainsKey(tag.Key))
{
telemetry.Context.Properties.Add(tag.Key, tag.Value);
}
}
current = current.Parent;
}
}
}
```
Then register it in ApplicationInsights.config:
```
...
```
Then you can populate proper tags:
```
[AjaxErrorHandling]
[HttpPost]
public async Task SyncDriverToVistracks(int DriverID)
{
Activity.Current.AddTag("DriverID", DriverID.ToString());
Activity.Current.AddTag("UserID", User.Identity.Name);
try
{
if ([condition])
{
// some actions here
try
{
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("AddNewDriverToVistrackAsync"))
{
driver.VistrackId = await \_vistracksService.AddNewDriverToVistrackAsync(domain);
}
// If below call is HTTP then no need to use StartOperation
using (telemetryClient.StartOperation("SaveChanges"))
{
await db.SaveChangesAsync();
}
}
catch (VistracksApiException api\_ex)
{
// external service throws exception type VistracksApiException
throw new AjaxException("vistracksApiClient", api\_ex.Response.Message);
}
catch (VistracksApiCommonException common\_ex)
{
// external service throws exception type VistracksApiCommonException
throw new AjaxException("vistracksApiServer", "3MD HOS server is not available");
}
catch (Exception ex)
{
// something wrong at all
throw new AjaxException("General", ex.Message);
}
}
else
{
// condition is not valid
throw new AjaxException("General", "AccountId is not found");
}
}
catch (Exception ex)
{
// Upcoming 2.6 AI SDK will track exceptions for MVC apps automatically.
telemetryClient.TrackException(ex);
throw;
}
}
```
You should have the following telemetry:
1. Incoming request
2. Outgoing requests (dependencies)
3. Exceptions for failed requests
All telemetry will be stamped with ChangedBy and DriverID
Upvotes: 4 [selected_answer]
|
2018/03/18
| 657 | 2,318 |
<issue_start>username_0: Is there any way to do inline unpacking in a with statement in python?
Right now, I have a custom context manager that returns a `sqlalchemy` `row` object, and the associated `session` needed to potentially delete it as a 2-tuple, and handles the necessary database manipulations on context exit:
```
with self.row_sess_context(dbid=relid) as tup:
row, sess = tup
...[manipulation code]...
```
Now, it seems to me like it'd be particularly "pythonic" to be able to do something like:
```
with self.row_sess_context(dbid=relid) as row, sess:
...[manipulation code]...
```
Particularly as python already supports sequence unpacking in most other contexts (`for`, list comprehension, normal assignment, etc...).
Experimenting with things like trying to put `row, sess` is invalid [confuses the sublime text syntax highlighter](https://github.com/sublimehq/Packages/issues/1467), and I'm apparently not smart enough to understand if this is just flat out not possible from the formal grammar definition.
Is there a better way then having to manually unpack the tuple?<issue_comment>username_1: Arrrgh, so I got stymied by syntax highlighting.
You *can* do:
```
with self.row_sess_context(dbid=relid) as (row, sess):
```
but it breaks the native sublime-text python highlighting, so I *thought* it wasn't valid.
See: <https://github.com/sublimehq/Packages/issues/1467>
At least I got a bug report out of it.
Upvotes: 4 [selected_answer]<issue_comment>username_2: What you're trying to write doesn't work:
```
with self.row_sess_context(dbid=relid) as row, sess:
```
… because a `with` statement can take multiple context managers and bind each one's context value, so you're asking it to enter `self.row_sess_context(dbid=relid)` and bind its value as `row`, and enter `sess` and ignore its value. Since `sess` probably isn't a context manager, this is an error.
But if you just parenthesize the unpackables, it does exactly what you want:
```
with self.row_sess_context(dbid=relid) as (row, sess):
```
Since it's impossible to demonstrate with your incomplete code fragment, here's a minimal example that anyone can run:
```
import contextlib
@contextlib.contextmanager
def ctx():
yield (1, 2)
with ctx() as (x, y):
print(x, y)
```
Upvotes: 2
|
2018/03/18
| 363 | 1,307 |
<issue_start>username_0: I have a flashing sprite css animation for an empty div.
```css
#flashIt{
width: 50%;
height: 100px;
background: blue;
margin: 10px auto;
border: solid 2px black;
left: 25%;
animation: flash 1s linear infinite;
}
@keyframes flash {
0% { opacity: 1; }
50% { opacity: .1 }
100% { opacity: 1; }
}
```
So this animation works as it is. However I want the animation to begin when a key is pressed by the user on their keyboard. How can I do this using JS? Help on this would be much appreciated. Thanks<issue_comment>username_1: A simple way to do this would be to listen for a keypress and then, when a key is pressed, apply a class to the appropriate DOM element. This class would contain your animation styling which would then animate the element just like you want.
```
var elementToAnimate = document.findElementById("flashIt");
document.addEventListener('keypress', function(event) {
elementToAnimate.classList.add('your-animation-class');
});
```
Upvotes: 0 <issue_comment>username_2: Here is an example of what you could do.
```
$(document).keypress('keypress',function(e){
if(e.which==13){
$('div').toggleClass('animation');
}
});
```
This will activate the animation class when you press the enter key.
Upvotes: -1
|
2018/03/18
| 484 | 1,675 |
<issue_start>username_0: How do i pass a variable from Jquery to PHP?
```
var itemId = $(this).attr('name');
$.ajax({
url: "loaditems.php",
method: "GET",
success: function(result){
alert(result);
}});
```
I want to add a number in PHP at the end of my SQL request.
```
$sql = "SELECT * FROM SmiteItems WHERE ID = ";
```
I know there are many questions like this, but other questions are made by people who have more complicated structures which i don't understand.<issue_comment>username_1: add `data` in ajax call and use that data in target url:
```
var itemId = $(this).attr('name');
$.ajax({
url: "loaditems.php",
method: "GET",
data: {number:itemId},
success: function(result){
alert(result);
}
});
```
and then in loaditems.php
```
$sql = "SELECT * FROM SmiteItems WHERE ID = " . $_GET['number'];
```
As this is not a database and security question, I write no more about **SQL INJECTION**. Please use "post" method and read more about injection.
Upvotes: -1 <issue_comment>username_2: Use the POST method, then try using PHP PDO for making sql queries
<http://php.net/manual/en/pdo.query.php>
```
var itemId = $(this).attr('name');
$.ajax({
url: "loaditems.php",
method: "POST", //change
data: { myVar: itemId }
success: function(result) {
alert(result);
}
});
```
Then in your PHP code
```
//Get post value from AJAX
$itemId = $_POST['myVar'];
\\PDO Example
$sql = "SELECT * FROM SmiteItems WHERE ID = ?";
$result = $pdo->prepare($sql);
$result->bindparam(1, $itemId);
$result->execute();
```
Upvotes: 2 [selected_answer]
|
2018/03/18
| 539 | 1,914 |
<issue_start>username_0: Is it possible to validate in Vuetify group of checkboxes in the same manner as group of radios? I tried to validate them 'as whole' but each checkbox is validated separately. How to enforce checking at least one of the checkbox fields?
```html
```
I would like to have just one mandatory checkbox. Not all of them. Any checkbox from the group of them.<issue_comment>username_1: How about something like this?
Pen here : <https://codepen.io/anon/pen/WzoVQZ>
```
{{ selected }}
SUBMIT
Please select at least one checkbox.
Close
data: () => ({
//
snackbar:false,
selected:['John'],
}),
methods: {
submit () {
if (this.selected.length > 0){
this.snackbar = true;
}
}
}
```
Upvotes: -1 <issue_comment>username_2: Try this way:
```html
```
Upvotes: 2 <issue_comment>username_3: i know this is too late for answare this thread but it may help someone who want to validate the checkbox in array
---
how work?
this concept is simple,must select atleast one checkbox in array
---
here index==0 ,i want to show error on first element so i applied :rules
and then i want to check atleast one element selected so i decided to write condition in given following method by alllow\_validate:false. then validation performed in computed.
```
```
2.declare data
```
data(){
yourarray:[{cv:'checkbox1'},{cv:'checkbox2'},{cv:'checkbox3'}],
alllow_validate:false,
}
```
3.method
```
methods: {
Checkboxlist(){
this.$nextTick(() => {
var checked=document.querySelectorAll('input[type=checkbox]:checked');
var store="";
var firstelement=false;
for(var i=0;i
```
3.computed
```
computed:{
checkbox_rules(){
const rules=[];
if(this.alllow_validate){
// alert("rule");
const rule=
v => (!!v) || "Field is required";
rules.push(rule)
}
return rules;
}
```
Upvotes: 0
|
2018/03/18
| 1,412 | 5,455 |
<issue_start>username_0: I am attempting to implement Automatic SMS Verification with the SMS Retriever API, [as described here](https://developers.google.com/identity/sms-retriever/request).
To initially test this I had planned on using the Android Emulator and manually sending SMS messages using its GUI interface:
[](https://i.stack.imgur.com/P7MiM.png)
However, my BroadcastReceiver callback is never invoked:
```
@Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
Status status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch(status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
// Get SMS message contents
String message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
Log.i(TAG, "Got message: " + message);
// Extract one-time code from the message and complete verification
// by sending the code back to your server.
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
// Handle the error ...
break;
}
}
}
```
Does the [`SmsRetriever`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/phone/SmsRetriever) class work inside the [Android emulator](https://developer.android.com/studio/run/emulator.html)?<issue_comment>username_1: I was not properly computing my App's Hash String:
<https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string>
This is a six-step process:
1. Get your app's public key certificate as a lower-case hex string.
For example, to get the hex string from your keystore, type the
following command:
`keytool -alias MyAndroidKey -exportcert -keystore MyProduction.keystore | xxd -p | tr -d "[:space:]"`
2. Append the hex
string to your app's package name, separated by a single space.
3. Compute the SHA-256 sum of the combined string. Be sure to remove
any leading or trailing whitespace from the string before computing
the SHA-256 sum.
4. Base64-encode the binary value of the SHA-256 sum.
You might need to decode the SHA-256 sum from its output format
first.
5. Your app's hash string is the first 11 characters of the
base64-encoded hash.
Once computed, you have to send a specially-crafted SMS message to your device starting with a `<#>` and ending with this app hash string; just any old SMS message will not do.
Note that the command-line steps using `keytool` above to extract my App's hash string never did work for me; I had to use the [helper class Google provided](https://github.com/googlesamples/android-credentials/blob/master/sms-verification/android/app/src/main/java/com/google/samples/smartlock/sms_verify/AppSignatureHelper.java).
Upvotes: 2 <issue_comment>username_2: Yes, the issue here is the incorrect hash string. Please note that **debug and release hash strings are usually different**.
To get this hash string you can follow the instructions in the accepted answer. But here's an **alternative approach** with a quick code snippet:
```
class AppSignatureHelper(context: Context?) :
ContextWrapper(context) {// Get all package signatures for the current package
// For each signature create a compatible hash
/**
* Get all the app signatures for the current package
*
* @return
*/
val appSignatures: ArrayList
get() {
val appCodes = ArrayList()
try {
// Get all package signatures for the current package
val packageName = packageName
val packageManager = packageManager
val signatures = packageManager.getPackageInfo(
packageName,
PackageManager.GET\_SIGNATURES
).signatures
// For each signature create a compatible hash
for (signature in signatures) {
val hash = hash(packageName, signature.toCharsString())
if (hash != null) {
appCodes.add(String.format("%s", hash))
}
}
} catch (e: PackageManager.NameNotFoundException) {
Log.v(TAG, "Unable to find package to obtain hash.", e)
}
return appCodes
}
companion object {
val TAG = AppSignatureHelper::class.java.simpleName
private const val HASH\_TYPE = "SHA-256"
const val NUM\_HASHED\_BYTES = 9
const val NUM\_BASE64\_CHAR = 11
private fun hash(packageName: String, signature: String): String? {
val appInfo = "$packageName $signature"
try {
val messageDigest = MessageDigest.getInstance(HASH\_TYPE)
messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF\_8))
var hashSignature = messageDigest.digest()
// truncated into NUM\_HASHED\_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM\_HASHED\_BYTES)
// encode into Base64
var base64Hash =
Base64.encodeToString(hashSignature, Base64.NO\_PADDING or Base64.NO\_WRAP)
base64Hash = base64Hash.substring(0, NUM\_BASE64\_CHAR)
Log.v(
TAG + "sms\_sample\_test",
String.format("pkg: %s -- hash: %s", packageName, base64Hash)
)
return base64Hash
} catch (e: NoSuchAlgorithmException) {
Log.v(TAG + "sms\_sample\_test", "hash:NoSuchAlgorithm", e)
}
return null
}
}
}
```
Then you can call from, for example, your application class:
```
val appSignature = AppSignatureHelper(this)
val signature = appSignature.appSignatures[0]
```
Upvotes: 0
|
2018/03/18
| 1,542 | 5,729 |
<issue_start>username_0: I built an application in java on android that sends the bytes of a .jpg file through a socket and an [Asynchronous Server Socket](https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example) in C# on windows that receives the bytes and writes them into a .jpg a file. The received file can't be open.
In the java application, which is the client, I used the folowing asynctask class executed on the onCreate:
```
class asyncTask extends AsyncTask{
@Override
protected Void doInBackground(Void... voids) {
try {
final File myFile = new File("//sdcard/DCIM/Camera/img1.jpg");
byte[] bytes = new byte[(int) myFile.length()];
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(myFile));
buf.read(bytes, 0, bytes.length);
s = new Socket(ip,3333);
OutputStream OS = s.getOutputStream();
OS.write(bytes, 0, bytes.length);
OS.flush();
s.close();
} catch (IOException e) {
Log.d("Error",e.toString());
e.printStackTrace();
}
return null;
}
}
```
And in the C# application I received the data and saved it to a file in the following async callback method that is called when data is received:
```
public static void ReadCallback(IAsyncResult ar)
{
Socket clientSocket = (Socket)ar.AsyncState;
int buffLength = clientSocket.EndReceive(ar);
Array.Resize(ref buffer, buffLength);
totaLength += buffLength;
buffer.CopyTo(allData, totaLength - 1);
if (buffLength == 0)
{
Array.Resize(ref allData, totaLength);
File.WriteAllBytes("C: /Users/fxavi/Desktop/img.jpg", allData);
Console.WriteLine(totaLength);
}
else
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), clientSocket);
}
```<issue_comment>username_1: I was not properly computing my App's Hash String:
<https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string>
This is a six-step process:
1. Get your app's public key certificate as a lower-case hex string.
For example, to get the hex string from your keystore, type the
following command:
`keytool -alias MyAndroidKey -exportcert -keystore MyProduction.keystore | xxd -p | tr -d "[:space:]"`
2. Append the hex
string to your app's package name, separated by a single space.
3. Compute the SHA-256 sum of the combined string. Be sure to remove
any leading or trailing whitespace from the string before computing
the SHA-256 sum.
4. Base64-encode the binary value of the SHA-256 sum.
You might need to decode the SHA-256 sum from its output format
first.
5. Your app's hash string is the first 11 characters of the
base64-encoded hash.
Once computed, you have to send a specially-crafted SMS message to your device starting with a `<#>` and ending with this app hash string; just any old SMS message will not do.
Note that the command-line steps using `keytool` above to extract my App's hash string never did work for me; I had to use the [helper class Google provided](https://github.com/googlesamples/android-credentials/blob/master/sms-verification/android/app/src/main/java/com/google/samples/smartlock/sms_verify/AppSignatureHelper.java).
Upvotes: 2 <issue_comment>username_2: Yes, the issue here is the incorrect hash string. Please note that **debug and release hash strings are usually different**.
To get this hash string you can follow the instructions in the accepted answer. But here's an **alternative approach** with a quick code snippet:
```
class AppSignatureHelper(context: Context?) :
ContextWrapper(context) {// Get all package signatures for the current package
// For each signature create a compatible hash
/**
* Get all the app signatures for the current package
*
* @return
*/
val appSignatures: ArrayList
get() {
val appCodes = ArrayList()
try {
// Get all package signatures for the current package
val packageName = packageName
val packageManager = packageManager
val signatures = packageManager.getPackageInfo(
packageName,
PackageManager.GET\_SIGNATURES
).signatures
// For each signature create a compatible hash
for (signature in signatures) {
val hash = hash(packageName, signature.toCharsString())
if (hash != null) {
appCodes.add(String.format("%s", hash))
}
}
} catch (e: PackageManager.NameNotFoundException) {
Log.v(TAG, "Unable to find package to obtain hash.", e)
}
return appCodes
}
companion object {
val TAG = AppSignatureHelper::class.java.simpleName
private const val HASH\_TYPE = "SHA-256"
const val NUM\_HASHED\_BYTES = 9
const val NUM\_BASE64\_CHAR = 11
private fun hash(packageName: String, signature: String): String? {
val appInfo = "$packageName $signature"
try {
val messageDigest = MessageDigest.getInstance(HASH\_TYPE)
messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF\_8))
var hashSignature = messageDigest.digest()
// truncated into NUM\_HASHED\_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM\_HASHED\_BYTES)
// encode into Base64
var base64Hash =
Base64.encodeToString(hashSignature, Base64.NO\_PADDING or Base64.NO\_WRAP)
base64Hash = base64Hash.substring(0, NUM\_BASE64\_CHAR)
Log.v(
TAG + "sms\_sample\_test",
String.format("pkg: %s -- hash: %s", packageName, base64Hash)
)
return base64Hash
} catch (e: NoSuchAlgorithmException) {
Log.v(TAG + "sms\_sample\_test", "hash:NoSuchAlgorithm", e)
}
return null
}
}
}
```
Then you can call from, for example, your application class:
```
val appSignature = AppSignatureHelper(this)
val signature = appSignature.appSignatures[0]
```
Upvotes: 0
|
2018/03/18
| 454 | 1,351 |
<issue_start>username_0: So I have this program that takes in PID input and a character.
```
$ ./transmit 1111 a
```
My question is. If it were
```
$ ./transmit 111a x
```
since PID are all numbers I'd need to catch that.
given:
```
char *a[] = {"./transmit", "111a", "x"};
```
how would I check if "111a" is numeric only? isdigit only works if it's a character. Do I have to loop through the entire input?<issue_comment>username_1: You could maybe use the [strspn()](https://www.tutorialspoint.com/c_standard_library/c_function_strspn.htm) function:
```
#include
#include
int main(int argc, char\* argv[]) {
if (argc > 1) {
if (argv[1][strspn(argv[1], "0123456789")] == '\0') {
puts("Yes, the first command line argument is all numeric.");
}
else {
puts("No, the first command line argument is not all numeric.");
}
}
else {
puts("Please provide an argument on the command line");
}
return 0;
}
```
Upvotes: 2 <issue_comment>username_2: ```
char *err;
unsigned long pid = strtoul(argv[1], &err, 10);
if (*err || err == argv[1])
error();
if ((pid_t)pid != pid || (pid_t)pid <= 0)
error();
```
When you are really pedantic, you can check for `ULONG_MAX` and `errno == ERANGE` too, but because `pid_t` is smaller than `unsigned long`, this will be catched by the second check already.
Upvotes: 3 [selected_answer]
|
2018/03/18
| 464 | 1,608 |
<issue_start>username_0: I am trying to move a UIView up and off the screen by its height in ios. Below is my code for doing this. What I am finding is that the UIView does indeed move up and off the screen but instead of moving slowly as intended it continues to move off instantaneously without animation. Please can someone advise?
```
UIView.animate(withDuration: 300, animations: {
let heightOfViewContainingProgrBar = self.viewContainingProgressBar.frame.height
self.viewContainingProgressBar.topAnchor.constraint(equalTo: self.view.topAnchor, constant: -heightOfViewContainingProgrBar).isActive = true
})
```<issue_comment>username_1: You could maybe use the [strspn()](https://www.tutorialspoint.com/c_standard_library/c_function_strspn.htm) function:
```
#include
#include
int main(int argc, char\* argv[]) {
if (argc > 1) {
if (argv[1][strspn(argv[1], "0123456789")] == '\0') {
puts("Yes, the first command line argument is all numeric.");
}
else {
puts("No, the first command line argument is not all numeric.");
}
}
else {
puts("Please provide an argument on the command line");
}
return 0;
}
```
Upvotes: 2 <issue_comment>username_2: ```
char *err;
unsigned long pid = strtoul(argv[1], &err, 10);
if (*err || err == argv[1])
error();
if ((pid_t)pid != pid || (pid_t)pid <= 0)
error();
```
When you are really pedantic, you can check for `ULONG_MAX` and `errno == ERANGE` too, but because `pid_t` is smaller than `unsigned long`, this will be catched by the second check already.
Upvotes: 3 [selected_answer]
|
2018/03/18
| 628 | 2,312 |
<issue_start>username_0: We have a FTL that has -
`[Link](javascript:func("${event.title}");)`
When the value has an apostrophe, like `<NAME>` - it breaks.
We used `js_string` to fix it -
`[Link](javascript:func('${event.title?js_string}');)`
But we also had to change the double quotes around `$expression` to single quotes - this does Not work with double quotes.
**Question** -
Is there a way to fix this with the original double quotes around the `$expression` ?
Something like -
`[Link](javascript:func("${event.title?js_string}");)`
Note the above does not work.<issue_comment>username_1: Modify the value of `event.title` so that single quotes are replaces with `'` and double quotes are replaces with `"`, then you won't have to worry at all about which kind of quotes you use for the rest of it.
Upvotes: 0 <issue_comment>username_2: You need two kind of escaping applied here: JavaScript string escaping and HTML escaping. You need both, as the two formats are independent, and the JavaScript is embedded into HTML.
How to do that... the primitive way is `event.title?js_string?html`, but it's easy to forget to add that `?html`, so don't do that. Instead, use auto-escaping (see <https://freemarker.apache.org/docs/dgui_quickstart_template.html#dgui_quickstart_template_autoescaping>). If you can't use that form of auto-escaping for some reason (like you are using some old FreeMarker version and aren't allowed to upgrade), put the whole template into `<#escape x as x?html>...`. In both cases, you can just write `${event.title?js_string}`, and it will just work.
However, if you are using `#escape`, ensure that the `incompatible_improvements` setting (see <https://freemarker.apache.org/docs/pgui_config_incompatible_improvements.html>) is at least 2.3.20, or else `?html` doesn't escape `'`.
Upvotes: 2 <issue_comment>username_3: `?js_string` should be outside curly brackets {}. Now you should use double quotes " " around href value, if you wanna handle single quotes ' ' inside the string and vice versa. Single and double quote can not be used in same string, so either of them needs to be replaced to other.
solution:
`[Link](javascript:func('${event.title!?js_string}');)`
Same expression can be used in JavaScript to handle special characters
Upvotes: 0
|
2018/03/18
| 621 | 2,401 |
<issue_start>username_0: I have two tables cars table and bookings table.I want to list all the cars which are available between search dates from and to date, using la-ravel query builder.
```
$cars= DB::table('bookings')->select('*')
->where('from', '>=', $from)
->where('from', '<=', $till)
->where('status','!=','booked')
->get();
```
I am able to get results when from date is not between the dates of all ready booked cars. but I have a problem when from date and to date is not between the dates where car is already booked.
how can i check date ranges between the date ranges of the already booked cars from and to date.<issue_comment>username_1: Modify the value of `event.title` so that single quotes are replaces with `'` and double quotes are replaces with `"`, then you won't have to worry at all about which kind of quotes you use for the rest of it.
Upvotes: 0 <issue_comment>username_2: You need two kind of escaping applied here: JavaScript string escaping and HTML escaping. You need both, as the two formats are independent, and the JavaScript is embedded into HTML.
How to do that... the primitive way is `event.title?js_string?html`, but it's easy to forget to add that `?html`, so don't do that. Instead, use auto-escaping (see <https://freemarker.apache.org/docs/dgui_quickstart_template.html#dgui_quickstart_template_autoescaping>). If you can't use that form of auto-escaping for some reason (like you are using some old FreeMarker version and aren't allowed to upgrade), put the whole template into `<#escape x as x?html>...`. In both cases, you can just write `${event.title?js_string}`, and it will just work.
However, if you are using `#escape`, ensure that the `incompatible_improvements` setting (see <https://freemarker.apache.org/docs/pgui_config_incompatible_improvements.html>) is at least 2.3.20, or else `?html` doesn't escape `'`.
Upvotes: 2 <issue_comment>username_3: `?js_string` should be outside curly brackets {}. Now you should use double quotes " " around href value, if you wanna handle single quotes ' ' inside the string and vice versa. Single and double quote can not be used in same string, so either of them needs to be replaced to other.
solution:
`[Link](javascript:func('${event.title!?js_string}');)`
Same expression can be used in JavaScript to handle special characters
Upvotes: 0
|
2018/03/18
| 391 | 1,509 |
<issue_start>username_0: I want the variable $con to get data(country) from a JavaScript function and save it in SQL database. the insert query is working fine without JavaScript code but when I want to add $con into my database using insert query, the insert query do not add data to my SQL database
Here is my code:
```
$con = "
function jsonpCallback(data) {
var con = document.write(data.address.country) }
";
$sql = "INSERT INTO `searched1`
(`search`, `longitude`, `latitude`, `country`, `date`)
VALUES ('$phone','$lon','$lat','$con','$datetime')";
$result=mysqli_query($conn,$sql);
```<issue_comment>username_1: I don't know how you're initiating the SQL query but I would use a `form`:
```
document.getElementById('con').value = data.address.country;
php
$con = $_POST['$con'];
$sql = "INSERT INTO `searched1`
(`search`, `longitude`, `latitude`, `country`, `date`)
VALUES ('$phone','$lon','$lat','$con','$datetime')";
?
```
Upvotes: 1 <issue_comment>username_2: I'd like to add to the previous answer that username_1 wrote, whats wrong with this is that you can never get a value from Javascript into a PHP variable like this.
That code is rendered on the server, and Js only renders in the 'viewers' browser.
At best this would just input a string containing your script function. You should use a form or Ajax to send data to the PHP script/function which executes the database insert query. That's the proper way.
Upvotes: 0
|
2018/03/18
| 2,363 | 7,499 |
<issue_start>username_0: I created a bloom filter using murmur3, blake2b, and Kirsch-Mitzenmacher-optimization, as described in the second answer to this question: [Which hash functions to use in a Bloom filter](https://stackoverflow.com/questions/11954086/which-hash-functions-to-use-in-a-bloom-filter)
However, when I was testing it, the bloom filter constantly had a much higher error rate than I was expecting.
Here is the code I used to generate the bloom filters:
```
public class BloomFilter {
private BitSet filter;
private int size;
private int hfNum;
private int prime;
private double fp = 232000; //One false positive every fp items
public BloomFilter(int count) {
size = (int)Math.ceil(Math.ceil(((double)-count) * Math.log(1/fp))/(Math.pow(Math.log(2),2)));
hfNum = (int)Math.ceil(((this.size / count) * Math.log(2)));
//size = (int)Math.ceil((hfNum * count) / Math.log(2.0));
filter = new BitSet(size);
System.out.println("Initialized filter with " + size + " positions and " + hfNum + " hash functions.");
}
public BloomFilter extraSecure(int count) {
return new BloomFilter(count, true);
}
private BloomFilter(int count, boolean x) {
size = (int)Math.ceil((((double)-count) * Math.log(1/fp))/(Math.pow(Math.log(2),2)));
hfNum = (int)Math.ceil(((this.size / count) * Math.log(2)));
prime = findPrime();
size = prime * hfNum;
filter = new BitSet(prime * hfNum);
System.out.println("Initialized filter with " + size + " positions and " + hfNum + " hash functions.");
}
public void add(String in) {
filter.set(getMurmur(in), true);
filter.set(getBlake(in), true);
if(this.hfNum > 2) {
for(int i = 3; i <= (hfNum); i++) {
filter.set(getHash(in, i));
}
}
}
public boolean check(String in) {
if(!filter.get(getMurmur(in)) || !filter.get(getBlake(in))) {
return false;
}
for(int i = 3; i <= hfNum; i++) {
if(!filter.get(getHash(in, i))) {
return false;
}
}
return true;
}
private int getMurmur(String in) {
int temp = murmur(in) % (size);
if(temp < 0) {
temp = temp * -1;
}
return temp;
}
private int getBlake(String in) {
int temp = new BigInteger(blake256(in), 16).intValue() % (size);
if(temp < 0) {
temp = temp * -1;
}
return temp;
}
private int getHash(String in, int i) {
int temp = ((getMurmur(in)) + (i * getBlake(in))) % size;
return temp;
}
private int findPrime() {
int temp;
int test = size;
while((test * hfNum) > size ) {
temp = test - 1;
while(!isPrime(temp)) {
temp--;
}
test = temp;
}
if((test * hfNum) < this.size) {
test++;
while(!isPrime(test)) {
test++;
}
}
return test;
}
private static boolean isPrime(int num) {
if (num < 2) return false;
if (num == 2) return true;
if (num % 2 == 0) return false;
for (int i = 3; i * i <= num; i += 2)
if (num % i == 0) return false;
return true;
}
@Override
public String toString() {
final StringBuilder buffer = new StringBuilder(size);
IntStream.range(0, size).mapToObj(i -> filter.get(i) ? '1' : '0').forEach(buffer::append);
return buffer.toString();
}
```
}
Here is the code I'm using to test it:
```
public static void main(String[] args) throws Exception {
int z = 0;
int times = 10;
while(z < times) {
z++;
System.out.print("\r");
System.out.print(z);
BloomFilter test = new BloomFilter(4000);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
for(int i = 0; i < 4000; i++) {
test.add(blake256(Integer.toString(random.nextInt())));
}
int temp = 0;
int count = 1;
while(!test.check(blake512(Integer.toString(temp)))) {
temp = random.nextInt();
count++;
}
if(z == (times)) {
Files.write(Paths.get("counts.txt"), (Integer.toString(count)).getBytes(), StandardOpenOption.APPEND);
}else {
Files.write(Paths.get("counts.txt"), (Integer.toString(count) + ",").getBytes(), StandardOpenOption.APPEND);
}
if(z == 1) {
Files.write(Paths.get("counts.txt"), (Integer.toString(count) + ",").getBytes());
}
}
}
```
I expect to get a value relatively close to the fp variable in the bloom filter class, but instead I frequently get half that. Anyone know what I'm doing wrong, or if this is normal?
EDIT: To show what I mean by high error rates, when I run the code on a filter initialized with count 4000 and fp 232000, this was the output in terms of how many numbers the filter had to run through before it found a false positive:
```
158852,354114,48563,76875,156033,82506,61294,2529,82008,32624
```
This was generated using the extraSecure() method for initialization, and repeated 10 times to generate these 10 numbers; all but one of them took less than 232000 generated values to find a false positive. The average of the 10 is about 105540, and that's common no matter how many times I repeat this test.
Looking at the values it found, the fact that it found a false positive after only generating 2529 numbers is a huge issue for me, considering I'm adding 4000 data points.<issue_comment>username_1: Turns out the issue was that the answer on the other page wasn't completely correct, and neither was the comment below it.
The comment said:
>
> in the paper hash\_i = hash1 + i x hash2 % p, where p is a prime, hash1 and hash2 is within range of [0, p-1], and the bitset consists k \* p bits.
>
>
>
However, looking at the paper reveals that while all the hashes are mod p, each hash function is assigned a subset of the total bitset, which I understood to mean hash1 mod p would determine a value for indices 0 through p, hash2 mod p would determine a value for indices p through 2\*p, and so on and so forth until the k value chosen for the bitset is reached.
I'm not 100% sure if adding this will fix my code, but it's worth a try. I'll update this if it works.
UPDATE: Didn't help. I'm looking into what else may be causing this problem.
Upvotes: 0 <issue_comment>username_2: I'm afraid I don't know where the bug is, but you can simplify a lot. You don't actually need prime size, you don't need SecureRandom, BigInteger, and modulo. All you need is a good 64 bit hash (seeded if possible, for example murmur):
```
long bits = (long) (entryCount * bitsPerKey);
int arraySize = (int) ((bits + 63) / 64);
long[] data = new long[arraySize];
int k = getBestK(bitsPerKey);
void add(long key) {
long hash = hash64(key, seed);
int a = (int) (hash >>> 32);
int b = (int) hash;
for (int i = 0; i < k; i++) {
data[reduce(a, arraySize)] |= 1L << index;
a += b;
}
}
boolean mayContain(long key) {
long hash = hash64(key, seed);
int a = (int) (hash >>> 32);
int b = (int) hash;
for (int i = 0; i < k; i++) {
if ((data[reduce(a, arraySize)] & 1L << a) == 0) {
return false;
}
a += b;
}
return true;
}
static int reduce(int hash, int n) {
// http://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
return (int) (((hash & 0xffffffffL) * n) >>> 32);
}
static int getBestK(double bitsPerKey) {
return Math.max(1, (int) Math.round(bitsPerKey * Math.log(2)));
}
```
Upvotes: 1
|
2018/03/18
| 808 | 2,928 |
<issue_start>username_0: I am running a telegram bot in python and i am using python3.6 on raspbian ( pi3 )
Below is my imports:
```
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import (
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
from uuid import uuid4
import re
import telegram
from telegram.utils.helpers import escape_markdown
from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
import random
import telepot
import unicodedata
import json
import requests
import bs4
from bs4 import BeautifulSoup
```
When i try to run my bot with sudo python3 bot.py i get
```
ImportError: No module named 'future'
```
I have searched and found many answers on this but none have worked for me such as `pip install future` and `pip3 install future` The module does show in my lib for python 3.6 [future in lib](https://i.stack.imgur.com/zvTXE.png)
Any idea why it still says `No module named future`? ?<issue_comment>username_1: I ran into a similar problem using Python code written by someone else. See <http://python-future.org/>. future is a module that aids in conversion between Python 2 and 3. It was an easy installation for me by doing `pip3 install future`
Upvotes: 5 <issue_comment>username_2: I had the similar problem, solved it using `easy_install future`
Upvotes: 0 <issue_comment>username_3: I had the similar problem, solved it using `conda install future`
Upvotes: 1 <issue_comment>username_4: I tried install, reinstall, easy\_install and conda install but nothing worked for me. I was finally able to import my package by running upgrade on future.
```
pip install -U future
```
This solved my issue.
Upvotes: 4 <issue_comment>username_5: None of these work for me, despite uninstalling the module, then reinstalling it with `pip3 install future` I keep getting the error (trying to run ardupilot's `sim_vehicle.py --console --map` in case it matters)
Upvotes: 2 <issue_comment>username_6: I know this is an old question, but if anyone needs it. This happened when I was trying to builds tests for ArduPilot.
I was facing a similar problem, the pip that you'd have been using was for python3. So you need to install pip for python2.7. You can do that using curl
```
apt-get install curl
curl https://bootstrap.pypa.io/2.7/get-pip.py -o get-pip.py
python get-pip.py
```
Then you can run
```
pip install future
```
to install future.
Upvotes: 0 <issue_comment>username_7: I encountered the same problem.
The previous answer isn't effective anymore.
I had to install python 3.7 and use this :
```
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.7 get-pip.py
```
Upvotes: 0
|
2018/03/18
| 750 | 2,795 |
<issue_start>username_0: Lets say I have a `Namespace` class like follows:
```
abstract class Namespace {
protected prefix;
protected Map tags;
public setTag(String tagKey, String tagValue) {
tags.put(tagKey, tagValue);
}
}
```
I have been told that a good design is to have separate implementations of each namespace with getters defining the information being retrieved from the `tags` map. ie.
```
class FooNamespace extends Namespace {
public String getNameTag() {
return tags.get("name");
}
}
```
We can have separate implementations of a namespace like `BarNamespace` which will have different tags stored (`BarNamespace` does not have a name tag for ex. and instead has an age tag). Why does the above design make more sense than simply having the consumer of a simple `Namespace` class request the tag they want. ie:
```
class Namespace {
private prefix;
private Map tags;
public String getTag(String key) {
return tags.get(key);
}
}
```
The above is used like
```
Namespace.getTag("name");
```<issue_comment>username_1: I ran into a similar problem using Python code written by someone else. See <http://python-future.org/>. future is a module that aids in conversion between Python 2 and 3. It was an easy installation for me by doing `pip3 install future`
Upvotes: 5 <issue_comment>username_2: I had the similar problem, solved it using `easy_install future`
Upvotes: 0 <issue_comment>username_3: I had the similar problem, solved it using `conda install future`
Upvotes: 1 <issue_comment>username_4: I tried install, reinstall, easy\_install and conda install but nothing worked for me. I was finally able to import my package by running upgrade on future.
```
pip install -U future
```
This solved my issue.
Upvotes: 4 <issue_comment>username_5: None of these work for me, despite uninstalling the module, then reinstalling it with `pip3 install future` I keep getting the error (trying to run ardupilot's `sim_vehicle.py --console --map` in case it matters)
Upvotes: 2 <issue_comment>username_6: I know this is an old question, but if anyone needs it. This happened when I was trying to builds tests for ArduPilot.
I was facing a similar problem, the pip that you'd have been using was for python3. So you need to install pip for python2.7. You can do that using curl
```
apt-get install curl
curl https://bootstrap.pypa.io/2.7/get-pip.py -o get-pip.py
python get-pip.py
```
Then you can run
```
pip install future
```
to install future.
Upvotes: 0 <issue_comment>username_7: I encountered the same problem.
The previous answer isn't effective anymore.
I had to install python 3.7 and use this :
```
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.7 get-pip.py
```
Upvotes: 0
|
2018/03/18
| 1,453 | 3,665 |
<issue_start>username_0: I've just read about HSV and what I found out is that the Hue, actually specifies that in what color range (like pink, orange,etc.) the color is, the Saturation specifies its tendency to white (the lower the value is, the whiter the color is) , and about the Value, it's just the same as Saturation, but about black color. I hope I've understood it correctly so far, because my actual question is, how can I get these H S V values from pixels? Is there a way I can get the values like I do for RGB? Or is there a way I can turn RGB values to HSV? Could someone help me on this please? Thanks. (I'm working with C++, and I shouldn't use OpenCV, I can only use CImg, and Imagemagick.)<issue_comment>username_1: In Imagemagick command line, you can do:
```
convert -size 1x1 xc:red -colorspace HSV -format "%[pixel:u.p{0,0}]\n" info:
hsv(0,100%,100%)
```
or
```
convert lena.png[3x3+10+10] -colorspace HSV txt:
# ImageMagick pixel enumeration: 3,3,65535,hsv
0,0: (1944,34369,57825) #0886E1 hsv(11,52%,88%)
1,0: (1560,32622,57825) #067FE1 hsv(9,50%,88%)
2,0: (1643,33060,57568) #0681E0 hsv(9,50%,88%)
0,1: (2072,33787,57825) #0883E1 hsv(11,52%,88%)
1,1: (2129,34369,57825) #0886E1 hsv(12,52%,88%)
2,1: (2036,34678,57311) #0887DF hsv(11,53%,87%)
0,2: (1805,33347,58082) #0782E2 hsv(10,51%,89%)
1,2: (2012,33057,58082) #0881E2 hsv(11,50%,89%)
2,2: (1916,33204,57825) #0781E1 hsv(11,51%,88%)
```
Sorry, I do not know C++. I would think all you need to do is use the equivalent of -colorspace HSV and then do what you normal do for RGB.
If that does not work, then you could ask on the Imagemagick Discourse Server Users or Magick++ forum at <https://www.imagemagick.org/discourse-server/>
P.S. Looking at <http://cimg.eu/reference/structcimg__library_1_1CImg.html#a6c0ab36ca2418c9b62590cdfdcbdc793>, I see
```
CImg< T > & RGBtoHSV ()
Convert pixel values from RGB to HSV color spaces.
```
Upvotes: 0 <issue_comment>username_2: >
> how can I get these H S V values from pixels? Is there a way I can get the values like I do for RGB? Or is there a way I can turn RGB values to HSV?
>
>
>
With [magick++](/questions/tagged/magick%2b%2b "show questions tagged 'magick++'") you would convert the colorspace to HSV, and access the color as RGB. Although the methods would still be red (hue), green (saturation), & blue (value).
```cpp
#include
#include
using namespace Magick;
using namespace std;
int main(int argc, const char \* argv[]) {
InitializeMagick(\*argv);
Image
rgb\_img,
hsv\_img;
rgb\_img.read("rose:");
hsv\_img.read("rose:");
Color point;
// Get Color @ index 10x10
point = rgb\_img.pixelColor(10, 10);
cout << "Pixel Type : Default RGB Pixel" << endl;
cout << "First Channel : " << point.quantumRed() / QuantumRange << endl;
cout << "Second Channel : " << point.quantumGreen() / QuantumRange << endl;
cout << "Third Channel : " << point.quantumBlue() / QuantumRange << endl;
cout << endl;
// Convert to HSV
hsv\_img.colorSpace(HSVColorspace);
// Get Color @ index 10x10
point = hsv\_img.pixelColor(10, 10);
cout << "Pixel Type : HSV Pixel" << endl;
cout << "First Channel : " << point.quantumRed() / QuantumRange << endl;
cout << "Second Channel : " << point.quantumGreen() / QuantumRange << endl;
cout << "Third Channel : " << point.quantumBlue() / QuantumRange << endl;
cout << endl;
return 0;
}
```
Which would output...
```
Pixel Type : Default RGB Pixel
First Channel : 0.282353
Second Channel : 0.25098
Third Channel : 0.223529
Pixel Type : HSV Pixel
First Channel : 0.0777778
Second Channel : 0.208333
Third Channel : 0.282353
```
Upvotes: 1
|
2018/03/18
| 480 | 1,949 |
<issue_start>username_0: I am currently working on a react app where I am adding and changing classes based on certain state changes. It worked successfully in testing with a ternary operator but now I realized I will have to add mutiple else-if statements so I am trying to convert it to a classic if else format but am getting syntax errors and I'm not sure how to do it.
Here is the ternary operator that worked fine:-
```
```
Here is my attempt to make it a classic if-else in JSX and failed:-
```
```
Pls help me out :)<issue_comment>username_1: One approach you could adopt is to handle this **outside** of your JSX. So, in your render function still but just above where you return.
```
render() {
let gradientValue;
// Put your if-else here and update gradientValue on each condition.
return (
Your html here
==============
);
}
```
Upvotes: 1 <issue_comment>username_2: `return` only returns values from inside a function, just putting parentheses around an if/else statement like that isn't going to work. You'd be better off sticking with the ternary operator, and nesting them as required.
Upvotes: 0 <issue_comment>username_3: If and else statements, are just that... **statements**. Inline JSX expressions that you wrap with `{…}` only allow *expressions*; statements are not expressions.
Your ternary approach is fine, though since there's some commonality between the two strings you can actually use interpolation:
```
```
Upvotes: 2 <issue_comment>username_4: You can only use expressions inside of a React Component attribute. You'll need to move your logic into a function.
```
function temperatureClassname(temp){
const prefix = 'wrapper-gradient-'
switch (temp) {
case 'hot': return prefix + 'hot'
case 'cold': return prefix + 'cold'
case 'ice-cold': return prefix + 'too-cool'
}
}
```
And your react component would look like this:
```
```
Upvotes: 4 [selected_answer]
|
2018/03/18
| 525 | 2,083 |
<issue_start>username_0: I'm trying to make a sweetalert when the user clicks the delete button it will trigger a sweetalert and when the user clicks `Yes, Delete it!` it should make an axois request to delete the status. When the user clicks on `Yes, Delete it!` the sweetalert closes but the request is never made. If I remove the sweetalert and just leave the request it will delete the record.
Delete button
```
```
Delete method
```
methods: {
destroy(id) {
swal({
title: "Delete this order status?",
text: "Are you sure? You won't be able to revert this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
confirmButtonText: "Yes, Delete it!",
}, () => {
del('status-delete/' + id)
})
}
}
```<issue_comment>username_1: Based from the documentation, you can do this.
```
swal({
title: "Delete this order status?",
text: "Are you sure? You won't be able to revert this!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
confirmButtonText: "Yes, Delete it!"
}).then((result) => { // <--
if (result.value) { // <-- if confirmed
del('status-delete/' + id);
}
});
```
Reference: <https://sweetalert2.github.io/>
Upvotes: 4 [selected_answer]<issue_comment>username_2: Try this:
```
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
buttonsStyling: true
}).then(function (isConfirm) {
if(isConfirm.value === true) {
axios.post('status-delete/'+id, {
data: {
id: id
}
}).then(function (response) {
console.log('success')
})
}
});
```
Upvotes: 2
|
2018/03/18
| 338 | 1,477 |
<issue_start>username_0: NetInfo returns true when connected to wifi but there is no internet. So apart from NetInfo what are the other best options to check internet connectivity in react native?<issue_comment>username_1: unfortunately there is no alternative to pinging some kind of host and wait for the response.
You could do something like this:
```
poll() {
setTimeout(() => {
poll();
return fetch('http://www.google.com')
.then((response) => {
// this is the success callback
// you could check if the app was previously offline
// and set it back to online to get rid of the offline hint
})
.catch((err) => {
// error callback
// use this to handle some sort of notification for the user
// you could update a state within your root container
// or redux to update the app with some visual hints
});
}, 5000);
}
```
Hope this helps
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to ping and see if connection actually has internet connection.
First use netInfo. Using it's **icConnected** method find out if the device is connected to a network. If so use your HTTP client to add an interceptor and try to ping and check internet connectivity before sending the actual request.
Also if you need more advanced stuff try out this library to work with offline data. It'll solve your problem.
<https://github.com/rauliyohmc/react-native-offline>
Upvotes: 2
|
2018/03/18
| 2,147 | 9,266 |
<issue_start>username_0: How does one create an enum multidimensional array in Unity Inspector and make it serializable so I can call it from a different script?
```cs
public enum colors {red, blue, green, yellow, cyan, white, purple};
public int rows = 7;
public int column = 4;
public colors[,] blockColors;
private void Awake() {
blockColors = new colors[rows, column];
}
```
For me to manually type all 28 colors in the script is time consuming, especially, when I have to do this for hundreds of levels. Is there a way to create a table in the Inspector to make workflow faster?
[](https://i.stack.imgur.com/n9x3S.png)
I tried making `blockColors` a `[Serializefield]` but it doesn't work.
I've never tried coding a chart for the inspector before. Can someone please direct me to a tutorial that can help me understand how to code a chart like in the picture?<issue_comment>username_1: You can build a CustomEditor script for your class, and then display your multidimensional array using GUI, just like you code normal OnGUI event.
Here's a simple pseudo code
```
Loop for every Rows
Divide inspector width with columns length;
Loop for every Columns
Render Custom Field with dividen width;
End Loop
Incrase posY for new rows ++;
End Loop
```
Here are some links that will help you get started
<https://docs.unity3d.com/Manual/editor-CustomEditors.html>
<https://unity3d.com/learn/tutorials/topics/interface-essentials/building-custom-inspector>
Upvotes: 1 <issue_comment>username_2: You need to create a custom editor (or more specifically CustomPropertDrawer if you want to re-use it for other components
The only non-obvious part required to create a table like that is forcing the elements to lay out the way you want. One way is manually handling position Rect's given you by Unity, but there is a much simple (albeit a bit less flexible) way, just wrap your elements in horizontal/vertical layout combos.
The intuitive approach would be to wrap your elements in
```
GUILayout.BeginHorizontal();
{
// your elements line 1
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
// your elements line 2 and so on
}
GUILayout.EndHorizontal();
```
but it has a downside - autolayout will only take widts of elements in a current line, but if element size varies this will break vertical alingment. A solution is to wrap each column in a layout first, and than use the horizontal layout to combine vertical strips, it goes like this
```
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical();
{
// your elements column 1
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
{
// your elements column 2
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
```
Brackets are just for clarity, they do nothing.
I hope this helps
Upvotes: 2 [selected_answer]<issue_comment>username_3: Thanks to all the answers provided I have come up with this solution:
[](https://i.stack.imgur.com/gR7jH.png)
>
> **Levels.cs**
>
>
>
```
using UnityEngine;
public enum BlockColors {blank, red, blue, green, yellow, cyan, white, purple};
[System.Serializable] public class level {
#if UNITY_EDITOR
[HideInInspector] public bool showBoard;
#endif
public int rows = 9;
public int column = 9;
public BlockColors [,] board = new BlockColors [columns, rows];
}
public class Levels : MonoBehaviour {
public Level[] allLevels;
}
```
>
> **Editor/LevelEditor.cs**
>
>
>
```
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Levels))]
public class LevelEditor : Editor {
public bool showLevels = true;
public override void OnInspectorGUI() {
Levels levels = (Levels)target;
EditorGUILayout.Space ();
showLevels = EditorGUILayout.Foldout (showLevels, "Levels ("+levels.allLevels.Length+")");
if (showLevels) {
EditorGUI.indentLevel++;
for (ushort i = 0; i < levels.allLevels.Length; i++) {
levels.allLevels[i].showBoard = EditorGUILayout.Foldout(levels.allLevels[i].showBoard, "Board");
if (levels.allLevels [i].showBoard) {
EditorGUI.indentLevel = 0;
GUIStyle tableStyle = new GUIStyle ("box");
tableStyle.padding = new RectOffset (10, 10, 10, 10);
tableStyle.margin.left = 32;
GUIStyle headerColumnStyle = new GUIStyle ();
headerColumnStyle.fixedWidth = 35;
GUIStyle columnStyle = new GUIStyle ();
columnStyle.fixedWidth = 65;
GUIStyle rowStyle = new GUIStyle ();
rowStyle.fixedHeight = 25;
GUIStyle rowHeaderStyle = new GUIStyle ();
rowHeaderStyle.fixedWidth = columnStyle.fixedWidth - 1;
GUIStyle columnHeaderStyle = new GUIStyle ();
columnHeaderStyle.fixedWidth = 30;
columnHeaderStyle.fixedHeight = 25.5f;
GUIStyle columnLabelStyle = new GUIStyle ();
columnLabelStyle.fixedWidth = rowHeaderStyle.fixedWidth - 6;
columnLabelStyle.alignment = TextAnchor.MiddleCenter;
columnLabelStyle.fontStyle = FontStyle.Bold;
GUIStyle cornerLabelStyle = new GUIStyle ();
cornerLabelStyle.fixedWidth = 42;
cornerLabelStyle.alignment = TextAnchor.MiddleRight;
cornerLabelStyle.fontStyle = FontStyle.BoldAndItalic;
cornerLabelStyle.fontSize = 14;
cornerLabelStyle.padding.top = -5;
GUIStyle rowLabelStyle = new GUIStyle ();
rowLabelStyle.fixedWidth = 25;
rowLabelStyle.alignment = TextAnchor.MiddleRight;
rowLabelStyle.fontStyle = FontStyle.Bold;
GUIStyle enumStyle = new GUIStyle ("popup");
rowStyle.fixedWidth = 65;
EditorGUILayout.BeginHorizontal (tableStyle);
for (int x = -1; x < levels.allLevels [i].columns; x++) {
EditorGUILayout.BeginVertical ((x == -1) ? headerColumnStyle : columnStyle);
for (int y = -1; y < levels.allLevels [i].rows; y++) {
if (x == -1 && y == -1) {
EditorGUILayout.BeginVertical (rowHeaderStyle);
EditorGUILayout.LabelField ("[X,Y]", cornerLabelStyle);
EditorGUILayout.EndHorizontal ();
} else if (x == -1) {
EditorGUILayout.BeginVertical (columnHeaderStyle);
EditorGUILayout.LabelField (y.ToString (), rowLabelStyle);
EditorGUILayout.EndHorizontal ();
} else if (y == -1) {
EditorGUILayout.BeginVertical (rowHeaderStyle);
EditorGUILayout.LabelField (x.ToString (), columnLabelStyle);
EditorGUILayout.EndHorizontal ();
}
if (x >= 0 && y >= 0) {
EditorGUILayout.BeginHorizontal (rowStyle);
levels.allLevels [i].board [x, y] = (BlockColors)EditorGUILayout.EnumPopup (levels.allLevels [i].board [x, y], enumStyle);
EditorGUILayout.EndHorizontal ();
}
}
EditorGUILayout.EndVertical ();
}
EditorGUILayout.EndHorizontal ();
}
}
}
}
}
```
My main problem now is it won't serialize. Any change I made to the level will automatically reset on Play. How can I serialize the custom array setup from the Inspector?
Upvotes: 2 <issue_comment>username_4: Thanks to all the excellent answers above.
For anyone having trouble persisting their custom arrays, one issue is that multidimensional arrays are not serializable. Possible workarounds include implementing your 2D array as a jagged array (an array whose elements are arrays) or creating a wrapper class that is serializable itself.
As username_1 suggested, you'll also want to prompt Unity to save changes to your object using `EditorUtility.SetDirty()`. Adding the following to the end of `OnInspectorGUI()` should do the trick:
```
if (GUI.changed) {
Undo.RecordObject(levels, "Edit levels");
EditorUtility.SetDirty(levels);
}
```
Upvotes: 0 <issue_comment>username_5: For anyone stumbling over this:
This has also been discussed here: <https://answers.unity.com/questions/1485842/serialize-custom-multidimensional-array-from-inspe.html>
The tl;dr is that two dimensional arrays just don't work and you're better off either flattening the array and just display it two dimensional or nest both dimensions in separate classes.
Upvotes: 0
|
2018/03/18
| 2,133 | 9,227 |
<issue_start>username_0: I am trying to read the file, then create a temporary file then copy and replace the temporary file to the original file at the end.
Is it possible to do the following?
>
>
> ```
> // read the original file then save it to temporary file
> fs.readFile(originalPath, function (err, data) {
> var json = JSON.parse(data);
> json.items.push("sample item");
> fs.writeFileSync(tmpPath, JSON.stringify(json))
> })
>
> // copy the temporary file to the original file path
> fs.readFile(tmpPath, (err, contents) => {
> var json = JSON.parse(contents);
> fs.writeFileSync(originalPath, JSON.stringify(json));
> });
>
> ```
>
>
I am doing this to prevent the changes made to original file until the process has been completed.
It doesn't seem to work due the the file is not physically saved when reading it.
Thanks.<issue_comment>username_1: You can build a CustomEditor script for your class, and then display your multidimensional array using GUI, just like you code normal OnGUI event.
Here's a simple pseudo code
```
Loop for every Rows
Divide inspector width with columns length;
Loop for every Columns
Render Custom Field with dividen width;
End Loop
Incrase posY for new rows ++;
End Loop
```
Here are some links that will help you get started
<https://docs.unity3d.com/Manual/editor-CustomEditors.html>
<https://unity3d.com/learn/tutorials/topics/interface-essentials/building-custom-inspector>
Upvotes: 1 <issue_comment>username_2: You need to create a custom editor (or more specifically CustomPropertDrawer if you want to re-use it for other components
The only non-obvious part required to create a table like that is forcing the elements to lay out the way you want. One way is manually handling position Rect's given you by Unity, but there is a much simple (albeit a bit less flexible) way, just wrap your elements in horizontal/vertical layout combos.
The intuitive approach would be to wrap your elements in
```
GUILayout.BeginHorizontal();
{
// your elements line 1
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
// your elements line 2 and so on
}
GUILayout.EndHorizontal();
```
but it has a downside - autolayout will only take widts of elements in a current line, but if element size varies this will break vertical alingment. A solution is to wrap each column in a layout first, and than use the horizontal layout to combine vertical strips, it goes like this
```
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical();
{
// your elements column 1
}
GUILayout.EndVertical();
GUILayout.BeginVertical();
{
// your elements column 2
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
```
Brackets are just for clarity, they do nothing.
I hope this helps
Upvotes: 2 [selected_answer]<issue_comment>username_3: Thanks to all the answers provided I have come up with this solution:
[](https://i.stack.imgur.com/gR7jH.png)
>
> **Levels.cs**
>
>
>
```
using UnityEngine;
public enum BlockColors {blank, red, blue, green, yellow, cyan, white, purple};
[System.Serializable] public class level {
#if UNITY_EDITOR
[HideInInspector] public bool showBoard;
#endif
public int rows = 9;
public int column = 9;
public BlockColors [,] board = new BlockColors [columns, rows];
}
public class Levels : MonoBehaviour {
public Level[] allLevels;
}
```
>
> **Editor/LevelEditor.cs**
>
>
>
```
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Levels))]
public class LevelEditor : Editor {
public bool showLevels = true;
public override void OnInspectorGUI() {
Levels levels = (Levels)target;
EditorGUILayout.Space ();
showLevels = EditorGUILayout.Foldout (showLevels, "Levels ("+levels.allLevels.Length+")");
if (showLevels) {
EditorGUI.indentLevel++;
for (ushort i = 0; i < levels.allLevels.Length; i++) {
levels.allLevels[i].showBoard = EditorGUILayout.Foldout(levels.allLevels[i].showBoard, "Board");
if (levels.allLevels [i].showBoard) {
EditorGUI.indentLevel = 0;
GUIStyle tableStyle = new GUIStyle ("box");
tableStyle.padding = new RectOffset (10, 10, 10, 10);
tableStyle.margin.left = 32;
GUIStyle headerColumnStyle = new GUIStyle ();
headerColumnStyle.fixedWidth = 35;
GUIStyle columnStyle = new GUIStyle ();
columnStyle.fixedWidth = 65;
GUIStyle rowStyle = new GUIStyle ();
rowStyle.fixedHeight = 25;
GUIStyle rowHeaderStyle = new GUIStyle ();
rowHeaderStyle.fixedWidth = columnStyle.fixedWidth - 1;
GUIStyle columnHeaderStyle = new GUIStyle ();
columnHeaderStyle.fixedWidth = 30;
columnHeaderStyle.fixedHeight = 25.5f;
GUIStyle columnLabelStyle = new GUIStyle ();
columnLabelStyle.fixedWidth = rowHeaderStyle.fixedWidth - 6;
columnLabelStyle.alignment = TextAnchor.MiddleCenter;
columnLabelStyle.fontStyle = FontStyle.Bold;
GUIStyle cornerLabelStyle = new GUIStyle ();
cornerLabelStyle.fixedWidth = 42;
cornerLabelStyle.alignment = TextAnchor.MiddleRight;
cornerLabelStyle.fontStyle = FontStyle.BoldAndItalic;
cornerLabelStyle.fontSize = 14;
cornerLabelStyle.padding.top = -5;
GUIStyle rowLabelStyle = new GUIStyle ();
rowLabelStyle.fixedWidth = 25;
rowLabelStyle.alignment = TextAnchor.MiddleRight;
rowLabelStyle.fontStyle = FontStyle.Bold;
GUIStyle enumStyle = new GUIStyle ("popup");
rowStyle.fixedWidth = 65;
EditorGUILayout.BeginHorizontal (tableStyle);
for (int x = -1; x < levels.allLevels [i].columns; x++) {
EditorGUILayout.BeginVertical ((x == -1) ? headerColumnStyle : columnStyle);
for (int y = -1; y < levels.allLevels [i].rows; y++) {
if (x == -1 && y == -1) {
EditorGUILayout.BeginVertical (rowHeaderStyle);
EditorGUILayout.LabelField ("[X,Y]", cornerLabelStyle);
EditorGUILayout.EndHorizontal ();
} else if (x == -1) {
EditorGUILayout.BeginVertical (columnHeaderStyle);
EditorGUILayout.LabelField (y.ToString (), rowLabelStyle);
EditorGUILayout.EndHorizontal ();
} else if (y == -1) {
EditorGUILayout.BeginVertical (rowHeaderStyle);
EditorGUILayout.LabelField (x.ToString (), columnLabelStyle);
EditorGUILayout.EndHorizontal ();
}
if (x >= 0 && y >= 0) {
EditorGUILayout.BeginHorizontal (rowStyle);
levels.allLevels [i].board [x, y] = (BlockColors)EditorGUILayout.EnumPopup (levels.allLevels [i].board [x, y], enumStyle);
EditorGUILayout.EndHorizontal ();
}
}
EditorGUILayout.EndVertical ();
}
EditorGUILayout.EndHorizontal ();
}
}
}
}
}
```
My main problem now is it won't serialize. Any change I made to the level will automatically reset on Play. How can I serialize the custom array setup from the Inspector?
Upvotes: 2 <issue_comment>username_4: Thanks to all the excellent answers above.
For anyone having trouble persisting their custom arrays, one issue is that multidimensional arrays are not serializable. Possible workarounds include implementing your 2D array as a jagged array (an array whose elements are arrays) or creating a wrapper class that is serializable itself.
As username_1 suggested, you'll also want to prompt Unity to save changes to your object using `EditorUtility.SetDirty()`. Adding the following to the end of `OnInspectorGUI()` should do the trick:
```
if (GUI.changed) {
Undo.RecordObject(levels, "Edit levels");
EditorUtility.SetDirty(levels);
}
```
Upvotes: 0 <issue_comment>username_5: For anyone stumbling over this:
This has also been discussed here: <https://answers.unity.com/questions/1485842/serialize-custom-multidimensional-array-from-inspe.html>
The tl;dr is that two dimensional arrays just don't work and you're better off either flattening the array and just display it two dimensional or nest both dimensions in separate classes.
Upvotes: 0
|
2018/03/18
| 2,816 | 7,607 |
<issue_start>username_0: I am trying to read a json file `wifi_build_audit.json` from my webpage ,match the version (lets say `9.130.28.12.32.1.31`) and click on `submit` button in "Actions" column,I was able to get the point where I can open and login using password but need some help one how to read the json file and click on submit button?
```
from selenium import webdriver
import selenium
driver = webdriver.Chrome("/Users/username/Downloads/chromedriver")
driver.get("http://wifi-firmware-web.company.com:8080/wifi_build_audit")
username = driver.find_element_by_id('username')
password = driver.find_element_by_id('password')
username.send_keys("username")
password.send_keys("<PASSWORD>)
driver.find_element_by_id("login-submit").click()
#Read json from wifi_build_audit.json
#Match the version `9.130.28.12.32.1.31` and click on "submit" in Actions column
```
Screenshot of my webpage
[](https://i.stack.imgur.com/tLlJd.png)
```
UPDATE:
Following are the steps am trying to automate
1.How to read json from wifi_build_audit.json file?
2.Match the version `9.130.28.12.32.1.31` in the JSON and click on "submit" in Actions column on the web page
wifi_build_audit.json
[{
"_id": "5aac5fb75071011018001015cff1010c",
"status": "Completed",
"endRev": "c7a9aa810159699638d906f5de10195e990699973f1019",
"chip": "9369",
"startRev": "d009c101d7fb1016a66e89cd1019b010110110165ad3730e66f6",
"audit": "Build Audit 9369/goatHW_9369 [9.10130.1018.101101.3101.101.36] \n",
"sanity": "none",
"version": "9.10130.1018.101101.3101.101.36",
"branch": "goatHW_9369",
"directory": "/SWE/Teams/tech/Furm/submissions/9369/9.10130.1018.101101.3101.101.36",
"requestTime": "10101018-03-1017T00:101101:1015.907Z",
"__v": 0,
"tag": "Official_9.10130.1018.101101.3101.101.36",
"swe": "baseline2101A10130",
"projects": [
{
"name": "BCMFurm_9369_B101_ekans",
"_id": "5aac5fb75071011018001015cff1011015",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_sid",
"_id": "5aac5fb75071011018001015cff1011019",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_maui",
"_id": "5aac5fb75071011018001015cff1011013",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_kauai",
"_id": "5aac5fb75071011018001015cff101101101",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_midway",
"_id": "5aac5fb75071011018001015cff101101101",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_nihau",
"_id": "5aac5fb75071011018001015cff1011010",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_lanai",
"_id": "5aac5fb75071011018001015cff1010f",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_B101_hanauma",
"_id": "5aac5fb75071011018001015cff1010e",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9369_Notes",
"_id": "5aac5fb75071011018001015cff1010d",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
}
],
"approvalNotes": [],
"stepping": []
},
{
"_id": "5aac638a60eb8c001015ff38cb",
"status": "Queued",
"endRev": "99d101c101d79ddbd10110169bc101cfb53f6339e1011019101d799f",
"chip": "9355",
"startRev": "6fad101101e9101d9ab81016ee67509101101101e9e9101e101931017f79",
"audit": "Build Audit 9355/goatHW_9355 [9.10130.1018.101101.3101.101.3101] \n",
"sanity": "none",
"version": "9.130.28.12.32.1.31",
"branch": "goatHW_9355",
"directory": "/SWE/Teams/tech/Furm/submissions/9355/9.10130.1018.101101.3101.101.3101",
"requestTime": "10101018-03-1017T00:38:39.1011019Z",
"__v": 0,
"tag": "Official_9.10130.1018.101101.3101.101.3101",
"swe": "baseline101A10199",
"projects": [
{
"name": "BCMFurm_9355_C101_hawaii",
"_id": "5aac638a60eb8c001015ff38cd",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
},
{
"name": "BCMFurm_9355_Notes",
"_id": "5aac638a60eb8c001015ff38cc",
"submission": {
"status": "passed",
"system": "machine.company.com"
}
}
],
"approvalNotes": [],
"stepping": []
}]
```<issue_comment>username_1: You can try open the url of `wifi_build_audit.json` in an new Tab, then read the content from browser, or using http client library to send a http request in your script and get the content from response.
```
driver.find_element_by_id("login-submit").click()
# open the json file in new tab
json_url = 'http://xxxxxx/wifi_build_audit.json'
driver.execute_script('window.open("'+json_url+'")')
# switch to the new tab
driver.switch_to_window(driver.window_handles[-1])
# read the json content
json_content = driver.find_element_by_css_selector('body > pre').text
# switch to the last window
driver.switch_to_default_content()
```
Upvotes: 1 <issue_comment>username_2: Since you don't need to scrape the data from the webpage, as its available in the json file - selenium may not the right solution.
You just need to find the *link* for the submit button. You can do that by visiting the page in a browser, and right clicking on the link to view its source.
You need to find out what are the parameters passed to the server when that Submit is clicked.
Now your steps are:
1. Download the json file and read it.
2. Search for the desired version number
3. If found, send a request to the website (ie, click the Submit button)
Using [`requests`](http://docs.python-requests.org); here is one way to do the above.
```
import requests
username = 'user'
password = '<PASSWORD>'
target_wifi_version = '1.2.3'
login_url = 'http://example.com/login'
json_url = 'http://example.com/sample.json'
submit_target = 'http://example.com/submit_results'
submit_form_params = {'wifi_id': ''}
with requests.Session() as s:
s.post(login_url, data={'username': username, 'password': <PASSWORD>})
results = s.get(json_url).json()
found = next((i for i in results if i['version'] == target_wifi_version), None)
if found:
submit_form_params['wifi_id'] = target_wifi_version
s.post(submit_url, data=submit_form_params)
```
Upvotes: 0
|
2018/03/18
| 1,269 | 3,470 |
<issue_start>username_0: I have this data:
```
list_of_dicts_of_lists = [
{'a': [1,2], 'b': [3,4], 'c': [3,2], 'd': [2,5]}
{'a': [2,2], 'b': [2,2], 'c': [1,6], 'd': [4,7]}
{'a': [2,2], 'b': [5,2], 'c': [3,2], 'd': [2,2]}
{'a': [1,2], 'b': [3,4], 'c': [1,6], 'd': [5,5]}
]
```
I need this result:
```
median_dict_of_lists = (
{'a': [1.5,2], 'b': [3,3], 'c': [2,4], 'd': [3,5]}
)
```
...where each value is the median of the respective column above.
I need the mode dictionary where available and median dictionary when no mode exists. I was able to do quick and dirty `statistics.mode()` by stringing each dict, getting mode of list of strings, then `ast.literal_eval(most_common_string)` back to a dict, but I need a column wise median in cases where there is no mode.
I know how to use `statistics.median()`; however, the nested notation to apply it to this case, column wise, is frazzling me.
The data is all floats; I wrote it as int just to make easier to read.<issue_comment>username_1: You can use `statistics.median` with `itertools.groupby`:
```
import statistics
import itertools
list_of_dicts_of_lists = [
{'a': [1,2], 'b': [3,4], 'c': [3,2], 'd': [2,5]},
{'a': [2,2], 'b': [2,2], 'c': [1,6], 'd': [4,7]},
{'a': [2,2], 'b': [5,2], 'c': [3,2], 'd': [2,2]},
{'a': [1,2], 'b': [3,4], 'c': [1,6], 'd': [5,5]}
]
new_listing = [(a, list(b)) for a, b in itertools.groupby(sorted(itertools.chain(*map(lambda x:x.items(), list_of_dicts_of_lists)), key=lambda x:x[0]), key=lambda x:x[0])]
d = {a:zip(*map(lambda x:x[-1], b)) for a, b in new_listing}
last_data = ({a:[statistics.median(b), statistics.median(c)] for a, [b, c] in d.items()},)
```
Output:
```
({'a': [1.5, 2.0], 'b': [3.0, 3.0], 'c': [2.0, 4.0], 'd': [3.0, 5.0]},)
```
Upvotes: 2 <issue_comment>username_2: You can use the following dictionary comprehension with `numpy`:
```
import numpy as np
median_dict_of_lists = {i : list(np.median([x[i] for x in list_of_dicts_of_lists], axis=0))
for i in 'abcd'}
```
Which returns the same:
```
{'a': [1.5, 2.0], 'c': [2.0, 4.0], 'b': [3.0, 3.0], 'd': [3.0, 5.0]}
```
To explain, `np.median([x[i] for x in list_of_dicts_of_lists], axis=0)`, embedded in the dictionary comprehension, is going through each key `i` in `['a', 'b', 'c', 'd']`, and getting the median of each key for all of your dicts in your original list of dicts. This median is getting assigned to a new dictionary with the appropriate key via the dictionary comprehension syntax.
There is a good explanation of the dictionary comprehension syntax [here](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it), and the [documentation for np.median](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.median.html) explains the function itself quite well
Upvotes: 3 [selected_answer]<issue_comment>username_3: You could also break it down in small steps with meaningful names to make the solution more maintainable. For example:
```
# combine dictionary arrays into a 3d matrix, removing dictionary keys
valueMatrix3D = [ list(row.values()) for row in list_of_dicts_of_lists ]
# compute the median for each row's array (axis 1)
medianArrays = np.median(valueMatrix3D,axis=1)
# reassemble into a dictionary with original keys
medianDict = { key:list(array) for key,array in zip(list_of_dicts_of_lists[0] ,medianArrays) }
```
Upvotes: 2
|
2018/03/18
| 387 | 1,598 |
<issue_start>username_0: We are implementing a web app where we want users to log in to our website and enter API keys that allows them to authenticate to website #2. We want to save the API keys to a database so that users only have to enter them once. What are the standard best practices for securely saving the API keys to the database such that we, the developers, can’t access them? Salt and hash? How do we make users feel at ease with providing our app with the API keys?<issue_comment>username_1: Salt and hash (or more precisely just hashing) is a one-way street, you can't get back the contents you put into the hashing function from the hash you've received.
Frankly for protection against devs you should probably set up a legal contract between the two parties (you and customer) and SO can't help with that.
The keyword you're looking for is *encryption*. For example public/private key encryption through GnuPG or OpenSSL where you hand over the private key to the user (through a SSL connection of course) or encrypt the bytes with GnuPG with a passphrase that is the user's password.
There are a lot of options but you should probably re-submit this question with better phrasing using the knowledge you gain after googling all of the phrases I just used.
Upvotes: 1 <issue_comment>username_2: Maybe you can go with the salt & hash but there is another option too which is to implement a [Diffie–Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) or [SRP protocol](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol)
Upvotes: 0
|
2018/03/18
| 650 | 2,431 |
<issue_start>username_0: I am storing a Rich Text html string in our database, examples as follows (I have shortened the bit info):
```
data:image/png;base64,iVBORw0...ORK5CYII
data:image/jpeg;base64,/9j/4AAQS...TcUQrQf/Z
```
I need to basically take this HTML and create a `System.Drawing.Image` in C# and then save the image to a location within the Images folder. With the first png example above this all seemed to work fine with the following code:
```
string imageBase64String = "iVBORw0...ORK5CYII";
byte[] bytes = Convert.FromBase64String(imageBase64String);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
string fileNameFull = Guid.NewGuid().ToString() + "." + imageFormat;
string relativePath = @"~\Images\pdfExports\" + fileNameFull;
string fileLocation = HttpContext.Current.Server.MapPath(relativePath);
image.Save(fileLocation);
```
However when I try other formats including jpg/jpeg it seems like the image is not being created correctly and cannot be read/opened.
Is there a better, more generic way of getting C# `System.Drawing.Image` from this Html String? Or am I just missing something simple with how the base64 string is passed?
**EDIT**
I was late up posting this and missed out some vital info on the code example where I am stripping out the meta data. I have updated now. By the time the string **imageBase64String** is populated I have already stripped out the meta.<issue_comment>username_1: You are corrupting the image's data, `data:image/png;base64,` is metainformation, not real image content, you must remove that information before converting the data to binary:
```
string imageBase64String = "data:image/png;base64,iVBORw0...ORK5CYII";
int index = imageBase64String.IndexOf(",");
imageBase64String = imageBase64String .Substring(index + 1);
byte[] bytes = Convert.FromBase64String(imageBase64String);
```
Upvotes: 1 <issue_comment>username_2: I have managed to get this working fine with a simple change. Instead of trying to create a **System.Drawing.Image** object from the byte-array and saving that, i have found using:
```
File.WriteAllBytes(fileLocation, bytes);
```
does the job simply passing the original bytes and a file location. Now I seem to be able to save and open any image format I need.
Upvotes: 1 [selected_answer]
|
2018/03/18
| 1,252 | 3,938 |
<issue_start>username_0: Is it possible encode *IPV4* into 6 or less *ASCII* Printable Characters to create an ultra portable ID that users can tell to each other, which really represents an IP.<issue_comment>username_1: You could try this `base95` implementation it will get it down to 5 printable characters
```
public static class Base95Extension
{
private const string PrintableChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !?\"'`^#$%@&*+=/.,:;|\\_<>[]{}()~-";
private const int Length = 95;
public static uint ToUInt32(this IPAddress ip)
{
return BitConverter.ToUInt32(ip.GetAddressBytes(), 0);
}
public static IPAddress ToIpAddress(this uint source)
{
return new IPAddress(BitConverter.GetBytes(source));
}
public static string ToBase95(this IPAddress ip)
{
var num = ip.ToUInt32();
var result = string.Empty;
uint index = 0;
while (num >= Math.Pow(Length, index))
{
index++;
}
while (index-- > 0)
{
var pow = (uint)Math.Pow(Length, index);
var div = num / pow;
result += PrintableChars[(int)div];
num -= pow * div;
}
return result;
}
public static IPAddress ToIpAddress(this string s)
{
uint result = 0;
var chars = s.Reverse()
.ToArray();
for (var i = 0; i < chars.Length; i++)
{
var pow = Math.Pow(Length, i);
var ind = PrintableChars.IndexOf(chars[i]);
result += (uint)(pow * ind);
}
return new IPAddress(BitConverter.GetBytes(result));
}
}
```
**Usage**
```
var ip = "255.255.255.255";
var ipAddress = IPAddress.Parse(ip);
var result = ipAddress.ToBase95();
Console.WriteLine(ip);
Console.WriteLine(result);
Console.WriteLine(result.ToIpAddress());
```
**Output**
```
255.255.255.255
Q#F 5
255.255.255.255
```
[**Demo Here**][1]
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can either try:
uint iaddress = BitConverter.ToUInt32(IPAddress.Parse(address).GetAddressBytes(), 0);
or use the structure [here](https://github.com/rubberduck203/Katas/blob/497e37b9a7d4854f44f08e734a7b71c7d2ef3eb6/Rubberduck.Katas.Network/Rubberduck.Katas.Network/Ip4Address.cs)
or use the formula:
a.b.c.d => a\*2^24 + b\*2^16 + c\*2^8 + d (which I think is faster)
[see a similar question with reasonable answers](https://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c)
Upvotes: 0 <issue_comment>username_3: So I have figured something out. it accomplishes the same thing as <NAME>all's answer, in essence. His is probably more efficient, and uses less dependencies. this is just what I came up with. the main upside I see with mine is less special chars are included in the encoded string, so its easy for people to verbally communicate.
```
public static string Base64EncodeIP(string ip)
{
UInt32 ipasint = BitConverter.ToUInt32(IPAddress.Parse(ip).GetAddressBytes(), 0);
byte[] ipasbytes = BitConverter.GetBytes(ipasint);
string encodedip = Convert.ToBase64String(ipasbytes);
return encodedip.Replace("=", "");
}
public static string Base64DecodeIP(string encodedIP)
{
//re-add however much padding is needed, to make the length a multiple of 4
if (encodedIP.Length % 4 != 0)
encodedIP += new string('=', 4 - encodedIP.Length % 4);
byte[] ipasbytes = Convert.FromBase64String(encodedIP);
UInt32 ipasint = BitConverter.ToUInt32(ipasbytes, 0);
return new IPAddress(BitConverter.GetBytes(ipasint)).ToString();
}
```
EDIT
----
Links for some code I used:
[How to convert an IPv4 address into a integer in C#?](https://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c#)
[Remove trailing "=" when base64 encoding](https://stackoverflow.com/questions/4492426/remove-trailing-when-base64-encoding)
Upvotes: 0
|
2018/03/18
| 795 | 2,859 |
<issue_start>username_0: I want to get the date, when I click on the ***grid inside an event***.
I have tried the callback functions.
* dayClick: Not clickable inside events.
* eventClick: No date arguments
Extra information
I have created an AJAX crud for *Event* and an *EventException* which goes inside the event.
Let's say we have a event 20th-30th December 20XX.
I want to use the exception 25th December 20XX for Christmas Day.<issue_comment>username_1: I hope the documentation of FullCalendar JS will help you with it..
refer to the article here: <https://fullcalendar.io/docs/dayClick>
Upvotes: -1 <issue_comment>username_2: Since each Fullcalendar day is stacked behind the event occurring in that date, you cannot get the clicked date. You have three possible workaround:
1. when you click the event you can show a modal with datepicker and select the "exception date/range"... then you set the break of your event in the backend.
2. To set the "exception date/range" you can directly click on the date (not the event) and set it as "invalid" or whatever.
3. Create a context menu with item "Add exception here" which would fire only when clicking on date (not event)
Anyway, if you have a 10 days event, and set an exception in the middle.. The end date should be moved forward by one day..
Youc an eventually set some days as "holiday", check [this](https://stackoverflow.com/questions/26361913/add-italian-holidays-into-fullcalendar?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)
Upvotes: 0 <issue_comment>username_3: In html, note that we are going to add another method handler call eventClickEx to the current fullcalender.
```
eventClickEx: function(jsEvent,ev,view,cellDate){
alert(cellDate);
}
```
In fullcalendar.js. Also in fullcalendar. In here we are calling getCellDate which is not available in view right now.
```
EventPointing.prototype.handleClick = function (seg, ev) {
var hit = this.view.queryHit(getEvX(ev),getEvY(ev));
var cellDate = this.view.getCellDateEx(hit.row,hit.col);
var res = this.component.publiclyTrigger('eventClickEx', {
context: seg.el[0],
args: [seg.footprint.getEventLegacy(), ev, this.view,cellDate]
});
if (res === false) {
ev.preventDefault();
}
};
```
Since it's not available, we will be using the BasicView class which has access to the dayGrid object.
```
BasicView.prototype.getCellDateEx = function (row,col){
return this.dayGrid.getCellDate(row,col);
};
```
There you go, when you click the event, you will get the underlying date from cellDate .
Upvotes: 1 <issue_comment>username_4: Try with:
```
$('#calendar').fullCalendar({
dayClick: function(date, jsEvent, view) {
alert('Clicked on: ' + date.format());
}
});
```
Upvotes: -1
|
2018/03/18
| 1,238 | 5,384 |
<issue_start>username_0: I am attempting to use Autofac with a .NET Core console application using the `Microsoft.Extensions.DependencyInjection` and `Autofac.Extensions.DependencyInjection` packages but the load methods inside my modules never get invoked and leads to `Program` being null during resolution. I would have expected them to load either when I called the `AddAutofac()` extension method or when the service provider was built.
```
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
public class Startup
{
private static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddAutofac(builder =>
{
builder.RegisterModule(new MyFirstModule(configuration));
builder.RegisterModule(new MySecondModule(configuration));
});
using (var serviceProvider = services.BuildServiceProvider())
{
var program = serviceProvider.GetService();
program.Start();
}
}
}
```<issue_comment>username_1: According to [this issue](https://github.com/autofac/Autofac.Extensions.DependencyInjection/issues/12), when the `AddAutofac` method was added to the documentation, it was also split between [ASP.NET Core](http://autofac.readthedocs.io/en/latest/integration/aspnetcore.html) and [.NET Core](http://autofac.readthedocs.io/en/latest/integration/netcore.html). Apparently, `AddAutofac` is specific to ASP.NET Core applications (hence the different documents).
For [console applications](http://autofac.readthedocs.io/en/latest/integration/netcore.html), the registration should look like:
```
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
public class Startup
{
private static void Main(string[] args)
{
var services = new ServiceCollection();
var builder = new ContainerBuilder();
// Once you've registered everything in the ServiceCollection, call
// Populate to bring those registrations into Autofac. This is
// just like a foreach over the list of things in the collection
// to add them to Autofac.
containerBuilder.Populate(services);
// Make your Autofac registrations. Order is important!
// If you make them BEFORE you call Populate, then the
// registrations in the ServiceCollection will override Autofac
// registrations; if you make them AFTER Populate, the Autofac
// registrations will override. You can make registrations
// before or after Populate, however you choose.
builder.RegisterModule(new MyFirstModule(configuration));
builder.RegisterModule(new MySecondModule(configuration));
// Creating a new AutofacServiceProvider makes the container
// available to your app using the Microsoft IServiceProvider
// interface so you can use those abstractions rather than
// binding directly to Autofac.
var container = containerBuilder.Build();
var serviceProvider = new AutofacServiceProvider(container);
var program = serviceProvider.GetService();
program.Start();
}
}
```
Upvotes: 2 <issue_comment>username_2: Your entry point should be `Program.cs` in a dotnet core application. Also I am not sure why do you have a private Main method. But regardless, please follow these steps
Autofac documentation says that:
>
> You don’t have to use Microsoft.Extensions.DependencyInjection. If you
> aren’t writing a .NET Core app that requires it or if you’re not using
> any of the DI extensions provided by other libraries you can consume
> Autofac directly.
>
>
>
You can actually use Autofac without extensions. See a very basic example of a dotnet core console application. Make sure you install a nuGet package Autofac (current version 4.8.1)
We can have an interface:
```
public interface IPrintService
{
void Print();
}
```
And an implementation of this interface.
```
public class PrintService
: IPrintService
{
public void Print()
{
Console.WriteLine("I am a print service injected");
}
}
```
then we can have, for example, a class where we inject a `IPrintService` through its constructor
```
public class Client
{
public Client(IPrintService printService)
{
printService.Print();
}
}
```
And finally, in the main console program we can configure Autofac and register the services. Notice that I have decided to autoActivate a `Client` instance just to illustrate an example and prove that Autofac is injecting the desired implementation.
```
class Program
{
static void Main(string[] args)
{
ConfigureIoCc();
Console.WriteLine("Using Autofac");
Console.ReadKey();
}
public static IContainer ConfigureIoCc()
{
var builder = new ContainerBuilder();
builder
.RegisterType()
.As();
builder
.RegisterType()
.AsSelf()
.AutoActivate(); //to automatically instantiate it
var container = builder.Build();
return container;
}
}
```
Upvotes: 0
|
2018/03/18
| 384 | 1,469 |
<issue_start>username_0: On `Android Studio 3.0` I have a `layout.xml` resource for a layout. Its dimensions, text/hint and other attributes aren't hard coded (like having `android:width="2dp"`, but instead all referencing `dim.xml` and `strings.xml` - as it is advised on google.developers (like `android:width="@dim/width"`.
However, every time I either reopen Android Studio or the respective `layout.xml` tab my `@dim/dimensions` or `@strings/strings` references disappear and give room to the originals `2dp` or `text` respectively. Then I have to hover and click each of those items to the reference suggestion. If the tab is closed and reopened I need to do everything again...
Is this a bug from the IDE, and is there any way to solve this?<issue_comment>username_1: That's a feature of Android Studio, but you can turn it off. It's not actually *replacing* your resource references with hardcoded values; it's showing you what the resources actually map to.
To turn it off, uncheck this option (Editor > General > Code Folding > Android String References):
[](https://i.stack.imgur.com/P6XZP.png)
Upvotes: 3 [selected_answer]<issue_comment>username_2: Android Studio shows the values of these references and the color is gray by default but these actually are references, you don't need to worry about that.^\_^
just like this:
[reference](https://i.stack.imgur.com/j6cTI.png)
Upvotes: 0
|
2018/03/18
| 684 | 2,608 |
<issue_start>username_0: I'm working on a Web API 2 app and I'm implementing request validation. I've included a validation check which looks like this:
```
if (string.IsNullOrEmpty(userCredentials.UserName))
return BadRequest("UserCredentials.UserName is required");
```
A 400 response code is returned as expected but the provided message does not appear to be included in the response returned to the client. Am I missing something in the implementation or is there a special way in which I need to process the response received by the client?
**UPDATE**
The BadRequest message is returned to Postman but when I call it using the C# via a console app I'm not able to find the validation message. Here's the code I'm using in the console app:
```
static async Task Authenticate(string domain, string userName, string password)
{
using (var client = GetHttpClient())
{
var encoding = Encoding.GetEncoding("iso-8859-1");
var userName64 = Convert.ToBase64String(encoding.GetBytes(userName));
var password64 = Convert.ToBase64String(encoding.GetBytes(password));
var credentials = new { DomainName = domain, UserName = userName64 /\*, Password = <PASSWORD>\*/ };
var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
var user = await response.Content.ReadAsAsync();
return user;
//return response.Content.ReadAsAsync();
}
}
```<issue_comment>username_1: You are not checking for the bad response. You seem to assume all responses will be 200 as you do not check and just try to parse the response content to your return type.
```
//...
var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
if(response.IsSuccessStatusCode) { // If 200 OK
//parse response body to desired
var user = await response.Content.ReadAsAsync();
return user;
} else {
//Not 200. You could also consider checking for if status code is 400
var message = await response.Content.ReadAsStringAsync();
//Do something with message like
//throw new Exception(message);
}
//...
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
using(var response = await client.PostAsJsonAsync("api/v1/auth", credentials)){
if(response.IsSuccessStatusCode) {
//This Code is Executed in Case of Success
var user = await response.Content.ReadAsAsync();
return user;
}
else {
//This Code is Executed in Case of In Case of Other Than Success
var message = await response.Content.ReadAsStringAsync();
}
}
```
>
> You Can use this refactored code, If you want to catch the error message in case of bad request or NotFound etc.
>
>
>
Upvotes: 0
|
2018/03/19
| 320 | 1,106 |
<issue_start>username_0: I have an outbound application that sends SMS to customers.
In each SMS is a link to a web-page that they click on.
Each link is unique to each customer so that I can identify who they are.
I know there are short link tools around but I need to have a unique link for each customer.
Does Twilio have a nice solution for this? Or do I need to insert a long URL in each SMS.<issue_comment>username_1: Twilio developer evangelist here.
Twilio doesn't have an in built URL shortener for plain SMS (though this is an option [when sending MMS messages](https://support.twilio.com/hc/en-us/articles/223181228-Why-do-my-messages-include-a-Twilio-URL-)).
I recommend using a URL shortening API, like the [Bitly API](https://dev.bitly.com/). You can make a request to shorten your URL, then use the result when [sending the SMS with the Twilio API](https://www.twilio.com/docs/api/rest/sending-messages).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Twilio has had this feature since 2022:
<https://www.twilio.com/docs/messaging/how-to-configure-link-shortening>
Upvotes: 0
|
2018/03/19
| 514 | 1,638 |
<issue_start>username_0: I have a sentence: `db.COLLECTION_NAME.insert(document)`
1. I need to extract whatever's between `db.` and `.insert`, which in the example is `COLLECTION_NAME`.
2. And Anything between the `()` which in the example is `document`.
I tried:
```
document="${cmd#db*insert(}"
```
for `document`, but it gets `document)` and will crash if document has special characters
Any suggestions?<issue_comment>username_1: ```
$ echo "db.COLLECTION_NAME.insert(document)" | awk -F'[.()]' '{print $2,$4}'
```
will give
```
COLLECTION_NAME document
```
You can assign these to variables with `read`
```
read a b < <(echo "db.COLLECTION_NAME.insert(document)" | awk -F'[.()]' '{print $2,$4}');
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I guess you can do it using brace expansion in two steps:
```
str='db.COLLECTION_NAME.insert(document)'
temp=${str/db./}
str=${temp/.insert*/}
echo $str
COLLECTION_NAME
```
Upvotes: 2 <issue_comment>username_3: ```
#!/bin/bash
# set x to a "typical" input value
x='db.COLLECTION_NAME.insert(document)'
# print it out, just so you see it
echo "x == ${x}"
if [[ "${x}" =~ ^db\.(.*)\.insert.* ]]; then
# we have a match
ans="${BASH_REMATCH[1]}"
# print the substring that matches the pattern
echo "answer == ${ans}"
else
# sorry no match
echo "no match"
fi
```
Upvotes: 2 <issue_comment>username_2: Here is an alternative using BASH's match operator:
```
regex='db[.](.*)[.]insert.*'
str='db.COLLECTION_NAME.insert(document)'
if [[ $str =~ $regex ]]; then
result=${BASH_REMATCH[1]}
fi
echo $result
COLLECTION_NAME
```
Upvotes: 1
|
2018/03/19
| 1,809 | 6,789 |
<issue_start>username_0: I have a cluster running with services and am also able to launch fargate tasks from the command line. I can get the taskArn as a response to launching the task and I can wait for the task to be in the running state by using "aws ecs wait". I'm stuck figuring out how to get the the public IP of the task. I can find it via the web page easily enough and can access the machine via it's public IP...
How do I get the public IP of a fargate task using the CLI interface?
I'm using the following commands to launch the task, wait for it to run and retrieve the task description:
```
$ aws ecs run-task --launch-type FARGATE --cluster xxxx --task-definition xxxx --network-configuration xxxx
$ aws ecs wait
$ aws ecs describe-tasks --cluster xxxx --task | grep -i ipv4
```
The last command only gives me the private IP...
```
"privateIpv4Address": "10.0.1.252",
"name": "privateIPv4Address"
```
I've also tried using:
```
$ ecs-cli ps --cluster xxxx
```
But the Ports column is blank.
```
Name State Ports TaskDefinition
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxxx RUNNING xxxx:1
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxxx RUNNING xxxx:1
```<issue_comment>username_1: Once I realized that describe-tasks gave me the ENI id along with the private IP I was able to get the public IP with:
```
$ aws ec2 describe-network-interfaces --network-interface-ids eni-xxxxxxxx
```
Upvotes: 5 <issue_comment>username_2: ```
describe-addresses
```
the docs are here: <https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-addresses.html>
Upvotes: -1 <issue_comment>username_3: This was specific to my usecase, but perhaps its useful to someone else (intended to be run as javascript in Lambda just after you run ecs.createService() )
Yes, I know this topic is for CLI but this is the first result that popped up when looking for "Fargate public IP" and i was looking for a javascript based solution.
```js
// get container IP
getContainerIP(myServiceName).then(ip => {
console.log("Container IP address is: ", ip);
}).catch(err => {
console.log(err);
});
function getContainerIP(servicename) {
// note: assumes that only 1 task with 1 container is in the provided service, and that a container only has 1 network interface
return new Promise(function (resolve, reject) {
// get task arns (needs a delay because we just launched it)
setTimeout(getTasks, 6000);
// get task arns
function getTasks() {
ecs.listTasks({
cluster: process.env.ecs_cluster,
launchType: "FARGATE",
serviceName: servicename
}, function (err, res) {
if (err) {
reject("Unable to get task list");
return;
}
// loop until we have a result
if (!res.taskArns.length) {
setTimeout(getTasks, 2000);
return;
}
// get details
getTaskDetails(res.taskArns);
});
}
// get the details of the task (we assume only one task because that's how its configured)
function getTaskDetails(taskArns) {
ecs.describeTasks({
cluster: process.env.ecs_cluster,
tasks: taskArns
}, function (err, res) {
if (err) {
reject("Unable to get task details");
return;
}
// no results
if (!res.tasks.length || !res.tasks[0].attachments.length) {
reject("No tasks available");
return;
}
// network needs to be in status ATTACHING to see the eni, else wait
if (res.tasks[0].attachments[0].status !== "ATTACHING") {
setTimeout(function () { getTaskDetails(taskArns); }, 2000);
return;
}
// get network ID from result
let eni = "";
for (let i in res.tasks[0].attachments[0].details) {
if (!res.tasks[0].attachments[0].details.hasOwnProperty(i)) continue;
if (res.tasks[0].attachments[0].details[i].name !== "networkInterfaceId") continue;
// get the eni
eni = res.tasks[0].attachments[0].details[i].value;
break;
}
// no eni
if (eni === "") {
reject("Unable to retrieve container ENI");
return;
}
// get network details
getNetworkDetails(eni);
});
}
// get network details
function getNetworkDetails(eni) {
// get the ENI details
ec2.describeNetworkInterfaces({
NetworkInterfaceIds: [eni]
}, function (err, res) {
if (err) {
reject("Unable to retrieve ENI details");
return;
}
// confirm available data
if (!res.NetworkInterfaces.length || typeof res.NetworkInterfaces[0].Association === "undefined" || typeof res.NetworkInterfaces[0].Association.PublicIp === "undefined") {
reject("Unable to retrieve IP from ENI details");
return;
}
// resolve the public IP address
resolve(res.NetworkInterfaces[0].Association.PublicIp);
});
}
});
}
```
Upvotes: 3 <issue_comment>username_4: You can use a script like this.
```sh
SERVICE_NAME="my-service"
TASK_ARN=$(aws ecs list-tasks --service-name "$SERVICE_NAME" --query 'taskArns[0]' --output text)
TASK_DETAILS=$(aws ecs describe-tasks --task "${TASK_ARN}" --query 'tasks[0].attachments[0].details')
ENI=$(echo $TASK_DETAILS | jq -r '.[] | select(.name=="networkInterfaceId").value')
IP=$(aws ec2 describe-network-interfaces --network-interface-ids "${ENI}" --query 'NetworkInterfaces[0].Association.PublicIp' --output text)
echo "$IP"
```
Upvotes: 3 <issue_comment>username_5: I tinkered around with one of the comments here and came up with the following shell script:
```
#!/bin/bash
# Take the cluster name from the script arguments
CLUSTER_NAME=$1
# Get a list of tasks in the cluster
TASKS=$(aws ecs list-tasks --cluster "$CLUSTER_NAME" --query "taskArns" --output text)
# Loop through each task to get the container instance ARN
for TASK_ARN in $TASKS
do
# Get a human readable ARN.
TASK_ID=$(basename $TASK_ARN)
# Get the network interface ID for the task
NETWORK_INTERFACE_ID=$(aws ecs describe-tasks --cluster $CLUSTER_NAME --tasks $TASK_ARN --query 'tasks[0].attachments[0].details[?name==`networkInterfaceId`].value' --output text)
#Get the public IP of the network interface
PUBLIC_IP=$(aws ec2 describe-network-interfaces --network-interface-ids $NETWORK_INTERFACE_ID --query 'NetworkInterfaces[0].Association.PublicIp')
echo "Task: $TASK_ID -- Public IP: $PUBLIC_IP"
done
```
you can call your script like `./list-ecs-tasks.sh` and it loops through the tasks in your cluster and prints out the TaskID and Public IP of each one.
Upvotes: 0
|
2018/03/19
| 996 | 3,409 |
<issue_start>username_0: I'm using Mapbox GL JS to load in GeoJSON from an external URL on some pages. I would like to automatically fit the map to the boundaries of the polygon I'm loading.
I understand that [turf.js's bbox method](http://turfjs.org/docs#bbox) can help with this, but I'm not sure how to get the GeoJSON into the `turf.bbox` call.
This is my code right now:
```
map.addSource('mylayer', {
type: 'geojson',
data: '/boundaries.geojson'
});
map.addLayer({
"id": "mylayer",
"type": "fill",
"source": "mylayer",
'paint': {
'fill-color': '#088',
'fill-opacity': 0.6
}
});
var bbox = turf.bbox('mylayer');
map.fitBounds(bbox, {padding: 20});
```
But it fails with `turf.min.js:1 Uncaught Error: Unknown Geometry Type`. The docs say that `bbox` wants "any GeoJSON object".
How do I do this correctly? I'd obviously rather not load the external file twice.<issue_comment>username_1: The [turf.bbox](http://turfjs.org/docs/#bbox) function accepts the GeoJSON as an Object, it doesn't know about Mapbox.
A Mapbox GeoJSON Source has the full GeoJSON object stored privately at .\_data when you created the Source by passing the full GeoJSON (rather than passing a URL), so you could do:
```
turf.bbox(map.getSource('mylayer')._data);
```
However `._data` could change at any time in any new release without it being detailed in the release notes since it's a private API.
There is a public API [map.querySourceFeatures](https://www.mapbox.com/mapbox-gl-js/api/#map#querysourcefeatures):
```
map.querySourceFeatures('mylayer');
```
but it will only return the features in the current view and after being tiled by geojson-vt meaning even when viewing the whole world it's still not guaranteed to return all features.
Upvotes: 0 <issue_comment>username_1: Instead of passing the URL to addSource, download it first and then pass the full GeoJSON Object.
```
$.getJSON('/boundaries.geojson', (geojson) => {
map.addSource('mylayer', {
type: 'geojson',
data: geojson
});
map.fitBounds(turf.bbox(geojson), {padding: 20});
}
```
Subsitite jQuery with any other request library.
Upvotes: 0 <issue_comment>username_2: 1. Loading data from a remote source is asynchronous. That is, you are trying to analyze the data before it was loaded.
So you need handle the [`sourcedata`](https://www.mapbox.com/mapbox-gl-js/api/#map.event:sourcedata) event.
2. The input parameter of the [`bbox`](http://turfjs.org/docs#bbox) function is a valid [`GeoJson object`](https://www.rfc-editor.org/rfc/rfc7946#section-3).
3. As already noted, the `Turf.js` does not know anything about the `Mapbox`, so you need to read the loaded data from the source in addition.
4. And for an example:
```
map.addSource('mylayer', {
type: 'geojson',
data: '/boundaries.geojson'
});
map.addLayer({
"id": "mylayer",
"type": "fill",
"source": "mylayer",
'paint': {
'fill-color': '#088',
'fill-opacity': 0.6
}
});
map.on('sourcedata', function (e) {
if (e.sourceId !== 'mylayer' || !e.isSourceLoaded) return
var f = map.querySourceFeatures('mylayer')
if (f.length === 0) return
var bbox = turf.bbox({
type: 'FeatureCollection',
features: f
});
map.fitBounds(bbox, {padding: 20});
})
```
Upvotes: 3
|
2018/03/19
| 1,220 | 3,820 |
<issue_start>username_0: I am learning Tensorflow, and this is a simple code I wrote today. It doesn't give the expected output, and I am exhausted in figuring out why. Could you give me a hint? Many thanks!!
I just want TF to do a line fitting: **find 'a' and 'b' to fit a line a\*(0:99)+b**.
```
import math
import numpy as np
import tensorflow as tf
a=0.05
b=18.7
data = a*np.linspace(0,99,num=100)+b+np.random.randn(100)/100
tf.reset_default_graph()
X=tf.constant(np.linspace(0,99,num=100),dtype=tf.float32)
Y=tf.placeholder(tf.float32,shape=[None])
a_hat = tf.get_variable("a_hat", initializer =0.0,dtype=tf.float32)
b_hat = tf.get_variable("b_hat", initializer =0.0,dtype=tf.float32)
Y_hat= tf.add(tf.multiply(X,a_hat),b_hat)
loss = tf.reduce_mean((Y-Y_hat)**2)
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.00001).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(100):
_ , lossnow = sess.run([optimizer, loss], feed_dict={Y: data})
print(lossnow)
print(a_hat.eval())
print(b_hat.eval())
```
In the result, I can see the loss is going down. But finally it gives result
a\_hat = 0.33133847 (it should be 0.05)
b\_hat = 0.014483764 (it should be 18.7)
Any help is appreciated...<issue_comment>username_1: The [turf.bbox](http://turfjs.org/docs/#bbox) function accepts the GeoJSON as an Object, it doesn't know about Mapbox.
A Mapbox GeoJSON Source has the full GeoJSON object stored privately at .\_data when you created the Source by passing the full GeoJSON (rather than passing a URL), so you could do:
```
turf.bbox(map.getSource('mylayer')._data);
```
However `._data` could change at any time in any new release without it being detailed in the release notes since it's a private API.
There is a public API [map.querySourceFeatures](https://www.mapbox.com/mapbox-gl-js/api/#map#querysourcefeatures):
```
map.querySourceFeatures('mylayer');
```
but it will only return the features in the current view and after being tiled by geojson-vt meaning even when viewing the whole world it's still not guaranteed to return all features.
Upvotes: 0 <issue_comment>username_1: Instead of passing the URL to addSource, download it first and then pass the full GeoJSON Object.
```
$.getJSON('/boundaries.geojson', (geojson) => {
map.addSource('mylayer', {
type: 'geojson',
data: geojson
});
map.fitBounds(turf.bbox(geojson), {padding: 20});
}
```
Subsitite jQuery with any other request library.
Upvotes: 0 <issue_comment>username_2: 1. Loading data from a remote source is asynchronous. That is, you are trying to analyze the data before it was loaded.
So you need handle the [`sourcedata`](https://www.mapbox.com/mapbox-gl-js/api/#map.event:sourcedata) event.
2. The input parameter of the [`bbox`](http://turfjs.org/docs#bbox) function is a valid [`GeoJson object`](https://www.rfc-editor.org/rfc/rfc7946#section-3).
3. As already noted, the `Turf.js` does not know anything about the `Mapbox`, so you need to read the loaded data from the source in addition.
4. And for an example:
```
map.addSource('mylayer', {
type: 'geojson',
data: '/boundaries.geojson'
});
map.addLayer({
"id": "mylayer",
"type": "fill",
"source": "mylayer",
'paint': {
'fill-color': '#088',
'fill-opacity': 0.6
}
});
map.on('sourcedata', function (e) {
if (e.sourceId !== 'mylayer' || !e.isSourceLoaded) return
var f = map.querySourceFeatures('mylayer')
if (f.length === 0) return
var bbox = turf.bbox({
type: 'FeatureCollection',
features: f
});
map.fitBounds(bbox, {padding: 20});
})
```
Upvotes: 3
|
2018/03/19
| 493 | 1,534 |
<issue_start>username_0: I am having one (associative) data array `$data` with values, and another associative array `$replacements`.
I am looking for a short, easy and fast way to replace values in `$data` using the `$replacements` array.
The verbose way would be this:
```
function replace_array_values(array $data, array $replacements) {
$result = [];
foreach ($data as $k => $value) {
if (array_key_exists($value, $replacements)) {
$value = $replacements[$value];
}
$result[$k] = $value;
}
return $result;
}
```
Is there a native way to do this?
I know `array_map()`, but maybe there is something faster, without an extra function call per item?
Example:
--------
See <https://3v4l.org/g0sIJ>
```
$data = array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
'd' => 'D',
);
$replacements = array(
'B' => '(B)',
'D' => '(D)',
);
$expected_result = array(
'a' => 'A',
'b' => '(B)',
'c' => 'C',
'd' => '(D)',
);
assert($expected_result === replace_array_values($data, $replacements));
```<issue_comment>username_1: You can give a try to [array\_replace](http://php.net/manual/en/function.array-replace.php)
Upvotes: -1 <issue_comment>username_2: The simplest/least verbose way I can think of:
```
return array_map(function($value) use ($replacements) {
return array_key_exists($value, $replacements) ? $replacements[$value] : $value;
}, $data);
```
Using `array_map` is basically just looping over the array, which any other base function would also have to do anyway.
Upvotes: 2
|
2018/03/19
| 821 | 2,487 |
<issue_start>username_0: i use function script in google spread sheet.
this function is used maybe... 150,000 cell.
my question is... infinite loading.
when i use my custom function in sheet, infinite loading appear
how can i resolve that?
here is my script code :
```
function s2hex(str1){
var s2hex = 0;
var byte_check = 0;
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tbl");
var range1 = sheet1.getRange(1, 1, sheet1.getMaxRows(),
sheet1.getMaxColumns());
for(var i = 0; i < str1.length; ++i){
for(var k = 1; k < sheet1.getMaxRows(); ++k){
if(str1[i] == range1.getCell(k, 2).getValue() || str1[i] == " "){
s2hex = s2hex + 1;
byte_check = 1;
break;
}
}
if(byte_check == 0){
s2hex = s2hex + 2;
}
byte_check = 0;
}
return s2hex;
};
```<issue_comment>username_1: 150,000 function calls will slow down any sheet.
That said, your function is in dire need of optimization: you need to remove the need for extensive calls over the Spreadsheet interface. Each such call can take as much as 0.1 second. You can do this simply, by reading the entire range of your values to search with `getValues()`, and then iterating that in the same manner as you do currently.
Upvotes: 0 <issue_comment>username_2: * `getMaxRows()` will return all rows in the sheet. If you have content in `A1:A10` and there are empty rows from A10 to A100000. It'll return 100,000 instead of 10. Use `getLastRow()` instead.
* If you're only using the second column,Specify `2` as column number and `1` instead of `getMaxColumns()`
* Use `getValues()` to get a single array instead of making multiple calls to spreadsheet.
Try Modifying from:
```
var range1 = sheet1.getRange(1, 1, sheet1.getMaxRows(), sheet1.getMaxColumns());
for(var i = 0; i < str1.length; ++i)
{
for(var k = 1; k < sheet1.getMaxRows(); ++k)
{
if(str1[i] == range1.getCell(k, 2).getValue() || str1[i] == " ")
{
s2hex = s2hex + 1;
```
To
```
var lr =sheet1.getLastRow(); //One last row call to be used in multiple places
var range = sheet1.getRange(1, 2, lr,1);
var range1 = range.getValues(); //get all values in a single call
for(var i = 0; i < str1.length; ++i)
{
for(var k = 0; k < lr; ++k) //k to 0.Array index start at 0
{
if(str1[i] == range1[k][0] || str1[i] == " ") //Check the 2D value of already retrieved array
{
s2hex = s2hex + 1;
```
Upvotes: 1
|
2018/03/19
| 3,604 | 15,623 |
<issue_start>username_0: I have lots of code shared between web and web worker parts of my browser app.
How can I tell webpack to split my code up into common chunks so that the result is garanteed to work 100%?
The webworker code breaks (fails at runtime) after I tell webpack to generate the common chunks (which it does). Even after I fix the trivial "window not defined" error the worker just does nothing.
I believe this has to do with the webpack "target" option, which per default is set to "web". But I need "web" target because I don't have purely webworker code.
I also cannot do multiple webpack configs because I cannot do the common chunks thing with multiple configs...
What should I do?
If anybody is interested: I am trying build a minimal sized build for my app which includes the monaco editor (which provides the workers):
<https://github.com/Microsoft/monaco-editor/blob/master/docs/integrate-esm.md>
You can see here (at the bottom of the page) that the entry points consist of 1 main entry file + the workers.
Currently at least 6 MB is wasted because of duplicate code I am using and currently can not be split up because of this problem. That is a lot of wasted traffic.
Any ideas? :)
my webpack 4.1.1 config is basically:
```
module.exports = (env, options) => {
const mode = options.mode;
const isProduction = mode === 'production';
const outDir = isProduction ? 'build/release' : 'build/debug';
return {
entry: {
"app": "./src/main.tsx",
"editor.worker": 'monaco-editor/esm/vs/editor/editor.worker.js',
"ts.worker": 'monaco-editor/esm/vs/language/typescript/ts.worker.js'
},
output: {
filename: "[name].bundle.js",
path: `${__dirname}/${outDir}`,
libraryTarget: 'umd',
globalObject: 'this',
library: 'app',
umdNamedDefine: true
},
node: {
fs: 'empty'
},
devtool: isProduction ? undefined : "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".json"],
alias: {
"@components": path.resolve(__dirname, "src/components"),
"@lib": path.resolve(__dirname, "src/lib"),
"@common": path.resolve(__dirname, "src/common"),
"@redux": path.resolve(__dirname, "src/redux"),
"@services": path.resolve(__dirname, "src/services"),
"@translations": path.resolve(__dirname, "src/translations"),
"@serverApi": path.resolve(__dirname, "src/server-api")
}
},
optimization: isProduction ? undefined : {
splitChunks: {
minSize: 30000,
minChunks: 1,
name: true,
maxAsyncRequests: 100,
maxInitialRequests: 100,
cacheGroups: {
default: {
chunks: "all",
priority: -100,
test: (module) => {
const req = module.userRequest;
if (!req) return false;
return (!/node_modules[\\/]/.test(req));
},
},
vendor: {
chunks: "all",
test: (module) => {
const req = module.userRequest;
if (!req) return false;
if (!/[\\/]node_modules[\\/]/.test(req)) return false;
return true;
},
priority: 100,
}
}
},
},
module: {
rules: [...(isProduction ? [] : [
{
enforce: "pre", test: /\.js$/, loader: "source-map-loader",
exclude: [
/node_modules[\\/]monaco-editor/
]
}
]),
{
test: require.resolve('jquery.hotkeys'),
use: 'imports-loader?jQuery=jquery'
},
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader",
options: {
configFileName: 'src/tsconfig.json',
getCustomTransformers: () => {
return {
before: [p => keysTransformer(p)]
};
}
}
},
{
test: /\.(css|sass|scss)$/,
use: extractSass.extract({
use: [
{
loader: 'css-loader',
options: {
minimize: isProduction
}
},
{
loader: "postcss-loader",
options: {
plugins: () => [autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})]
}
},
{ loader: "sass-loader" }
],
fallback: "style-loader"
})
},
{
test: /node_modules[\/\\]font-awesome/,
loader: 'file-loader',
options: {
emitFile: false
}
},
{
test: { not: [{ test: /node_modules[\/\\]font-awesome/ }] },
rules: [
{
test: { or: [/icomoon\.svg$/, /fonts[\/\\]seti\.svg$/] },
rules: [
{ loader: 'file-loader?mimetype=image/svg+xml' },
]
}, {
test: { not: [/icomoon\.svg$/, /fonts[\/\\]seti\.svg$/] },
rules: [
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'svg-url-loader',
options: {}
}
},
]
},
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader'
},
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader" },
]
},
]
},
plugins: [
new HardSourceWebpackPlugin({
cacheDirectory: '../node_modules/.cache/hard-source/[confighash]', configHash: function (webpackConfig) {
return require('node-object-hash')({ sort: false }).hash(Object.assign({}, webpackConfig, { devServer: false }));
},
environmentHash: {
root: process.cwd(),
directories: [],
files: ['../package-lock.json'],
}
}),
new webpack.ProvidePlugin({
"window.$": "jquery"
}),
new CleanWebpackPlugin(outDir),
extractSass,
new HtmlWebpackPlugin({
title: 'my title',
filename: 'index.html',
minify: isProduction ? {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
} : false,
template: 'index_template.html',
excludeChunks: ['ts.worker', "editor.worker"]
}),
new webpack.IgnorePlugin(/^((fs)|(path)|(os)|(crypto)|(source-map-support))$/, /vs[\\\/]language[\\\/]typescript[\\\/]lib/)
].concat(isProduction ? [new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})] : [])
}
};
```<issue_comment>username_1: You're looking for universal [library target](https://webpack.js.org/configuration/output/#output-librarytarget), aka **umd**.
>
> This exposes your library under all the module definitions, allowing
> it to work with CommonJS, AMD and as global variable.
>
>
>
To make your Webpack bundle compile to **umd** you should configure `output` property like this:
```
output: {
filename: '[name].bundle.js',
libraryTarget: 'umd',
library: 'yourName',
umdNamedDefine: true,
},
```
There is an [issue](https://stackoverflow.com/questions/49111086/webpack-4-universal-library-target/) with Webpack 4, but if you still want to use it, you can workaround the issue by adding `globalObject: 'this'` to the configuration:
```
output: {
filename: '[name].bundle.js',
libraryTarget: 'umd',
library: 'yourName',
umdNamedDefine: true,
globalObject: 'this'
},
```
Upvotes: 1 <issue_comment>username_2: This is really bad answer, but i've managed to share chunks between workers and main thread.
The clue is that
1. `globalObject` has to be defined as above to `(self || this)`:
```
output: {
globalObject: "(self || this)"
}
```
2. Webpack loads chunks with `document.createElement('script')` and `document.head.appendChild()` sequence, which is not available in worker context, but we have `self.importScript`. So it's just a matter of "polyfiling" it.
Here is working "polyfill" (straight from the hell):
```js
console.log("#faking document.createElement()");
(self as any).document = {
createElement(elementName: string): any {
console.log("#fake document.createElement", elementName);
return {};
},
head: {
appendChild(element: any) {
console.log("#fake document.head.appendChild", element);
try {
console.log("loading", element.src);
importScripts(element.src);
element.onload({
target: element,
type: 'load'
})
} catch(error) {
element.onerror({
target: element,
type: 'error'
})
}
}
}
};
```
3. Ensure, that your real code is resolved *after* polyfill is installed, by using dynamic import, which will. Assuming, that normal "worker main" is in "./RealWorkerMain", that would be "main worker script":
```
// so, typescript recognizes this as module
export let dummy = 2;
// insert "polyfill from hell" from here
import("./RealWorkerMain").then(({ init }) => {
init();
});
```
4. You may need to configure dynamic `import` in webpack, as documented [here](https://webpack.js.org/guides/code-splitting/#dynamic-imports) is not easy too, [this answer](https://stackoverflow.com/a/52108403/269448) was very helpful.
Upvotes: 2 <issue_comment>username_3: EDIT: Alright I wrote a webpack plugin based on everyone's knowledge just put together.
<https://www.npmjs.com/package/worker-injector-generator-plugin>
You can ignore the content below, and use the plugin or if you want to understand how the plugin came to be and do it by hand yourself (so you don't have to depend on my code) you can keep reading.
=====================================================
Alright after so much researching I figured out this solution, you need to create an injection file, for a simple case you need the <https://github.com/webpack-contrib/copy-webpack-plugin> as it works pretty well... so let's say your setup is:
```
entry: {
"worker": ["./src/worker.ts"],
"app": ["./src/index.tsx"],
},
```
And you have setup your common plugins already let's say this example.
```
optimization: {
splitChunks: {
cacheGroups: {
commons: {
name: 'commons',
chunks: 'initial',
minChunks: 2
},
}
}
},
```
You need to now create an injection "Vanilla JS" which might look like this:
```
var base = location.protocol + "//" + location.host;
window = self;
self.importScripts(base + "/resources/commons.js", base + "/resources/worker.js");
```
Then you can add that alongside your worker, say in `src/worker-injector.js`
And using the copy plugin
```
new CopyPlugin([
{
from: "./src/worker-injector.js",
to: path.resolve(__dirname, 'dist/[name].js'),
},
]),
```
Make sure your output is set to umd.
```
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: "umd",
globalObject: "this",
}
```
This is nothing but a hack, but allows you to use everything as it is without having to do something as overblown.
If you need hashing (so that copy plugin doesn't work) functionality you would have to generate this file (rather than copying it), refer to this.
[How to inject Webpack build hash to application code](https://stackoverflow.com/questions/50228128/how-to-inject-webpack-build-hash-to-application-code)
For that you would have to create your own plugin which would generate the vanilla js file and consider the hash within itself, you would pass the urls that you want to load together, and it would attach the hash to them, this is more tricky but if you need hashes it should be straightforward to implement with your custom plugin.
Sadly so far there doesn't seem to be other way.
I could probably write the plugin myself that would do the workaround and create the injectors, but I do think this is more of a hack and shouldn't be the accepted solution.
I might later go around and write the injector plugin, it could be something as:
something like `new WorkerInjectorGeneratorPlugin({name: "worker.[hash].injector.js", importScripts: ["urlToLoad.[hash].js", secondURLToLoad.[hash].js"])`
refer to this issues for reference, and why it should be fixed within webpack and something as a WorkerInjectorGeneratorPlugin would be pretty much a hack plugin.
<https://github.com/webpack/webpack/issues/6472>
Upvotes: 2 <issue_comment>username_4: Native Worker support is introduced in webpack 5. With this feature, you can share chunks between app code and webwokers with simple `splitChunk` options like
```js
{
optimization: {
splitChunks: {
chunks: 'all',
minChunks: 2,
},
},
}
```
>
> When combining new URL for assets with new Worker/new SharedWorker/navigator.serviceWorker.register webpack will automatically create a new entrypoint for a web worker.
>
>
> `new Worker(new URL("./worker.js", import.meta.url))`
>
>
> The syntax was chosen to allow running code without bundler too. This syntax is also available in native ECMAScript modules in the browser.
>
>
>
<https://webpack.js.org/blog/2020-10-10-webpack-5-release/#native-worker-support>
Upvotes: 0
|
2018/03/19
| 575 | 1,906 |
<issue_start>username_0: I'm uses a previous design of shopping cart, but can't applied the option hover shoppign cart, this its a code example.
My code
```
$('#cart').hover(function(e) {
$(".shopping-cart").stop(true, true).addClass("active");
}, function() {
$(".shopping-cart").stop(true, true).removeClass("active");
});
```
I need the contents of the cart not to disappear until the mouse pointer is out.
**Example codepen**
See the Pen [Shopping Cart Dropdown](https://codepen.io/alexd2/pen/PRbjxz/) by Eduardo ([@alexd2](https://codepen.io/alexd2)) on [CodePen](https://codepen.io).<issue_comment>username_1: use [Multiple Selector](https://api.jquery.com/multiple-selector/) will solve your issue.
```
$('#cart, .shopping-cart').hover(function(e) {
$(".shopping-cart").stop(true, true).addClass("active");
}, function() {
$(".shopping-cart").stop(true, true).removeClass("active");
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Just remove "active" from this
```
$(".shopping-cart").stop(true, true).removeClass("active");
```
to this one
```
$(".shopping-cart").stop(true, true).removeClass("");
```
Upvotes: 0 <issue_comment>username_3: With pure css, you could probably do something like this.
```css
.cart {
background-color: lightblue;
float: right;
text-align: right;
position: relative;
}
.list {
background-color: lightgreen;
height: 250px;
width: 300px;
border: 2px solid red;
right: 0;
position: absolute;
transition: 1s all;
transform: scale(0) ;
transform-origin: 100% 0%;
}
.cart:hover > .list {
transform: scale(1);
}
```
```html
This is a cart
some long list
```
`position: absolute` is optional (along with the accompanying css), just that if you don't have it, then the cart will be as long as the child's width, which may or may not be desirable.
Upvotes: 1
|
2018/03/19
| 660 | 2,205 |
<issue_start>username_0: I have recently moved to Visual Studio Code and have a question that I have found an answer for.
When I split the editor it shows the focused file on both sides of the split.
I want the focused file to be moved with the split rather than showing a duplicate view.
Is there a setting or an extension that I can use to do this split / move?<issue_comment>username_1: Try the `Move Editor into next Group` command:
```
{
"key": "ctrl+cmd+right",
"command": "workbench.action.moveEditorToNextGroup"
}
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: on mac default shortcut is:
control+command+ -> or <- arrow ;-)
Upvotes: 4 <issue_comment>username_3: Personally, i always used ctrl+enter combination to open the next file in the side editor. So far, it is the most recommended way that I always use.
Upvotes: 2 <issue_comment>username_4: on `Windows`, `vscode v1.59.0`
To move file to **right** side
click on file to focus:
`ctrl`+`alt`+`right arrow`
To move file to **left** side
click on file to focus:
`ctrl`+`alt`+`left arrow`
Upvotes: 4 <issue_comment>username_5: In `Ubuntu` (20.04) the keybindings are the same as in windows:
`ctrl + alt + right` and `ctrl + alt + left` **however** gnome blocks these keybindings. In order to liberate them, run the following in the terminal which changes your gnome settings:
```
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "[]"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "[]"
```
After that, it should work.
See also:
[Some VSCode Keybindings not working in Ubuntu](https://stackoverflow.com/questions/33636531/some-vscode-keybindings-not-working-in-ubuntu)
And:
<https://askubuntu.com/questions/1041914/something-blocks-ctrlaltleft-right-arrow-keyboard-combination>
<https://github.com/microsoft/vscode/issues/6197>
Upvotes: 2 <issue_comment>username_6: Windows: Ctrl-Alt-X
File -> Preferences -> Keyboard shortcuts.
Search "move editor" for wider set of options, or as in the attached image search "move editor into"
[](https://i.stack.imgur.com/86zOE.png)
Upvotes: 0
|
2018/03/19
| 765 | 2,605 |
<issue_start>username_0: ```
import UIkit
// ViewController file
class ViewController: UITableViewController, UIViewController{
@IBAction func aaaSwitch(_ sender: UISwitch) {
if (sender.isOn == true)
{
ClickCounterA+=2
UserDefaults.standard.set(aaaSwitch, forKey: "aaaSwitch")
UserDefaults.standard.bool(forKey: "aaaSwitch")
defaults.set(aaaSwitch, forKey: "aaaSwitch")
}
else
{
defaults.set(aaaSwitch, forKey: "aaaSwitch")
}
}
```
I change the switch(aaaSwitch) in tableview and move to another tableview. After that, I return to the first tableview, the switch is the statement before I change. In other words, I can't save the switch statement.<issue_comment>username_1: Try the `Move Editor into next Group` command:
```
{
"key": "ctrl+cmd+right",
"command": "workbench.action.moveEditorToNextGroup"
}
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: on mac default shortcut is:
control+command+ -> or <- arrow ;-)
Upvotes: 4 <issue_comment>username_3: Personally, i always used ctrl+enter combination to open the next file in the side editor. So far, it is the most recommended way that I always use.
Upvotes: 2 <issue_comment>username_4: on `Windows`, `vscode v1.59.0`
To move file to **right** side
click on file to focus:
`ctrl`+`alt`+`right arrow`
To move file to **left** side
click on file to focus:
`ctrl`+`alt`+`left arrow`
Upvotes: 4 <issue_comment>username_5: In `Ubuntu` (20.04) the keybindings are the same as in windows:
`ctrl + alt + right` and `ctrl + alt + left` **however** gnome blocks these keybindings. In order to liberate them, run the following in the terminal which changes your gnome settings:
```
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "[]"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "[]"
```
After that, it should work.
See also:
[Some VSCode Keybindings not working in Ubuntu](https://stackoverflow.com/questions/33636531/some-vscode-keybindings-not-working-in-ubuntu)
And:
<https://askubuntu.com/questions/1041914/something-blocks-ctrlaltleft-right-arrow-keyboard-combination>
<https://github.com/microsoft/vscode/issues/6197>
Upvotes: 2 <issue_comment>username_6: Windows: Ctrl-Alt-X
File -> Preferences -> Keyboard shortcuts.
Search "move editor" for wider set of options, or as in the attached image search "move editor into"
[](https://i.stack.imgur.com/86zOE.png)
Upvotes: 0
|
2018/03/19
| 952 | 3,741 |
<issue_start>username_0: I am trying to use React router with asp.net core. The problem is that I can't access the Blog component.
Here's the error:
`Failed to load resource: the server responded with a status of 404 (Not Found)`
Here's my code:
**webpack.config.js**
```
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: { 'main':'./Client/index.js'},
output: {
path:path.resolve(__dirname,'wwwroot/dist'),
filename: 'bundle.js',
publicPath: 'dist/'
},
watch: true,
mode: 'development',
module: {
rules: [
{test: /\.css$/, use: [{ loader: "style-loader" },
{ loader: "css-loader" }]},
{ test: /\.js?$/,
use: { loader: 'babel-loader', options: { presets:
['@babel/preset-react','@babel/preset-env'] } } },
]
}
}
```
index.js from client side. I am fully aware that asp.net core has template for react application. I just don't like to use typescript
**index.js**
```
import React from 'react';
import ReactDom from 'react-dom';
import { createStore,applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import ReduxPromise from 'redux-promise'
import reducers from './reducers';
import Blog from './components/Blog';
import NavBar from './components/NavBar';
import { BrowserRouter,Route } from 'react-router-dom'
import './style/index.css'
import App from './components/App';
const store = applyMiddleware(ReduxPromise)(createStore);
ReactDom.render(
//Can't access this Component
,document.getElementById('react-app')
)
```
**Startup.cs**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.SpaServices.Webpack;
namespace server
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ReactHotModuleReplacement = true
});
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
```<issue_comment>username_1: Turns out, I just need to add this to **Startup.cs**
```
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
```
Upvotes: 3 <issue_comment>username_2: I too have the same issue with the new frameworks but turn out to be above solution works below the 3.0 framework.
Below is the way for above frameworks
**ASP.NET Core MVC 3.0+**
```
endpoints.MapFallbackToController("Index", "Home");
```
**ASP.NET Core MVC Before 3.0**
```
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
```
Upvotes: 1
|
2018/03/19
| 354 | 1,464 |
<issue_start>username_0: I am trying to demonstrate a buffer overflow, and I wish to overwrite a local varible with `gets`. I have compiled my program using gcc with `-fno-stack-protector`, so I know that the buffer that `gets` uses is right next to another local variable I am trying to overwrite. My goal is to overflow the buffer and overwrite the adjacent variable so that both of them have the same string. However, I noticed that I need to be able to input the `'\0'` character so that strcmp will actually show that both are equal. How can I input `'\0'`?<issue_comment>username_1: On many keyboards, you can enter a NUL character with `ctrl``@` (might be `ctrl``shift``2` or `ctrl``alt``2`).
Barring that, you can create a file with a NUL byte and redirect that as stdin.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I'm not sure you'll be able to input a `'\0'` into a `gets(3)` or `fgets(3)` function, as the function checks for newline terminators and probably has some way of protecting you from inputing a nul terminator to a C string (which is assumed to terminate on nul character).
Probably, what you are trying to demonstrate is something implementation dependant (so, undefined behaviour), and will work differently for different implementations.
If you want to correctly overwrite a local variable with only one input statement, just use `read(2)`, which allows you to enter nulls and any other possible character value.
Upvotes: 0
|
2018/03/19
| 5,679 | 18,214 |
<issue_start>username_0: I have been trying to create a way to stream a youtube url (preferably audio only, although this doesn't matter too much) right from python code. I have tried numerous things but none really seem to work. So far, I am able to search for videos or playlists using youtube data api, grab the first video or playlist and pass it into pafy to get different streaming urls. Does anyone know of a way to play youtube audio/video through python without downloading the video first? I would think it is possible with a cmd line tool such as mplayer or vlc using the sub process to pop open a cmd for the cmd line and pass in the url, but I am stuck. Any help is needed. Please! Here is my following code:
```
import argparse
import pafy
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
DEVELOPER_KEY = 'DEVELOPER KEY'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def pafy_video(video_id):
url = 'https://www.youtube.com/watch?v={0}'.format(video_id)
vid = pafy.new(url)
def pafy_playlist(playlist_id)
url = "https://www.youtube.com/playlist?list={0}".format(playlist_id)
playlist = pafy.get_playlist(url)
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q='Hello world',
part='id,snippet',
maxResults=options.max_results
).execute()
videos = []
playlists = []
channels = []
for search_result in search_response.get('items', []):
if search_result['id']['kind'] == 'youtube#video':
videos.append('%s' % (search_result['id']['videoId']))
elif search_result['id']['kind'] == 'youtube#channel':
channels.append('%s' % (search_result['id']['channelId']))
elif search_result['id']['kind'] == 'youtube#playlist':
playlists.append('%s' % (search_result['id']['playlistId']))
if videos:
print('Videos:{0}'.format(videos))
pafy_video(videos[0])
elif playlists:
print('Playlists:{0}'.format(playlists))
pafy_video(playlists[0])
#https://www.youtube.com/watch?v=rOU4YiuaxAM
#url = 'https://www.youtube.com/watch?v={0}'.format(videos[0])
#print(url)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--q', help='Search term', default='Google')
parser.add_argument('--max-results', help='Max results', default=3)
args = parser.parse_args()
youtube_search(args)
```
Tldr; I would like to stream a youtube video (using the url or id) straight from python code without downloading the video first
Thank you!<issue_comment>username_1: `pafy` according to its [documentation](https://github.com/mps-youtube/pafy) do not list playing media directly (at least I didn't find any).
However we can use it to get correct url, and then use player such as `vlc` to play directly without downloading.
You can download [vlc from here](https://wiki.videolan.org/PythonBinding)
First we get correct / best URL from `youtube` using `pafy`
```
import pafy
import vlc
url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
video = pafy.new(url)
best = video.getbest()
playurl = best.url
```
Over here `playurl` is best URL to play.
Then we use VLC to play it.
```
Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()
```
This will open a window with no controls (play/pause/stop etc).
You can run these command on the `repr` window or at python prompt (depending upon how you are using it)
You will need to build one accordingly using vlc commands such as
```
>>> player.pause() #-- to pause video
>>> player.play() #-- resume paused video. On older versions,
# this function was called resume
>>> player.stop() #-- to stop/end video
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: The best way to accomplish this is to use [mpv](https://mpv.io/) with [youtube-dl](http://youtube-dl.org/) (a light weight media player that comes with a command line console which allows you to stream any type of video/audio codecs via copy and pasting url to mpv console (works for cmd and terminal). **Usage**: path\to\mpv https://your/video/audioURL.com/
First import these modules - install via `pip install bs4 requests`
```
import re, requests, subprocess, urllib.parse, urllib.request
from bs4 import BeautifulSoup
```
Then create a variable to store music title of your choice
```
music_name = "<NAME>"
query_string = urllib.parse.urlencode({"search_query": music_name})
```
The goal here to use this search query to extract the output title and link of the first video result. We can then endcode the youtube url `"https://www.youtube.com/results?search_query="` with the identifier using `urllib` (eg., `"https://www.youtube.com/results?search_query=linkin+park+numb"`)
```
formatUrl = urllib.request.urlopen("https://www.youtube.com/results?" + query_string)
```
This right here `re.findall(r"watch\?v=(\S{11})"` views the 11 character identifier of all the video results from our query
```
search_results = re.findall(r"watch\?v=(\S{11})", formatUrl.read().decode())
```
After decoding the content, we can extract the full url by concatenating the main youtube url with the 11 character identifier
```
clip = requests.get("https://www.youtube.com/watch?v=" + "{}".format(search_results[0]))
clip2 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[0])
print(clip2)
```
* Output ==> **`https://www.youtube.com/watch?v=kXYiU_JCYtU`**
---
To further inspect the content, we can use beautifulsoup to scrape the extact title of the video
```
inspect = BeautifulSoup(clip.content, "html.parser")
yt_title = inspect.find_all("meta", property="og:title")
for concatMusic1 in yt_title:
pass
print(concatMusic1['content'])
```
* Output ==> **`Numb (Official Video) - Linkin Park`**
---
Finally, to play our music we input this to the command line
```
subprocess.Popen(
"start /b " + "path\\to\\mpv.exe" + clip2 + " --no-video --loop=inf --input-ipc-server=\\\\.\\pipe\\mpv-pipe > output.txt",
shell=True)
```
Full script
-----------
===================================================================
```
import re, requests, subprocess, urllib.parse, urllib.request
from bs4 import BeautifulSoup
music_name = "<NAME>"
query_string = urllib.parse.urlencode({"search_query": music_name})
formatUrl = urllib.request.urlopen("https://www.youtube.com/results?" + query_string)
search_results = re.findall(r"watch\?v=(\S{11})", formatUrl.read().decode())
clip = requests.get("https://www.youtube.com/watch?v=" + "{}".format(search_results[0]))
clip2 = "https://www.youtube.com/watch?v=" + "{}".format(search_results[0])
inspect = BeautifulSoup(clip.content, "html.parser")
yt_title = inspect.find_all("meta", property="og:title")
for concatMusic1 in yt_title:
pass
print(concatMusic1['content'])
subprocess.Popen(
"start /b " + "path\\to\\mpv.exe " + clip2 + " --no-video --loop=inf --input-ipc-server=\\\\.\\pipe\\mpv-pipe > output.txt",
shell=True)
# Alternatively, you can do this for simplicity sake:
# subprocess.Popen("start /b " + "path\\to\\mpv.exe " + clip2 + "--no-video", shell=True)
```
Upvotes: 3 <issue_comment>username_3: I made exactly this, including options like moving through the video with a scale, play/pause function, making playlist, shuffle function.
One thing to know is that youtube\_dl has trouble with some videos, there is a fork called yt\_dlp which works better. For my app, I changed pafy so that it uses yt\_dlp instead of youtube\_dl. I can share the whole code, it's a lot, but it's pretty good I think.
```
#! /usr/bin/python3
from tkinter import *
from bs4 import BeautifulSoup
from youtube_search import YoutubeSearch
import re,random, vlc, pafy, datetime, time,yt_dlp
#global vars
ran = 0
x = []
win = Tk()
count = 0
count2=-1
playurl = ""
scalevar = ""
scalevar2= 100
url2 = []
dur = 0
#window, player
win.geometry('610x100')
win.title("Youtube Player")
menubar = Menu(win)
instance = vlc.Instance()
player = instance.media_player_new()
#toggling shuffle
def funcRAN():
global ran
ran = not(ran)
#this function keeps track of time and moves the timescale
def every_second():
global count2
global ran
length = player.get_length()
place = player.get_time()
if player.is_playing() == 0 and len(url2) > (count2 + 1) and len(url2) > 0 and abs(place-length) < 10000:
if ran ==0:
count2 += 1
else:
counttemp = count2
while counttemp == count2:
count2 = random.randrange(len(url2))
scale.set(1)
player.set_time(1)
xvar = funcGO3(url2[count2], playurl)
player.set_time(xvar)
place = 1
if player.is_playing() == 1:
timee =str(datetime.timedelta(seconds = round(place/1000))) + " / " + str(datetime.timedelta(seconds = round(length/1000)))
my_label2.config(text=timee)
scale.set(place)
win.after(1000,lambda:every_second())
def settime(scalevar):
place = player.get_time()
scalevar = int(scalevar)
if abs(scalevar - place) > 4000:
player.set_time(scalevar)
def songskip(amount):
global count2
global ran
win.focus()
if ran == 0:
skip = count2 + amount
else:
counttemp = count2
while counttemp == count2:
count2 = random.randrange(len(url2))
skip = count2
if amount == -1 and player.get_time() > 10000:
player.set_time(0)
elif skip >= 0 and skip < len(url2):
count2 = skip
funcGO3(url2[skip], playurl)
#this function is for downloading the song
def funcDL(song_url, song_title):
outtmpl = song_title + '.%(ext)s'
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': outtmpl,
'postprocessors': [
{'key': 'FFmpegExtractAudio','preferredcodec': 'mp3',
'preferredquality': '192',
},
{'key': 'FFmpegMetadata'},
],
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info_dict = ydl.extract_info("youtube.com" + song_url, download=True)
#this function is for moving back and forth in time of the song
def funcSKIP(amount):
win.focus()
timee = player.get_time() + amount
if timee < 0:
timee = 0
timeall = player.get_length()
if timee>timeall:
timee = timeall
scale.set(timee)
#to pause
def funcPPTRANSFER():
if str(win.focus_get()) != str(".!entry"):
funcPP()
#to pause
def funcPP():
win.focus()
pause = player.is_playing()
player.set_pause(pause)
if pause == 1:
btnPP.config(text="|>")
else:
btnPP.config(text="||")
#moving through the songlist
def funcMOVE(title, move, resultcount):
win.focus()
global count
count += move
if count < 0:
count =resultcount
if count > resultcount:
count = 0
my_label.config(text = title[count])
#starting the song
def funcGO(title, URL, playurl):
global count2
global count
win.focus()
instance.vlm_stop_media(playurl)
URL = URL[count]
url = "https://www.youtube.com" + str(URL)
count2 += 1
url2.insert(count2,url)
video = pafy.new(url)
#best = video.getbestaudio()
best = video.audiostreams[0]
print(best.quality, int(best.get_filesize()/10000)/100, "mb")
printer = video.title
playurl = best.url
media=instance.media_new(playurl)
media.get_mrl()
player.set_media(media)
btnPP.place(x=340, y=2)
btnGO2.place(x=170, y=62)
btnBACK.place(x=295, y=2)
btnBACK2.place(x=240, y=2)
btnFWD.place(x=395, y=2)
btnFWD2.place(x=445, y=2)
scale.place(x=370, y=68)
player.play()
btnPP.config(text="||")
scale.set(0)
while player.is_playing() == 0:
time.sleep(1)
scale.config(to = player.get_length())
win.title(title[count])
#this is to select the next song in the list
def funcGO2(URL):
global url2
global count
win.focus()
URL2 = URL[count]
url2.append("https://www.youtube.com" + str(URL2))
#this is to play the next song in the list
def funcGO3(url, playurl):
win.focus()
instance.vlm_stop_media(playurl)
video = pafy.new(url)
#best = video.getbestaudio()
best = video.audiostreams[0]
print(best.quality, int(best.get_filesize()/10000)/100, "mb")
printer = video.title
playurl = best.url
media=instance.media_new(playurl)
media.get_mrl()
btnPP.place(x=340, y=2)
btnGO2.place(x=170, y=62)
btnBACK.place(x=295, y=2)
btnBACK2.place(x=240, y=2)
btnFWD.place(x=395, y=2)
btnFWD2.place(x=445, y=2)
scale.place(x=370, y=68)
player.set_media(media)
player.set_time(1)
player.play()
player.set_time(1)
btnPP.config(text="||")
scale.set(0)
scalevar = scale.get()
while player.is_playing() == 0:
time.sleep(1)
player.set_time(1)
length = player.get_length()
scale.config(to = length)
timee =str(datetime.timedelta(seconds = 0)) + " / " + str(datetime.timedelta(seconds = round(length/1000)))
my_label2.config(text=timee)
win.title(printer)
#win.after(2000, lambda:every_second(player, scale, count2))
return(scalevar)
#controlling the volume
def funcSCALE(scalevar2):
player.audio_set_volume(int(scalevar2))
#extracting info from the html of the search
def titlee(URL, question):
results = YoutubeSearch(URL, max_results=40).to_dict()
title=[]
URL=[]
resultcount = -1
for v in results:
length = v['duration']
if length.count(':') > 1 and dur == 1:
continue
if length.count(':') == 1:
m, s = length.split(':')
length = int(m) * 60 + int(s)
if length > 300 and dur == 1:
continue
URL.append(v['url_suffix'])
resultcount+= 1
print(resultcount)
title.append(re.sub(r"[^a-zA-Z0-9 .,:;+-=!?/()öäßü]", "", v['title']))
if question == 1:
url2.append("https://www.youtube.com" + str(v['url_suffix']))
if resultcount == 20:
break
btnDL.place(x=505, y=2)
return(URL, title, 0, resultcount)
#making the search
def func(event):
global count
global x
btnGO.focus()
btnDL.place(x=500, y=2)
x = str(var.get())
URL, title, count, resultcount = titlee(x, 0)
btnL.config(command = (lambda: funcMOVE(title, -1, resultcount)))
btnR.config(command = (lambda:funcMOVE(title, 1, resultcount)))
btnGO.config(command = (lambda: funcGO(title,URL, playurl)))
btnGO2.config(command = (lambda: funcGO2(URL)))
btnDL.config(command =(lambda: funcDL(URL[count],title[count])))
my_label.config(text = title[count])
#import all songs from querie
def funcImportall():
global x
titlee(x, 1)
#toggle limit duration of song
def funcDur():
global dur
dur = not(dur)
#clear playlist
def funcClear():
global url2
url2 = []
btnPP = Button(win, text = "||", command =(lambda: funcPP()))
btnBACK = Button(win, text = "<", command =(lambda: funcSKIP(-10000)))
btnBACK2 = Button(win, text = "<<", command =(lambda: songskip(-1)))
btnFWD = Button(win, text = ">", command =(lambda: funcSKIP(10000)))
btnFWD2 = Button(win, text = ">>", command =(lambda: songskip(1)))
btnDL = Button(win, text = "↓")
btnL = Button(win, text = "<-")
btnR = Button(win, text = "->")
btnGO = Button(win, text = "OK")
btnGO2 = Button(win, text = "+")
scale = Scale(win, from_=0, to=1000, orient=HORIZONTAL,length=200, variable = scalevar, showvalue=0, command = settime)
scale2 = Scale(win, from_=200, to=0, orient=VERTICAL,length=80, variable = scalevar2, showvalue=0, command = funcSCALE)
scale2.place(x=580, y=2)
scale2.set(100)
my_label = Label(win, text = "")
my_label.place(x=5, y=36)
my_label2 = Label(win, text = "")
my_label2.place(x=220, y=66)
var = Entry(win, width=20)
var.place(x=5, y=5)
var.focus()
var.bind('', func)
btnL.place(x=5, y=62)
btnR.place(x=60, y=62)
btnGO.place(x=115, y=62)
win.bind\_all("", lambda event: event.widget.focus\_set())
filemenu = Menu(win, tearoff=0)
filemenu.add\_command(label="toggle shuffle", command=funcRAN)
filemenu.add\_command(label="toggle limit duration", command=funcDur)
editmenu = Menu(menubar, tearoff=0)
editmenu.add\_command(label="all results to playlist", command=funcImportall)
editmenu.add\_command(label="clear playlist", command=funcClear)
menubar.add\_cascade(label="Options", menu=filemenu)
menubar.add\_cascade(label="Playlists", menu=editmenu)
win.config(menu=menubar)
win.bind('',lambda event:funcPPTRANSFER())
win.after(2000, lambda:every\_second())
var.focus()
win.mainloop()
```
Upvotes: 1 <issue_comment>username_4: MVP non python
==============
This way doesn't use python but uses clitools some one might care for.
Save the file something like ~/.music.sh
Then in a bashrc file `source ~/.music.sh`
Example command after sourcing:
`play_mesh_up 75`
```bash
#!/usr/bin/env zsh
# requirements:
# mvp
# youtube-dl
function play_mesh_up() {
_VOLUME="${1:-50}"
mpv --no-video --volume=$_VOLUME "https://youtu.be/NCZPJrH_DqQ"
}
function play_lofi_focus() {
_VOLUME="${1:-50}"
mpv --no-video --volume=$_VOLUME "https://www.youtube.com/watch?v=5qap5aO4i9A"
}
```
Upvotes: 0
|
2018/03/19
| 685 | 2,244 |
<issue_start>username_0: I am working on a project involving a series of Queues. These Queues are intended to be Global in scope as they are handled and modified by a series of functions. As of right now, my implementation raises the "Initializer element is not constant" flag. I understand why, for the most part, but I was wondering if there is an alternative way to achieve this. (ie. An array containing each Queue?) Is this possible?
main.c
```
LIST* queue0 = ListCreate(); //0
LIST* queue1 = ListCreate(); //1
LIST* queue2 = ListCreate(); //2
int main(){......}
```
ListCreate occurs as follows:
implement.c
```
LIST *ListCreate()
{
int popped = popList();
if (popped != -1){
//Create list
lists[popped].currSize = 0;
return &lists[popped];
}
else{
return NULL;
}
}
```
(Bear in mind, I was required to build a Linked List without the use of malloc.)<issue_comment>username_1: ```
LIST* queue0 = NULL;
LIST* queue1 = NULL;
LIST* queue2 = NULL;
void initQueues(void) {
queue0 = ListCreate();
queue1 = ListCreate();
queue2 = ListCreate();
}
void main(int argc, char *argv[]) {
initQueues();
// ... (i.e. other stuff)
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You don't actually need dynamic allocation for linked lists. You can put them in global (or static) memory, but you'll have to initilise them manually, which is doable for small lists (Note: the initialiser values are all constant, or at least computable at compile time). Example:
---
```
struct llist {
struct llist *next;
// Whatever
char *payload;
};
struct llist lists[] =
{{ lists+1, "one" }
,{ lists+2, "two" }
,{ lists+3, "three" }
,{ lists+4, "four" }
,{ lists+5, "five" }
,{ lists+6, "six" }
,{ lists+7, "seven" }
,{ lists+8, "eight" }
,{ lists+9, "nine" }
,{ NULL, "ten" }
};
struct llist *freelist = lists;
struct llist *queue = NULL;
/* example for constructor / destructor */
struct llist *newnode (void)
{
struct llist *this ;
this = freelist;
if (this) freelist = this->next;
return this;
}
void freenode (struct llist *ptr)
{
if (!ptr) return;
ptr->next = freelist;
freelist= ptr;
}
```
Upvotes: 0
|
2018/03/19
| 491 | 1,695 |
<issue_start>username_0: I am going through Introduction to Statistical Learning in R by Hastie and Tibshirani. I came across two concepts: RSE and MSE. My understanding is like this:
```
RSE = sqrt(RSS/N-2)
MSE = RSS/N
```
Now I am building 3 models for a problem and need to compare them. While MSE come intuitively to me, I was also wondering if calculating `RSS/N-2` will make any use which is according to above is `RSE^2`
I think I am not sure which to use where?<issue_comment>username_1: I think RSE ⊂ MSE (i.e. RSE is part of MSE).
And MSE = RSS/ degree of freedom
MSE for a single set of data (X1,X2,....Xn) would be RSS over N
or more accurately is RSS/N-1
(since your freedom to vary will be reduced by one when U have used up all the freedom)
But in linear regression concerning X and Y with binomial term, the degree of freedom is affected by both X and Y thus N-2
thus yr MSE = RSS/N-2
and one can also call this RSE
And in over parameterized model, meaning one have a collection of many ßs (more than 2 terms| y~ ß0 + ß1\*X + ß2\*X..), one can even penalize the model by reducing the denominator by including the number of parameters:
MSE= RSS/N-p (p is the number of fitted parameters)
Upvotes: 1 <issue_comment>username_2: RSE is an estimate of the standard deviation of the residuals, and therefore also of the observations. Which is why it's equal to RSS/df. And in your case, as a simple linear model df = 2.
MSE is mean squared error observed in your models, and it's usually calculated using a test set to compare the predictive accuracy of your fitted models. Since we're concerned with the mean error of the model, we divide by n.
Upvotes: 4 [selected_answer]
|
2018/03/19
| 519 | 1,850 |
<issue_start>username_0: I want to remove `basket One`div if `basket Two` div is clicked and vice versa.
```js
var basketClass = document.getElementsByClassName("basketClass");
var basketOne = document.getElementById("basketOne");
var basketTwo = document.getElementById("basketTwo");
for (var i = 0; i < basketClass.length; i++) {
basketClass[i].addEventListener('click', function(event) {
if (event.target === basketOne || basketTwo) {
//removeSibling(basketOne||basketTwo);
//want to remove basketone if basketTwo is clicked and vice versa
}
})
};
```
```html
Basket One
Basket Two
```<issue_comment>username_1: I think RSE ⊂ MSE (i.e. RSE is part of MSE).
And MSE = RSS/ degree of freedom
MSE for a single set of data (X1,X2,....Xn) would be RSS over N
or more accurately is RSS/N-1
(since your freedom to vary will be reduced by one when U have used up all the freedom)
But in linear regression concerning X and Y with binomial term, the degree of freedom is affected by both X and Y thus N-2
thus yr MSE = RSS/N-2
and one can also call this RSE
And in over parameterized model, meaning one have a collection of many ßs (more than 2 terms| y~ ß0 + ß1\*X + ß2\*X..), one can even penalize the model by reducing the denominator by including the number of parameters:
MSE= RSS/N-p (p is the number of fitted parameters)
Upvotes: 1 <issue_comment>username_2: RSE is an estimate of the standard deviation of the residuals, and therefore also of the observations. Which is why it's equal to RSS/df. And in your case, as a simple linear model df = 2.
MSE is mean squared error observed in your models, and it's usually calculated using a test set to compare the predictive accuracy of your fitted models. Since we're concerned with the mean error of the model, we divide by n.
Upvotes: 4 [selected_answer]
|
2018/03/19
| 698 | 1,720 |
<issue_start>username_0: How can I replace `NA`s in one column with values from another column (when all values are dates)? I can do it with numbers, but for date values when I try
```
mydata$enddate <- ifelse(!is.na(mydata$End.date.html),
mydata$End.date1,
mydata$End.date2)
```
it changes all dates to unrelated numbers. I am sure there is a way to replace missing dates.<issue_comment>username_1: One way is just to store which values in the column are NA, and then use that vector to query the second column and assign those values back to the first column, like so:
```
invalid.dates <- is.na(mydata$datecol1)
if(any(invalid.dates)) {
mydata$datecol1[invalid.dates] <- mydata$datecol2[invalid.dates]
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Straight from the `ifelse` documentation (`?ifelse`) examples:
```
> ## ifelse() strips attributes
> ## This is important when working with Dates and factors
> x <- seq(as.Date("2000-02-29"), as.Date("2004-10-04"), by = "1 month")
> head(x)
[1] "2000-02-29" "2000-03-29" "2000-04-29" "2000-05-29" "2000-06-29" "2000-07-29"
> ## has many "yyyy-mm-29", but a few "yyyy-03-01" in the non-leap years
> y <- ifelse(as.POSIXlt(x)$mday == 29, x, NA)
> head(y) # not what you expected ... ==> need restore the class attribute:
[1] 11016 11045 11076 11106 11137 11167
> class(y) <- class(x)
> head(y)
[1] "2000-02-29" "2000-03-29" "2000-04-29" "2000-05-29" "2000-06-29" "2000-07-29"
```
Upvotes: 1 <issue_comment>username_3: I would drop the `ifelse` altogether:
```
mydata$enddate<-mydata$End.date1
mydata$enddate[is.na(mydata$End.date1)]<-mydata$End.Date2[is.na(mydata$End.date1)]
```
Upvotes: 0
|
2018/03/19
| 1,460 | 5,061 |
<issue_start>username_0: I have 2 Docker containers using the following configuration:
```
version: '2'
volumes:
db_data: {}
services:
db:
container_name: database-mysql-5.7
build:
context: ./docker/db/
ports:
- "3321:3306"
volumes:
- db_data:/var/lib/mysql
web:
container_name: apache-symfony-4
build:
context: ./docker/web/
image: php
links:
- db
depends_on:
- db
ports:
- "8021:80"
volumes:
- ./app/:/var/www/symfony
```
I can connect to the db container from my local host (Mac OS) and I can connect to the db container (and execute sql statements successfully) from the web container. Additionally, when I exec to the web container I can execute doctrine:migrations:diff commands successfully.
However, when I try and run code like the following:
```
$User = $this->getDoctrine()
->getRepository(User::class)
->findAll();
```
I receive the following error:
```
An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
octrine\DBAL\Exception\ConnectionException:
An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused
at vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:108
at Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException('An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused', object(PDOException))
(vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:176)
at Doctrine\DBAL\DBALException::wrapException(object(Driver), object(PDOException), 'An exception occurred in driver: SQLSTATE[HY000] [2002] Connection refused')
(vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:161)
at Doctrine\DBAL\DBALException::driverException(object(Driver), object(PDOException))
(vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOMySql/Driver.php:47)
```
Here is the contents of my .env file
```
# This file is a "template" of which env vars need to be defined for your application
# Copy this file to .env file for development, create environment variables when deploying to production
# https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=7c2deaf7464ad40b484d457e02a56918
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS=localhost,example.com
###< symfony/framework-bundle ###
###> symfony/swiftmailer-bundle ###
# For Gmail as a transport, use: "gmail://username:password@localhost"
# For a generic SMTP server, use: "smtp://localhost:25?encryption=&auth_mode="
# Delivery is disabled by default via "null://localhost"
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://hereswhatsontap:####@db:####/hereswhatsontap
###< doctrine/doctrine-bundle ###
```
Additionally, if I try and use the DBAL it returns the same error:
```
/**
* @Route("/test")
*/
public function testAction(Connection $connection){
$users = $connection->fetchAll('SELECT * FROM users');
return $this->render("startup/startup.html/twig", [
"NewUser" => $users
]);
}
```
Attempts to use the root username/password are also failing.
Ok, last additional data (I promise :)
Executing the following code works fine from within the /public folder of Symfony
```
php
$dsn = 'mysql:host=db;dbname=hereswhatsontap;';
$username = 'hereswhatsontap';
$password = '####';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND = 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
$sql = "SELECT * from user";
$statement = $dbh->prepare($sql);
$statement->execute();
$users = $statement->fetchAll(2);
print_r($users);
?>
```<issue_comment>username_1: This issue was caused by a full lack of understanding for me on how the containers communicate amongst each other.
The web container and the db container are essentially on their own 'vpn' network which means that the web container can communicate with db directly and would then use the internal port (3306) based on my configuration.
So removing the port (which I had as the external port) from my .env files' DATABASE\_URL value was the answer.
DANG!
Upvotes: 1 <issue_comment>username_2: Thanks a lot for your comment, it saved me some further hours of research lol. I would just add for newbies in Docker like me, that if you want to get your container IP you can run the following command (so that you won't have to look for in the whole configuration dump you get by using only inspect):
```
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' YOURCONTAINERID
```
Thanks again!
Upvotes: 2
|
2018/03/19
| 349 | 1,380 |
<issue_start>username_0: I have a 4 indexes Dataframe and I'd like to know how can I make sure that all combinations of indexes are displayed.
I'm running this to sum :
```
df.sum(level=[0,1,2,3]).unstack(fill_value=0).stack()
```
But its only displaying all possible values of the fourth index for each one of the third one. I'd like this to work also for the first and second indexes (filling empty rows with 0).
Thanks<issue_comment>username_1: This issue was caused by a full lack of understanding for me on how the containers communicate amongst each other.
The web container and the db container are essentially on their own 'vpn' network which means that the web container can communicate with db directly and would then use the internal port (3306) based on my configuration.
So removing the port (which I had as the external port) from my .env files' DATABASE\_URL value was the answer.
DANG!
Upvotes: 1 <issue_comment>username_2: Thanks a lot for your comment, it saved me some further hours of research lol. I would just add for newbies in Docker like me, that if you want to get your container IP you can run the following command (so that you won't have to look for in the whole configuration dump you get by using only inspect):
```
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' YOURCONTAINERID
```
Thanks again!
Upvotes: 2
|
2018/03/19
| 831 | 3,063 |
<issue_start>username_0: I am wanting to dynamically create input field values for each category a user creates, the issue is how can I keep track of what the user enters into the input field. As I cannot create X amount of states as it is dynamic. Any tips would be much appreciated, my code is shown below:
```
var categories = newData.map((category,index) => {
console.log(category)
return (
{category.category}
//How do I keep track of what was entered for this input field??
this.addCategoryLink(category.\_id)}>Add
link
)
})
```<issue_comment>username_1: >
> I am wondering how to bind that to the button element
>
>
>
The React docs have a section related to the core of this question:
<https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers>
Assuming your state holds an array of "categories" objects- essentially, I think what you're looking for boils down to something like this in your map function:
```
{this.state.categories.map(category => (
this.handleCategoryChange(category, event)}
value={category.value}
/>
)}
```
And then a change handler that looks something like this:
```
handleCategoryChange = (category, event) => {
const value = event.currentTarget.value;
this.setState(state => {
// Create a copy of the categories array:
const categories = [...state.categories];
// Create a copy of the category, with an updated value:
categories[category.index] = {
...category,
value
};
// Update state with the new values:
return { categories };
});
};
```
Here's a simple demo:
<https://codesandbox.io/s/woqpwvl777>
Upvotes: 3 [selected_answer]<issue_comment>username_2: i have other Way for doing this , Of course this way just working well in some situation , forExample when you have just 1 or 3 value
i think you wanna create Input , and there Input are dynamic , and you want define that , if user click in first Button , you get and use first TextInput (value)
in my way ( again i say this : this way just well in some situation ) , we Create data Json like this
```
[
{ id: n ,
category: 'some',
value: ''
}
```
in this structure Value key , in the mounting contain nothing or null value if the Value not defined before
for now i create one handler method and this method, called after onChange Event fired on
```
this.getValue(category.id,e)} />
```
that element , this means when user start fill input onChange event handle function and update your state
```
getValue(id,e) {
let thisId = id-1;
let vs = this.state.c;
vs[thisId].value = e.target.value;
this.setState({
c:vs
});
let v = this.state.c[thisId];
console.log(v);
}
```
i create Pen in this address -> <https://codepen.io/hamidrezanikoonia/pen/vRyJRx?editors=1111>
you can check console , for more details ( open console tab in codepen )
and for more details , i create two method , the first fired when input (text) filled ( onChange event ) , and the other fired when clicked on button ( click event )
Upvotes: 1
|
2018/03/19
| 538 | 1,521 |
<issue_start>username_0: I thought initializing an multi dimensional array would be easy:
```
row = Array(4).fill(0)
block = Array(4).fill(row)
block[2][2] = 15
```
but that just creates an array of one row, 4 times, so if I assign block[2][2] = 15, then the whole column is 15.
```
(4) [Array(4), Array(4), Array(4), Array(4)]
0:(4) [0, 0, 15, 0]
1:(4) [0, 0, 15, 0]
2:(4) [0, 0, 15, 0]
3:(4) [0, 0, 15, 0]
```
I tried `Array(4).fill(Array(4).fill(0))` but had the same result.<issue_comment>username_1: You could write a helper function to initialize your two dimensional array. For example:
```js
const grid = (r, c) => Array(r).fill(null).map(r => Array(c).fill(null));
const g = grid(4, 4);
g[2][2] = 15;
console.log(g);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This was actually quite challenging to solve. I much prefer the accepted answer from username_1 - however I thought I would add another possibility for some variance.
**Pro:** Doesn't obfuscate that you are dealing with an Array (like with the accepted answer).
**Con:** Hard to read.
```js
var row = new Array(4).fill(0)
var block = new Array(4).fill(0).map(v => deepClone(row))
block[2][2] = 15
console.log(block);
function deepClone(array){return JSON.parse(JSON.stringify(array));}
```
How does this work? Well after you fill the array with blank values, `.map` is now able to iterate each and replace the value. In this case, it is a hacky deep clone of row thanks to the trusty ole `JSON.parse`.
Upvotes: 0
|
2018/03/19
| 695 | 2,741 |
<issue_start>username_0: I'm trying to switch a scene using a button which created by Scene Builder.
That is my Controller class
```
public class Controller implements Initializable {
@FXML Button LoginButton;
@FXML private void handleButtonAction(ActionEvent event) throws IOException {
Parent tableViewParent = FXMLLoader.load(getClass().getResource("../FXML/MainMenu.fxml"));
Scene tableViewScene = new Scene(tableViewParent);
Stage window = (Stage) ((Node)event.getSource()).getScene().getWindow();
window.setScene(tableViewScene);
window.show();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
```
And there is FXML
```
```
For some reason IntelliJ shows error Cannot resolve 'handleButtonAction'
>
> `onAction="#handleButtonAction"`
>
>
><issue_comment>username_1: Write below code in your controller
```
@FXML
protected void handleButtonAction() {
System.out.println("In handleButtonAction");
// your logic
}
```
and **FXML file**
```
```
I hope it will work... I used scenebuilder for **FXML**, if not works send me error screenshot
Upvotes: 0 <issue_comment>username_2: You can retrieve the Scene (and the Stage) with any FXML element belonging to it. You only have to do `anyElement.getScene().getWindow()`
```
public class Controller {
@FXML
Button loginButton;
@FXML
private void handleButtonAction() {
Parent tableViewParent = FXMLLoader.load(getClass().getResource("../FXML/MainMenu.fxml"));
Scene tableViewScene = new Scene(tableViewParent);
// Instead of retrieving the stage by the event's source, you can do it by one of your FXML component.
Stage window = (Stage) loginButton.getScene().getWindow();
window.setScene(tableViewScene);
window.show();
}
@FXML
public void initialize() {
//initialize the field you want here.
}
}
```
And the FXML :
```
```
Some explanation/remarks on your code.
- Useless to implements Initializable since JavaFX 8. `initialize` method with FXML annotation is now sufficient (look at the [note in interface definition](https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/Initializable.html)).
- Change the loginButton with a lowercase for the first letter ([Java naming convention](http://www.oracle.com/technetwork/java/codeconventions-135099.html))
- Fabian is right in his comment, you forgot the children starting element for VBox node in your FXML.
- I did not found the loginButton `fx:id` in your FXML. Did you forget it ? I added it in `Button` element in the FXML. (I do not know if it was effectively the loginButton...)
Upvotes: 3 [selected_answer]
|
2018/03/19
| 892 | 3,200 |
<issue_start>username_0: I'm trying to remove the event listener that I've added to my `UL`; so that the listener function will only fire on the first click and will be cleared after that.
Is there a way to do this with pure js?
```
var cardDeck = document.getElementById('listDeck').getElementsByTagName('li')
for (var i = 0; i < cardDeck.length; i++) {
cardDeck[i].addEventListener('click', flip, false)
}
function flip(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log(e.target.id + 'card was clicked');
}
}
```<issue_comment>username_1: You could bind to the `onclick` method instead of using the `addEventListener`. Thus, after the click is performed just set `onclick` to `null`:
```
var cardDeck = document.getElementById('listDeck').getElementsByTagName('li')
for (var i = 0; i < cardDeck.length; i++) {
cardDeck[i].onclick = flip.bind(cardDeck[i])
}
function flip(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log(e.target.id + 'card was clicked');
this.onclick = null;
}
}
```
Upvotes: 0 <issue_comment>username_2: If you added an event handler via `addEventListener`, you can remove it using:
```
element.removeEventListener(event, function);
```
This allows you to selectively remove event handlers and not remove any other handlers that may have been registered.
```
function flip(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id);
firstMove.classList.add('open', 'show');
console.log(e.target.id + 'card was clicked');
e.currentarget.removeEventListener('click', flip);
}
}
```
Upvotes: 0 <issue_comment>username_3: If you want to remove an event listener when it is called, you can use the `removeEventListener` on the DOM element like so :
```js
var cardDeck = document.getElementById('listDeck').getElementsByTagName('li')
for (var i = 0; i < cardDeck.length; i++) {
cardDeck[i].addEventListener('click', flip, false)
}
function flip(e) {
//remove the event listener.
this.removeEventListener("click",flip);
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log(e.target.id + 'card was clicked');
}
}
```
Upvotes: 0 <issue_comment>username_4: Just add option of {Once :true} to event listener. No need to write a code for it.Just try these
```
cardDeck[i].addEventListener('click', flip, {once:true} )
```
Here's the jsfiddle [link](https://jsfiddle.net/oum0c7jn/6/)
Reference link for this.[Here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
PS:
The way you are adding evenListener to every element is not efficient. Use delegation instead of bubbling if possible for your use case.Here's fiddle for [delegation](https://jsfiddle.net/jm1x4755/)
Upvotes: 3 [selected_answer]
|
2018/03/19
| 862 | 3,162 |
<issue_start>username_0: I'm trying to get data from my database and after obtaining a piece of data, using that piece of data to find a new piece of data.
At the end, I can piece these together and return the derived data. I'm not sure this is the best way to approach this, but this is where im at as of now.
My problem is that each call to the database (Firebase) is async and therefore I need to somehow wait for the async to finish, before going on.
I've looked at dispatch group and heres what I have so far:
```
let taskGroup = DispatchGroup()
for buildingKey in building.allKeys
{
var aprt = NSDictionary()
taskGroup.enter()
// ASYNC REQUEST
getAbodesWithUID(UID: buildingKey as! String, callback: { (success, abodes) in
aprt = abodes
taskGroup.leave()
})
taskGroup.enter()
for key in aprt.allKeys
{
// ASYNC REQUEST
getTenantsWithAprt(UID: key as! String, callback: { (success, user) in
for userKey in user.allKeys
{
let dict = NSMutableDictionary()
dict.setValue(((building[buildingKey] as? NSDictionary)?["Address"] as? NSDictionary)?.allKeys[0] as? String, forKey: "Building")
dict.setValue((user[userKey] as? NSDictionary)?["Aprt"], forKey: "Number")
dict.setValue((user[userKey] as? NSDictionary)?["Name"], forKey: "Name")
dict.setValue(userKey, forKey: "UID")
dict.setValue((user[userKey] as? NSDictionary)?["PhoneNumber"], forKey: "Phone")
apartments.append(dict)
}
taskGroup.leave()
})
}
}
taskGroup.notify(queue: DispatchQueue.main, execute: {
print("DONE")
callback(true, apartments)
})
```
I can't seem to get it to callback properly<issue_comment>username_1: First, you should be iterating over `aprt.allKeys` inside of the callback for `getAbodesWithUID`, other wise, when the for loop executes `aprt` will be an empty dictionary.
Secondly, the `taskGroup.enter()` call above that for loop should be inside of the for loop, because it needs to be called once for every key. It should be placed where the `// ASYNC REQUEST` comment currently is.
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is precisely what "promises" are for is for. They are available in Swift via a 3rd party add-in. A popular way to do this is to push all your reads/gets into an array. Then you promise.all(yourArray) which returns the array of results/values that you then iterate over to get at each one.
From [this other answer](https://stackoverflow.com/questions/43700548/swift-promisekit-resolving-all-promises-from-a-loop):
>
> You can look into when which may provide what you need and is covered
> [here](http://promisekit.org/docs/handbook/Functions.html#/s:F10PromiseKit4whenurFT9fulfilledGSaGCS_7Promisex___GS0_GSax__).
>
>
> Use the loop to put your promises into an array and then do something
> like this:
>
>
>
> ```
> when(fulfilled: promiseArray).then { results in
> // Do something
> }.catch { error in
> // Handle error
> }
>
> ```
>
>
Upvotes: 0
|
2018/03/19
| 530 | 1,862 |
<issue_start>username_0: I have hundreds of excel files and I want to create a df that has the name of the excel file in one column and then the name of each tab in the second column. My script will iterate through each file name but the way I am appending is not right, and I'm not having much luck finding a solution.
```
os.chdir(r'C:\Users\mbobak\Documents\\')
FileList = glob.glob('*.xlsx')
tabs= pd.DataFrame(columns=['filename','tabs'])
for filename in FileList:
xl = pd.ExcelFile(filename).sheet_names
tabs= tabs.append([filename,xl])
```
desired output:
```
filename tabs
doc1.xlsx tab1
doc1.xlsx tab2
doc1.xlsx tab3
doc1.xlsx tab4
doc2.xlsx tab1
doc2.xlsx tab2
doc2.xlsx tab3
```<issue_comment>username_1: Here is one way. It is good practice, and efficient, to create your dataframe in a single step. This is because appending to a list is cheaper than appending to a dataframe.
```
FileList = glob.glob('*.xlsx')
def return_files_tabs(FileList):
for filename in FileList:
for sheet in pd.ExcelFile(filename).sheet_names:
yield [filename, sheet]
df = pd.DataFrame(list(return_files_tabs(FileList)),
columns=['Filename', 'Tab'])
```
**Explanation**
* Cycle through each file and each sheet within `sheet_names` attribute.
* Yield filename and sheet via a generator.
* Build dataframe from list of exhausted generator, name columns.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I like @username_1's answer but if you don't want to use a generator this is how I would do it:
```
FileList = glob.glob('*.xlsx')
filenames = []
sheets = []
for filename in FileList:
for sheet in pd.ExcelFile(filename).sheet_names:
filenames.append(filename)
sheets.append(sheet)
df = pd.DataFrame(
{'Filename': filenames, 'Tab': sheets}
)
```
Upvotes: 2
|
2018/03/19
| 1,425 | 5,826 |
<issue_start>username_0: I created a dialog with three buttons, where the third should save a Word document (Office Pro Plus 2013, BTW) as a PDF file.
```vb
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
With Dialogs(wdDialogFileSaveAs)
.Format = wdFormatPDF
' .Format = 17 '17 = PDF
.Show
End With
Options.PrintDrawingObjects = Grafik
End Sub
```
If the PDF exists I can choose to overwrite it, which does work in most cases.
If the PDF to be overwritten is already open, in Adobe Reader for instance, then the file isn't saved, as it is locked. I don't get any notification that the file is locked.
How can I catch this and pop up the same message that I get when saving manually within Word?
EDIT:
To explain why my question is different to others that have been answered:
I don't need to check if the file is open in Word already. I'm saving the file as a PDF not as a Word file.
I need to check if the file is open and locked in any other application, such as **Adobe Reader**, **Edge** or whatever.
This check is done by Word (and/or the OS?) already, and **THIS** is the event I need to catch. I don't understand why I need to catch it at all, as the result of the check if the file does exist does come up, but the result of the check if the file is locked seems to be ignored.
The VBA code behaves as if the file has been saved, but it is not, if locked by any application other than Word.
I have no clue which code snippet exactly I would need to grab from [Detect whether Excel workbook is already open](https://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open)<issue_comment>username_1: Here is what you might be looking for:
```
Sub SaveAsPdf()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
fDialog.Title = "Save a file"
'works only in Word2016 not in word 2013;
'fDialog.InitialFileName = "*.pdf"
'we can use the filterindex property instead
fDialog.FilterIndex = 7
If fDialog.Show = -1 Then
Dim selectedFilePath As String
selectedFilePath = fDialog.SelectedItems(1)
If IsFileInUse(selectedFilePath) Then
MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the pdf file and try again.", vbExclamation
Else
ActiveDocument.SaveAs2 selectedFilePath, wdFormatPDF
End If
End If
Options.PrintDrawingObjects = Grafik
End Sub
Private Function IsFileInUse(ByVal filePath As String) As Boolean
On Error Resume Next
Open filePath For Binary Access Read Lock Read As #1
Close #1
IsFileInUse = IIf(Err.Number > 0, True, False)
On Error GoTo 0
End Function
```
If you would like to use wdDialogFileSaveAs dialog, you can try the below code:
The Display method will display the dialog box without executing the actual functionality. You can validate the result of the display to identify the button clicked and use the execute method to execute the actual functionality.
```
'Save As Pdf using wdDialogFileSaveAs dialog
'However, it doesn't work as expected.
'The Display method should
Sub SaveAsPdf()
Dim dlg As Dialog
Dim dlgResult As Long
Set dlg = Dialogs(wdDialogFileSaveAs)
With dlg
.Format = wdFormatPDF
dlgResult = .Display
If dlgResult = -1 Then 'user clicks save button;
If .Name <> "" Then
If IsFileInUse(.Name) Then
MsgBox "The target pdf file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the pdf file and try again.", vbExclamation
Else
.Execute
End If
End If
End If
End With
End Sub
```
Please note that, the above code (wdDialogFileSaveAs dialog) doesn't work as expected in Word 2016 at least in my local enviornment. The Display method executes the actual functionality once the save button is clicked. Also it returns -2 as a dialog result if Save button is clicked.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Thanks to the help of @username_1 (see answer and comments above), this is the full currently working code (unless I'd still find any flaws):
```
Private Sub Button_Dokument_mit_Grafik_als_PDF_speichern_Click()
Dim Grafik As Boolean
Grafik = Options.PrintDrawingObjects
Options.PrintDrawingObjects = True
Dim dlg As Dialog
Dim dlgResult As Long
Set dlg = Dialogs(wdDialogFileSaveAs)
With dlg
.Format = wdFormatPDF
dlgResult = .Display
If dlgResult = -1 Then 'user clicked save button
If .Name <> "" Then
If IsFileInUse(.Name) Then
MsgBox "The target PDF file you are trying to save is locked or used by other application." & vbCrLf & _
"Please close the PDF file and try again.", vbExclamation
Else
.Execute
End If
End If
End If
End With
Options.PrintDrawingObjects = Grafik
End Sub
Private Function IsFileInUse(ByVal filePath As String) As Boolean
On Error Resume Next
Open filePath For Binary Access Read Lock Read As #1
Close #1
IsFileInUse = IIf(Err.Number > 0, True, False)
On Error GoTo 0
End Function
```
Thanks to @username_1 again. :)
You may want to edit your answer, though, so that it does reflect the finally working code. I've given appropriate thanks.
Upvotes: 0
|
2018/03/19
| 448 | 1,625 |
<issue_start>username_0: The WebSocket has the option to add a headers to the request but you can't add a SecurityContext to it. The SecureSocket has the SecurityContext so I can add the ssl certs but can't add headers. Any idea on this?
**UPDATE:**
I'm trying to create a websocket with a SecurityContext object
As I don't have access to the underling HttpClient I've tried to use the
runZoned method
```
int i = 0;
socket = await io.HttpOverrides.runZoned>(
() => io.WebSocket.connect(uri, headers: headers),
createHttpClient: (io.SecurityContext securityContext) {
log.w('creating HttpClient ${i++}');
return new io.HttpClient(context: options.securityContext);
},
);
```
the createHttpClient is called some 3550 times
and then nothing happens
It should be very simple because the websocket httpclient just lays there
<https://github.com/dart-lang/sdk/blob/dcd275fa74ee5cfa86bb115fc67f0ccf6248fd7f/sdk/lib/_http/websocket_impl.dart#L981><issue_comment>username_1: The solution would be to pass a `SecureSocket` to create a `WebSocket`.
Example:
```
SecureSocket socket = await SecureSocket.connect("host", port);
WebSocket ws = new WebSocket.fromUpgradedSocket(socket);
```
Hope that helps!
Upvotes: 0 <issue_comment>username_2: try this
```
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext context) {
return super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}
// Run this code in main function
HttpOverrides.global = new MyHttpOverrides();
```
Upvotes: 2
|
2018/03/19
| 652 | 2,124 |
<issue_start>username_0: I need help. I'm a complete beginner and I can't find solution anywhere, so sorry if it was already asked, but no matter what I tried I couldn't display background image on one page.
**What I want to do?**
Display the background image on home page.
**Notes:**
* I didn't have assets folder by default.
* Trying on Localhost:4200
* Going to Localhost:4200/assets/images/bg.jpg in browser displays the picture.
* If I put an online hosted image in url(), everything works.
---
Since there was no assets folder in my root, I created one in src folder.
**Structure:**
```
► node_modules
▼ src
▼ app
▼ components
▼ home
home.component.html
home.component.scss
home.component.spec.ts
home.component.ts
▼ assets
▼ images
▼ bg.jpg
```
---
**.angular-cli.json**
```
"assets": [
"assets",
"images",
"favicon.ico"
],
```
---
**home.component.scss**
```
.homeBg {
background-image: url('../../../assets/images/bg.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
width: 100vw;
height: 100vh;
}
```
---
Can someone please help me and tell me what I did wrong? I'm losing my mind for almost 3 hours trying to figure this out.
Thanks in advance.<issue_comment>username_1: Solved [here](https://stackoverflow.com/a/11421058/1116276).
>
> This is because you've also specified "no-repeat" along with your
> background image. Alter your code to:
>
>
>
> ```
> background: url('../../../assets/images/bg.jpg') no-repeat center center fixed;
>
> ```
>
>
Thanks [@Mike Lun](https://stackoverflow.com/users/2394409/mike-lunn) for reminding me to check the actual error.
Upvotes: 2 <issue_comment>username_2: For those who are working with Ionic you need to set the background property this way:
```
ion-content {
--background: url("/assets/images/my-background.jpeg") no-repeat center center /
cover;
}
```
That two dashes before the background worked for me
Upvotes: 0
|
2018/03/19
| 1,077 | 3,555 |
<issue_start>username_0: If I call the filter function, I get this array returned [ 1, , 3, , 5 ]. From where come the additional commas? I don't understand this effect. Can somebody explain it to me?
The array should be that: [ 1, 3, 5 ].
```js
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
let newList = new Array();
let indexList = 0;
let indexNewList = 0;
while (this._list[indexList] != undefined) {
if (func(this._list[indexList]) === true) {
newList[indexNewList] = this._list[indexList];
indexNewList++;
}
indexList++;
}
this._list = newList;
return this;
}
get values() { return this._list }
}
var isOdd = function (x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd).values);
```<issue_comment>username_1: If an item in the list matches the filter, you're inserting it into the new list at the index of the item in the *original list*. You want to simply be appending the item to the new list.
Use another variable to keep track of what index the element should be inserted into the new list at:
```
let newList = new Array();
let indexList = 0;
let newIndex = 0;
while (this._list[indexList] != undefined) {
if (func(this._list[indexList]) === true) {
newList[newIndex] = this._list[indexList];
newIndex++;
}
indexList++;
}
```
The `newIndex` variable will only be incremented when an item has been inserted into `newList`, instead of being incremented with every iteration of the loop.
Upvotes: 2 [selected_answer]<issue_comment>username_2: The problem is the increment of the variable `index`, that increment is creating empty/undefined elements.
**For example:**
* `Array = [1];`
* `index = 1`
* callback returns `false`
* The index is incremented by `1` `->` `index =`2`
* Next iteration callback returns `true`
* A new element is added to `Array` at position `2` `->`
* `Array = [1, undefined, 3]`.
Use a separated index for the newArray.
```js
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
let newList = new Array();
let index = 0;
let newListIndex = 0;
while (this._list[index] != undefined) {
if (func(this._list[index]) === true) {
newList[newListIndex++] = (this._list[index]);
}
index++;
}
this._list = newList;
return this;
}
get values() {
return this._list
}
}
var isOdd = function(x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd));
```
Upvotes: 0 <issue_comment>username_3: I would suggest sticking with a functional-programming style definition of array#filter since that is the paradigm it originates from.
This is the fully immutable version of List#filter where you get a new instance of List back and the underlying array never goes through any form of mutation.
```js
class List {
constructor(values = []) {
this._list = values;
}
filter(func) {
var reduce = function(values, accum) {
if(values.length === 0) return accum;
if(func(values[0])) return reduce(values.slice(1), accum.concat(values[0]));
else return reduce(values.slice(1), accum)
}
return new List(reduce(this._list, []))
}
get values() {
return this._list
}
}
var isOdd = function(x) {
return x % 2 === 1;
};
var list = new List([1, 2, 3, 4, 5]);
console.log(list.filter(isOdd));
```
Upvotes: 0
|
2018/03/19
| 1,054 | 3,994 |
<issue_start>username_0: im newbie on android. I need to send data from ListView with customAdapter to detailActivity that show detail's item from selected item of listView. I have seen a few post about it and i still confuse about it.
Would you help me?
This is my data class :
public class ListData {
```
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
```
}
This is my arrayList declaration :
```
ArrayList data = new ArrayList();
data.add(new ListData("<NAME>", "Telkom University"));
```
I don't have idea, how i can send my arraylist data to another activity. Please help me :) give me some example too :) Thanks<issue_comment>username_1: You need to make your base object, ListData parcelable:
```
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
@Override
public int describeContents() {
return 0;
}
public ListData(Parcel source) {
title = source.readString();
desc = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(desc);
}
public static final Creator CREATOR = new Creator(){
@Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
@Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
```
Once it is parcelable you can simply do in the first activity:
```
ArrayList data = new ArrayList();
data.add(new ListData("<NAME>", "Telkom University"));
intent.putParcelableArrayListExtra("ARRAY\_LIST", data);
```
And you can read it in the other activity as:
```
ArrayList data = (ArrayList) getIntent().getExtras().getParcelableArrayList("ARRAY\_LIST");
```
**EDIT:**
```
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterViewadapter,View v, int position){
ListData item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,DetailActivity.class);
intent.putExtra("ARRAY_ITEM", item);
startActivity(intent);
}
});
```
Then in the destination activity:
```
ListData data = (ListData) getIntent().getExtras().getParcelable("ARRAY_ITEM");
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First step: ListData implements Parcelable:
```
public class ListData implements Parcelable {
private String title;
private String desc;
public ListData(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.desc);
}
protected ListData(Parcel in) {
this.title = in.readString();
this.desc = in.readString();
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public ListData createFromParcel(Parcel source) {
return new ListData(source);
}
@Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
```
}
Second step:send data:
```
ArrayList data = new ArrayList();
data.add(new ListData("<NAME>", "Telkom University"));
Intent intent = new Intent(this, TargetActivity.class);
intent.putParcelableArrayListExtra("data",data);
```
Third step:receive data
```
ArrayList data = intent.getParcelableArrayListExtra("data");
```
Upvotes: 0
|
2018/03/19
| 475 | 1,534 |
<issue_start>username_0: Using the `text-right` class on my form labels, when going responsive, I want the label to left align so it's top-left instead of top-right, however the change to `text-align:left` does not appear to take effect.
```css
@media (max-width: 767px) {
.form-group > label.text-right {
text-align: left;
color: red;
}
}
```
```html
Label
```<issue_comment>username_1: **Note: The accepted answer is best for Bootstrap 4, but the following will work for Bootstrap 3**
That's become `!important` is set on `.text-right`
You can also set `!important`. I might suggest not using the `.text-right` class and maybe make your own. Using `!important` to override another `!important` makes me cringe. I wouldn't recommend it, and I would recommend using `!important` as infrequently as possible. I can understand why Bootstrap uses it here, though.
I'll give you two options.
Here's what you could do:
```css
@media (max-width: 767px) {
.form-group > label.text-right {
text-align: left !important;
color: red;
}
}
```
```html
Label
```
Here's what I suggest doing:
```css
@media (max-width: 767px) {
.form-group > label.align-label {
text-align: left;
color: red;
}
}
```
```html
Label
```
Upvotes: 2 <issue_comment>username_2: Bootstrap's text alignment classes are *responsive*. You **don't need any extra CSS**.
Use **`text-sm-right text-left`**...
```
Label
```
Demo: <https://www.codeply.com/go/djMd492DHA>
Upvotes: 4 [selected_answer]
|
2018/03/19
| 2,669 | 5,964 |
<issue_start>username_0: I want to merge a nested list of dictionaries to single list of a dictionary in python 2.6,
Example data - Here is given only two iterations of thousands of iterations.
```
INPUTJSON=[
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-12 12:11:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'},
{'LASTOCCURED': '2018-03-12 12:11:42', 'COUNT': 10, 'NAME': 'SRV0145GH'}
],
'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10},
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-13 12:14:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'},
{'LASTOCCURED': '2018-03-18 12:55:23', 'COUNT': 10, 'NAME': 'SRV0145GH'}
],
'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}
]
```
**EXPECTED RESULT:**
```
[
{'JVM_NAME':'TestiingAWS01','GCCOUNT':10, 'LASTOCCURED': '2018-03-12 12:11:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-12 12:11:42', 'COUNT': 10, 'NAME': 'SRV0145GH', 'JVM_NAME':'TestiingAWS01','GCCOUNT':10},
{'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'LASTOCCURED': '2018-03-13 12:14:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-18 12:55:23', 'COUNT': 10, 'NAME': 'SRV0145GH', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}
]
```
Requesting experts to help me to achieve this so that I could process the final data to sqlite easily.
**UPDATE:** Thanks, all experts for prompt solutions, consolidating from all answers here I've got a working code for my data by avoiding hardcode "keys" (as there would be 40 keys on each iteration) on python 2.6.
```
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
resultlist =[]
for i,v in enumerate(INPUTJSON):
EXCEPTIONS = v["EXCEPTIONS"]
del v["EXCEPTIONS"]
for j,val in enumerate(EXCEPTIONS):
resultlist.append(merge_two_dicts(EXCEPTIONS[j],INPUTJSON[i]))
print resultlist
```
>
> ***Can it be compiled in comprehension list using lambda?***
>
>
><issue_comment>username_1: You can try this:
```
INPUTJSON=[
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-12 12:11:23', 'COUNT': 25, 'NAME':
'CLFRW0134W'},
{'LASTOCCURED': '2018-03-12 12:11:42', 'COUNT': 10, 'NAME':
'SRV0145GH'}
],
'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10},
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-13 12:14:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'},
{'LASTOCCURED': '2018-03-18 12:55:23', 'COUNT': 10, 'NAME': 'SRV0145GH'}
],
'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}
]
new_result = [i for b in [[dict([('JVM_NAME', i['JVM_NAME']), ('GCCOUNT', i['GCCOUNT'])]+b.items()) for b in i['EXCEPTIONS']] for i in INPUTJSON] for i in b]
```
Output:
```
[{'LASTOCCURED': '2018-03-12 12:11:23', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10, 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-12 12:11:42', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10, 'COUNT': 10, 'NAME': 'SRV0145GH'}, {'LASTOCCURED': '2018-03-13 12:14:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-18 12:55:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'COUNT': 10, 'NAME': 'SRV0145GH'}]
```
Note, however, that this problem is simpler in Python3 when utilizing unpacking:
```
final_result = [i for b in [[{**{a:b for a, b in i.items() if a != 'EXCEPTIONS'}, **c} for c in i['EXCEPTIONS']] for i in INPUTJSON] for i in b]
```
Output:
```
[{'LASTOCCURED': '2018-03-12 12:11:23', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10, 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-12 12:11:42', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10, 'COUNT': 10, 'NAME': 'SRV0145GH'}, {'LASTOCCURED': '2018-03-13 12:14:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-18 12:55:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'COUNT': 10, 'NAME': 'SRV0145GH'}]
```
Upvotes: 1 <issue_comment>username_2: Here is one way.
```
lst = [{**{'JVM_NAME': i['JVM_NAME'], 'GCCOUNT': i['GCCOUNT'], **w}} \
for i in INPUTJSON for w in i['EXCEPTIONS']]
```
For the `**` syntax, see [How to merge two dictionaries in a single expression?](https://stackoverflow.com/questions/38987/how-to-merge-two-dictionaries-in-a-single-expression)
**Result**
```
[{'COUNT': 25,
'GCCOUNT': 10,
'JVM_NAME': 'TestiingAWS01',
'LASTOCCURED': '2018-03-12 12:11:23',
'NAME': 'CLFRW0134W'},
{'COUNT': 10,
'GCCOUNT': 10,
'JVM_NAME': 'TestiingAWS01',
'LASTOCCURED': '2018-03-12 12:11:42',
'NAME': 'SRV0145GH'},
{'COUNT': 25,
'GCCOUNT': 10,
'JVM_NAME': 'QAAWS02',
'LASTOCCURED': '2018-03-13 12:14:23',
'NAME': 'CLFRW0134W'},
{'COUNT': 10,
'GCCOUNT': 10,
'JVM_NAME': 'QAAWS02',
'LASTOCCURED': '2018-03-18 12:55:23',
'NAME': 'SRV0145GH'}]
```
Upvotes: 2 <issue_comment>username_3: ```
data = list()
for item in INPUTJSON:
EXCEPTIONS = item["EXCEPTIONS"]
del item["EXCEPTIONS"]
for ex in EXCEPTIONS:
tmp = dict()
tmp.update(ex)
tmp.update(item)
data.append(tmp)
print data
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: You can try:
```
final_one=[]
for i in data:
final=[]
temp={}
for m,n in i.items():
if not isinstance(n,list):
temp[m]=n
else:
final+=n
for h in final:
h.update(temp)
final_one+=final
print(final_one)
```
output:
```
[{'COUNT': 25, 'NAME': 'CLFRW0134W', 'LASTOCCURED': '2018-03-12 12:11:23', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10}, {'COUNT': 10, 'NAME': 'SRV0145GH', 'LASTOCCURED': '2018-03-12 12:11:42', 'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10}, {'COUNT': 25, 'NAME': 'CLFRW0134W', 'LASTOCCURED': '2018-03-13 12:14:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}, {'COUNT': 10, 'NAME': 'SRV0145GH', 'LASTOCCURED': '2018-03-18 12:55:23', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}]
```
Upvotes: 1
|
2018/03/19
| 4,594 | 9,070 |
<issue_start>username_0: I have a time series for stock prices. The data isn't always continuous, some days are missing. I'd like to fill in these days with the previous value. How can I do that efficiently?
There may be over a thousand markets with 1000+ days of data. Each day has an object of timestamps and pricing.
I want to do things like get the prices for every market on a particular day and sort them.
I'm not sure if it's better to fill in all the missing days by inserting timestamps and prices where needed? (It expands the memory usage but probably faster for data access - I don't know how much memory this needs to be honest. 1000 markets, 1000 days, with 6 object keys. If a number is 8 bytes then that's about 43Mb + whatever object overheads there are?).
**Or** to try return the previous match which would require searching every array for the matching timestamp. This seems expensive if I want to do this for every day of the data.
[Sample data set (jsbin)](http://jsbin.com/honijicodu/edit?html,js,console,output)
```js
let data = {
"name": "MARKET",
"values": [{
"time": 1440338400000,
"close": 0.142163,
"high": 0.152869,
"low": 0.142163,
"open": 0.152221,
"volume": 14.2163,
"marketCap": 0
}, {
"time": 1440511200000,
"close": 0.158082,
"high": 0.161828,
"low": 0.15139,
"open": 0.154371,
"volume": 441.882,
"marketCap": 0
}, {
"time": 1440597600000,
"close": 0.162958,
"high": 0.165483,
"low": 0.15688,
"open": 0.158235,
"volume": 335.53,
"marketCap": 0
}, {
"time": 1440684000000,
"close": 0.16487,
"high": 0.167594,
"low": 0.160171,
"open": 0.162908,
"volume": 492.134,
"marketCap": 0
}, {
"time": 1440770400000,
"close": 0.162612,
"high": 0.166171,
"low": 0.162327,
"open": 0.164979,
"volume": 81.1436,
"marketCap": 0
}, {
"time": 1440856800000,
"close": 0.156701,
"high": 0.161385,
"low": 0.155568,
"open": 0.161316,
"volume": 514.921,
"marketCap": 0
}, {
"time": 1440943200000,
"close": 0.144589,
"high": 0.157018,
"low": 0.141987,
"open": 0.156943,
"volume": 635.154,
"marketCap": 0
}, {
"time": 1441029600000,
"close": 0.145655,
"high": 0.146195,
"low": 0.142581,
"open": 0.144715,
"volume": 10.1958,
"marketCap": 0
}, {
"time": 1441116000000,
"close": 0.142958,
"high": 0.146204,
"low": 0.142701,
"open": 0.145595,
"volume": 0.544275,
"marketCap": 0
}, {
"time": 1441202400000,
"close": 0.148987,
"high": 0.148987,
"low": 0.141326,
"open": 0.142983,
"volume": 58.1051,
"marketCap": 0
}, {
"time": 1441288800000,
"close": 0.15025,
"high": 0.150856,
"low": 0.148987,
"open": 0.148987,
"volume": 34.4072,
"marketCap": 0
}, {
"time": 1441375200000,
"close": 0.155935,
"high": 0.156681,
"low": 0.15228,
"open": 0.152503,
"volume": 0.155935,
"marketCap": 0
}, {
"time": 1441461600000,
"close": 0.159049,
"high": 0.160032,
"low": 0.155711,
"open": 0.155836,
"volume": 0.159049,
"marketCap": 0
}, {
"time": 1441634400000,
"close": 0.163826,
"high": 0.16474,
"low": 0.162861,
"open": 0.164304,
"volume": 327.651,
"marketCap": 0
}, {
"time": 1441720800000,
"close": 0.124591,
"high": 0.16437,
"low": 0.124427,
"open": 0.163697,
"volume": 1558.32,
"marketCap": 0
}, {
"time": 1441807200000,
"close": 0.115118,
"high": 0.125665,
"low": 0.115,
"open": 0.124679,
"volume": 110.436,
"marketCap": 0
}, {
"time": 1441893600000,
"close": 0.10203,
"high": 0.115274,
"low": 0.101593,
"open": 0.115047,
"volume": 1795.72,
"marketCap": 0
}, {
"time": 1441980000000,
"close": 0.101996,
"high": 0.102003,
"low": 0.101886,
"open": 0.102003,
"volume": 1795.14,
"marketCap": 0
}, {
"time": 1442066400000,
"close": 0.104842,
"high": 0.106246,
"low": 0.104305,
"open": 0.106246,
"volume": 2.09684,
"marketCap": 0
}, {
"time": 1442152800000,
"close": 0.105386,
"high": 0.106185,
"low": 0.103682,
"open": 0.104886,
"volume": 2192.04,
"marketCap": 0
}, {
"time": 1442239200000,
"close": 0.102747,
"high": 0.114521,
"low": 0.102498,
"open": 0.105317,
"volume": 21.0632,
"marketCap": 0
}, {
"time": 1442325600000,
"close": 0.0736399,
"high": 0.105086,
"low": 0.0697372,
"open": 0.102713,
"volume": 863.28,
"marketCap": 0
}, {
"time": 1442412000000,
"close": 0.0805882,
"high": 0.0805882,
"low": 0.0736,
"open": 0.073644,
"volume": 79.9028,
"marketCap": 0
}, {
"time": 1442498400000,
"close": 0.0882002,
"high": 0.0885284,
"low": 0.0805882,
"open": 0.0805882,
"volume": 52.9201,
"marketCap": 0
}, {
"time": 1442584800000,
"close": 0.102387,
"high": 0.102535,
"low": 0.0878508,
"open": 0.0881813,
"volume": 738.121,
"marketCap": 0
}, {
"time": 1442671200000,
"close": 0.102663,
"high": 0.10276,
"low": 0.102129,
"open": 0.102387,
"volume": 10.2663,
"marketCap": 0
}, {
"time": 1442757600000,
"close": 0.104525,
"high": 0.106224,
"low": 0.104265,
"open": 0.106224,
"volume": 72.0357,
"marketCap": 0
}, {
"time": 1442844000000,
"close": 0.109941,
"high": 0.110287,
"low": 0.104422,
"open": 0.104472,
"volume": 5.49706,
"marketCap": 0
}, {
"time": 1442930400000,
"close": 0.109915,
"high": 0.110532,
"low": 0.109467,
"open": 0.110108,
"volume": 5.49574,
"marketCap": 0
}, {
"time": 1443016800000,
"close": 0.115694,
"high": 0.116243,
"low": 0.113882,
"open": 0.114151,
"volume": 23.1389,
"marketCap": 0
}, {
"time": 1443103200000,
"close": 0.116584,
"high": 0.116939,
"low": 0.115274,
"open": 0.115608,
"volume": 23.3168,
"marketCap": 0
}, {
"time": 1443189600000,
"close": 0.119464,
"high": 0.119717,
"low": 0.118964,
"open": 0.119519,
"volume": 11.9464,
"marketCap": 0
}, {
"time": 1443276000000,
"close": 0.122498,
"high": 0.122824,
"low": 0.118839,
"open": 0.119362,
"volume": 12.2498,
"marketCap": 0
}, {
"time": 1443362400000,
"close": 0.125336,
"high": 0.125755,
"low": 0.122345,
"open": 0.122539,
"volume": 12.5336,
"marketCap": 0
}, {
"time": 1443535200000,
"close": 0.118549,
"high": 0.119365,
"low": 0.118333,
"open": 0.119131,
"volume": 1460.31,
"marketCap": 0
}, {
"time": 1443621600000,
"close": 0.120841,
"high": 0.121297,
"low": 0.118471,
"open": 0.118521,
"volume": 12.0841,
"marketCap": 0
}, {
"time": 1443708000000,
"close": 0.121266,
"high": 0.121307,
"low": 0.120696,
"open": 0.120696,
"volume": 12.1266,
"marketCap": 0
}, {
"time": 1444053600000,
"close": 0.124926,
"high": 0.125369,
"low": 0.122085,
"open": 0.122188,
"volume": 0.249852,
"marketCap": 0
}, {
"time": 1444140000000,
"close": 0.124018,
"high": 0.12524,
"low": 0.124018,
"open": 0.124926,
"volume": 0.248037,
"marketCap": 0
}, {
"time": 1444312800000,
"close": 0.127015,
"high": 0.12717,
"low": 0.126854,
"open": 0.127056,
"volume": 269.89,
"marketCap": 0
}, {
"time": 1444399200000,
"close": 0.129375,
"high": 0.129437,
"low": 0.126736,
"open": 0.126915,
"volume": 12.9375,
"marketCap": 0
}, {
"time": 1444485600000,
"close": 0.129097,
"high": 0.129523,
"low": 0.129063,
"open": 0.12927,
"volume": 12.9097,
"marketCap": 0
}]
};
data.values.forEach(value => {
let date = new Date(value.time)
console.log(date.toString())
})
```<issue_comment>username_1: There is an alternate solution for this, Re-Sampling of data.
Have a look <https://content.pivotal.io/blog/time-series-analysis-part-3-resampling-and-interpolation>
Upvotes: 2 [selected_answer]<issue_comment>username_2: My solution will be to loop through the array backward and splice in the missing timeframe data. The data will be a reference to the last value seen which will mean the timestamp will be incorrect, but since intervals are uniform (daily), I can just use the array index to get the correct data I'm after. I assume a reference like this will reduce unneeded duplicate memory usage too.
Upvotes: 0
|
2018/03/19
| 617 | 2,340 |
<issue_start>username_0: `mongo_prefix` looks ideally designed for simple and effective data separation, it seems though you need to pre-define your available prefixes in settings.py. Is it possible to create a new prefix dynamically - for example to create a new instance per user on creation of that user?<issue_comment>username_1: The authentication base class has the `set_mongo_prefix()` method that allows you to set the active db based on the current user. This snippet comes from the [documentation](http://python-eve.org/authentication.html#auth-driven-database-access):
>
> Custom authentication classes can also set the database that should be used when serving the active request.
>
>
>
```
from eve.auth import BasicAuth
class MyBasicAuth(BasicAuth):
def check_auth(self, username, password, allowed_roles, resource, method):
if username == 'user1':
self.set_mongo_prefix('USER1_DB')
elif username == 'user2':
self.set_mongo_prefix('USER2_DB')
else:
# serve all other users from the default db.
self.set_mongo_prefix(None)
return username is not None and password == '<PASSWORD>'
app = Eve(auth=MyBasicAuth)
app.run()
```
The above is, of course, a trivial implementation, but can probably serve a useful starting point. See the above documentation link for the complete breakdown.
Upvotes: 2 <issue_comment>username_2: Ultimately the answer to the question is that your prefixed database will be created for you *with defaults* if you have not first specified the matching values in your settings.py. In cases where you cannot put the values in settings.py (probably because you don't know them at the time) happily you can add them dynamically later; trivial example below.
```
def add_db_to_config(app, config_prefix='MONGO'):
def key(suffix):
return '%s_%s' % (config_prefix, suffix)
if key('DBNAME') in app.config:
return
app.config[key('HOST')] = app.config['MONGO_HOST']
app.config[key('PORT')] = app.config['MONGO_PORT']
app.config[key('DBNAME')] = key('DBNAME')
app.config[key('USERNAME')] = None
app.config[key('PASSWORD')] = None
```
and then later, e.g. in `check_auth(...)`:
```
add_db_to_config(app, 'user_x_db')
self.set_mongo_prefix('user_x_db')
```
Upvotes: 1
|
2018/03/19
| 2,244 | 7,583 |
<issue_start>username_0: I'm looking to see if there is a better way in obtaining the same result as the following code:
```
Calendar date = Calendar.getInstance();
date.setTimeInMillis(System.currentTimeMillis());
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
```
I'm using this to be able to compare the difference in days between two dates. I am currently coding for target API 24 and am not interested in using Joda Time for such a simple task.
I've come up with the following function, but would love to hear if there is a simpler, perhaps built in, method for either zeroing out the date or an entire different method for getting the amount of days between two dates.
```
private long getFlatDateInMillis() {
Calendar currentDate = Calendar.getInstance();
currentDate.setTimeInMillis(System.currentTimeMillis());
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.MILLISECOND, 0);
return currentDate.getTimeInMillis();
}
```
That way, I could quickly use:
```
Calendar date = getFlatDateInMillis();
```
I just want to make sure I'm not missing anything that is simpler, already pre-defined.
Thank you!<issue_comment>username_1: **EDIT:** Thanks to Basil and Kareem, I've updated to the following code (so, so much easier):
Added to gradle.build:
```
compile 'com.jakewharton.threetenabp:threetenabp:1.0.5'
```
Then, in my activity, etc,
```
AndroidThreeTen.init(this);
LocalDate today = LocalDate.now();
LocalDate anotherDay = LocalDate.of(2019, 3, 25);
long dayDifference = ChronoUnit.DAYS.between(today, anotherDay); //dayDifference = 365
```
One thing of note is that Calendar references months starting at 0 index, whereas LocalDate references months starting at 1 index.
Upvotes: 0 <issue_comment>username_2: The correct way to do this is with the `java.time.LocalDate` class. It stores only the date, not the time, and it has a `now()` static method, which returns the current day.
```
LocalDate today = LocalDate.now();
```
If you're looking at Android, this was added at API level 26, but there are other ways of using the "new style" date classes with Android, such as the [ThreeTen-Backport](http://www.threeten.org/threetenbp/) library.
Upvotes: 2 <issue_comment>username_3: tl;dr
=====
```
ChronoUnit.DAYS.between( // Calculate elapsed time between a pair of `LocalDate` date-only objects. Returns a total number of elapsed days.
( (GregorianCalendar) myJavaUtilCal ) // Cast your legacy `java.util.Calendar` object to the subclass `java.util.GregorianCalendar`, also legacy.
.toZonedDateTime() // Convert from legacy `GregorianCalendar` to modern `ZonedDateTime` class.
.toLocalDate() , // Extract the date-only value, a `LocalDate`, lacking time-of-day and lacking time zone.
otherLocalDate // Compare to some other `LocalDate` object.
) // Returns a `long` number of days. Uses Half-Open approach where the beginning is *inclusive* while the ending is *exclusive*.
```
Details
=======
The [Answer by Kareem](https://stackoverflow.com/a/49354986/642706) is correct. Some more thoughts here.
>
> Is there a better way to zero out Calendar date?
>
>
>
**Yes, there is a better way: don’t.**
* Trying to clear out the time-of-day on a date+time types is the wrong approach; use a date-only type instead ([`LocalDate`](https://docs.oracle.com/javase/9/docs/api/java/time/LocalDate.html)).
* And don’t use the troublesome old legacy classes such as `Calendar`, `Date`, `SimpleDateFormat` as they are now supplanted by the *java.time* classes.
>
> the difference in days between two dates
>
>
>
First convert your legacy `Calendar` object to the modern `ZonedDateTime` class. To convert, call new methods added to the old classes.
```
GregorianCalendar myGregCal = (GregorianCalendar) myJavaUtilCal ; // Cast from superclass to subclass.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ; // Convert from legacy class to modern class.
```
Extract the date-only value.
```
LocalDate ld = zdt.toLocalDate() ; // Extract date-only object from date-time object.
```
Calculate elapsed time in days
```
long days = ChronoUnit.DAYS.between( ld , otherLd ) ;
```
Or represent the elapsed time as a [`Period`](https://docs.oracle.com/javase/9/docs/api/java/time/Period.html).
```
Period p = Period.between( ld , otherLd ) ;
```
---
About *java.time*
=================
The [*java.time*](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html).
The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes.
To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310).
You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes.
Where to obtain the java.time classes?
* [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), and later
+ Built-in.
+ Part of the standard Java API with a bundled implementation.
+ Java 9 adds some minor features and fixes.
* [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7)
+ Much of the java.time functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/).
* [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system))
+ Later versions of Android bundle implementations of the java.time classes.
+ For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts *ThreeTen-Backport* (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706).
The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
Upvotes: 1 [selected_answer]
|
2018/03/19
| 1,842 | 5,931 |
<issue_start>username_0: I am generating .ics calendar invitation with the node package `ical-generator` and sending the attachment in an email via mandrill.
The .ics calendar invite contains information for one event at a specific time and date.
example generated file:
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//sebbo.net//ical-generator//EN
METHOD:REQUEST
NAME: xxxx Events
X-WR-CALNAME: xxxxx
BEGIN:VEVENT
UID:<EMAIL>
SEQUENCE:0
DTSTAMP:20180318T202459Z
DTSTART:20180330T230000Z
DTEND:20180330T230000Z
SUMMARY:test
LOCATION:test
DESCRIPTION:test
ORGANIZER;CN="info":mailto:<EMAIL>
END:VEVENT
END:VCALENDAR
```
Right now, the user receives the calendar invitation as an attachment in the email and is able to add the event to their calendar if they open up the attachment and click on "add to calendar" (in outlook).
What changes do I need to make so that the calendar invite is automatically parsed by the mail client and added to the user's calendar (similar functionality is found in email confirmation from sites like meetup and eventbrite).
Not sure I have the context knowledge around how email clients, calendar systems or .ics files work to have a framework of how to approach this problem
Any suggestions or pointers to resources is greatly appreciated! Thank you!<issue_comment>username_1: The best you can do is ensure that the ics file is well setup, with the text/calendar header etc.
The providing system cannot force on the users device how the file is dealt with, it is entirely within the control of the receiver and their device setup.
For example I have my windows pc set to open ics files in a text editor, while my iphone will try to do an add to calendar (the icloud one), but I actually use google calendar. And Gmail used to not automatically add invites unless they'd been sent to the gmail address, whereas I use other domains for personal/family vs work, which all go to gmail. I'm not sure whether that is still a problem. I don't want the auto added.
Depending on the sort of system you developing for, You might want to consider having the recipients subscribe once to a personal ics url, rather than sending individual invites all the time. If subscribed, then future events/classes etc will automatically show up. I love it when systems do that, but too often they don't. EG: classes that one signs up individually for.
Upvotes: 0 <issue_comment>username_2: You need two things to get this working:
1) The correct encoding of the attachment in your email, see this email headers:
```
Content-Disposition: attachment;
filename=meeting.ics
Content-class: urn:content-classes:calendarmessage
Content-Type: text/calendar;
name="meeting.ics";
component="VEVENT"
Content-Transfer-Encoding: 7bit
```
2) The correct format for the ics file. If you work in PHP to generate the ICS file you should use the library provided from icalendar.org
Try to use this event to test if working and use the validator present in the site mentioned above.
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//ZContent.net//ZapCalLib 1.0//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
BEGIN:VEVENT
SUMMARY:Simple Event
DTSTART:20200101T120000
DTEND:20200101T130000
UID:2020-02-12-11-02-23@<EMAIL>
DTSTAMP:20200212T100223
Description:This is a simple event\, using the Zap Calendar PHP library. Vi
sit http://icalendar.org to validate icalendar files.
END:VEVENT
END:VCALENDAR
```
Upvotes: 2 <issue_comment>username_3: You need to consider three points in order to add events automatically:
1. Email Header
2. iCalendar Method
3. ATTENDEE information the "VEVENT" calendar component
**Email Header**
In order to get the email client to parse correctly the attached .ics file, you should add the scheduling method and MIME information to the email headers. This is specified by the [iCalendar Message-Based Interoperability Protocol (RFC 2447)](https://datatracker.ietf.org/doc/html/rfc2447).
For this reason, your header should include [Content-Type](https://datatracker.ietf.org/doc/html/rfc2447#section-2.4),
[Content-Transfer-Encoding](https://datatracker.ietf.org/doc/html/rfc2447#section-2.5) and [Content-Disposition](https://datatracker.ietf.org/doc/html/rfc2447#section-2.6) as specified in the following example:
```
Content-Type: text/calendar; charset=utf-8; method=REQUEST; name=invite.ics'
Content-Transfer-Encoding: Base64
Content-Disposition: attachment; filename=invite.ics
```
**iCalendar Method**
When used in a MIME message entity, the value of "METHOD" must be the same as the Content-Type "method". This can only appear once within the iCalendar object. The value of this field is defined by the [iCalendar Transport-Independent Interoperability Protocol (iTIP) (RFC 5546)](https://datatracker.ietf.org/doc/html/rfc5546#section-3.2).
In order to request for a meeting, the value should be ["REQUEST"](https://datatracker.ietf.org/doc/html/rfc5546#section-3.2.2).
```
METHOD:REQUEST
```
**ATTENDEE information the "VEVENT" calendar component**
This property is the state of a particular "Attendee" relative to an event. It is used for scheduling and is defined by the "PARTSTAT" parameter in the "ATTENDEE" property for each attendee.
```
ATTENDEE;PARTSTAT=ACCEPTED;CN="<NAME>";EMAIL=<EMAIL>:MAILTO:<EMAIL>
```
**Here is an example of a minimal .ics file:**
```
BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
UID:@.com
DTSTAMP:20210605T073803Z
DTSTART;TZID=America/Guayaquil:20210614T030000
DTEND;TZID=America/Guayaquil:20210614T040000
SUMMARY:My Event
ORGANIZER;CN="<NAME>":mailto:<EMAIL>
ATTENDEE;PARTSTAT=ACCEPTED;CN="<NAME>";EMAIL=<EMAIL>:MAILTO:<EMAIL>
URL;VALUE=URI:https://.com/event/5960492994476830083
END:VEVENT
END:VCALENDAR
```
For more details, [please take a look at my gist](https://gist.github.com/flandrade/394d9df95e1be2a584f267ae91505239).
Upvotes: 4
|
2018/03/19
| 939 | 3,120 |
<issue_start>username_0: I'm new with Bootstrap 4 and SASS. I've been struggling to learn how to make changes but have been able get a couple done. However, one of them I can't seem to figure out is the margin or padding at the top and bottom of the navbar item.
Here is what I've done. On a new MVC project I installed Bootstrap 4 and Bootstrap.sass. I then created a new \_custom-variables and copied the \_variables content into it so that I can make some changes. I then created a \_my-theme.scss file and imported all of them into my site.scss like this.
```
@import "scss/_custom-variables.scss";
@import "scss/_bootstrap.scss";
@import "scss/_my-theme.scss";
```
I was finally able to figure out how to change the background color of the navbar by creating a variable for my color and applying it to the \_custom-variables and changing the link text to white:
```
$main-color: #0078D2;
// Navbar links
$navbar-default-link-color: #fff !default;
$navbar-default-link-hover-color: #fff !default;
$navbar-default-link-hover-bg: darken($main-color, 6.5%) !default;
```
I also had to set the following in the \_my-theme.css to actually change the text color to white. I've watched some videos and I know it has to do with specifcicity but I still haven't really got my head wrapped around it. Based on a video I watched, what I did was inspect the link and found the properties that I just copied straight in to the \_my-theme.scss.
This is what I had to add to the \_my-theme.scss to get the text white.
```
.navbar-dark
.navbar-nav
.nav-link {
color: #fff;
margin-top: 0px;
margin-bottom: 0px;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus{
color: #fff;
}
```
However, there is still some padding or margin at the top each link that I would like to get rid of. You can see that I tried setting the `margin-top: 0px` and `margin-bottom: 0px` but that didn't work, neither did setting padding to 0px.
I also tried finding the setting in dev tools in Chrome but couldn't find what it is that is setting this.
This is my navbar layout:
```
[Fixed navbar](#)
* [Home (current)](#)
* [Link](#)
* [Disabled](#)
```
[](https://i.stack.imgur.com/27bjf.png)
How can I remove this spacing and make the dark blue take the whole height of the navbar?<issue_comment>username_1: By default the `navbar` class contains internal padding. If you want to remove the top and bottom padding, just add this CSS:
```
.navbar {
padding-top: 0;
padding-bottom: 0;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The space is padding, and not margins. Use the `py-0` utility class to remove the padding from the navbar. And then add padding back to the `nav-link` to maintain the original height:
<https://www.codeply.com/go/roU5MIf724>
```
.navbar-dark
.navbar-nav
.nav-link {
color: #fff;
padding: 10px 0;
}
[Fixed navbar](#)
* [Home (current)](#)
* [Link](#)
* [Disabled](#)
```
Upvotes: 0
|
2018/03/19
| 500 | 1,606 |
<issue_start>username_0: I am using the rails js helper image\_path to update an images source using javascript.
The actual string for the new img src path lives inside of a variable and I need to inject that into the image\_path string below, which has been giving me problems.
Here is what I'm working with:
Object:
var bike = { image: "bikes/diamondback/diamondback-29-ht.png"}
Image path:
```
$('.ga-recommended-bike').attr('src', "<%= image_path 'bikes/diamondback/diamondback-29-ht.png' %>")
```
I've been trying to do something like this to inject the url into the image path:
```
$('.ga-recommended-bike').attr('src', "<%= image_path `${bike.image}` %>")
```
also tried the non es6 way
```
$('.ga-recommended-bike').attr('src', "<%= image_path " + bike.image + " %>")
```
I think the problem is the intermingling of the rails and js code.
Does anyone know of a good way to solve this using rails and javascript?<issue_comment>username_1: By default the `navbar` class contains internal padding. If you want to remove the top and bottom padding, just add this CSS:
```
.navbar {
padding-top: 0;
padding-bottom: 0;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: The space is padding, and not margins. Use the `py-0` utility class to remove the padding from the navbar. And then add padding back to the `nav-link` to maintain the original height:
<https://www.codeply.com/go/roU5MIf724>
```
.navbar-dark
.navbar-nav
.nav-link {
color: #fff;
padding: 10px 0;
}
[Fixed navbar](#)
* [Home (current)](#)
* [Link](#)
* [Disabled](#)
```
Upvotes: 0
|
2018/03/19
| 536 | 1,891 |
<issue_start>username_0: I want to inject Service in a controller. The Service will return $http.get() method.
Error : [$injector:unpr] <http://errors.angularjs.org/1.6.4/>$injector/unpr?p0=JsonFilterProvider%20%3C-%20JsonFilter
Please suggest whats wrong in my code?
```
var app = angular.module("myApp", []);
app.controller("myCntlr", ['$scope', 'myhttpService', function ($scope, myhttpService) {
$scope.myHttpMessage = myhttpService.httpGetService();
}]);
app.service("myhttpService", ['$http', '$scope', function ($http, $scope) {
this.httpGetService = function () {
console.log("httGetService");
$http.get('https://reqres.in/api/users').then(function (successResponse) {
console.log("http Get");
return successResponse;
}, function (errorResponse) {
console.log("http Get Error");
return errorResponse
});
};
}]);
Http Message:{{myHttpMessage|Json}}
```<issue_comment>username_1: The actual issue is you are not getting the response from your service. So the json filter throws an error
```
Http Message:{{myHttpMessage | json}}
```
Make sure yo return the result back from the service with a return command.
```
return $http.get('https://reqres.in/api/users').then(function (successResponse)
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can not inject `$scope` in service. that's not allowed. Instead, you can return promise from service and process inside controller something like this.
```
app.service("myhttpService",['$http', function ($http) {
this.httpGetService = function () {
return $http.get('https://reqres.in/api/users');
}
}]);
app.controller("myCntlr", ['$scope', 'myhttpService', function ($scope, myhttpService) {
myhttpService.httpGetService().then(function(response){
$scope.myHttpMessage = response.data;
}, function(error){
//do something on failure
});
}]);
```
Upvotes: 2
|
2018/03/19
| 820 | 2,848 |
<issue_start>username_0: I have followed instructions in examples like [this](https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux), and [this](https://stackoverflow.com/questions/19256127/two-versions-of-python-on-linux-how-to-make-2-7-the-default).
I have this line in my ~/.bashrc file
```
export python="/usr/local/bin/python3.6"
```
This lines in my ~/.bash\_aliases file
```
alias python='/usr/local/bin/python3.6'
```
This is my PATH variable
```
/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Wireshark.app/Contents/MacOS
```
And I still have the following python version and path
```
User$ which python
/usr/bin/python
User$ python --version
Python 2.7.10
```
I have also already tried exiting the terminal and reopening
Here is what is within the directories /usr/local/bin/python3.6\* and /usr/bin/python\*
```
User$ /usr/local/bin/python3.6
python3.6 python3.6-config python3.6m-config
python3.6-32 python3.6m
User$ /usr/bin/python
python python2.6-config pythonw
python-config python2.7 pythonw2.6
python2.6 python2.7-config pythonw2.7
```
Thank-you<issue_comment>username_1: Copy those into your `.bash_profile` file, which is what terminal sessions in OS X look for. Also, as others have mentioned, exporting python as an environment variable will not do anything- the alias should be enough.
Upvotes: 0 <issue_comment>username_2: **I think the problem may be, you started a login shell which looks for `~/.bash_profile`, and `~/.bash_aliases` is not sourced in `~/.bash_profile`. So the `alias` command in `~/.bash_aliases` was never executed. You can check this by invoking `alias python`.**
BTW, export a variable named python is pointless in your case since it
will never be used.
Apropos which ~/.bash\* files is read, you can reference `man bash` at the `INVOCATION` chapter. Here is some of them.
>
> When bash is invoked as an interactive login shell, or as a non-interactive shell with the
> --login option, it first reads and executes commands from the file /etc/profile, if that file
> exists. After reading that file, it looks for ~/.bash\_profile, ~/.bash\_login, and ~/.profile, in
> that order, and reads and executes commands from the first one that exists and is readable. The
> --noprofile option may be used when the shell is started to inhibit this behavior.
>
>
> When an interactive shell that is not a login shell is started, bash reads and executes commands
> from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The
> --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc.
>
>
>
Upvotes: 2 [selected_answer]
|
2018/03/19
| 1,446 | 5,435 |
<issue_start>username_0: I have 3 `DateTimePicker`, one for setting date, the second adds 3 days and the 3rd one adds 5 weekdays. But my code don't calculate correctly.
I calculate "manually" the future days adding more or less days deppending current day.
```
Private Sub Calculatedelivery()
Dim normaldlvy As Integer
Dim latedlvy As Integer
If DateTimePicker1.Value.DayOfWeek = Day.Monday Then
normaldlvy = 3
latedlvy = 7
End If
If DateTimePicker1.Value.DayOfWeek = Day.Tuesday Then
normaldlvy = 3
latedlvy = 6
End If
If DateTimePicker1.Value.DayOfWeek = Day.Wednesday Then
normaldlvy = 5
latedlvy = 7
End If
If DateTimePicker1.Value.DayOfWeek = Day.Thursday Then
normaldlvy = 5
latedlvy = 7
End If
If DateTimePicker1.Value.DayOfWeek = Day.Friday Then
normaldlvy = 5
latedlvy = 7
End If
If DateTimePicker1.Value.DayOfWeek = Day.Saturday Then
normaldlvy = 4
latedlvy = 6
End If
If DateTimePicker1.Value.DayOfWeek = Day.Sunday Then
normaldlvy = 3
latedlvy = 5
End If
DateTimePicker2.Value = DateTimePicker1.Value.AddDays(normaldlvy )
DateTimePicker3.Value = DateTimePicker1.Value.AddDays(latedlvy)
End Sub
```<issue_comment>username_1: Here is an extension method that you can call much as you already call `AddDays`:
```
Imports System.Runtime.CompilerServices
Public Module DateTimeExtensions
Public Function AddWeekDays(source As Date, value As Integer) As Date
Dim result = source
Do
result = result.AddDays(1)
If result.IsWeekDay() Then
value -= 1
End If
Loop Until value = 0
Return result
End Function
Public Function IsWeekDay(source As Date) As Boolean
Return source.DayOfWeek <> DayOfWeek.Saturday AndAlso
source.DayOfWeek <> DayOfWeek.Sunday
End Function
End Module
```
You can then call that something like this:
```
DateTimePicker3.Value = DateTimePicker1.Value.AddWeekDays(latedlvy)
```
Note that, unlike `Date.AddDays`, that method takes an `Integer` rather than a `Double`. Also, it will only work for positive values as it is. It could be improved to work in pretty much exactly the way `AddDays` does but you probably don't need that in this case.
If you're not sure how extension methods work, I suggest that you do some reading on that subject.
**EDIT**: I've done some work on this method and improved it significantly. It now handles negative and fractional values, just like `Date.AddDays` does.
```
Imports System.Runtime.CompilerServices
'''
''' Contains methods that extend the structure.
'''
Public Module DateTimeExtensions
'''
''' Gets a value indicating whether a value represents a week day.
'''
'''
''' The input , which acts as the **this** instance for the extension method.
'''
'''
''' **true** if the represents a week day; otherwise **false**.
'''
'''
''' All days other than Saturday and Sunday are considered week days.
'''
Public Function IsWeekDay(source As Date) As Boolean
Return source.DayOfWeek <> DayOfWeek.Saturday AndAlso
source.DayOfWeek <> DayOfWeek.Sunday
End Function
'''
''' Returns a new that adds the specified number of week days to a specified value.
'''
'''
''' The input , which acts as the **this** instance for the extension method.
'''
'''
''' A number of whole and fractional days. The *value* parameter can be negative or positive.
'''
'''
''' An object whose value is the sum of the date and time represented by this instance and the number of week days represented by *value*.
'''
'''
''' All days other than Saturday and Sunday are considered week days.
'''
Public Function AddWeekDays(source As Date, value As Double) As Date
'A unit will be +/- 1 day.
Dim unit = Math.Sign(value) \* 1.0
'Start increasing the date by units from the initial date.
Dim result = source
'When testing for zero, allow a margin for precision error.
Do Until Math.Abs(value) < 0.00001
If Math.Abs(value) < 1.0 Then
'There is less than one full day to add so we need to see whether adding it will take us past midnight.
Dim temp = result.AddDays(value)
If temp.Date = result.Date OrElse temp.IsWeekDay() Then
'Adding the partial day did not take us into a weekend day so we're done.
result = temp
value = 0.0
Else
'Adding the partial day took us into a weekend day so we need to add another day.
result = result.AddDays(unit)
End If
Else
'Add a single day.
result = result.AddDays(unit)
If result.IsWeekDay() Then
'Adding a day did not take us into a weekend day so we can reduce the remaining value to add.
value -= unit
End If
End If
Loop
Return result
End Function
End Module
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here's another way to do this. One that I think it fairly straight forward - especially if you're only doing the calculation a few times.
```
Dim someDate As DateTime = DateTime.Now.Date
Dim dates = _
Enumerable _
.Range(1, 100000) _
.Select(Function (x) someDate.AddDays(x)) _
.Where(Function (x) x.DayOfWeek <> DayOfWeek.Saturday) _
.Where(Function (x) x.DayOfWeek <> DayOfWeek.Sunday)
Dim nextDate = dates.Take(5).First()
```
The big advantage with this approach is that you can also add further `.Where` calls to remove public holidays.
Simple.
Upvotes: 0
|
2018/03/19
| 2,768 | 9,830 |
<issue_start>username_0: I have a reusable component that is a video.js video player. This component works fine when the data is passed in on the initial DOM load.
I need to figure out why my component is not re-rendering after the state is updated in Vuex.
The parent component passes down the data for the video via props. I also have this set to be used with multiple videos and it works fine with a single one or many.
```
```
I'm setting the initial state to a generic video for all users in my Vuex store.
```
getFreeVideo: [
{
videoName: "the_video_name",
videoURL: "https://demo-video-url.mp4",
thumbnail: "https://s3.amazonaws.com/../demo-video-poster.jpg"
}
]
```
This is set in data in `videos` *(and later set to getFreeVideo)*
```
data () {
return {
videos: []
}
}
```
I'm setting `videos` in data() to getFreeVideo in the store within the created() lifecycle:
```
this.videos = this.getFreeVideo
```
..and checking if a user has a personal video and updating the state in the created() lifecycle.
```
this.$store.dispatch('getFreeVideo', 'the_video_name')
```
This makes a request with axios and returns our video data successfully.
I'm using mapState `import { mapState } from 'vuex` to watch for a state change.
```
computed: {
...mapState(['getFreeVideo'])
}
```
I am not seeing why `this.videos` is not being updated.
Here, my assumption regarding the expected behaviour would be `videos[]` being updated from the state change and a re-rendering of the component.
As you can see below, the state has been updated, and the `videoUpdate()` within the computed properties has the new data as well:
[](https://i.stack.imgur.com/Ne4hm.png)
[](https://i.stack.imgur.com/Hy8Ui.png)
..but, `videos[]` is never updated thus the video component never gets the props new props etc..
A couple of notes:
* already tried, hiding the child component with `v-if` *(and showing after state change)*
* tried `setTimeout` to test things, but the data will come through and then the videoJS player never instantiates correctly *(must have initial data)*
* tried doing this with a local method / not using Vuex state
* console is showing error `TypeError: Cannot read property '_withTask' of undefined` but this happens even when the demo video loads correctly, so this seem unrelated, and I can't find anything anywhere in here that presents itself as undefined.
**TL;DR**
I basically can't get child component to re-render after the state change.
And although I can get the data into `videos[]` with a different structure, it still never re-renders.
**Why is the data not making it through, and the re-render never happening?**
*Please don't post answers that only contain links to 'understanding reactivity' or something without any explanation.*
*appended for @acdcjunior*
```
//action
getFreeVideo: (context, videoName) => {
axios({
method: 'post',
url: 'https://hidden-for-posting',
data: {
action: 'getVideo',
userId: '1777', // (hardcoded to test)
videoName: videoName
},
headers: {
'x-api-key': apiKey,
'Content-Type': 'application/json'
}
})
.then(response => {
let video = [
{
videoName: response.data.videoName,
videoURL: response.data.videoURLs.mp4,
thumbnail: response.data.thumbnails['1280']
}
]
return context.commit('updateGetFreeVideo', video)
})
.catch(error => {
if (error.response) {
console.log(error.response)
} else if (error.request) {
console.log(error.request)
} else {
console.log('Error', error.message)
}
console.log(error.config)
})
}
// mutation:
updateGetFreeVideo: (state, payload) => {
return state.getFreeVideo = payload
}
// getter:
getFreeVideo: state => {
return state.getFreeVideo
}
```<issue_comment>username_1: If the computed property isn't referenced (e.g. "used") somewhere in your template code vue will skip reactivity for it.
First it's a bit confusing the way you're structuring the store and the state properties.
I would:
1) Have a "videos" property in the store state
2) Initialise it as an empty array
3) On application start populate it correctly with the "load" defaults, with a mutation that pushes the "default" video to it
4) Have the components `mapGetter` to it under the name of `videos`
5) Whenever you load a component that "updates" the possible videos, then dispatch the action and call the appropriate mutation to substitute the store "videos" property
Note: If components can have different "default" videos, then probably you'll want to have a `videos` property in the store that is initialised as `false`. This then allows you to have a computed property that uses the getter for the `videos` property in the store and in case it is `false`
What I mean is, for the first case
```
// store
state: {
videos: []
}
getters: {
videos(state) { return state.videos }
}
//components
...
computed: {
videos() {
this.$store.getters.videos
}
}
For the second case
// store
state: {
videos: false
}
getters: { personal_videos(state) { return state.videos } }
//components
data() { return { default: default_videos } },
computed: {
...mapGetters([ 'personal_videos' ]),
videos() {
if (this.personal_videos) {
return this.personal_videos
} else {
return this.default
}
}
```
}
Personal: give them better names -\_- and the first option is the clearest
Upvotes: 2 <issue_comment>username_2: **NOTE: at the bottom of this answer, see the general point I make about update/reactivity issues with Vue.**
---
Now, about the question, *based on the code you posted*, considering the template:
```html
```
It picks the `videos` from:
```js
data () {
return {
videos: freeVideo
}
}
```
Although it initializes from `freeVideo`, in nowhere in your code you show an **update of `videos`**.
**Solution:**
You already have the state mapped in the `getFreeVideo` computed:
```js
computed: {
...mapState(['getFreeVideo'])
}
```
Use it:
```html
```
---
Update:
=======
>
> I'm setting `videos` in data() to getFreeVideo in the store within the
> created() lifecycle:
>
>
>
> ```
> this.videos = this.getFreeVideo
>
> ```
>
>
This is not enough to keep `this.videos` updated with whatever `this.getFreeVideo` is. Whenever something is set to `this.getFreeVideo` it will only change `this.getFreeVideo`, not `this.videos`.
If you want to automatically update `this.videos` whenever `this.getFreeVideo` changes, create a watcher:
```js
watch: {
getFreeVideo() {
this.videos = this.getFreeVideo
}
}
```
And then keep using `videos` in the `v-for`:
```html
```
Vue's reactivity
================
>
> All explanation below applies to Vue2 only. Vue3 doesn't have any of these caveats.
>
>
>
If your state is not getting updated in the view, perhaps you are not exploring Vue at its best:
>
> To have Vue ***automatically*** react to value changes, the objects must be **initially declared in `data`**. Or, if not, they must be **added using `Vue.set()`**.
>
>
>
See the comments in the demo below. Or open the [same demo in a **JSFiddle** here](https://jsfiddle.net/username_2/ynm9nLmo/).
```js
new Vue({
el: '#app',
data: {
person: {
name: 'Edson'
}
},
methods: {
changeName() {
// because name is declared in data, whenever it
// changes, Vue automatically updates
this.person.name = 'Arantes';
},
changeNickname() {
// because nickname is NOT declared in data, when it
// changes, Vue will NOT automatically update
this.person.nickname = 'Pele';
// although if anything else updates, this change will be seen
},
changeNicknameProperly() {
// when some property is NOT INITIALLY declared in data, the correct way
// to add it is using Vue.set or this.$set
Vue.set(this.person, 'address', '123th avenue.');
// subsequent changes can be done directly now and it will auto update
this.person.address = '345th avenue.';
}
}
})
```
```css
/* CSS just for the demo, it is not necessary at all! */
span:nth-of-type(1),button:nth-of-type(1) { color: blue; }
span:nth-of-type(2),button:nth-of-type(2) { color: red; }
span:nth-of-type(3),button:nth-of-type(3) { color: green; }
span { font-family: monospace }
```
```html
person.name: {{ person.name }}
person.nickname: {{ person.nickname }}
person.address: {{ person.address }}
this.person.name = 'Arantes'; (will auto update because `name` was in `data`)
this.person.nickname = 'Pele'; (will NOT auto update because `nickname` was not in `data`)
Vue.set(this.person, 'address', '99th st.'); (WILL auto update even though `address` was not in `data`)
For more info, read the comments in the code. Or check the docs on **Reactivity** (link below).
```
To master this part of Vue, check the [Official Docs on **Reactivity** - Change Detection Caveats](https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats). It is a must read!
Upvotes: 7 [selected_answer]<issue_comment>username_3: So turns out the whole issue was with video.js. I'm half tempted to delete this question, but I would not want anyone who helped to lose any points.
The solution and input here did help to rethink my use of watchers or how I was attempting this. I ended up just using the central store for now since it works fine, but this will need to be refactored later.
I had to just forego using video.js as a player for now, and a regular html5 video player works without issues.
Upvotes: 3
|
2018/03/19
| 2,043 | 7,273 |
<issue_start>username_0: I am trying to setup a react component called `FullscreenImage` that displays my image as 100% of the width/height in parallax style. As I am going to use this component more often, I thought it would be a good idea to pass the URL for the picture via props. The problem is that if I pass the URL as a prop, it doesnt load the image, but just inserts the URL. How can I also load the picture? I saw on my Webpage, that statically inserted URLs translate into URLs with the prefix `static/media/`.
FullscreenImage.jsx
```
let defaultStyle = {
minHeight: '100vh !important',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
backgroundAttachment: 'fixed',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
overflow: 'hidden'
};
class FullscreenImage extends Component {
constructor() {
super();
this.state = {
defaultStyle: defaultStyle,
background: {}
};
}
componentDidMount() {
this.setState({background: this.props.source.uri});
}
render() {
console.log(this.state);
return ();
}
}
export default FullscreenImage;
```
App.jsx
```
let picture1 = {
uri: "url(../img/austin-neill-247237-unsplash.jpg)"
};
class App extends Component {
render() {
return (
);
}
}
export default Login;
```
Thanks in advance.<issue_comment>username_1: If the computed property isn't referenced (e.g. "used") somewhere in your template code vue will skip reactivity for it.
First it's a bit confusing the way you're structuring the store and the state properties.
I would:
1) Have a "videos" property in the store state
2) Initialise it as an empty array
3) On application start populate it correctly with the "load" defaults, with a mutation that pushes the "default" video to it
4) Have the components `mapGetter` to it under the name of `videos`
5) Whenever you load a component that "updates" the possible videos, then dispatch the action and call the appropriate mutation to substitute the store "videos" property
Note: If components can have different "default" videos, then probably you'll want to have a `videos` property in the store that is initialised as `false`. This then allows you to have a computed property that uses the getter for the `videos` property in the store and in case it is `false`
What I mean is, for the first case
```
// store
state: {
videos: []
}
getters: {
videos(state) { return state.videos }
}
//components
...
computed: {
videos() {
this.$store.getters.videos
}
}
For the second case
// store
state: {
videos: false
}
getters: { personal_videos(state) { return state.videos } }
//components
data() { return { default: default_videos } },
computed: {
...mapGetters([ 'personal_videos' ]),
videos() {
if (this.personal_videos) {
return this.personal_videos
} else {
return this.default
}
}
```
}
Personal: give them better names -\_- and the first option is the clearest
Upvotes: 2 <issue_comment>username_2: **NOTE: at the bottom of this answer, see the general point I make about update/reactivity issues with Vue.**
---
Now, about the question, *based on the code you posted*, considering the template:
```html
```
It picks the `videos` from:
```js
data () {
return {
videos: freeVideo
}
}
```
Although it initializes from `freeVideo`, in nowhere in your code you show an **update of `videos`**.
**Solution:**
You already have the state mapped in the `getFreeVideo` computed:
```js
computed: {
...mapState(['getFreeVideo'])
}
```
Use it:
```html
```
---
Update:
=======
>
> I'm setting `videos` in data() to getFreeVideo in the store within the
> created() lifecycle:
>
>
>
> ```
> this.videos = this.getFreeVideo
>
> ```
>
>
This is not enough to keep `this.videos` updated with whatever `this.getFreeVideo` is. Whenever something is set to `this.getFreeVideo` it will only change `this.getFreeVideo`, not `this.videos`.
If you want to automatically update `this.videos` whenever `this.getFreeVideo` changes, create a watcher:
```js
watch: {
getFreeVideo() {
this.videos = this.getFreeVideo
}
}
```
And then keep using `videos` in the `v-for`:
```html
```
Vue's reactivity
================
>
> All explanation below applies to Vue2 only. Vue3 doesn't have any of these caveats.
>
>
>
If your state is not getting updated in the view, perhaps you are not exploring Vue at its best:
>
> To have Vue ***automatically*** react to value changes, the objects must be **initially declared in `data`**. Or, if not, they must be **added using `Vue.set()`**.
>
>
>
See the comments in the demo below. Or open the [same demo in a **JSFiddle** here](https://jsfiddle.net/username_2/ynm9nLmo/).
```js
new Vue({
el: '#app',
data: {
person: {
name: 'Edson'
}
},
methods: {
changeName() {
// because name is declared in data, whenever it
// changes, Vue automatically updates
this.person.name = 'Arantes';
},
changeNickname() {
// because nickname is NOT declared in data, when it
// changes, Vue will NOT automatically update
this.person.nickname = 'Pele';
// although if anything else updates, this change will be seen
},
changeNicknameProperly() {
// when some property is NOT INITIALLY declared in data, the correct way
// to add it is using Vue.set or this.$set
Vue.set(this.person, 'address', '123th avenue.');
// subsequent changes can be done directly now and it will auto update
this.person.address = '345th avenue.';
}
}
})
```
```css
/* CSS just for the demo, it is not necessary at all! */
span:nth-of-type(1),button:nth-of-type(1) { color: blue; }
span:nth-of-type(2),button:nth-of-type(2) { color: red; }
span:nth-of-type(3),button:nth-of-type(3) { color: green; }
span { font-family: monospace }
```
```html
person.name: {{ person.name }}
person.nickname: {{ person.nickname }}
person.address: {{ person.address }}
this.person.name = 'Arantes'; (will auto update because `name` was in `data`)
this.person.nickname = 'Pele'; (will NOT auto update because `nickname` was not in `data`)
Vue.set(this.person, 'address', '99th st.'); (WILL auto update even though `address` was not in `data`)
For more info, read the comments in the code. Or check the docs on **Reactivity** (link below).
```
To master this part of Vue, check the [Official Docs on **Reactivity** - Change Detection Caveats](https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats). It is a must read!
Upvotes: 7 [selected_answer]<issue_comment>username_3: So turns out the whole issue was with video.js. I'm half tempted to delete this question, but I would not want anyone who helped to lose any points.
The solution and input here did help to rethink my use of watchers or how I was attempting this. I ended up just using the central store for now since it works fine, but this will need to be refactored later.
I had to just forego using video.js as a player for now, and a regular html5 video player works without issues.
Upvotes: 3
|
2018/03/19
| 470 | 1,251 |
<issue_start>username_0: how can I get these `loops` and `if statements` into a comprehension?
```
raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]
for one in raw:
if one[0] == '-':
for two in raw:
if two[1] == one[1] and two[0] == '=': two[0] = '--'
```
So far:
```
[two+one for two in raw for one in raw]
```
But not sure where to put the if statements:
`if one[0] == '-'` and `if two[1] == one[1] and two[0] == '=': two[0] = '--'`<issue_comment>username_1: A simple list comprehension should be sufficient:
```
raw = [['-', 'bla'], ['-', 'la'], ['=', 'bla']]
res = [['--' if (i != '-') and (['-', j] in raw) else i, j] for i, j in raw]
```
Result:
```
[['-', 'bla'], ['-', 'la'], ['--', 'bla']]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can set item in list comprehension ,
Your code:
```
for one in raw:
if one[0] == '-':
for two in raw:
if two[1] == one[1] and two[0] == '=': two[0] = '--'
```
>
> convert to list comprehension :
>
>
>
```
[[two.__setitem__(0,'--') if two[1]==one[1] and two[0]=='=' else two for two in raw] if one[0]=='-' else one for one in raw]
print(raw)
```
output:
```
[['-', 'bla'], ['-', 'la'], ['--', 'bla']]
```
Upvotes: 0
|
2018/03/19
| 992 | 3,222 |
<issue_start>username_0: I am trying to determine if all letters in myString are found in myList. Here is my code so far.
```
def findLetters(myList,myString):
myList = set(myList)
myString = list(myString)
myString = set(myString)
for x in myString:
if x not in myList:
return bool (False)
if x in myList:
return bool (True)
```
One of the examples which should return True is the following:
>
>
> >
> > findLetters(["hello","world"],"old")
> >
> >
> >
>
>
>
However, I get False. Can someone explain where I went wrong?<issue_comment>username_1: Here is one solution.
```
def findLetters(myList, myString):
WordLetters = set(''.join(myList))
StringLetters = set(myString)
for s in StringLetters:
yield s, s in WordLetters
res = list(findLetters(['hello', 'world'], 'old'))
# [('d', True), ('o', True), ('l', True)]
res2 = all(list(zip(*findLetters(['hello', 'world'], 'old')))[1])
# True
```
Upvotes: 0 <issue_comment>username_2: >
> I am trying to determine if all letters in myString are found in myList.
>
>
>
You can use a combination of the built-in functions `any` and `all` to accomplish this:
```
>>> def findLetters(myList,myString):
return all(any(c in word for word in myList) for c in myString)
>>> findLetters(["hello","world"],"old")
True
>>>
```
Upvotes: 0 <issue_comment>username_3: This is a one-liner in Python:
```
def findLetters(myList, myString):
return set(myString) <= set(''.join(myList))
```
You had the right idea to convert both parameters to sets, just forgot to join the list of strings before... then set inclusion operator `<=` is very handy
Upvotes: 1 <issue_comment>username_4: The problem with your code is that you are comparing each letter to *words*.
In your example, `set(myList)` results in `{'hello', 'world'}`. You then compare each letter in 'old' to this set. As you can see, this will fail (e.g. the letter 'o' is not in the set {'hello', 'world'} even though it is in a *word* in the set).
```
>>> 'o' in set(my_list)
False
```
You may find this useful, where your a set of unique letters are created from the list of words using a set comprehension, and then another set is taken of the unique letters in your string.
```
my_list = ["hello","world"]
my_string = 'old'
list_letters = {letter for letter in word for word in my_list} # {'d', 'e', 'h', 'l', 'o', 'r', 'w'}
word_letters = set(my_string) # {'d', 'l', 'o'}
>>> word_letters.issubset(list_letters)
# Output: True
```
Turning this into a one liner:
```
>>> set(my_string).issubset({letter for letter in word for word in my_list})
True
```
The other problem with your code is that you do not want to return `True` when it finds a letter in `my_list` (i.e. the last line of your code). You can return `False` if a letter is not in `my_list`, but must then return `True` if you've iterated through all the letters, e.g.
```
for word in myList:
if x not in word:
return False
return True
```
You could also use `all`:
```
if all(x in word for word in myList):
return True
return False # Not really needed, since it would return None which is a falsey.
```
Upvotes: 1
|
2018/03/19
| 1,460 | 5,731 |
<issue_start>username_0: I am having difficulty with my music app. The idea is to tap a button and play more songs from the artist that is currently playing. When I am IN the app and I hit next song it works fine. However if I let the song end naturally the app would play a random song. So I added logic to say if the songs remaining time is 0 then play next song using media players func because I know that works. This solved it except if the app is in the background. I tried to keep the app alive if it is in the background but I guess that is not working.
Every time I think I have solved something it the issue comes back.
**What I expect to happen** is lock on an Artist, close app to background and when the song ends play another song from Artist.
**What actually happens** is when I lock the artist and close app to background is the song will end and sometimes it will play the right song. Sometimes it will not. **HOWEVER** when it plays the wrong song and I open the app back up it ends the currently (Wrong) playing song and starts playing a song by the proper artist
**to be clear, I think it’s unwise to need logic that runs when the song time remaining is 0 to skip to next song but for whatever reason I need it**
I have set the Capabilities to background fetch and Audio Airplay and picture in picture
I have tried to only post relevant code in order..
I have a property
```
let mediaPlayer = MPMusicPlayerController.systemMusicPlayer
var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
```
In my **ViewDidLoad**
```
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategorySoloAmbient)
try? AVAudioSession.sharedInstance().setActive(true)
DispatchQueue.main.async {
self.clearSongInfo()
MediaManager.shared.getAllSongs { (songs) in
guard let theSongs = songs else {
return
}
self.mediaPlayer.nowPlayingItem = nil
self.newSongs = theSongs.filter({ (item) -> Bool in
return !MediaManager.shared.playedSongs.contains(item)
})
self.aSongIsInChamber = true
self.mediaPlayer.setQueue(with: MPMediaItemCollection(items: self.newSongs.shuffled())
)
self.mediaPlayer.shuffleMode = .off
self.mediaPlayer.repeatMode = .none
}
NotificationCenter.default.addObserver(self, selector: #selector(self.songChanged(_:)), name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange, object: self.mediaPlayer)
self.mediaPlayer.beginGeneratingPlaybackNotifications()
}
```
I have a func that updates the played time and remaining time and in that I have
```
if Int(self.songProgressSlider.maximumValue - self.songProgressSlider.value) < 1 {
print("song ended naturally, skipped")
mediaPlayer.prepareToPlay(completionHandler: { (error) in
DispatchQueue.main.async {
self.mediaPlayer.skipToNextItem()
}
})
}
```
When I play the music I have a bool **isPlaying**
If it is then the time is running and I have this
```
let app = UIApplication.shared
var task: UIBackgroundTaskIdentifier?
task = app.beginBackgroundTask {
app.endBackgroundTask(task!)
}
```
I have that to keep the timer on in the background so it will play the next song when the time remaining is 0
Now to lock onto an Artist I have the following code that executes on button tap
```
let artistPredicate: MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: nowPlaying.artist, forProperty: MPMediaItemPropertyArtist)
let query: MPMediaQuery = MPMediaQuery.artists()
let musicPlayerController: MPMusicPlayerController = MPMusicPlayerController.systemMusicPlayer
query.addFilterPredicate(artistPredicate)
musicPlayerController.setQueue(with: query)
```<issue_comment>username_1: I found a solution that isn't 100% what I wanted, but at this point I'll take it.
On the IBAction where I lock onto an artist I was originally just
```
self.mediaPlayer.prepareToPlay { error in
let artistPredicate: MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: nowPlaying.artist, forProperty: MPMediaItemPropertyArtist)
let query: MPMediaQuery = MPMediaQuery.artists()
let musicPlayerController: MPMusicPlayerController = MPMusicPlayerController.systemMusicPlayer
query.addFilterPredicate(artistPredicate)
musicPlayerController.setQueue(with: query)
}
```
What I have done to fix my issue is added
```
musicPlayerController.play()
```
after I set the queue.
The downside to this approach is that if I am midway through a song and I tap the button to lock the artist the app immediately ends the now playing song and goes to songs by that artist and I would rather the song finish playing and THEN go the songs I want.
If anybody can think of a way to use play() AND let the song ends naturally ill mark that answer as correct...
**NOTE** I never wanted to use the logic that checks how long is left in a song and I never wanted to use background code. So I got rid of that and it still works with new idea.
Upvotes: 0 <issue_comment>username_2: I find that setting the queue does not "take" until you say `prepareToPlay` (literally or implicitly by saying `play`). The current edition of my book says:
>
> My experience is that the player can behave in unexpected ways if you don't ask it to `play`, or at least `prepareToPlay`, immediately after setting the queue. Apparently the queue does not actually take effect until you do that.
>
>
>
You have also said (in a comment):
>
> ideally I would like the song to finish first and then go onto the queue I have
>
>
>
Okay, but then perhaps what you want here is the (new in iOS 11) `append` feature that allows you modify the queue without replacing it entirely.
Upvotes: 2 [selected_answer]
|
2018/03/19
| 573 | 1,856 |
<issue_start>username_0: How do I check in Ubuntu 16.04, which version of aiohttp is installed?
This works
```
python -V
Python 2.7.12
```
but this doesn't
```
aiohttp -V
-bash: aiohttp: command not found
```<issue_comment>username_1: It is not a command line tool. That's why it says `command not found`. It is a `pip` package. So, you can do this:
```
pip freeze | grep aiohttp
```
to find the version.
Upvotes: 0 <issue_comment>username_2: If you installed it with `pip` (>= 1.3), use
```
$ pip show aiohttp
```
For older versions,
```
$ pip freeze | grep aiohttp
```
`pip freeze` has the advantage that it shows editable VCS checkout versions correctly, while `pip show` does not.
... or
```
$ pip list | grep aiohttp
$ pip list --outdated | grep aiohttp
```
(`--outdated` to see Current and Latest versions of the packages).
**Credits**: [Find which version of package is installed with pip](https://stackoverflow.com/questions/10214827/find-which-version-of-package-is-installed-with-pip)
**Note**: the property `__version__` comes in handy, but [it is not always available](https://stackoverflow.com/a/20180597/2707864). This is an issue that evolved with time. YMMV.
Upvotes: 0 <issue_comment>username_3: A general way that works for pretty much any module, regardless of how it was installed is the following:
```
$ python -c "import aiohttp; print(aiohttp.__version__)"
2.3.3
```
What this does is run a Python interpreter, import the module, and print the module's `__version__` attribute. Pretty much all Python libraries define `__version__`, so this should be very general (especially since `__version__` is recommended by [PEP8](https://www.python.org/dev/peps/pep-0008/)).
This is analogous to:
```
$ python
>>> import aiohttp
>>> print(aiohttp.__version__)
2.3.3
>>> quit()
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 610 | 2,038 |
<issue_start>username_0: I want to create 9 sets and put them in vector.The following code error outs
```
class X{
vector > rowset(9,set());
};
Line 2: expected identifier before numeric constant
```
Following works ok. But i want to insert empty sets in vector so that i don't have to do a push\_back. Please suggest why the above code is erroring out.
```
class X{
vector > rowset;
};
```<issue_comment>username_1: It is not a command line tool. That's why it says `command not found`. It is a `pip` package. So, you can do this:
```
pip freeze | grep aiohttp
```
to find the version.
Upvotes: 0 <issue_comment>username_2: If you installed it with `pip` (>= 1.3), use
```
$ pip show aiohttp
```
For older versions,
```
$ pip freeze | grep aiohttp
```
`pip freeze` has the advantage that it shows editable VCS checkout versions correctly, while `pip show` does not.
... or
```
$ pip list | grep aiohttp
$ pip list --outdated | grep aiohttp
```
(`--outdated` to see Current and Latest versions of the packages).
**Credits**: [Find which version of package is installed with pip](https://stackoverflow.com/questions/10214827/find-which-version-of-package-is-installed-with-pip)
**Note**: the property `__version__` comes in handy, but [it is not always available](https://stackoverflow.com/a/20180597/2707864). This is an issue that evolved with time. YMMV.
Upvotes: 0 <issue_comment>username_3: A general way that works for pretty much any module, regardless of how it was installed is the following:
```
$ python -c "import aiohttp; print(aiohttp.__version__)"
2.3.3
```
What this does is run a Python interpreter, import the module, and print the module's `__version__` attribute. Pretty much all Python libraries define `__version__`, so this should be very general (especially since `__version__` is recommended by [PEP8](https://www.python.org/dev/peps/pep-0008/)).
This is analogous to:
```
$ python
>>> import aiohttp
>>> print(aiohttp.__version__)
2.3.3
>>> quit()
```
Upvotes: 3 [selected_answer]
|
2018/03/19
| 241 | 774 |
<issue_start>username_0: I have an Excel function that I want to move into Python. The BDP function is:
`=BDP("IBM US Equity","BEST_EBITDA","BEST_FPERIOD_OVERRIDE","1FY")`
```
from tia.bbg import LocalTerminal
resp = LocalTerminal.get_reference_data("IBM US Equity", "BEST_EBITDA")
```
how do I add overrides to this request?<issue_comment>username_1: Just passing the override as an additional parameter should work:
```
resp = LocalTerminal.get_reference_data("IBM US Equity", "BEST_EBITDA",
BEST_FPERIOD_OVERRIDE="1FY")
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Using `xbbg` you can just write:
```
from xbbg import blp
blp.bdp("IBM US Equity", "BEST_EBITDA", BEST_FPERIOD_OVERRIDE="1FY")
```
Upvotes: 0
|
2018/03/19
| 524 | 1,982 |
<issue_start>username_0: I'm writing a text classification system in Python. This is what I'm doing to canonicalize each token:
```
lem, stem = WordNetLemmatizer(), PorterStemmer()
for doc in corpus:
for word in doc:
lemma = stem.stem(lem.lemmatize(word))
```
The reason I don't want to just lemmatize is because I noticed that `WordNetLemmatizer` wasn't handling some common inflections. In the case of adverbs, for example, `lem.lemmatize('walking')` returns `walking`.
Is it wise to perform both stemming and lemmatization? Or is it redundant? Do researchers typically do one or the other, and not both?<issue_comment>username_1: The lemmatization of *walking* is ambiguous. Walking, when used as an adjective, is its own baseform (rather than walk).
**Correction**:
Research has shown that generally stemming outperforms lemmatization in IR tasks.
A qualitative comparison between the two and an explanation can be found [here](https://stackoverflow.com/a/11177381/9412325).
Upvotes: 2 <issue_comment>username_2: I think stemming a lemmatized word is redundant if you get the same result than just stemming it (which is the result I expect). Nevertheless, the decision between stemmer and lemmatizer depends on your need. My intuition said that steamming increses recall and lowers precision and the opposite for a lemmatization. Consider this scores, what matter for your specific problem? Other option talking about this scores is to calculate F-1 score which is the harmonic average of the precision and recall.
Upvotes: 1 <issue_comment>username_3: From my point of view, doing both stemming and lemmatization or only one will result in really SLIGHT differences, but I recommend for use just stemming because lemmatization sometimes need 'pos' to perform more presicsely.
For example, if you want to lemmatize "better", you should explicitly indicate pos: print(lemmatizer.lemmatize("better", pos="a"))
If not supplied, the default is "noun"
Upvotes: 3
|
2018/03/19
| 490 | 1,699 |
<issue_start>username_0: I have done the following snippet, a list where I went line by line and replaced the dots with commas, however in the end the list remains the same since only the line variable changes. How to update the list with the replaced values?
```
for line in mylist:
line=line.replace('.',',')
line=line.replace('a','b')
```
I am looking for a quick pythonic solution, other than using a 2nd list to save the replaced value. I'd like to use only 1 list, if possible and "update" it on the go.
I have multiple operations inside the `for`, for example in the way edited above, making the list update from the for is not possible as a "1 liner" like it's commonly done. I was looking for some sort of other way to update it if possible.<issue_comment>username_1: Try:
```
mylist[:] = [line.replace('.',',').replace('a','b') for line in mylist]
```
Upvotes: 2 <issue_comment>username_2: Something along this should work:
```
def do_stuff(elem):
return ...
for i in range(len(mylist)):
mylist[i] = do_stuff(mylist[i])
```
or
```
mylist[:] = [do_stuff(line) for line in mylist]
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: If you want to avoid creating a new list, do it like this:
```
for n, line in enumerate(mylist):
mylist[n] = line.replace('.',',')
```
You might prefer this if the list is very long. But if you're OK with creating a new list, username_1's solution is more "Pythonic."
Upvotes: 0 <issue_comment>username_4: Another one solution is to use str.translate, if replacements have always one character of length.
```
replace = lambda x: x.translate(str.maketrans('.a', ',b'))
mylist[:] = map(replace, mylist)
```
Upvotes: 0
|
2018/03/19
| 2,704 | 9,115 |
<issue_start>username_0: I have the following `Attendance` table in my Microsoft SQL Server 2016:
```
ID StudentID Date AbsenceReasonID
----------------------------------------------------
430957 10158 2018-02-02 2
430958 10158 2018-02-03 2
430959 10158 2018-02-04 11
430960 12393 2018-03-15 9
430961 1 2018-03-15 9
430962 12400 2018-03-15 9
430963 5959 2018-03-15 11
```
I would like to have a query that retrieves a group of rows where 3 or MORE absences have occurred consecutively by the `Date` column for a single student (`StudentID`). Ideally, the following data after running the query would be
```
ID StudentID Date AbsenceReasonID
----------------------------------------------------
430957 10158 2018-02-02 2
430958 10158 2018-02-03 2
430959 10158 2018-02-04 11
```
Note that if a student is absent on a Friday, I would like that to carry through over the weekend to Monday (Disregard Weekend dates).
If anymore information is required to better assist you in assisting me, please let me know. I have used the following query as a starter but know it is not what I am looking for:
```
SELECT
CONVERT(datetime, A.DateOF, 103),
A.SchoolNum, EI.FullName,
COUNT(A.SchoolNum) as 'Absences'
FROM
Attendance A
INNER JOIN
EntityInformation EI ON EI.SchoolNum = A.SchoolNum AND EI.Deleted = 0
INNER JOIN
Enrolment E ON EI.SchoolNum = E.SchoolNum AND E.Deleted = 0
GROUP BY
A.SchoolNum, A.DateOf, FullName
HAVING
COUNT(A.SchoolNum) > 1
AND A.DateOf = GETDATE()
AND A.SchoolNum in (SELECT SchoolNum FROM Attendance A1
WHERE A1.DateOf = A.DateOf -7)
```
This is more of a static solution that retrieves absences where the student's ID occurred twice in the past 7 days. This is neither consecutive or three or more days.<issue_comment>username_1: If you need to get the absence in a time period (let's say in past 7 days), then you can do something like this
```
SELECT
ID,
StudentID,
[Date],
AbsenceReasonID
FROM(
SELECT
ID,
StudentID,
[Date],
AbsenceReasonID,
COUNT(StudentID) OVER(PARTITION BY StudentID ORDER BY StudentID) AS con,
((DATEPART(dw, [Date]) + @@DATEFIRST) % 7) AS dw
FROM attendance
) D
WHERE
D.con > 2
AND [Date] >= '2018-02-02'
AND [Date] <= GETDATE()
AND dw NOT IN(0,1)
```
and based on your given data the output will be
```
| ID | StudentID | Date | AbsenceReasonID |
|--------|-----------|------------|-----------------|
| 430957 | 10158 | 2018-02-02 | 2 |
```
you could adjust the output as you like.
[SQL Fiddle](http://www.sqlfiddle.com/#!18/6b2a1c/3)
Upvotes: 0 <issue_comment>username_2: Try this:
`CTE` contains the absence dates when a student was absent on both the day before and the day after (excluding weekend). The 2 `UNION` at the end add back the first and last of each group and eliminate the duplicates.
```
with cte(id, studentId, dateof , absenceReasonId)
as
(
select a.*
from attendance a
where exists (select 1 from attendance preva
where preva.studentID = a.studentID
and datediff(day, preva.dateof, a.dateof)
<= (case when datepart(dw, preva.dateof) >= 5
then 8 - datepart(dw, preva.dateof)
else 1
end)
and preva.dateof < a.dateof)
and exists (select 1 from attendance nexta
where nexta.studentID = a.studentID
and datediff(day, a.dateof, nexta.dateof)
<= (case when datepart(dw, a.dateof) >= 5
then 8 - datepart(dw, a.dateof)
else 1
end)
and nexta.dateof > a.dateof))
select cte.*
from cte
union -- use union to remove duplicates
select preva.*
from
attendance preva
inner join
cte
on preva.studentID = cte.studentID
and preva.dateof < cte.dateof
and datediff(day, preva.dateof, cte.dateof)
<= (case when datepart(dw, preva.dateof) >= 5
then 8 - datepart(dw, preva.dateof)
else 1
end)
union
select nexta.*
from attendance nexta
inner join
cte
on nexta.studentID = cte.studentID
and datediff(day, cte.dateof, nexta.dateof)
<= (case when datepart(dw, cte.dateof) >= 5
then 8 - datepart(dw, cte.dateof)
else 1
end)
and nexta.dateof > cte.dateof
order by studentId, dateof
```
[sqlfiddle](http://sqlfiddle.com/#!18/8ead7/1)
Upvotes: 0 <issue_comment>username_3: You can use this to find your absence ranges. In here I use a recursive `CTE` to number all days from a few years while at the same time record their week day. Then use another recursive `CTE` to join absence dates for the same student that are one day after another, considering weekends should be skipped (read the `CASE WHEN` on the join clause). At the end show each absence spree filtered by N successive days.
```
SET DATEFIRST 1 -- Monday = 1, Sunday = 7
;WITH Days AS
(
-- Recursive anchor: hard-coded first date
SELECT
GeneratedDate = CONVERT(DATE, '2017-01-01')
UNION ALL
-- Recursive expression: all days until day X
SELECT
GeneratedDate = DATEADD(DAY, 1, D.GeneratedDate)
FROM
Days AS D
WHERE
DATEADD(DAY, 1, D.GeneratedDate) <= '2020-01-01'
),
NumberedDays AS
(
SELECT
GeneratedDate = D.GeneratedDate,
DayOfWeek = DATEPART(WEEKDAY, D.GeneratedDate),
DayNumber = ROW_NUMBER() OVER (ORDER BY D.GeneratedDate ASC)
FROM
Days AS D
),
AttendancesWithNumberedDays AS
(
SELECT
A.*,
N.*
FROM
Attendance AS A
INNER JOIN NumberedDays AS N ON A.Date = N.GeneratedDate
),
AbsenceSpree AS
(
-- Recursive anchor: absence day with no previous absence, skipping weekends
SELECT
StartingAbsenceDate = A.Date,
CurrentDateNumber = A.DayNumber,
CurrentDateDayOfWeek = A.DayOfWeek,
AbsenceDays = 1,
StudentID = A.StudentID
FROM
AttendancesWithNumberedDays AS A
WHERE
NOT EXISTS (
SELECT
'no previous absence date'
FROM
AttendancesWithNumberedDays AS X
WHERE
X.StudentID = A.StudentID AND
X.DayNumber = CASE A.DayOfWeek
WHEN 1 THEN A.DayNumber - 3 -- When monday then friday (-3)
WHEN 7 THEN A.DayNumber - 2 -- When sunday then friday (-2)
ELSE A.DayNumber - 1 END)
UNION ALL
-- Recursive expression: find the next absence day, skipping weekends
SELECT
StartingAbsenceDate = S.StartingAbsenceDate,
CurrentDateNumber = A.DayNumber,
CurrentDateDayOfWeek = A.DayOfWeek,
AbsenceDays = S.AbsenceDays + 1,
StudentID = A.StudentID
FROM
AbsenceSpree AS S
INNER JOIN AttendancesWithNumberedDays AS A ON
S.StudentID = A.StudentID AND
A.DayNumber = CASE S.CurrentDateDayOfWeek
WHEN 5 THEN S.CurrentDateNumber + 3 -- When friday then monday (+3)
WHEN 6 THEN S.CurrentDateNumber + 2 -- When saturday then monday (+2)
ELSE S.CurrentDateNumber + 1 END
)
SELECT
StudentID = A.StudentID,
StartingAbsenceDate = A.StartingAbsenceDate,
EndingAbsenceDate = MAX(N.GeneratedDate),
AbsenceDays = MAX(A.AbsenceDays)
FROM
AbsenceSpree AS A
INNER JOIN NumberedDays AS N ON A.CurrentDateNumber = N.DayNumber
GROUP BY
A.StudentID,
A.StartingAbsenceDate
HAVING
MAX(A.AbsenceDays) >= 3
OPTION
(MAXRECURSION 5000)
```
If you want to list the original Attendance table rows, you can replace the last select:
```
SELECT
StudentID = A.StudentID,
StartingAbsenceDate = A.StartingAbsenceDate,
EndingAbsenceDate = MAX(N.GeneratedDate),
AbsenceDays = MAX(A.AbsenceDays)
FROM
AbsenceSpree AS A
INNER JOIN NumberedDays AS N ON A.CurrentDateNumber = N.DayNumber
GROUP BY
A.StudentID,
A.StartingAbsenceDate
HAVING
MAX(A.AbsenceDays) >= 3
```
with this `CTE + SELECT`:
```
,
FilteredAbsenceSpree AS
(
SELECT
StudentID = A.StudentID,
StartingAbsenceDate = A.StartingAbsenceDate,
EndingAbsenceDate = MAX(N.GeneratedDate),
AbsenceDays = MAX(A.AbsenceDays)
FROM
AbsenceSpree AS A
INNER JOIN NumberedDays AS N ON A.CurrentDateNumber = N.DayNumber
GROUP BY
A.StudentID,
A.StartingAbsenceDate
HAVING
MAX(A.AbsenceDays) >= 3
)
SELECT
A.*
FROM
Attendance AS A
INNER JOIN FilteredAbsenceSpree AS F ON A.StudentID = F.StudentID
WHERE
A.Date BETWEEN F.StartingAbsenceDate AND F.EndingAbsenceDate
OPTION
(MAXRECURSION 5000)
```
Upvotes: 2 [selected_answer]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.