date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/20 | 760 | 3,308 | <issue_start>username_0: We have a few IBM Notes databases here, at least one hundred I think, and if we have to identify a user we are using the given Name at the moment. We are also connecting this with a database of all the employees here, using it to do time-management and administrative stuff.
Therefore we need to determine which user is which, as I said we are doing that by the name at the moment. But names change, so now we would like to change to a not changing ID. I thought we could use the key identifier, or one of them at least. So my question is, is there a way to get it through Lotus Script? If not, is there another way to identify the user of a certain key-file?<issue_comment>username_1: Lotus Notes and Domino do not have any builtin unique key identifier for users. It was never part of the design. You can't use the noteid of the Person document because that varies from one replica of the Domino Directory to another, and you should not use the unid, because although that's stable across replicas it can still change if you have to recreate the Person document, which you might have to do if the employee leaves your company and then comes back, or if the Person document is damaged.
The way most large organizations deal with this is to set the EmployeeID field in the Person document and use that as the unique identifier. Some organizations might also create unique identifiers and use them for the ShortName.
Upvotes: 1 <issue_comment>username_2: Whilst I don't diasagree with Richards answer in general, it is possible to 'capture' a Document-ID (UNID) in a separate 'created when composed' field. This will then hold a static 'unique' 32 character reference. Once this has been set, it should not change unless you have a process to change it. A UNID is based on/derived from a time-stamp so they are extremely unlikely to be reused or clash with future system generated unids, even after many years or many millions of docs being used. This captured value may or may not agree with the actual system assigned unid, but this generally doesn't matter.
If you are unhappy with a copy of an system unid, then this could be used on a temporary basis until it can be overridden with an external ID reference. Alternatively, use a proven external 'guid' reference and assign that to the records you want to track.
If the raw unid creates side issues for you, use @password to hash it to another unique value. This generates a quick/old MD5 style hash, but good enough for reference-IDs.
One other point to mention is that keeping previous names in a list is also feasible, so that matching an 'old name' is still viable. Either create an additional field in the person doc (admins may hate you for doing this) or add older names to the 'fullname' field list. This usually contains a list of name variations. If you add the older name to the bottom of the list (ie: append) the you and the system can match against this name (for logins and routing) but Notes only ever uses the first name in the list as the users 'official' name (for reader/author fields etc), which should be the current name. To find the name, just lookup the name in the ($Users) view if using the FullName field or create a new view in using your own field (again Admins may hate you more).
Upvotes: 0 |
2018/03/20 | 710 | 2,574 | <issue_start>username_0: I tried to integrate an existing table to my extension. The problem is that the content of the table isn't taken over. I created a new model with the name of the existing table and named the properties according to the existing column names. I also implemented the corresponding getters and setters of the properties.
[](https://i.stack.imgur.com/oeg7p.png)
The name of the existing table is `tx_institutsseminarverwaltung_domain_model_event.`
What is my failure in this case? Just want to access the data of an existing table from another extension.
Thanks in advance.
**UPDATE:**
I tried this:
```
/**
* Protected Variable objectManager wird mit NULL initialisiert.
*
* @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* @inject
*/
protected $objectManager = NULL;
```
and listAction():
```
/**
* action list
*
* @return void
*/
public function listAction() {
echo "test";
$theRepository = $this->objectManager->get('\TYPO3\institutsseminarverwaltung\Domain\Repository\EventRepository');
$yourRecords = $theRepository->findAll();
$this->view->assign('events', $yourRecords);
}
```
But no results returned.<issue_comment>username_1: You should use the repository linked to this table. Something like this :
```
$theRepository = $this->objectManager->get(\Your\VendorName\Domain\Repository\TheRepository::class);
$yourRecords = $theRepository->findAll();
```
Upvotes: 1 <issue_comment>username_2: How are you trying to "consume" or access the data from the other table in your extension?
Do you have a repository for the existing table (maybe there is already an existing repository, that you can reuse)?
See [german typo3 board mapping existing tables](https://www.typo3.net/forum/thematik/zeige/thema/118413/seite/2/) and [SO thread TYPO3 / How to make repository from existing table fe\_users?](https://stackoverflow.com/questions/18254124/typo3-how-to-make-repository-from-existing-table-fe-users)
Upvotes: 1 <issue_comment>username_3: solution is:
```
$querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$theRepository = $this->objectManager->get('TYPO3\\institutsseminarverwaltung\\Domain\\Repository\\EventRepository');
$theRepository->setDefaultQuerySettings($querySettings);
$yourRecords = $theRepository->findAll();
$this->view->assign('events', $yourRecords);
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 1,169 | 3,438 | <issue_start>username_0: I have a txt file with this lines:
```
2017-06-15 Take the car for inspection to change the wheels.mkd
2018-03-17 Crear un entorno virtual con Docker y xfce.mkd
2018-02-25 Envíar vídeo de explicación de configuración email de tunegocioenlanube a María.mkd
2018-03-08 crear curso tu formula emocional +tunegocio.mkd
```
I want to put in a array of bash the year, month and day:
```
year=( "2017","2018" )
month=( "03","06","02" )
day=( "08","15","17","25" )
```
Thanks for all.<issue_comment>username_1: You can to solve this using regex. See `awk` or `sed`
But, if regex it's so complex for you, you can solve the problem with a simpler form, using `cut` command.
`cut` is a command what allows to get a specific section of a line (similar to split in other languages).
You only have to set the delimiter with -d option, and select the field with -f
In your case, you can use, in each line of the file:
```
date=$(echo $line | cut -d " " -f 1)
year=$(echo $date | cut -d "-" -f 1)
month=$(echo $date | cut -d "-" -f 2)
day=$(echo $date | cut -d "-" -f 3)
```
With this, you can get the fields that you needs. Then, you can save this on a array or whatever you needs
To add elements to a existing array, you can read this post: <https://unix.stackexchange.com/questions/328882/how-to-add-remove-an-element-to-from-the-array-in-bash>
And, to read file line to line, this:
[Read a file line by line assigning the value to a variable](https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable)
Upvotes: 2 [selected_answer]<issue_comment>username_2: If the order isn't important, then you could use something like this:
```
#!/bin/bash
declare -A years months days # declare associative arrays
while read -r date file; do
IFS=- read -r year month day <<<"$date" # split date on -
# set keys in associative arrays
years[$year]=
months[$month]=
days[$day]=
done < file
# use keys to make arrays of values
year=( "${!years[@]}" )
month=( "${!months[@]}" )
day=( "${!days[@]}" )
```
If you want to sort the values in the output array, then you can change the final assignments to e.g.:
```
mapfile -d '' day < <(printf '%s\0' "${!days[@]}" | sort -zn)
```
This prints each of the keys in `days` followed by a null byte and sorts them in numerical order, saving the result into the array `day`.
Upvotes: 1 <issue_comment>username_3: You could do:
```
year=($(grep -Po '^\d+[^-]' InputFile.txt | uniq))
month=($(grep -Po '(?<=-)[0-9]+(?=-)' InputFile.txt | sort -u))
day=($(grep -Po '(?<=-)[0-9]+(?= )' InputFile.txt) | sort -u))
```
Sample output `echo ${day[@]}`:
```
08 15 17 25
```
Upvotes: 1 <issue_comment>username_4: ```
while read Line
do
echo $Line
var1=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $1}'`
var2=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $2}'`
var3=`echo "$Line" | awk 'BEGIN{FS=" "} {print $1}' | awk 'BEGIN{FS="-"} {print $3}'`
year+=("$var1")
month+=("$var2")
day+=("$var3")
done < array.txt
```
The above bash code will read the lines one by one from array.txt, extract the values and store it in an array.To print all the values in the array, you can use the following:
```
printf '%s\n' "${year[@]}"
printf '%s\n' "${month[@]}"
printf '%s\n' "${day[@]}"
```
Upvotes: 0 |
2018/03/20 | 489 | 1,533 | <issue_start>username_0: Why can't I go to the dynamic url like **"*<http://127.0.0.1:8000/movie/xyz>*"** with my code? `xyz` is movie name. Demo is my model's name.
This is my view.py:
```
from django.shortcuts import render
from .models import Demo
def home(request):
movie_list = Demo.objects.all()
return render(request, 'home.html', {movie_list': movie_list,})
def movie_detail(request,title):
detail = Demo.objects.get(title=title)
return render(request, 'detail.html', {'detail': detail})
```
urls.py:
```
from django.conf.urls import include, url
from django.contrib import admin
from netflix.views import home,movie_detail
urlpatterns = [url(r'^admin/', include(admin.site.urls)),
url(r'^movie', home),
url(r'^movie/(?P.\*)/$', movie\_detail, name='movie\_detail')]
```
detail.html:
```

##### {{detail.title}}
```<issue_comment>username_1: You miss terminate character in `url(r'^movie', home)`
Try this:
```
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^movie$', home),
url(r'^movie/(?P.\*)$', movie\_detail, name='movie\_detail')
]
```
Upvotes: 1 <issue_comment>username_2: You can do it like:
```
urlpatterns = [
url(r'^movie/(?P\d+)/$', movie\_detail, name='movie\_detail')
]
```
Upvotes: 0 <issue_comment>username_3: You need to add a terminating `$` to the /movie URL, otherwise it matches everything *starting* with that string.
```
url(r'^movie$', home),
```
Upvotes: 2 |
2018/03/20 | 235 | 789 | <issue_start>username_0: On renaming and moving a file using java code,the contents of the file is removed.How to rename and move a file using java code without erasing the content<issue_comment>username_1: You miss terminate character in `url(r'^movie', home)`
Try this:
```
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^movie$', home),
url(r'^movie/(?P.\*)$', movie\_detail, name='movie\_detail')
]
```
Upvotes: 1 <issue_comment>username_2: You can do it like:
```
urlpatterns = [
url(r'^movie/(?P\d+)/$', movie\_detail, name='movie\_detail')
]
```
Upvotes: 0 <issue_comment>username_3: You need to add a terminating `$` to the /movie URL, otherwise it matches everything *starting* with that string.
```
url(r'^movie$', home),
```
Upvotes: 2 |
2018/03/20 | 245 | 805 | <issue_start>username_0: Please, help to find appropriate query.
**Task**: table contains sms. Select latest sms from each conversation
**Table example**:
[](https://i.stack.imgur.com/fH5qp.png)
**Query result**
[](https://i.stack.imgur.com/bVmYB.png)
Thanks a lot in advance<issue_comment>username_1: Use *subquery* with correlation
```
select *
from table t
where date = (select max(date) from table where conversationid = t.conversationid)
```
Upvotes: 1 <issue_comment>username_2: Here is the solution to your problem:
```
SELECT MAX(id) AS ID, conversationId, Max(date) AS Date
FROM Table_name
GROUP BY conversationId
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 200 | 666 | <issue_start>username_0: When I split a string in java as shown in code below, it gives length as 3.
```
String data = "DK4..||VSDK4|";
String[] tokens = data.split("\\|");
System.out.println(tokens.length);
```
However it should be 4, what could be the reason behind this?<issue_comment>username_1: Use *subquery* with correlation
```
select *
from table t
where date = (select max(date) from table where conversationid = t.conversationid)
```
Upvotes: 1 <issue_comment>username_2: Here is the solution to your problem:
```
SELECT MAX(id) AS ID, conversationId, Max(date) AS Date
FROM Table_name
GROUP BY conversationId
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 447 | 1,488 | <issue_start>username_0: In JavaScript, I have an array `anArray` that could have several states like the following:
* the array might be empty `[]`
* the array might be containing exactly one value `[2]`
* the array might be containing multiple value but not in ordered index `[2, empty, 5, empty, empty, 10]` (obtained from chrome's console)
I want to count the exact number of element in that array, so:
* `[]` should give me `0`
* `[2]` should give me `1`
* `[2, empty, 5, empty, empty, 10]` should give me `3`
How can I achieve this?
What I already tried, say if the array's state was `[2, empty, 5, empty, empty, 10]`:
* accessing `anArray[1]` gave me error `"ReferenceError: element is not defined"`, because I think the index of `1` did not even existed.
* did compare eaach element with `null` or `undefined`, but like before, accessing empty element like `anArray[1]` will throw an error/warning before the evaluation
* used `in` like `1 in anArray`, but it gave me true everytime even if the element is empty.
Thanks in advance.
**EDIT**
Let me attach the snap I take directly from chrome console
[Please look me](https://i.stack.imgur.com/77411.png)<issue_comment>username_1: ```
anArray.reduce(c => c + 1,0)
```
As every array method skips unset array positions, this will count all elements of a sparse array
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
const arr = [2, , 5, , , 10]
const n = arr.filter(x => x).length
console.log(n)
```
Upvotes: 0 |
2018/03/20 | 685 | 2,260 | <issue_start>username_0: how can I remove emoji in text like this:
```
'ca va toi ;-) ?'
```
I used many solution about removing emoji but nothing work.
I want output like this:
```
ca va toi ?
```
I don't want to remove punctuation but only those thats form emojis.
Thanks<issue_comment>username_1: The following should work for you. You can add additional rules to make it generalize better.
```
x = 'ca va toi ;-) ?'
x = x.replace(';-)', '')
x = x.replace(';-(', '')
x = x.replace(';-|', '')
x = x.replace(';-D', '')
```
>
> 'ca va toi ?'
>
>
>
If you want to clean out all punctuation as well you can do the following
```
x = 'ca va toi ;-) ?'
''.join([i for i in x if (i >= 'a' and i<='z') or (i >= 'A' and i<='Z') or i == ' ')
```
>
> 'ca va toi '
>
>
>
Upvotes: 2 [selected_answer]<issue_comment>username_2: One simple way to do it is to specify a list of possible emojis.
```
emoji_list = [";-)", ":)"]
```
And then remove occurrences of those strings in your string.
```
# A dictionary with your emojis or any combination of characters you want to get rid of.
emoji_list = [";-)", ":)"]
# Your input string
string = 'ca va :) toi ;-) ?'
# Split the string into a list of substrings.
string_list = string.split()
# Using list comprehension, create a new list that excludes the emoji_list items.
clear_string = [string for string in string_list if string not in emoji_list]
# ALTERNATIVE a cleaner way is to use higher-order function filter to filter out the emojis.
clear_string = filter(lambda x: x not in emoji_list, string_list)
# Join the list into a string again.
output = " ".join(clear_string)
print(output)
```
You can make use of the list comprehension in python to create a list that excludes the substrings defined in `emoji_list`. Another way is to use the higher-order function `filter` to filter out those emojis.
You are then left with a new list that excludes those substrings you defined in `emoji_list` and then you are simply joining the list to a string to get your desired result.
**Note:** This is a very simple approach that can easily return a false positive (i.e a substring treated as emoji which in reality is not). These assumptions or cases are not covered by this solution.
Upvotes: 2 |
2018/03/20 | 593 | 1,890 | <issue_start>username_0: I am trying to match col C and col B from 2 different worksheets (wsMaster & wsSample) and retrieve col F from wsSample to put it inside col D in wsMaster. My code below run but there is no results. Anything wrong with my codes?
```
j = 2
Do While wsMaster.Cells(j, 3).Value <> ""
Set rngcell = wsSample.Range("B:B").Find(What:=wsMaster.Cells(j, 3), After:=wsSample.Range("A2"), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlRows, SearchDirection:=xlNext)
If Not rngcell Is Nothing Then wsMaster.Cells(j, 4) = rngcell.Offset(0, 4)
j = j + 1
Loop
```
Local windows show that my rngcell = Nothing but I'm not very sure why.
Thank you!!<issue_comment>username_1: You are searching in `Range("B:B")` AFTER `Range("A2")`. Thus, it does not find anything. Change the `After` range to correspond to the searched range.
Check this code, which has the searched value in the searched range, but it gives error 13, because the `After` is in another range:
```
Sub TestMe()
'On Error Resume Next
Dim rngCell As Range
Range("B1") = "test"
Set rngCell = Range("B:B").Find("test", Range("A1"))
If rngCell Is Nothing Then Debug.Print "Not Found!"
End Sub
```
If you uncomment the `On Error Resume Next` (which you are probably using), it will not find the value.
Upvotes: 2 <issue_comment>username_2: Actually, it's surprising your code runs, it should give you
>
> run-time error 13: Type mismatch
>
>
>
Either change to:
```
Set rngcell = wsSample.Range("B:B").Find(What:=wsMaster.Cells(j, 3), After:=wsSample.Range("B2"), LookIn:=xlValues, Lookat:=xlWhole)
```
or just remove the `After` entirely:
```
Set rngcell = wsSample.Range("B:B").Find(What:=wsMaster.Cells(j, 3), LookIn:=xlValues, Lookat:=xlWhole)
```
**Note**: You could also change `Range("B:B")` to `Columns(2)`.
Upvotes: 3 [selected_answer] |
2018/03/20 | 611 | 2,074 | <issue_start>username_0: I know that the j2ee spec doesn't allow for directly handing password expiry and change. See [IBM redbook "WebSphere Application Server on z/OS and Security Integration" at page 57](http://www.redbooks.ibm.com/redpapers/pdfs/redp4161.pdf) where this is clearly stated.
Has anyone managed to create a login suite that uses extensions to detect expired passwords, and allows them to be changed on some other page? I've tried using the com.ibm.390 suite but this seems to fail CICS authorisation when invoked, possibly because the caller is as yet unauthenticated.
This is a java -> ibm cics question so please could you constrain answers and comments to this sphere rather than Spring etc?
java 1.8, cics 5.3, liberty v17
Its the enquiry mechanism and update mechanism that I need assistance with, I can handle the login suite, filters and servlets myself.<issue_comment>username_1: I suggest looking at the [CICS API](https://www.ibm.com/docs/en/cics-ts/5.6?topic=development-cics-command-summaryl) and mapping to [JCICS](https://www.ibm.com/docs/en/cics-ts/5.6?topic=applications-java-development-using-jcics) classes. You could write COBOL (or PL/I, or Assembler) programs wrapped around those CICS APIs not exposed by the JCICS classes, then `invoke` with a channel or commarea.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You won't be able to use [com.ibm.os390.security.PlatformUser](https://www.ibm.com/support/knowledgecenter/en/SSYKE2_8.0.0/com.ibm.java.zsecurity.api.80.doc/com.ibm.os390.security/index.html) in a CICS JVM as it uses \_\_passwd which requires the caller to be program controlled, which is not feasible. If you can call into a CICS program this could issue a [CHANGE PASSWORD](https://www.ibm.com/support/knowledgecenter/SSGMCP_5.4.0/reference/commands-api/dfhp4_changepassword.html) command. You may also be able to create a Liberty [JASPIC](https://www.ibm.com/support/knowledgecenter/SS7K4U_liberty/com.ibm.websphere.wlp.zseries.doc/ae/twlp_develop_jaspic.html) provider to assist in the process.
Upvotes: 2 |
2018/03/20 | 496 | 1,940 | <issue_start>username_0: Now I write sample routes without grouping for localization my Laravel project :
```
Route::get('/{lang?}', function($lang=null){
App::setlocale($lang);
return view('welcome');
});
```
How I can create group of routes correctly for more one language with prefix or with argument instead of prefix or with domain routing in Laravel 5.6? And can be created localization in prefix and domain routing examples:
```
http://website.com/en
http://en.website.com
```<issue_comment>username_1: You can use group in routes to manage multiple routes and then apply functionality like middleware on them. For example:
```
Route::group([ 'middleware' => 'name', 'namespace' => 'prefix' ], function($router){
$router->get('/xyz','Controller@function);
});
```
Upvotes: 0 <issue_comment>username_2: Well here's my best try:
Keep all your route definitions in e.g. `web.php`
You can then use multi-domain routing in your `RouteServiceProvider`:
```
Route::group([
'domain' => '{lang}.example.com'
'middleware' => LangMiddleware::class,
'namespace' => $this->namespace // I guess?
], function ($router) {
require base_path('routes/web.php');
});
```
In addition, using the same routes you can also do prefixed route groups:
```
Route::group([
'middleware' => LangMiddleware::class,
'namespace' => $this->namespace,
'prefix' => {lang} //Note: This works but is undocumented so may change
], function ($router) {
require base_path('routes/web.php');
});
```
This all relies on that `LangMiddleware` middleware class which can be something like:
```
class LangMiddleware {
public function handle($request, $next) {
if ($request->route("lang")) {
// also check if language is supported?
App::setlocale($request->route("lang"));
}
return $next($request);
}
}
```
Upvotes: 2 |
2018/03/20 | 489 | 1,804 | <issue_start>username_0: I'm trying to make multiple functions where it shows a certain point if..
multiple conditions in excel showing points
```
if A1 is bigger than 500 shows 0
if A1 is smaller than 500 but greater than 200 then shows 0.3
if A1 is smaller than 200 but greater than 100 then shows 0.6
if A1 is smaller than 100 then shows 1
```
Thank you<issue_comment>username_1: You can use group in routes to manage multiple routes and then apply functionality like middleware on them. For example:
```
Route::group([ 'middleware' => 'name', 'namespace' => 'prefix' ], function($router){
$router->get('/xyz','Controller@function);
});
```
Upvotes: 0 <issue_comment>username_2: Well here's my best try:
Keep all your route definitions in e.g. `web.php`
You can then use multi-domain routing in your `RouteServiceProvider`:
```
Route::group([
'domain' => '{lang}.example.com'
'middleware' => LangMiddleware::class,
'namespace' => $this->namespace // I guess?
], function ($router) {
require base_path('routes/web.php');
});
```
In addition, using the same routes you can also do prefixed route groups:
```
Route::group([
'middleware' => LangMiddleware::class,
'namespace' => $this->namespace,
'prefix' => {lang} //Note: This works but is undocumented so may change
], function ($router) {
require base_path('routes/web.php');
});
```
This all relies on that `LangMiddleware` middleware class which can be something like:
```
class LangMiddleware {
public function handle($request, $next) {
if ($request->route("lang")) {
// also check if language is supported?
App::setlocale($request->route("lang"));
}
return $next($request);
}
}
```
Upvotes: 2 |
2018/03/20 | 1,024 | 3,189 | <issue_start>username_0: I need to filter/search all links (png,jpg,mp3) from an XXML file but I got stuck there. I did for example to get all mp3 but I did it knowing that was there, but for example if I put other file where the path is different, then it won't detect it.
```
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a){
echo '<'.$a->PATH.'>
';
}
```
[Example XML](https://i.stack.imgur.com/jMktW.png)<issue_comment>username_1: You could get the extension of each file and compare it to an array of "accepted extensions". Then use, `continue` to skip to write link:
```
$accepted_exts = ['png','jpg','mp3'];
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
$ext = strtolower(substr($path, strrpos($path, '.') + 1));
if (!in_array($ext, $accepted_exts)) continue ; // continue to next iteration
echo '<'.$path.'>
'; // write the link
}
```
---
To get other links:
```
$accepted_exts = ['png','jpg','mp3'];
$links = [] ;
foreach($xml->HEAD as $items) {
foreach ($items as $item) {
$path = (string)$item;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
}
foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
$path = $a->PATH;
if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
$links[] = $path ;
}
foreach ($links as $path) {
echo '<'.$path.'>
'; // write the link
}
function get_ext($path) {
return strtolower(substr($path, strrpos($path, '.') + 1));
}
```
Will outputs:
```
<http://player.glifing.com/img/Player/blue.png>
<http://player.glifing.com/img/Player/blue_intro.png>
<http://player.glifing.com/upload/fondoinstrucciones2.jpg>
<http://player.glifing.com/upload/stopbet2.png>
<http://player.glifing.com/upload/goglif2.png>
<http://player.glifing.com/img/Player/Glif 3 OK.png>
<http://player.glifing.com/img/Player/BetPensant.png>
<http://player.glifing.com/audio/Player/si.mp3>
<http://player.glifing.com/audio/Player/no.mp3>
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: To save having to know which individual tags may contain a URL, you can use XPath to search for any text content that starts with "http://" or "https://". Then process each part to check the extension.
```
$xml = simplexml_load_file("data.xml");
$extensions = ['png', 'jpg', 'mp3'];
$links = $xml->xpath('//text()[starts-with(normalize-space(), "http://")
or starts-with(normalize-space(), "https://")]');
foreach ( $links as $link ) {
$link = trim(trim($link),"_");
$path = parse_url($link, PHP_URL_PATH);
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if ( in_array($extension, $extensions)) {
// Do something
echo $link.PHP_EOL;
}
else {
echo "Rejected:".$link.PHP_EOL;
}
}
```
I found that using `trim()` helped clean up URL's which had blank lines after them (or at least some extra whitespace). And convert them all to lower to make checking easier.
You may not need the rejected bit, but I put it in to test my code.
You would have to repeat the above
Upvotes: 0 |
2018/03/20 | 1,139 | 3,681 | <issue_start>username_0: I am trying to test below method and i get funny dates.
```
public Pool AddPool(PoolDto poolDto, int createdByWho)
{
var pool = _mapper.Map(poolDto);
\_mycontext.Pools.Add(pool);
\_mycontext.Save();
}
```
this is my test
```
public void test_the_add_pool_method()
{
var date = DateTime.Parse(DateTime.Now.ToString(), new CultureInfo("en-US", true)).Date;
var poolDto= new PoolDto
{
RequestorId = 1,
ClientId = 1,
Description = "Pool request",
PoolStates = new List(),
BookingDate = date,
BookingFrom = date,
BookingTo = date.AddDays(1)
};
service.AddPool(poolDto,1);
Assert.That(Pools.Count(), Is.EqualTo(1));
Assert.That(Pools.First().RequestorId, Is.EqualTo(1));
Assert.That(Pools.First().ClientId, Is.EqualTo(1));
Assert.That(Pools.First().Description, Is.EqualTo("Pool request"));
Assert.That(Pools.First().BookingDate, Is.EqualTo(DateTime.Now.Date));
Assert.That(Pools.First().BookingFrom, Is.EqualTo(DateTime.Now.Date));
Assert.That(Pools.First().BookingTo, Is.EqualTo(DateTime.Now.AddDays(1).Date));
}
```
when i run the test it fails with this error Message:
```
Expected: 2018-03-20 00:00:00
But was: 0001-01-01 00:00:00
```
i did not capture `0001-01-01 00:00:00` and it is very confusing where is that date come from.
How can i find out the where abouts of the `0001-01-01 00:00:00` ??<issue_comment>username_1: "0001-01-01 00:00:00" is the default value for a DateTime (`default(DateTime)`). It is the value that a DateTime will have if it has not been set to anything.
My guess would be that your mapper is not mapping that value across.
P.S. did you really want to `var date = DateTime.Parse(DateTime.Now.ToString(), new CultureInfo("en-US", true)).Date;` (i.e. is that culture part relevant), or do you just not know that you could do `var date=DateTime.Today;`?
**UPDATE**
It's really hard to help you with more specific detail, since:
1. You haven't told us which line is throwing the assert failure (so we don't know which date it's complaining about)
2. We don't have the definition of Pool or PoolDto
3. We don't even know what type "\_mapper" is (we're just guessing that it's an AutoMapper)
I'm assuming that `service.AddPool(PoolDto,1);` is a typo since PoolDto is a type - I expect that should be `service.AddPool(pool,1);`?
Also I would recommend against having tests where you just use "1" for multiple things. If your code has a bug in it, and the RequestorId is accidentally put in the ClientId field and vice versa, then this test will pass even though the code doesn't work. Similar problem if you use the same date for different fields.
Upvotes: 1 <issue_comment>username_2: You need to pass pool to test not the PoolDto
```
public void test_the_add_pool_method()
{
var date = DateTime.Parse(DateTime.Now.ToString(), new CultureInfo("en-US", true)).Date;
var pool = new PoolDto
{
RequestorId = 1,
ClientId = 1,
Description = "Pool request",
PoolStates = new List(),
BookingDate = date,
BookingFrom = date,
BookingTo = date.AddDays(1)
};
service.AddPool(PoolDto,1); //service.AddPool(pool ,1);
Assert.That(Pools.Count(), Is.EqualTo(1));
Assert.That(Pools.First().RequestorId, Is.EqualTo(1));
Assert.That(Pools.First().ClientId, Is.EqualTo(1));
Assert.That(Pools.First().Description, Is.EqualTo("Pool request"));
Assert.That(Pools.First().BookingDate, Is.EqualTo(DateTime.Now.Date));
Assert.That(Pools.First().BookingFrom, Is.EqualTo(DateTime.Now.Date));
Assert.That(Pools.First().BookingTo, Is.EqualTo(DateTime.Now.AddDays(1).Date));
}
```
Upvotes: 0 |
2018/03/20 | 315 | 1,129 | <issue_start>username_0: Suppose, I have a table like below -
```
Id | Key | Value
----------------
01 | one | 1_val
02 | two | 2_val
```
I want the the two columns - Key and Value - as `HashMap`
What is the most suitable way to do that using Spring JDBC Template?<issue_comment>username_1: You could have a method to create that object for you
```
public Map getTableAsMap() throws SQLException
{
ResultSet rs = connection.createStatement().executeQuery("SELECT Key, Value FROM KeyValueTable;");
Map map = new HashMap<>();
while (rs.next())
{
map.put(rs.getString(1), rs.getString(2));
}
return map;
}
```
EDIT: This is not Spring but you should get the idea.
Upvotes: -1 <issue_comment>username_2: You need something along the lines:
```
JdbcTemplate template = new JdbcTemplate(dataSource);
ResultSetExtractor> rse = rs -> {
HashMap retVal = new HashMap<>();
while(rs.next()) {
retVal.put(rs.getString("Key"), rs.getString("Value"));
}
return retVal;
};
HashMap result = template.query("select Key, Value from Table", rse);
```
Why do you want to have this as `HashMap`?
Upvotes: 1 |
2018/03/20 | 682 | 1,703 | <issue_start>username_0: I have a dataframe looking like this
```
name value1 value2 value3
X 1 . 2 . 6
Y 2 . 5 . 7
```
Is there a way to make this into a single row dataframe using dplyr?
```
x_value1 x_value2 x_value3 y_value1 y_value2 y_value3
```
I tried using spread but it complains about the multiple columns value1 to value3.
Thx
c<issue_comment>username_1: We can do this by `gather`ing into 'long' format, `unite` the 'name', 'key' columns and then do the `spread`
```
library(tidyverse)
gather(df1, key, value, -name) %>%
unite(namekey, name, key) %>%
spread(namekey, value)
# X_value1 X_value2 X_value3 Y_value1 Y_value2 Y_value3
#1 1 2 6 2 5 7
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Since a `data.frame` is just a list of lists, you don't need anything fancy to do this. The plain old concatenation function `c` can do it for you. Calling `c` directly won't work because that will just return the data frame, but `do.call` will splice a list of arguments into actual arguments, so `do.call(c(df))` will do what you want.
```
> df <- data.frame(x = rnorm(3), y = rnorm(3), z = rnorm(3))
> df
x y z
1 -0.02600453 1.5596611 0.1419269
2 0.61540806 1.0944946 0.7526085
3 -0.79033738 0.1369467 -0.1867725
> do.call(c, df)
x1 x2 x3 y1 y2
-0.02600453 0.61540806 -0.79033738 1.55966113 1.09449457
y3 z1 z2 z3
0.13694672 0.14192691 0.75260853 -0.18677246
```
If you absolutely *want* to use `dplyr`, then I guess you could do
```
df %>% do.call(c, .)
```
;)
Upvotes: 0 |
2018/03/20 | 1,171 | 3,075 | <issue_start>username_0: I am developing an iOS app where I want to get the size of user's real face so that I can suggest him/her suitable (matched) sized glasses.
I have detected user's face using **OpenCV** and got various dimensions of *eyes, nose, face,* etc.
But I want the real size from that dimensions (i.e in **millimetres** that I am getting in pixels).
I have searched a lot but could not get any solution matching with my requirement.
Has anyone idea how to calculate real size (i.e in millimetres) of the someone's face?
Thank you.<issue_comment>username_1: If you have no reference point for size in the image, i guess there is really no way to tell the exact size. You would need at least one length that correlates to your picture to get some sort of a result.
That said, this would only work a 100% accurately on images of plain objects, because objects further away seem to be smaller in an image (like, e.g. [here](http://www.alamy.com/stock-photo-miniature-of-the-eiffel-tower-with-the-real-eiffel-tower-background-48300081.html?pv=1&stamp=2&imageid=003E45CC-AA24-4077-BD4D-CC6B2C524648&p=102532&n=0&orientation=0&pn=1&searchtype=0&IsFromSearch=1&srch=foo%3Dbar%26st%3D0%26pn%3D1%26ps%3D100%26sortby%3D2%26resultview%3DsortbyPopular%26npgs%3D0%26qt%3Dfrance%2520miniature%26qt_raw%3Dfrance%2520miniature%26lic%3D3%26mr%3D0%26pr%3D0%26ot%3D0%26creative%3D%26ag%3D0%26hc%3D0%26pc%3D%26blackwhite%3D%26cutout%3D%26tbar%3D1%26et%3D0x000000000000000000000%26vp%3D0%26loc%3D0%26imgt%3D0%26dtfr%3D%26dtto%3D%26size%3D0xFF%26archive%3D1%26groupid%3D%26pseudoid%3D%26a%3D%26cdid%3D%26cdsrt%3D%26name%3D%26qn%3D%26apalib%3D%26apalic%3D%26lightbox%3D%26gname%3D%26gtype%3D%26xstx%3D0%26simid%3D%26saveQry%3D%26editorial%3D1%26nu%3D%26t%3D%26edoptin%3D%26customgeoip%3D%26cap%3D1%26cbstore%3D1%26vd%3D0%26lb%3D%26fi%3D2%26edrf%3D%26ispremium%3D1 "stockphoto of eiffel tower next to miniture")).
You would need multiple pictures from different sides (all with a size reference) and there would be a horrendous amount of calculations to do.
The focal length of the camera will distort your image as well, making accurate measurement even harder (see [comparision of different focal lengths with different distances to the face](https://bakerdh.files.wordpress.com/2012/05/allsmall.jpg)).
Upvotes: 1 <issue_comment>username_2: I think there are two ways of doing it.
1. You have an object of *known size* in the image that you can use to compare with. That object must also be at the same (or known) distance from the camera as the face.
2. If the camera supports depth, you can get the distance to the face from the camera, and using that to calculate the actual size of the face. This option is currently only available on iPhone X. The accuracy of the depth data can vary, so I am not sure how well it might work for you.
[Read more about capturing depth data here](https://stackoverflow.com/a/45092986/4543629)
[Read more on depth data accuracy here](https://developer.apple.com/documentation/avfoundation/avdepthdataaccuracy?language=objc)
Upvotes: 2 |
2018/03/20 | 1,186 | 4,169 | <issue_start>username_0: **Question**
How to use Oracle DB sequences without losing the next sequence number in case of roll-back?
**Facts collected**
1 - In Oracle, we can create a sequence and use two main calls (`NEXTVAL`) to get the next sequence value and (`CURRVAL`) to get the current sequence value.
2 - When we call (`NEXTVAL`) will always get the next number and we will lose it if there is a rollback. In other words, Oracle sequence does not care if there is a roll-back or commit; whenever you are calling it, it will give a new number.
**Possible answers I found so far**
1 - I was thinking to create a simple table with one column of type (NUMBER) to service this purpose.
Simply pick the value and use it. If operation succeeded I will increment column value. Otherwise, I will keep it as it is for the next application call.
2 - Another way I found here ([How do I reset a sequence in Oracle?](https://stackoverflow.com/questions/51470/how-do-i-reset-a-sequence-in-oracle)) is to use (`ALTER SEQUENCE`) like the following if I want to go one step back.
That is, if the sequence is at 101, I can set it to 100 via
```
ALTER SEQUENCE serial INCREMENT BY -1;
SELECT serial.NEXTVAL FROM dual;
ALTER SEQUENCE serial INCREMENT BY 1;
```
**Conclusion**
Are any of the suggested solutions is good? Is their any better approach?<issue_comment>username_1: From my point of view, you should use a sequence and stop worrying about gaps.
From your point of view, I'd say that altering the sequence is *worse* than having a table. Note that access to that table must be restricted to a single user, otherwise you'll get duplicate values if two (or more) users access it simultaneously.
Here's a sample code; have a look, use/adjust it if you want.
```
SQL> create table broj (redni_br number not null);
Table created.
SQL>
SQL> create or replace function f_get_broj
2 return number
3 is
4 pragma autonomous_transaction;
5 l_redni_br broj.redni_br%type;
6 begin
7 select b.redni_br + 1
8 into l_redni_br
9 from broj b
10 for update of b.redni_br;
11
12 update broj b
13 set b.redni_br = l_redni_br;
14
15 commit;
16 return (l_redni_br);
17 exception
18 when no_data_found
19 then
20 lock table broj in exclusive mode;
21
22 insert into broj (redni_br)
23 values (1);
24
25 commit;
26 return (1);
27 end f_get_broj;
28 /
Function created.
SQL> select f_get_broj from dual;
F_GET_BROJ
----------
1
SQL> select f_get_broj from dual;
F_GET_BROJ
----------
2
SQL>
```
Upvotes: 2 <issue_comment>username_2: You can create a sequence table.
```
CREATE TABLE SEQUENCE_TABLE
(SEQUENCE_ID NUMBER,
SEQUENCE_NAME VARCHAR2(30 BYTE),
LAST_SEQ_NO NUMBER);
```
And in your PL/SQL block, you can get the sequence using below lines of code,
```
declare
CURSOR c1 IS
SELECT last_seq_no
FROM sequence_table
WHERE sequence_id = 21
FOR UPDATE NOWAIT;
v_last_seq_no NUMBER;
v_new_seq_no NUMBER;
resource_busy EXCEPTION;
PRAGMA EXCEPTION_INIT(resource_busy, -54);
BEGIN
LOOP
BEGIN
OPEN c1;
FETCH c1 INTO v_last_seq_no;
CLOSE c1;
v_new_seq_no := v_last_seq_no+1;
EXIT;
EXCEPTION
WHEN resource_busy THEN
NULL;
--or something you want to happen
END;
END LOOP;
--after the this line, you can put an update to the sequence table and be sure to commit/rollback at the end of the pl/sql block;
END;
/
ROLLBACK;
--or
COMMIT;
```
Try to run the PL/SQL code above in two oracle sessions to understand. Basically, if Oracle DB session 1 will run the code, the record queried from the cursor will be lock. So, if other session will run the same code, that session will wait for session 1's rollback/commit to finish running the code. Through this, two sessions won't have the same sequence\_no and you have a choice not to update the sequence if you issue a rollback for some reasons.
Upvotes: 1 |
2018/03/20 | 1,494 | 4,623 | <issue_start>username_0: I know add function to prototype doesn't cost more memory usage, prototype are share to all instances. So ok for memory but, what about global time to create instance ? Load functions's index at each new Object cost more time if the functions's index is bigger, no?
**Add lot of functions in Object prototype, it will decrease global performances ?**
For exemple, if I want add all functions of <http://underscorejs.org> lib directly in prototype of Object or Array, to write `myObject.where(...)` insteadof `_.where(myObject, ...)`
**it was good or bad practice ?**<issue_comment>username_1: >
> So ok for memory but, what about global time to create instance ? Load functions's index at each new Object cost more time if the functions's index is bigger, no?
>
>
>
No. When a new instance is created, it doesn't get a copy of everything on its prototype, it gets a reference to its prototype. So the number of properties on its prototype has no effect whatsoever on the time required to create an instance.
That is, we start (upon global initialization) with something like this in memory (ignoring a lot of details):
```
+−−−−−−−−−−−−+
Object−−−−−−−−−−>| (function) |
+−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+
| prototype |−−−−−−−−−>| (object) |
+−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+
| hasOwnProperty |
| toString |
| valueOf |
| ... |
+−−−−−−−−−−−−−−−−+
```
then if we do this:
```
var o = {};
```
...we have something like this:
```
+−−−−−−−−−−−−+
Object−−−−−−−−−−>| (function) |
+−−−−−−−−−−−−+ +−−−−−−−−−−−−−−−−+
| prototype |−−−−−+−−−>| (object) |
+−−−−−−−−−−−−+ | +−−−−−−−−−−−−−−−−+
| | hasOwnProperty |
| | toString |
| | valueOf |
| | ... |
| +−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−+ |
o−−−−−−−−−−−−−−−>| (object) | |
+−−−−−−−−−−−−−−−+ |
| [[Prototype]] |−−+
+−−−−−−−−−−−−−−−+
```
---
>
> For exemple, if I want add all functions of <http://underscorejs.org> lib directly in prototype of `Object` or `Array`, to write `myObject.where(...)` insteadof `_.where(myObject, ...)`
> it was good or bad practice ?
>
>
>
Whether it's good or bad practice is a matter of opinion and thus off-topic for SO. There are some objective issues to consider:
* If you do, you **must** make the new properties non-enumerable (via `Object.definedPropety`) so they don't show up in `for-in` and `Object.keys`; otherwise, you'll break a lot of thinsg.
* If JavaScript gets a standard `where`, you suddenly have a conflict to deal with.
* If you use a library that accepts objects with optional features, one of which happens to be called `where`, and you pass an object to that library, the library will assume that `where` is the one it's looking for.
Upvotes: 2 <issue_comment>username_2: A debate as old as time. Performance wise, going with Class based and other prototypical inheritance methodologies can create side effects later on as your application scales. This, will effect performance. Also, extending the prototype in a classical inheritance situation means each new instance has to run up the prototype chain to execute, slowing down performance. Lodash and other utils are great helpers but I try avoiding them in production in favor of a more efficient vanilla solution that doesn't rely on more deps to bloat the code base. Factory functions offer an alternative to extending native JS objects, and since they are only functions, execution doesn't need to worry about building to the prototype. As such, you get a boost in performance. Also, the context of `this` is much simpler to preserve and you don't have to worry about stupid bugs when forgetting to write `new` in front of your class instance. ES6 introduced classes and many have many the jump to using them without questioning potential bottlenecks. It's not a black and white scenario. All about choosing the best solution that fits with your project needs.
Upvotes: -1 |
2018/03/20 | 1,383 | 4,469 | <issue_start>username_0: For subtraction of pointers `i` and `j` to elements of the same array object [the note in [expr.add#5]](http://eel.is/c++draft/expr.add#5.note-1) reads:
>
> [ *Note:* If the value *i−j* is not in the range of representable values of type `std::ptrdiff_t`, the behavior is undefined. — *end note* ]
>
>
>
But given [[support.types.layout#2]](http://eel.is/c++draft/support.types.layout#2), which states that (**emphasis** mine):
>
> 2. The type `ptrdiff_t` is an implementation-defined signed integer type that **can hold** the difference of two subscripts in an array object, as described in [[expr.add]](http://eel.is/c++draft/expr.add).
>
>
>
Is it even possible for the result of `i-j` not to be in the range of representable values of `ptrdiff_t`?
PS: I apologize if my question is caused by my poor understanding of the English language.
**EDIT:** Related: [Why is the maximum size of an array "too large"?](https://stackoverflow.com/q/42574890/3919155)<issue_comment>username_1: >
> Is it even possible for the result of `i-j` not to be in the range of representable values of `ptrdiff_t`?
>
>
>
Yes, but it's unlikely.
In fact, `[support.types.layout]/2` does not say much except the proper rules about pointers subtraction and `ptrdiff_t` are defined in `[expr.add]`. So let us see this section.
>
> ### [`[expr.add]/5`](http://eel.is/c++draft/expr.add#5.sentence-1)
>
>
> When two pointers to elements of the same array object are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as `std::ptrdiff_t` in the header.
>
>
>
First of all, note that the case where `i` and `j` are subscript indexes of different arrays is not considered. This allows to treat `i-j` as `P-Q` would be where `P` is a pointer to the element of an array at subscript `i` and `Q` is a pointer to the element of *the same* array at subscript `j`. In deed, subtracting two pointers to elements of different arrays is *undefined behavior*:
>
> ### [`[expr.add]/5`](http://eel.is/c++draft/expr.add#5.sentence-2)
>
>
> If the expressions `P` and `Q` point to, respectively, elements `x[i]` and `x[j]` of the same array object `x`, the expression `P - Q` has the value `i−j`
> ; **otherwise, the behavior is undefined**.
>
>
>
As a conclusion, with the notation defined previously, `i-j` and `P-Q` are defined to have the same value, with the latter being of type [`std::ptrdiff_t`](http://en.cppreference.com/w/cpp/types/ptrdiff_t). But nothing is said about the possibility for this type to hold such a value. This question can, however, be answered with the help of [`std::numeric_limits`](http://en.cppreference.com/w/cpp/types/numeric_limits); especially, one can detect if an array `some_array` is *too big* for `std::ptrdiff_t` to hold all index differences:
```
static_assert(std::numeric_limits::max() > sizeof(some\_array)/sizeof(some\_array[0]),
"some\_array is too big, subtracting its first and one-past-the-end element indexes "
"or pointers would lead to undefined behavior as per [expr.add]/5."
);
```
Now, on usual target, this would usually not happen as `sizeof(std::ptrdiff_t) == sizeof(void*)`; which means an array would need to be stupidly big for `ptrdiff_t` to overflow. But there is no guarantee of it.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I think it is a bug of the wordings.
The rule in [expr.add] is inherited from the same rule for pointer subtraction in the C standard. In the C standard, `ptrdiff_t` is not required to hold any difference of two subscripts in an array object.
The rule in [support.types.layout] comes from [Core Language Issue 1122](http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1122). It added direct definitions for `std::size_t` and `std::ptrdiff_t`, which is supposed to solve the problem of circular definition. I don't see there is any reason (at least not mentioned in any official document) to make `std::ptrdiff_t` hold any difference of two subscripts in an array object. I guess it just uses an improper definition to solve the circular definition issue.
As another evidence, [[diff.library]](http://www.eel.is/c++draft/diff.library) does not mention any difference between `std::ptrdiff_t` in C++ and `ptrdiff_t` in C. Since in C `ptrdiff_t` has no such constraint, in C++ `std::ptrdiff_t` should not have such constraint too.
Upvotes: 1 |
2018/03/20 | 1,417 | 5,362 | <issue_start>username_0: I'm building a project using [angular 5.x](https://angular.io/) and [aws-amplify](https://github.com/aws/aws-amplify). I successfully managed to sign-up, confirm and sign-in my users via [aws-cognito](https://eu-central-1.console.aws.amazon.com/cognito/) and now, I would like to retrieve user's `jwt` to add it at requests header to perform CRUD operations on my [dynamoDb](http://aws.amazon.com/DynamoDB%E2%80%8E) collection.
Unluckily, when I try to perform such operation on dynamo I get the following error:
```
{
"message": "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=xxxxx"
}
```
I get user's token using the following **Cognito.service**:
```
import { Injectable } from '@angular/core';
/** rxjs **/
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
/** 3rd party **/
import { Auth } from 'aws-amplify';
@Injectable()
export class CognitoService {
getJwtToken(): Observable {
return this.getCurrentSession()
.switchMap((token) => {
return of(token.getIdToken().getJwtToken());
})
}
private getCurrentSession(): Observable {
return fromPromise(Auth.currentSession());
}
}
```
That get's called by:
```
this.cognitoService.getJwtToken()
.subscribe((token: string) => {
this.dynamoService.get(
'testResource?id=someValue',
{
Authorization: token
}
)
})
```
And where **Dynamo.service** is the following:
```
import { Injectable } from '@angular/core';
/** rxjs **/
import { fromPromise } from 'rxjs/observable/fromPromise';
import { Observable } from 'rxjs/Observable';
/** 3rd party **/
import { API } from 'aws-amplify';
/** App Environment **/
import { environment } from '../../../environments/environment';
@Injectable()
export class DynamoDBService {
apiName = environment.amplify.API.endpoints[0].name;
get(path: string, headers: any): Observable {
return fromPromise(
API.get(
this.apiName,
path,
{
headers: headers
}
)
);
}
}
```
My environment looks like:
```
export const environment = {
production: false,
amplify: {
Auth: {
region: 'eu-central-1',
identityPoolId: 'eu-central-1:xxx',
userPoolId: 'eu-central-1_xxx',
userPoolWebClientId: 'xxxx'
},
API: {
endpoints: [
{
name: "someName,
endpoint: "xxxxx"
}
]
}
}
};
```
And of course, at the startup of my application I'm configuring amplify like:
```
...
/** App Environment **/
import { environment } from '../../environments/environment';
...
Amplify.configure(environment.amplify);
...
```
On my [api-gatway](https://aws.amazon.com/it/api-gateway/) I enabled standard `CORS`, `Authorization` Required and no `Token` validation.
I feel like I'm doing everything alright and I don't get what I'm doing wrong.
**EDIT**:
`Authorization` header gets properly set when using `API.get(...)` and passing it an header object like:
```
{
Authorization: 'myToken'
}
```
More can be read at the following link [aws.github.io/aws-amplify](https://aws.github.io/aws-amplify/media/api_guide.html)
Any Suggestion?<issue_comment>username_1: I don't get your issue so I will rely on the title of your question.
If a header is missing, it's because Angular simplifies the headers before giving your the response.
If you want to get the header and put it in your request, you will have to expose it.
This is done with the **[Access Control Expose Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers)** header.
By default, Angular only handle a couple of headers and erase the other ones. You probably didn't get your token because it was in a non exposed header.
Upvotes: 1 <issue_comment>username_2: I managed to find out what was causing the problem. The error was caused not by headers nor by code but by the route called. In `api-gateway`, you can define resources and methods.
I had an `api-gateway` structure like:
```
/
----testResource/
----/{id}
---- GET
```
And I was calling `testResource?id=someValue` and it was wrong. The right way to call the same resource by id is `testResource/someValue`.
For some reason, the gateway, instead of give me a sensed error, gave me:
```
{
"message": "Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=xxxxx"
}
```
And I tought it was caused by headers in general. For those struggling with the same problem:
* Make sure you are calling the correct route
* Make sure you are not using `AWS_IAM` Authorization but one coming from your `cognito user pool`
* Make sure to get the current `jwt` and pass it to all your `API` requests like I've shown in the code above.
Upvotes: 1 [selected_answer] |
2018/03/20 | 2,391 | 7,564 | <issue_start>username_0: For school tutorial I need to make a component that receives integer values in the interval 0 to 1000. The output return `S`=`V`\*`C`, where `C` depends on:
* `C`=1 when `V` is in range [0,10]
* `C`=0.75 when `V` is in range [11,100]
* `C`=0.3125 when `V` is in range [101,1000]
I tried the code below, but it doesn't compile. I guess, I have a problem with types. How should I program a `real` number to multiply with a `std_logic_vector`?
```
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity comp1 is
port(
V: in std_logic_vector(9 downto 0);
S:out std_logic_vector(13 dowto 0));
end comp1;
architecture syn of comp1 is
begin
process is
variable c: unsigned(4 downto 0);
variable r: unsigned(13 downto 0);
begin
if unsigned(V) < 11 then
c:=1;
elsif unsigned(V) < 101 then
c:=0.75;
elsif others =>
c:=0.3125;
end if;
r:=unsigned(V)*C;
S<=std_logic_vector(r(13 downto 0));
end process;
end architecture;
```<issue_comment>username_1: 1. add V signal to process sensitivity list;
2. use shifting and addititon instead of direct multiplication as Brian said.
Upvotes: -1 <issue_comment>username_2: Your question is not fully clear: what do you need the code for. Depending on your answer, there are actually multiple solutions.
Prior problem: representation and rounding
==========================================
As you already found out, seeing you use `numeric_std`, is that a `std_logic_vector` by itself *doesn't represent any value*. It's just an array of `std_logic` elements. Therefore you should not do any operation of bare `std_logic_vector`s.
Now, by casting the vector to an `unsigned` type, you define it as representing an (unsigned) integer value. But now you get the problem that integers cannot represent fractions. So what's 0.1 in integer? 0. That's easy. But what's 0.9 in integer? Well, that depends on your **rounding scheme**. If you simply truncate the number, then the answer is 0 again. But using standard rounding (+0.5), the answer is 1. You haven't told us what rounding scheme you want (I don't know if you thought about it)
P.s. why is your `S` 14 bits wide? If `V` is 10 bits and the largest factor is 1.0, then `S` will also only need 10 bits...
Implementations
===============
Let's first define an entity
```
library ieee;
use ieee.std_logic_1164.all;
entity comp1 is
port(
V : in std_logic_vector(9 downto 0);
S : out std_logic_vector(9 downto 0)
);
end entity;
```
Real operations
===============
You can just convert everything to floating point (`real`) and perform you operation. This will solve all rounding for you and you have much freedom. The problem is that `real` types are not (yet) supported in synthesis. Still, for a test it works as it should
```
architecture behavior of comp1 is
signal V_real, S_real : real;
use ieee.numeric_std.all;
begin
V_real <= real(to_integer(unsigned(V)));
S_real <=
V_real when V_real <= 10.0 else
V_real * 0.75 when V_real <= 100.0
else V_real * 0.3125;
S <= std_logic_vector(to_unsigned(integer(S_real), S'length));
end architecture;
```
Fixed-point
===========
With VHDL-2008 they tried to bridge the problem of not having point-representation for synthesis, by introducing synthesizable fixed-point packages. When using these packages, you can even select the rounding scheme you want. This is because rounding requires extra resources and is not always necessary. Warning: Use of the packages takes some getting used to.
```
architecture behavior of comp1 is
use ieee.fixed_pkg.all;
signal V_fix : ufixed(9 downto 0);
signal C : ufixed(0 downto -15);
signal S_fix : ufixed(10 downto -15); -- range of V*C+1
use ieee.numeric_std.all;
begin
V_fix <= to_ufixed(V, V_fix);
C <= to_ufixed(1, C) when V_fix <= 10 else
to_ufixed(0.75, C) when V_fix <= 100 else
to_ufixed(0.3125, C);
S_fix <= V_fix * C;
S <= std_logic_vector(to_unsigned(S_fix, S'length));
end architecture;
```
p.s. as mentioned, you need to compile in VHDL-2008 mode for this to work.
Integer arithmetic
==================
If you look at you multiplication factors, you can see that they can be represented by fractions:
* 0.75 = 3/4
* 0.3125 = 5/16
This mean you can simply use integer arithmetic to perform the scaling.
```
architecture behavior of comp1 is
signal V_int, S_int : integer range 0 to 1000;
use ieee.numeric_std.all;
begin
V_int <= to_integer(unsigned(V));
S_int <=
V_int when V_int <= 10 else
V_int*3/4 when V_int <= 100
else V_int*5/16;
S <= std_logic_vector(to_unsigned(S_int, S'length));
end architecture;
```
*NB* Integer arithmetic has no rounding scheme, thus numbers are truncated!
Low-level optimizations: Shift-and-add
======================================
In the comments Brian referred to using shift and add operations. Going back to the integer arithmetic section of my answer, you see that the denominators are actually powers-of-2, which can be realized using bit-shift operations
* x/4 = x/(2^2) = x>>2 (right shift by 2)
* x/16 = x/(2^4) = x>>4 (rightshift by 4)
At the same time, the numerators can also be realized using bitshift and add operations
* x\*3 = x\*"11"b => x + x<<1 (left shift by 1)
* x\*5 = x\*"101"b => x + x<<2 (left shift by 2)
Both can be combined in one operations. Note, although you must remember that left shift will throw away the bits shifted out. This can cause a problem, as the fractions of the values are required for correct results. So you need to add bits to calculate the intermediate results.
```
architecture behavior of comp1 is
use ieee.numeric_std.all;
signal V_uns4, S_uns4 : unsigned(13 downto 0); -- add 4 bits for correct adding
begin
V_uns4 <= resize(unsigned(V),V_uns4'length);
S_uns4 <=
shift_left(V_uns4,4) when V_uns4 <= 10 else
shift_left(V_uns4,3) + shift_left(V_uns4,2) when V_uns4 <= 100 -- "11" >> 2
else shift_left(V_uns4,2) + V_uns4; --"101" >> 4
S <= std_logic_vector(resize(shift_right(S_uns4,4),S'length));
end architecture;
```
This method will likely require the least resourses in synthesis. But is does require low level optimizations, which require additional design effort.
Testbench
=========
Here's how I tested my code
```
entity comp1_tb is end entity;
library ieee;
architecture tb of comp1_tb is
use ieee.std_logic_1164.all;
signal V,S : std_logic_vector(9 downto 0);
use ieee.numeric_std.all;
signal V_int, S_int : integer range 0 to 1000;
begin
DUT: entity work.comp1
port map(
V => V,
S => S);
V <= std_logic_vector(to_unsigned(V_int, V'length));
S_int <= to_integer(unsigned(S));
V_stim : process begin
V_int <= 1;
wait for 1 ns;
assert (S_int = 1) report "S should be 1*1 = 1;" severity warning;
V_int <= 10;
wait for 1 ns;
assert (S_int = 10) report "S should be 10*1 = 10;" severity warning;
V_int <= 100;
wait for 1 ns;
assert (S_int = 75) report "S should be 100*0.75 = 75;" severity warning;
V_int <= 1000;
wait for 1 ns;
assert (S_int = 312 OR S_int = 313) report "S should be 1000*0.3125 = 312 or 313;" severity warning;
wait;
end process;
end architecture;
```
Upvotes: 2 |
2018/03/20 | 403 | 1,511 | <issue_start>username_0: Here is a class
```
export class ChatDetailPage {
constructor(){
}
funcA(){
var options = {
onSubmit: function (text) {
//i want to be able to access funcB from here
this.funcB(text)
},
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}
}
```
Here in this case how can i call funcB from onsubmit callback function in Anular 2 or Ionic 3.
Thanks in advance.<issue_comment>username_1: Use an arrow function, which captures the value of `this`:
```
export class ChatDetailPage {
constructor(){
}
funcA(){
var options = {
onSubmit: text => {
//i want to be able to access funcB from here
this.funcB(text)
},
};
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Sometimes you won't be able to use an arrow function, f.e. when it's an inbuilt or library function. The solution you can use in this case is bind the `this` variable to a variable called `self` or whatever you want.
```
funcA(){
// bind the this variable to 'self' outside of the function scope
var self = this;
var options = {
onSubmit: function (text) {
// and use self instead of this
self.funcB(text)
},
this.nativeKeyboard.showMessenger(options)
}
funcB(text){
alert (text);
}
```
Upvotes: 2 |
2018/03/20 | 381 | 1,300 | <issue_start>username_0: I have an angular 1 app. Every time I run
```
npm run build
```
I also want to start a gradle task. Can I automatize that somehow?<issue_comment>username_1: Of course you can, the command `npm run build` run the script defined in you `package.json` file.
It looks like this :
```
"scripts": {
"build": "myAwesomeCommand; gradle myTask"
},
```
You can change the command executed by `npm run build`. If your command is too long or if you need a script, you can also create a shell script in your current directory and execute it.
Upvotes: 3 [selected_answer]<issue_comment>username_2: The idea of using Gradle is that it automates the commands. Thus, you can use some construction of that type (in your build.gradle file):
```
task someGradleTask {
// ... Do something
}
task someNpmTask(type: NpmTask) {
args = ['run', 'build']
}
```
And then make one of the tasks dependant on the other:
```
someGradleTask.dependsOn(someNpmTask)
// Moreover
someNpmTask.dependsOn(npm_install) // This task comes with the plugin below
```
You will need an NPM plugin for Gradle, which may be included like this:
```
buildscript {
dependencies {
classpath "com.moowork.gradle:gradle-node-plugin:1.2.0"
}
}
apply plugin: 'com.moowork.node'
```
Upvotes: 2 |
2018/03/20 | 413 | 1,404 | <issue_start>username_0: Hi I am using findstr command to filter a file based on string and redirecting that output to seperate file.
```
findstr /C:"C=EODRevaluationProcess Temp table:TMP_EOD_REVAL_DATA" "C:\Users\Desktop\abc.txt" > C:\Users\Desktop\xyz.txt
pause
findstr /C:"sendSPPJMSMessage> "C:\Users\Desktop\xyz.txt"
pause
findstr /C:"POS\_HOURLY\_DATA : actualTable : POS\_HOURLY\_DATA\_" "C:\Users\Desktop\abc.txt" > "C:\Users\Desktop\xyz.txt"
```
I want all the filtered lines to be saved in same file xyz.
But only output of first findstr command is saving in xyz.
Can anyone please suggest any idea
Thank you.<issue_comment>username_1: You are redirecting the output to a file using the `>` operator which will create the file if it doesn't exist and replace its contents with the output.
If you want to append to the file, rather than replacing its contents, you can use the `>>` operator.
Upvotes: 3 [selected_answer]<issue_comment>username_2: There's no reason to run `FindStr` three times against the same file. Putting all the search strings in a single command would also prevent your overwrite issue.
```bat
@FindStr /I^
/C:"some string"^
/C:"another string"^
/C:"and a bigger string"^
"source.txt" > "output.txt"
```
*You'll note that I have used carets, `^`, to escape the line returns so that your strings are easier to maintain, (each to their own line)*
Upvotes: 0 |
2018/03/20 | 568 | 1,716 | <issue_start>username_0: I have table that I populate via ajax call
Here is table code
```
| # | Ф.И.О | Дата рождения | Телефон | График | Адрес | Паспортные данные | <NAME> |
| --- | --- | --- | --- | --- | --- | --- | --- |
```
And here is code of js script to populate it
```
function AllPeople() {
let getPeopleUrl = '/peopleforworks/index';
$.ajax({
url: getPeopleUrl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#people tr").remove();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '|' + ' ' +
(i + 1) +
' |' +
' ' +
list[i].FIO +
' |' +
' ' +
moment(list[i].Birthday).format('DD/MM/YYYY') +
' |' +
' ' +
list[i].TelephoneNumber +
' |' +
' ' +
list[i].WorkTime +
' |' +
' ' +
list[i].Adress +
' |' +
' ' +
list[i].PassportData +
' |' +
' ' +
list[i].MedicalBook +
' |'
+
'
';
$('#people').append(tableData);
}
}
})
```
}
It works great and data is passing to table
But when I call this table (it's on modal) second time it's not clear values in tbody
I tried to do it like this `$("#people tr").remove();`, but it not works and I have no errors.
How I can clear values correctly?<issue_comment>username_1: try this
```
$("#people").empty();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: If you want to clear all the rows.Then use below code.
var table = $('#example').DataTable();
table.clear().draw();
For more information follow api link
<https://datatables.net/reference/api/clear()>
Upvotes: 0 |
2018/03/20 | 1,258 | 4,389 | <issue_start>username_0: I was converting some old Python code to use [`pathlib`](https://docs.python.org/3/library/pathlib.html) instead of `os.path` for most path-related operations, but I ended up with the following problem: I needed to add another extension to a path that already had an extension (not replace it). With `os.path`, since we are merely manipulating strings, the solution was to add the extension with string operations:
```
newpath = path + '.res'
```
It doesn't work with `pathlib.Path` because it doesn't allow concatenation of arbitrary characters. The closest I could find was the following:
```
newpath = path.with_suffix(path.suffix + '.res')
```
It looks like a workaround because it still uses string addition in the end. And it has a new pitfall because I forgot at first to handle the case where there are already several extensions and you want to add a new one, leading to the following code to get back the old behaviour:
```
newpath = path.with_suffix(''.join(path.suffixes) + '.res')
```
Now it doesn't feel terse nor clean since it uses more and more string operations to achieve the old behaviour instead of pure path operations. The fact that `Path.suffixes` exists means that the library's developers considered the case where a file can have multiple extensions, yet I couldn't find a way to simply add a new extension to a path. Is there a more idiomatic way that I have missed to achieve the same behaviour?
EDIT: actually `path.with_suffix(path.suffix + '.res')` is enough to handle the case where there are already several file extensions, even though it wasn't immeditely obvious to me.<issue_comment>username_1: The following code should do what you want it to in a very dynamic way.
```
from pathlib import Path
import time
p = Path('.')
p = p / '..' / 'Python' / 'Files' / 'Texts_to_read' / 'a_text_file'
new_p = str(p).split('\\')
new_suffix = '.txt'
new_p[-1] = new_p[-1] + new_suffix
p = Path('.')
for x in new_p:
p = p / x
print(new_p)
print(p)
print(str(p))
time.sleep(5)
```
The fact that normal string operations can be used in this case is a good thing, as it adds a great deal of control over the file path desired without requiring a large assortment of new functions.
Upvotes: -1 <issue_comment>username_2: It doesn't seem like Path's like being modified in-place (you can't change `.parts[-1]` directory or change `.suffixes`, etc.), but that doesn't mean you need to resort to anything too unsavory. The following works just fine, even if it's not quite as elegant as I'd like:
```
new_path = path.with_suffix(path.suffix + new_suffix)
```
where `path` is your original Path variable, and `new_suffix` is the string with your new suffix/extension (including the leading ".")
Upvotes: 5 <issue_comment>username_3: You can just convert your `Path` to string then add new extension and convert back to `Path`:
```
from pathlib import Path
first = Path("D:/user/file.xy")
print(first)
second = Path(str(first)+".res")
print(second)
```
Upvotes: 4 <issue_comment>username_4: I find the following slightly more satisfying than the answers that have already been given:
```
new_path = path.parent / (path.name + '.suffix')
```
Upvotes: 7 <issue_comment>username_5: if you want to append the file name, but not change the extension, this works
```
matfile2 = pathlib.Path.joinpath(matfile.parent, matfile.stem+' insert'+matfile.suffix)
```
Upvotes: 1 <issue_comment>username_6: You might use pathlib3x - it offers a backport of the latest (at the date of writing this answer Python 3.11.a0) Python pathlib for Python 3.6 or newer, and a few additional functions like `append_suffix`
```
>>> python -m pip install pathlib3x
>>> import pathlib3x as pathlib
>>> pathlib.Path('some_path').append_suffix('.ext')
PosixPath('some_path.ext')
>>> pathlib.Path('some_path.ext.ext2').append_suffix('.ext3')
PosixPath('some_path.ext.ext2.ext3')
```
you can find it on [github](https://github.com/username_6/pathlib3x) or [PyPi](https://pypi.org/project/pathlib3x)
---
Disclaimer: I'm the author of the pathlib3x library.
Upvotes: 4 <issue_comment>username_7: I think this would be better since you just want to extend the current path with an arbitrary string.
```
old_path = Path("/the/old/path.foo") # "/the/old/path.foo"
new_path = Path(f"{old_path}.bar") # "/the/old/path.foo.bar"
```
Upvotes: 3 |
2018/03/20 | 394 | 1,559 | <issue_start>username_0: Can anyone tell, what is equivalent to handler in flutter?. i want to implement a splash screen which will last for 5 seconds and after another screen will be shown.<issue_comment>username_1: I don't think there is something similar to a `Handler` class, but you can just use `Future.delayed` and in `build()` render a different UI depending on `showSplash`:
```
showSplash = true;
new Future.delayed(const Duration(seconds: 5), () {
setState(() => showSplash = false);
});
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Handler.postDelayed()** -- Used to do work after some specific time
---------------------------------------------------------------------
We can either use `Future.postDelayed` (as answered by Günter) or we can use `Timer` class too.
```
Timer(Duration(seconds: 5), () {
// 5 seconds have past, you can do your work
}
```
**Handler.post()** -- Used to keep on doing work after some specific interval
-----------------------------------------------------------------------------
We can use `Timer.periodic` function for this like
```
Timer.periodic(Duration(seconds: 5), (_) {
// this code runs after every 5 second. Good to use for Stopwatches
});
```
Upvotes: 2 <issue_comment>username_3: ```
new Future.delayed(new Duration(seconds: 5), () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => NewScreen()),
(Route route) => false);
});
```
where `NewScreen` is the screen you wish to show, it will show a new screen.
Upvotes: 0 |
2018/03/20 | 4,178 | 12,889 | <issue_start>username_0: The below file is basically auto-generated from a script I got from ROS website, except for it that I modified some opencv related packages so that they can fit into my ROS project. Use Ctrl-F + "opencv" and you can find those names in variable "stlibs".
The error happens when I was linking opencv-3.3.1 to an open-source ROS project using NDK. I got many "undefined reference" errors from the opencv static library but those referred functions should be packed in other opencv .a files, right?
So I am wondering... does the order of those prebuilt\_static\_libraries in Android.mk matter? If so, could any one help me that?
Related Android.mk in */path/to/the/file/ros-android-ndk*:
```
LOCAL_PATH := $(call my-dir)
# These must go in some sort of order like include flags, otherwise they are dropped
# Oh no, need to automate this with catkin somehow....
stlibs := roscpp boost_signals boost_filesystem rosconsole \
rosconsole_print rosconsole_backend_interface boost_regex xmlrpcpp \
roscpp_serialization rostime boost_date_time cpp_common boost_system \
boost_thread console_bridge move_base rotate_recovery global_planner \
navfn layers boost_iostreams qhullstatic flann_cpp_s flann_cpp_s-gd \
nodeletlib bondcpp uuid rosbag rosbag_storage roslz4 lz4 topic_tools \
voxel_grid tf tf2_ros actionlib tf2 move_slow_and_clear \
dwa_local_planner clear_costmap_recovery carrot_planner \
base_local_planner trajectory_planner_ros urdfdom_sensor \
urdfdom_model_state urdfdom_model urdfdom_world rosconsole_bridge \
pointcloud_filters laser_scan_filters mean params increment median \
transfer_function compressed_image_transport cv_bridge image_transport \
compressed_depth_image_transport amcl_sensors amcl_map amcl_pf \
stereo_image_proc image_proc image_geometry ***opencv_imgproc \
opencv_core opencv_flann opencv_highgui opencv_features2d opencv_ml \
opencv_imgcodecs opencv_calib3d opencv_video opencv_objdetect \
opencv_photo opencv_videostab opencv_superres opencv_stitching \
opencv_dnn opencv_shape opencv_videoio*** cpufeatures IlmImf libjasper \
libjpeg libpng libprotobuf libtiff libwebp tbb tegra_hal polled_camera \
camera_info_manager collada_parser geometric_shapes octomap octomath \
shape_tools random_numbers camera_calibration_parsers costmap_2d \
laser_geometry message_filters resource_retriever \
dynamic_reconfigure_config_init_mutex tinyxml class_loader \
PocoFoundation roslib rospack boost_program_options pcl_ros_filters \
pcl_ros_io pcl_ros_tf pcl_common pcl_octree pcl_kdtree pcl_search \
pcl_sample_consensus pcl_filters pcl_io pcl_features pcl_registration \
pcl_keypoints pcl_ml pcl_segmentation pcl_stereo pcl_tracking \
pcl_recognition pcl_surface pluginlib pluginlib_tutorials \
image_transport_plugins nodelet_math yaml-cpp
#shlibs :=
define include_shlib
$(eval include $$(CLEAR_VARS))
$(eval LOCAL_MODULE := $(1))
$(eval LOCAL_SRC_FILES := $$(LOCAL_PATH)/lib/lib$(1).so)
$(eval include $$(PREBUILT_SHARED_LIBRARY))
endef
define include_stlib
$(eval include $$(CLEAR_VARS))
$(eval LOCAL_MODULE := $(1))
$(eval LOCAL_SRC_FILES := $$(LOCAL_PATH)/lib/lib$(1).a)
$(eval include $$(PREBUILT_STATIC_LIBRARY))
endef
#$(foreach shlib,$(shlibs),$(eval $(call include_shlib,$(shlib))))
$(foreach stlib,$(stlibs),$(eval $(call include_stlib,$(stlib))))
include $(CLEAR_VARS)
LOCAL_MODULE := roscpp_android_ndk
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_EXPORT_CPPFLAGS := -fexceptions -frtti
#LOCAL_SRC_FILES := dummy.cpp
LOCAL_EXPORT_LDLIBS := $(foreach l,$(shlibs),-l$(l)) -L$(LOCAL_PATH)/lib
#LOCAL_EXPORT_LDLIBS := -lstdc++ #-L$(LOCAL_PATH)/lib
#LOCAL_SHARED_LIBRARIES := $(shlibs)
LOCAL_STATIC_LIBRARIES := $(stlibs) gnustl_static
include $(BUILD_STATIC_LIBRARY)
```
The error Message is as follows,
```
/home/csx/ros-android-ndk/roscpp_android/output/roscpp_android_ndk/lib/libopencv_calib3d.a(calibration.cpp.o):calibration.cpp:function icvGetRectangles(CvMat const*, CvMat const*, CvMat const*, CvMat const*, CvSize, cv::Rect_&, cv::Rect\_&): error: undefined reference to 'cvUndistortPoints'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cvRodrigues2: error: undefined reference to 'cv::checkRange(cv::\_InputArray const&, bool, cv::Point\_\*, double, double)'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cvFindExtrinsicCameraParams2: error: undefined reference to 'cvUndistortPoints'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cvFindExtrinsicCameraParams2: error: undefined reference to 'cvCheckArr'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cvStereoRectify: error: undefined reference to 'cvUndistortPoints'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cv::rectify3Collinear(cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::Size\_, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, double, cv::Size\_, cv::Rect\_\*, cv::Rect\_\*, int): error: undefined reference to 'cv::undistortPoints(cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&)'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(calibration.cpp.o):calibration.cpp:function cv::rectify3Collinear(cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::Size\_, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, double, cv::Size\_, cv::Rect\_\*, cv::Rect\_\*, int): error: undefined reference to 'cv::undistortPoints(cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&)'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::PointSetRegistrator::~PointSetRegistrator(): error: undefined reference to 'cv::Algorithm::~Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::PointSetRegistrator::~PointSetRegistrator(): error: undefined reference to 'cv::Algorithm::~Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::LMeDSPointSetRegistrator::~LMeDSPointSetRegistrator(): error: undefined reference to 'cv::Algorithm::~Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::LMeDSPointSetRegistrator::~LMeDSPointSetRegistrator(): error: undefined reference to 'cv::Algorithm::~Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::createRANSACPointSetRegistrator(cv::Ptr const&, int, double, double, int): error: undefined reference to 'cv::Algorithm::Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:function cv::createLMeDSPointSetRegistrator(cv::Ptr const&, int, double, int): error: undefined reference to 'cv::Algorithm::Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:typeinfo for cv::PointSetRegistrator: error: undefined reference to 'typeinfo for cv::Algorithm'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::PointSetRegistrator: error: undefined reference to 'cv::Algorithm::save(cv::String const&) const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::PointSetRegistrator: error: undefined reference to 'cv::Algorithm::getDefaultName() const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::RANSACPointSetRegistrator: error: undefined reference to 'cv::Algorithm::save(cv::String const&) const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::RANSACPointSetRegistrator: error: undefined reference to 'cv::Algorithm::getDefaultName() const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::LMeDSPointSetRegistrator: error: undefined reference to 'cv::Algorithm::save(cv::String const&) const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(ptsetreg.cpp.o):ptsetreg.cpp:vtable for cv::LMeDSPointSetRegistrator: error: undefined reference to 'cv::Algorithm::getDefaultName() const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(solvepnp.cpp.o):solvepnp.cpp:function cv::solvePnP(cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, bool, int): error: undefined reference to 'cv::undistortPoints(cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&)'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(solvepnp.cpp.o):solvepnp.cpp:function cv::solvePnP(cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_OutputArray const&, bool, int): error: undefined reference to 'cv::undistortPoints(cv::\_InputArray const&, cv::\_OutputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&, cv::\_InputArray const&)'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(levmarq.cpp.o):levmarq.cpp:function cv::createLMSolver(cv::Ptr const&, int): error: undefined reference to 'cv::Algorithm::Algorithm()'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(levmarq.cpp.o):levmarq.cpp:typeinfo for cv::LMSolver: error: undefined reference to 'typeinfo for cv::Algorithm'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(levmarq.cpp.o):levmarq.cpp:vtable for cv::LMSolver: error: undefined reference to 'cv::Algorithm::save(cv::String const&) const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(levmarq.cpp.o):levmarq.cpp:vtable for cv::LMSolver: error: undefined reference to 'cv::Algorithm::getDefaultName() const'
/home/csx/ros-android-ndk/roscpp\_android/output/roscpp\_android\_ndk/lib/libopencv\_calib3d.a(triangulate.cpp.o):triangulate.cpp:function cvCorrectMatches: error: undefined reference to 'cvSolvePoly'
```<issue_comment>username_1: OpenCV 3.3.x had some trouble with supporting Android NDK R15+ releases, you can see that in their official [changelog](https://github.com/opencv/opencv/wiki/ChangeLog) , try to update your OCV to the latest version (3.4.1) and see if the problem persists.
Upvotes: 0 <issue_comment>username_2: Yes, linker success depends on the order of static libraries. See <https://github.com/android-ndk/ndk/issues/545> and some workarounds there, e.g.
```
LOCAL_LDLIBS += -Wl,--start-group -L $(TARGET_OUT) $(foreach l,$(stlibs),-l $(l)) -Wl,--end-group
```
Space between `-l` and `$(l)` is intended, otherwise NDK will complain.
Upvotes: 1 |
2018/03/20 | 307 | 1,381 | <issue_start>username_0: How I can serialize/flatten the following C++ structure into byte array or anything else without using any external library.
```
struct node
{
string splitOn;
string label;
bool isLeaf;
vector childrenValues;
vector children;
};
```<issue_comment>username_1: You can use memcpy to copy bit by bit information from your structure `node` into a character array `frame` like this:
```
struct node obj;
char frame[1024];
memcpy ( frame, &obj, sizeof(struct node) );
```
You can then send the `frame` serially bit by bit and recover the structure later like this:
```
memcpy ( &obj2, frame, sizeof(struct node) );
```
However, I have not tested this code. You may need to cast to a `void *` the first and second arguments.
Upvotes: -1 <issue_comment>username_2: There is no such header as part of C++, .h names are deprecated and no longer used. Do you mean or ? If you are not using serailization library, you have to write it yourself. E.g. define serialization operators. There is no language-defined serialization like in java and if you should account for version changes, you have to design a new or use an existing representation format.
Upvotes: 2 |
2018/03/20 | 469 | 1,299 | <issue_start>username_0: This is my data - how can I find itemId in the array.
```
let itemId=['001', '002', '003']
const data = [
{ id: 1, itemId: '001' },
{ id: 2, itemId: '002' },
{ id: 3, itemId: '003' },
];
```
This is my function in lodash but it does not work.
```
_.find(data, ['itemId',{$in: itemId}])
```<issue_comment>username_1: Use [`_.intersectionWith()`](https://lodash.com/docs/4.17.5#intersectionWith) to get all items from `data`, which id appears in the `itemId` array:
```js
const itemId=['001', '003'];
const data = [
{ id: 1, itemId: '001' },
{ id: 2, itemId: '002' },
{ id: 3, itemId: '003' },
];
const result = _.intersectionWith(data, itemId, ({ itemId }, id) => itemId === id);
console.log(result);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you want to filter all the item in `data` array that have `itemId` included in `Ids` array, you can try available supported `filter` method without using `lodash`
<https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter>
```js
const itemIds=['001', '003'];
const data = [
{ id: 1, itemId: '001' },
{ id: 2, itemId: '002' },
{ id: 3, itemId: '003' },
];
console.log(data.filter(item=> itemIds.includes(item.itemId)));
```
Upvotes: 2 |
2018/03/20 | 273 | 996 | <issue_start>username_0: I'm trying to submit a form which consists of text fields and tiny mce editor. The tiny mce editor contains *raw html elements* like this
```
[View Profile](http://testserver/my-development-app/web/users/profile/4567/3323)
```
After submitting the form via **POST** method using *cakePHP*, the *href* attribute of *anchor* tag value is automatically trimmed like this
```
[View Profile](../profile/4567/3323)
```
What is wrong here? Why the *href* attribute url is trimmed after submitting the form ?<issue_comment>username_1: You need to configure the **tiny mce editor** to handle the urls. Make sure in the javascript initialization you are using, that you have these lines in it:
```
relative_urls : false,
remove_script_host : false,
convert_urls : true,
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You'll need to set `relative_urls` to `false`. By default TinyMCE will assume that all links are relative to where the editor is.
Upvotes: 0 |
2018/03/20 | 443 | 1,790 | <issue_start>username_0: I am now attaching the console output of my python scripts and send the mail in jenkins.The recipient gets an link to open the console output
Is there any way to send the test result dashboard directly to the email using jenkins?
Any help would be greatly appreciated.Thank you<issue_comment>username_1: is your script generating any HTML reports, if yes, you can publish the HTML in the email body. [Display HTML page inside mail body with Email-ext plugin in Jenkins](https://stackoverflow.com/questions/22066936/display-html-page-inside-mail-body-with-email-ext-plugin-in-jenkins)
Upvotes: 2 <issue_comment>username_2: Add this to your pipeline with having email-ext plugin integrated with Jenkins.
```
post {
fixed {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'FIXED: $PROJECT_NAME - #$BUILD_NUMBER'
}
failure {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'FAILED: $PROJECT_NAME - #$BUILD_NUMBER'
}
unstable {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'UNSTABLE: $PROJECT_NAME - #$BUILD_NUMBER'
}
}
```
Upvotes: 0 |
2018/03/20 | 456 | 1,943 | <issue_start>username_0: I have already used Jenkins in the past integrated with GitHub and deploying zip file to AWS Elastic beanstalk.
I am new to kubernetes, how can I make full CI/CD pipeline to create dockers images from jenkins and deploying it to kubernetes cluster running minikube.
Any links, experiences from experts or guidance will be appreciated
Regards,
Aziz<issue_comment>username_1: There are multiple stages in this workflow.
1. Checkout the source code from Github and build a Docker image from a Dockerfile.
2. Push the resulting image to a remote Docker image registery such as Dockerhub.
3. Deploy the image to the Kubernetes cluster.
It doesn't matter if kubernetes is running on Minikube or some other cloud platform. To deploy to a kubernetes cluster you can either use `kubectl` or the [Jenkins Kubernetes Continuous Deploy Plugin](https://wiki.jenkins.io/display/JENKINS/Kubernetes+Continuous+Deploy+Plugin).
Upvotes: 1 <issue_comment>username_2: We're working on an open source project called [Jenkins X](https://jenkins-x.io/) which is a proposed sub project of the Jenkins foundation aimed at automating CI/CD on Kubernetes using Jenkins pipelines and GitOps for promotion across environments.
If you want to see how to automate CI/CD with multiple environments on Kubernetes using GitOps for promotion between environments and Preview Environments on Pull Requests you might wanna check out [my recent talk on Jenkins X at DevOxx UK](https://jenkins-x.io/demos/devoxx-uk-2018/) where I do a live demo of this on GKE. Though Jenkins X works on [AWS, AKS and GKE and other kubernetes clusters like minikube too](https://jenkins-x.io/getting-started/).
The only issue on minikube is there's no webhooks so it can take a while for promotion to kick in (there's a 5 minute backup poll for git events). You can manually trigger the jobs in the Jenkins UI though to work around the lack of webhooks ;)
Upvotes: 2 |
2018/03/20 | 965 | 3,347 | <issue_start>username_0: I am using HTTPClient Module of Angular 4 for retrieving data from a database.
The corresponding service has the following method,
```
getPosts() {
const httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
// tslint:disable-next-line:max-line-length
httpHeaders.set('Authorization for JWT', 'Token');
return this.http.get('http://localhost:9090/api/user' + '?user_id=' + this.user.id.toString(),
{headers: httpHeaders,
responseType: 'json'});
}
```
I am calling this method from a component as follows,
```
this.Servie.getPosts().subscribe(pos => {
console.log(pos);
});
```
But I am getting an error as follows in server side,
>
> java.lang.RuntimeException: JWT Token is missing
>
>
>
error at the client side,
>
> Failed to load <http://localhost:9090/api/user?user_id=1>: Response for
> preflight has invalid HTTP status code 500.
>
>
>
Please correct me where I am going wrong?
I Have made changes according to discussion below, but still problem is there as follows,
I think I have messed it up right now, I made the following changes as follows,
This is the code written in service,
```
const httpHeaders = new HttpHeaders()
.set('Content-Type', 'application/json')
// tslint:disable-next-line:max-line-length
.set('RequestAuthorization', 'Bearer ' + '<KEY>');
return this.http.get('http://localhost:9090/user' + '?user_id=' + this.user.id.toString(),
{headers: httpHeaders});
```
And i am calling the above service as follows,
```
this.userServie.getPosts().map((res: Response) =>
console.log(res.text()));
```
But the service is not hitting, i am not seeing the GET method in network tab of browser development tools. Where i am wrong ? Please correct me.<issue_comment>username_1: Headers have defined values.
```
httpHeaders.set('Authorization for JWT', 'Token');
```
Should be
```
httpHeaders.set('Authorization', 'Bearer ' + token);
```
If you provide random tokens to your server, of course it will tell you that the token is missing. In your case, you're sending this
```
Authorization for JWT --> Token
```
Upvotes: 1 <issue_comment>username_2: Once you figure out the real headers to send I think you'll have 2 problems:
**Issue #1**
`HttpHeaders` class is immutable
So you need to have something like this
```
const httpHeaders = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Authorization', 'Bearer [yourTokenHere]')
```
instead of declaring `httpHeaders` and calling set without chaining the call
```
const httpHeaders = new HttpHeaders();
//The line below has no effect on the httpHeaders instance
httpHeaders.set('Authorization', 'Bearer [yourTokenHere]');
```
**Issue #2**
Also, did you make sure that CORS was configured properly on your java server?
You are getting an error about missing token for the `preflight` request (i.e. the one with the Options method). AFAIK, browsers do not send custom headers like `Authorization` for preflight requests. So, the server should not check the token for the OPTIONS request (otherwise, you'll always end up getting 401 as tokens won't be sent)
Upvotes: 0 |
2018/03/20 | 245 | 713 | <issue_start>username_0: I want to get list of seasons from 1980 to today, and if somebody has selected one of them it should be selected in frontend but I do not know how to make it selected. It is my code: Can you help me?
```
@lang('main.season')
@for($i = 1980; $i < \Carbon\Carbon::now()->format('Y') ; $i++)
season == $i) selected @endif>{{$i}}/{{$i + 1}}
@endfor
```<issue_comment>username_1: Try something like this inside the
```
@for ($i = 1980; $i < date('Y'); $i++)
season ? ' selected' : ''}}>{{ $val }}
@endfor
```
Upvotes: 1 <issue_comment>username_2: Try this:
```
@foreach(range(\Carbon\Carbon::now()->year, 1998) as $year)
{{($year-1)}}/{{$year}}
@endforeach
```
Upvotes: 0 |
2018/03/20 | 486 | 1,157 | <issue_start>username_0: I have a object like that:
```
var days = {
0: 10,
1: 40
2: 20,
3: 15,
4: 5,
5: 18,
6: 9
};
```
I need to transform it to something like that:
```
var days2 = [
{0:10},
{1: 40},
{2: 20},
{3: 15},
{4: 5},
{5: 18},
{6: 9},
];
```
I know that it's easy, but I don't have any idea<issue_comment>username_1: You could take all entries of the object and build new objects with key/value pairs.
```js
var days = { 0: 10, 1: 40, 2: 20, 3: 15, 4: 5, 5: 18, 6: 9 },
result = Array.from(Object.entries(days), ([k, v]) => ({ [k]: v }));
console.log(result);
```
Upvotes: 2 <issue_comment>username_2: You can use [`Object.keys`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) and [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
```
Object.keys(days).map( key => {return { [key]: days[key]
```
```js
var days = {
0: 10,
1: 40,
2: 20,
3: 15,
4: 5,
5: 18,
6: 9
};
var output = Object.keys(days).map( key => {return { [key]: days[key] } });
console.log(output);
```
Upvotes: 0 |
2018/03/20 | 1,199 | 4,432 | <issue_start>username_0: ```
export function getAllHost(req, res) {
function findAllHost() {
let query = {};
query.company = req.query && req.query.companyId ? req.query.companyId : res.locals.payload.companyId;
query.active = true;
if(req.query && req.query.name) {
let regexp = new RegExp('\\b' + req.query.name);
query['name'] = {$regex: regexp, $options: 'i'};
}
return Host.find(query);
}
async function sendRes() {
let allHost = [];
let hosts = [];
try {
hosts = await findAllHost();
} catch(err){
console.log(err)
}
for (let host of hosts) {
allHost.push(new Host_V1(host));
}
return allHost
}
sendRes().then(data => res.status(200).json(data)).catch(error => {
console.log("error is", error);
res.status(error.status || 500).json({
message: error.status ? error.message : 'Server Error'
});
});
}
```
I have been trying to adapt async/await into my code, so I converted one of the `Promise` based api controller to make use of `async/await`, but the thing that bothers me is that my server responds with 500, and the `console.log` inside my catch block doesn't print anything.
No error gets thrown.
I am using babel `babel-plugin-syntax-async-functions` to parse it.
What is it that I am doing wrong?<issue_comment>username_1: EDIT : The value returned is indeed a promise
~~I think that the error is related to your 'SendRes.then' since what SendRes returns *is not* a promise but it's actually is the Array allHost~~
~~Your data argument is not an argument anymore it is the value returned from the sendRes function thanks to your async / await implementation.~~
```
const hosts = sendRes();
res.status(200).json(hosts);
```
~~if you want to handle an error you must return something from your catch block so that you can can handle it here.~~
```
if (!hosts) res.status(500);
```
~~To simplify your code you can also get rid of the sendRes function and make your getAllHost express middleware an async function~~
```
async getAllHost(req, res) { /*...*/ }
try {
let allHosts = await findAllHosts();
res.status(200).json(allHosts);
} catch (error) {
res.status(500).send({ error })
}
```
Upvotes: 0 <issue_comment>username_2: Your code is a bit overcomplicated, but judging by it you should receive an error in the console if one appears. It could instead be that you have a middleware producing an error? The main issue is that you're catching the error in the async function `sendRes`, so the `.catch`-method you call on the returned Promise will never be fired even if there is an error.
Like many others that are new to `async/await`, you've misunderstood and believe that you *have* to wrap every `await` expression in a `try/catch`-block. This is not the case. The error "trickles" up the call chain, and unless a particular function can provide a different return value, it's best to catch the error from the top-most callee. Take this simple example which shows a common anti-pattern: <https://repl.it/repls/PunySafeInterfacestandard> (await and async isn't even needed in these examples, but I added them for clarity)
But if you try to simplify your code, maybe something like the below snippet, you might be able to rule out if it's a middleware or not.
```
export async function getAllHosts (req, res) {
try {
let query = {
company: req.query && req.query.companyId ? req.query.companyId : res.locals.payload.companyId,
active: true
}
if (req.query && req.query.name) {
let regexp = new RegExp('\\b' + req.query.name)
query.name = {$regex: regexp, $options: 'i'}
}
let allHosts = (await Host.find(query)).map((host) => new Host_V1(host))
return res.json(allHosts)
} catch (e) {
console.log("error is", e)
res.status(error.status || 500).json({
message: error.status ? error.message : 'Server Error'
})
}
}
```
Take note of the `(await Host.find(query))` line. If the Promise that's returned from `Host.find()` rejects, the `.map()`-method won't be executed on the data and execution will jump to the `catch`-block.
I also heavily discourage using Babel since `async/await` has been natively supported in Node since version 7.6.
Upvotes: 2 [selected_answer] |
2018/03/20 | 888 | 2,962 | <issue_start>username_0: I am trying to create a simple loyalty program. In which users will be allotted a few Free visits.
so there's 2 fields One is"balance" which shows how many visits left and when they reach 0 it echo or show alert that u reach 0.
2nd is total which count total visits done by users.
This is what i tried but not getting the above solution:
```
if(isset($_POST['Submit'])) {
$my_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = ".$id);
if(mysqli_affected_rows($connection) > 0 ){
$query = "UPDATE `countvisits` SET `balance` = `balance` - 1 And `TotalVisits` = `TotalVisits` + 1 WHERE `id` = ".$id;
$result = mysqli_query($connection, $query);
echo '';
echo 'alert("Successfully Scanned")';
echo '';
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = '$id'");
}else{
echo '';
echo 'alert("User Not Found")';
echo '';
/* get new updated data */
}
}
?>
```
above query only subtract and shows balance & doesnt add +1 to total visits
How can i achieve above results?<issue_comment>username_1: Instead of `And` in query use `,` as a seperator.
Like below:-
```
$query = "UPDATE `countvisits` SET balance = balance - 1, TotalVisits = TotalVisits + 1 WHERE `id` = ".$id;
```
NOTE:- your query is wide-open for SQL INJECTION. So try to use `prepared-statements` to prevent from it.
Reference:-
[mysqli::prepare](http://php.net/manual/en/mysqli.prepare.php)
[PDO::prepare](http://php.net/manual/en/pdo.prepare.php)
***You can check the balance first to see if it is 0 or not:-***
```
if(isset($_POST['Submit'])) {
$my_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = ".$id);
if(mysqli_affected_rows($connection) > 0 ){
$data = mysqli_fetch_assoc($my_query);
if($data['balance'] ==0){
echo '';
echo 'alert("Balance become 0")';
echo '';
}else{
$query = "UPDATE `countvisits` SET balance = balance - 1, TotalVisits = TotalVisits + 1 WHERE `id` = ".$id;
$result = mysqli_query($connection, $query);
echo '';
echo 'alert("Successfully Scanned")';
echo '';
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = '$id'");
}
}else{
echo '';
echo 'alert("User Not Found")';
echo '';
/* get new updated data */
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Change this:
```
$query = "UPDATE `countvisits` SET `balance` = `balance` - 1 And `TotalVisits` = `TotalVisits` + 1 WHERE `id` = ".$id;
```
With this:
```
$query = "UPDATE `countvisits` SET `balance` = `balance` - 1, `TotalVisits` = `TotalVisits` + 1 WHERE `id` = ".$id;
```
When you update a table in sql the separator must be comma `,` not `and` keyword.
Upvotes: 2 |
2018/03/20 | 757 | 2,249 | <issue_start>username_0: I have 2 rows with dates and I want to mark both dates if the difference between them is greater than 14 days.
Example:
```
D E
```
14.03.2018 15.03.2018
14.03.2018 21.04.2018
14.03.2018 28.03.2018
14.03.2018 21.03.2018
Formula: = (E1-D1)>14
Format: infill yellow.
Applying it to the whole ROW E.
Problem is, that when its True then the whole row gets turned yellow, not the Cell in E.
Any ideas?<issue_comment>username_1: Instead of `And` in query use `,` as a seperator.
Like below:-
```
$query = "UPDATE `countvisits` SET balance = balance - 1, TotalVisits = TotalVisits + 1 WHERE `id` = ".$id;
```
NOTE:- your query is wide-open for SQL INJECTION. So try to use `prepared-statements` to prevent from it.
Reference:-
[mysqli::prepare](http://php.net/manual/en/mysqli.prepare.php)
[PDO::prepare](http://php.net/manual/en/pdo.prepare.php)
***You can check the balance first to see if it is 0 or not:-***
```
if(isset($_POST['Submit'])) {
$my_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = ".$id);
if(mysqli_affected_rows($connection) > 0 ){
$data = mysqli_fetch_assoc($my_query);
if($data['balance'] ==0){
echo '';
echo 'alert("Balance become 0")';
echo '';
}else{
$query = "UPDATE `countvisits` SET balance = balance - 1, TotalVisits = TotalVisits + 1 WHERE `id` = ".$id;
$result = mysqli_query($connection, $query);
echo '';
echo 'alert("Successfully Scanned")';
echo '';
/* get new updated data */
$new_query = mysqli_query($connection, "SELECT * FROM `countvisits` WHERE `id` = '$id'");
}
}else{
echo '';
echo 'alert("User Not Found")';
echo '';
/* get new updated data */
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Change this:
```
$query = "UPDATE `countvisits` SET `balance` = `balance` - 1 And `TotalVisits` = `TotalVisits` + 1 WHERE `id` = ".$id;
```
With this:
```
$query = "UPDATE `countvisits` SET `balance` = `balance` - 1, `TotalVisits` = `TotalVisits` + 1 WHERE `id` = ".$id;
```
When you update a table in sql the separator must be comma `,` not `and` keyword.
Upvotes: 2 |
2018/03/20 | 740 | 3,090 | <issue_start>username_0: Im new to C#!
So my Problem: I got a C# Demo Program from an extern company, the program sets the settings of an extern device, than initialize it and starts recording the Data. The Data is written into the Console and streamed into a CSV at a Location i can choose. After pressing a Key in the Console the Recording stops. I am trying now to write a short GUI that starts and stops this Recording.
What I did:
I converted the main-method, which started the recoding, into a normal static method and deleted all writelines so the console doesnt start, than I created a Windows Form with 2 Buttons, one Start and One Stop. If I press Start, the Recording starts, but I cant do anything with the Gui it is like freeezed, a Console still appeares and i can only stop the process by pressing a key in the console.
Here is a snippit of the Console Code:
```
class BHJKL
{
system
private static A;
private static B;
// This method will be executed every time new data is received
static void OnNewDataReceived(object sender, NewDataEventArgs eventArgs)
{
//some code in here
using (StreamWriter file = new StreamWriter(@"C:\Users\XYZ\File_Trial" + DateTime.Now.DayOfYear + ".csv", true))
{
//Writeline data..
}
}
}
```
// This was the Main Method before i changed it
```
public static void Record()
{
// Here is some Code that configure the Settings of the device
// initialize device
// MORE CODE USING THE COMPANYS EXTERN LIBRARYS TO START THE DEVICE
//start device
deviceManager.DeviceStart();
while (!Console.KeyAvailable) // as long as no key is pressed do...
{
Thread.Sleep(100); // do nothing, let the event processing thread that is managed by the library handle incomming data
}
//stop device
deviceManager.DeviceStop();
//unsubscribe event
deviceManager.NewDataReceived -= OnNewDataReceived;
//deinitialize device
deviceManager.DeinitializeDevice();
//dispose device
deviceManager.Dispose();
}
}
```
My Attempt:
Changing the main method into static Recording.
Than by Pressing the Start Button, call the method.
Write this at the end of the method:
```
while (Rec==true)
{
Thread.Sleep(100);
}
```
By Pressing the Stop Button: set.Rec(false)
But after Pressing the start Button, i cant press the stop button anyome.
I hope someone can understand my Problem and can give me some advices.<issue_comment>username_1: Thread.Sleep blocks your UI from doing anything. Consider using a System.Windows.Forms.Timer
Upvotes: 2 <issue_comment>username_2: Rather than sleeping in a loop, you should just let your `Start` method return. Move all of the code that comes after the sleep loop into your `Stop` button's click event handler.
(Depending on how the code is structured, you may also have to switch `deviceManager` from being a local variable to being a field in the class)
Upvotes: 1 [selected_answer] |
2018/03/20 | 369 | 1,520 | <issue_start>username_0: I'm new to R so please bear with me! I Have a dataframe named `mydata`. Here's a sample of the relevant columns:
```
Backlog.Item.Type Description
Feature Assignment 1
Product Backlog Item As a user I want to
Task Do this
```
Now, what I want to accomplish is the following: if part of the string in `Description` matches 'As a' or 'As an', I want to replace that rows value for the `Backlog.Item.Type` column with the string 'User Story'. To select these rows, I use
```
x <- mydata[grepl("As a", mydata[["Description"]]) | grepl("As an", mydata[["Description"]]), ]
```
However, I do not know how to then replace the corresponding value in the `Backlog.Item.Type` column. It is probably pretty simple to do this, but any help would be greatly appreciated! Thanks in advance, I hope I have been clear enough and formulated my question in an understandable manner!<issue_comment>username_1: Thread.Sleep blocks your UI from doing anything. Consider using a System.Windows.Forms.Timer
Upvotes: 2 <issue_comment>username_2: Rather than sleeping in a loop, you should just let your `Start` method return. Move all of the code that comes after the sleep loop into your `Stop` button's click event handler.
(Depending on how the code is structured, you may also have to switch `deviceManager` from being a local variable to being a field in the class)
Upvotes: 1 [selected_answer] |
2018/03/20 | 1,707 | 6,709 | <issue_start>username_0: I'm new to vuejs but I was trying to get the window size whenever I
resize it so that i can compare it to some value for a function that I
need to apply depending on the screen size. I also tried using the
watch property but not sure how to handle it so that's probably why it didn't work
```
methods: {
elem() {
this.size = window.innerWidth;
return this.size;
},
mounted() {
if (this.elem < 767){ //some code }
}
```<issue_comment>username_1: Put this code inside your Vue component:
```
created() {
window.addEventListener("resize", this.myEventHandler);
},
destroyed() {
window.removeEventListener("resize", this.myEventHandler);
},
methods: {
myEventHandler(e) {
// your code for handling resize...
}
}
```
This will register your Vue method on component creation, trigger myEventHandler when the browser window is resized, and free up memory once your component is destroyed.
Upvotes: 8 [selected_answer]<issue_comment>username_2: You can use this anywhere anytime
```
methods: {
//define below method first.
winWidth: function () {
setInterval(() => {
var w = window.innerWidth;
if (w < 768) {
this.clientsTestimonialsPages = 1
} else if (w < 960) {
this.clientsTestimonialsPages = 2
} else if (w < 1200) {
this.clientsTestimonialsPages = 3
} else {
this.clientsTestimonialsPages = 4
}
}, 100);
}
},
mounted() {
//callback once mounted
this.winWidth()
}
```
Upvotes: 1 <issue_comment>username_3: Simplest approach
=================
<https://www.npmjs.com/package/vue-window-size>
Preview
-------
```
import Vue from 'vue';
import VueWindowSize from 'vue-window-size';
Vue.use(VueWindowSize);
```
You would then access it normally from your components like this:
```
window width: {{ windowWidth }}
window height: {{ windowHeight }}
```
Upvotes: 3 <issue_comment>username_4: I looked at the code of that library `vue-window-size`, and besides the additional logic, it's just adding an event listener on window resize, and it looks like it can be instructed to debounce. [Source](https://github.com/mya-ake/vue-window-size/blob/master/src/window-size.js)
The critical problem for me is that my Vue SPA app does not emit a window resize event when a vue-router route changes that makes the element go from 1000px to 4000px, so it's causing me all kinds of problems watching a canvas element controlled by p5.js to redraw a wallpaper using `p5.resizeCanvas()`.
I have a different solution now that involves actively polling the page's offset height.
The first thing to be aware of is JavaScript memory management, so to avoid memory leaks, I put setInterval in the `created` lifecycle method and clearInterval in the `beforeDestroy` lifecycle method:
```
created() {
this.refreshScrollableArea = setInterval(() => {
const { offsetWidth, offsetHeight } = document.getElementById('app');
this.offsetWidth = offsetWidth;
this.offsetHeight = offsetHeight;
}, 100);
},
beforeDestroy() {
return clearInterval(this.refreshScrollableArea);
},
```
As hinted in the above code, I also placed some initial state:
```
data() {
const { offsetWidth, offsetHeight } = document.querySelector('#app');
return {
offsetWidth,
offsetHeight,
refreshScrollableArea: undefined,
};
},
```
>
> **Note:** if you are using `getElementById` with something like `this.id` (ie: an element that is a child in this component), `document.getElementById(this.id)` will be undefined because DOM elements load outer-to-inner, so if you see an error stemming from the `data` instantiation, set the width/height to `0` initially.
>
>
>
Then, I put a watcher on `offsetHeight` to listen for height changes and perform business logic:
```
watch: {
offsetHeight() {
console.log('offsetHeight changed', this.offsetHeight);
this.state = IS_RESET;
this.setState(this.sketch);
return this.draw(this.sketch);
},
},
```
**Conclusion:** I tested with `performance.now()` and:
```
document.querySelector('#app').offsetHeight
document.getElementById('app').offsetHeight
document.querySelector('#app').getClientBoundingRect().height
```
all execute in about the exact same amount of time: `0.2ms`, so the above code is costing about 0.2ms every 100ms. I currently find that reasonable in my app including after I adjust for slow clients that operate an order of magnitude slower than my localmachine.
Here is the test logic for your own R&D:
```
const t0 = performance.now();
const { offsetWidth, offsetHeight } = document.getElementById('app');
const t1 = performance.now();
console.log('execution time:', (t1 - t0), 'ms');
```
**Bonus:** if you get any performance issue due to long-running execution time on your `setInterval` function, try wrapping it in a double-requestAnimationFrame:
```
created() {
this.refreshScrollableArea = setInterval(() => {
return requestAnimationFrame(() => requestAnimationFrame(() => {
const { offsetWidth, offsetHeight } = document.getElementById(this.id);
this.offsetWidth = offsetWidth;
this.offsetHeight = offsetHeight;
}));
}, 100);
},
```
`requestAnimationFrame` itself a person should research. I will leave it out of the scope of this answer.
In closing, another idea I researched later, but am not using is to use a recursive `setTimeout` function with a dynamic timeout on it (ie: a timeout that decays after the page loads); however, if you consider the recursive setTimeout technique, be conscious of callstack/function-queue length and tail call optimization. Stack size could run away on you.
Upvotes: 3 <issue_comment>username_5: For Vue3, you may use the code below:
```
mounted() {
window.addEventListener("resize", this.myEventHandler);
},
unmounted() {
window.removeEventListener("resize", this.myEventHandler);
},
methods: {
myEventHandler(e) {
// your code for handling resize...
}
}
```
destroyed and beforeDestroyed is deprecated in Vue3, hence you might want to use the beforeUnmount and unmounted
Upvotes: 4 <issue_comment>username_6: If you are using composition api in vue 3, you may use following code
```
onMounted(() => {
window.addEventListener("resize", handleWindowSizeChange);
handleWindowSizeChange();
});
onUnmounted(() => {
window.removeEventListener("resize", handleWindowSizeChange);
});
const handleWindowSizeChange = () => {
// your code
};
```
Upvotes: 1 |
2018/03/20 | 1,151 | 4,915 | <issue_start>username_0: I'm trying to change the language of the application according to the user's input. I tried using this code to change the language of the application and it's working pretty fine.
```
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(MainActivity.this, MainActivity.class);
startActivity(refresh);
}
```
But the problem is that app has to restart/refresh in order to reload the resources.
* Is this the correct approach to set the language of the app programmatically?
* Is there any other way to change the language **without refreshing the app**?<issue_comment>username_1: Yes your code is correct and if you want without refreshing the application
then In Your **Application** class you need to call this in `onCreate()` method
```
String languageSelected = "en";//selected language
Locale myLocale = new Locale(languageSelected);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
getActivity().onConfigurationChanged(conf);//Call this method
```
You need to perform this particular language to be selected on Application class.
Upvotes: -1 <issue_comment>username_2: Try with recreate() on your activity. This approach was successful in my case. If you are on Fragment, then use getActivity().recreate();
```
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Constants.APP_STATE.SAVED_LOCALE, localeString);
editor.apply();
getActivity().recreate();
```
Override following method of your activity:
```
@Override
protected void attachBaseContext(Context newBase) {
SharedPreferences prefs = newBase.getSharedPreferences(Constants.APP_STATE.STATE_SHARED_PREFERENCES, MODE_PRIVATE);
String localeString = prefs.getString(Constants.APP_STATE.SAVED_LOCALE, Constants.DEFAULTS.DEFAULT_LOCALE);
Locale myLocale = new Locale(localeString);
Locale.setDefault(myLocale);
Configuration config = newBase.getResources().getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
config.setLocale(myLocale);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N){
Context newContext = newBase.createConfigurationContext(config);
super.attachBaseContext(newContext);
return;
}
} else {
config.locale = myLocale;
}
super.attachBaseContext(newBase);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
```
When user set wanted locale, what you want to do is to save it into some string in SharedPreferences and call recreate() of activity. This will then call attachBaseContext(Context context) and in this method proper locale will be set to configuration, then new context will be created with this configuration. After that, new context will be sent to super class which will update application context and proper locale will be shown.
It is also good because locale is automatically set when starting app next time.
Upvotes: 2 <issue_comment>username_3: Change locale is a `Configuration` which leads your acitivity restart. There are many other things have the same effect like `orientation` , `keyboardHidden`. Take care of your activity's states.
>
> If restarting your activity requires that you recover large sets of
> data, re-establish a network connection, or perform other intensive
> operations, then a full restart due to a configuration change might be
> a slow user experience. Also, it might not be possible for you to
> completely restore your activity state with the Bundle that the system
> saves for you with the onSaveInstanceState() callback—it is not
> designed to carry large objects (such as bitmaps) and the data within
> it must be serialized then deserialized, which can consume a lot of
> memory and make the configuration change slow. In such a situation,
> you can alleviate the burden of reinitializing part of your activity
> by retaining a Fragment when your activity is restarted due to a
> configuration change. This fragment can contain references to stateful
> objects that you want to retain.
>
>
>
Not the best-practice, but you can handle it
```
```
Then in your Activity
```
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Do your stuff here
}
```
Remember to take care of your state. Using `setRetainFragment(true)` is a good approach. Read [this](https://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html)
Upvotes: 0 |
2018/03/20 | 964 | 2,197 | <issue_start>username_0: i have 2 dataframes df1 & df2 as given below:
df1:
```
a
T11552
T11559
T11566
T11567
T11569
T11594
T11604
T11625
```
df2:
```
a b
T11552 T11555
T11560 T11559
T11566 T11562
T11568 T11565
T11569 T11560
T11590 T11594
T11604 T11610
T11621 T11625
T11633 T11631
T11635 T11634
T13149 T13140
```
I want to have a new dataframe df3 where i want to search the value of df1 in df2. if the value is present in df2, i want to add new column in df1 returning True/False as shown below.
df3:
```
a v
T11552 TRUE
T11559 TRUE
T11566 TRUE
T11567 FALSE
T11569 TRUE
T11594 TRUE
T11604 TRUE
T11625 TRUE
T11633 TRUE
T11634 TRUE
```<issue_comment>username_1: Try this:
```
df3 = df1[['a']].copy()
df3['v'] = df3['a'].isin(set(df2.values.ravel()))
```
The above code will:
1. Create a new dataframe using column 'a' from `df1`.
2. Create a Boolean column 'v' testing the existence of each value of column 'a' versus values in `df2` via `set` and [`numpy.ravel`](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.ravel.html).
Upvotes: 0 <issue_comment>username_2: Use [`assign`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html) for new `DataFrame` with [`isin`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html) and converting all values to flatten array by [`ravel`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html), for improve performance is possible check only [`unique`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html) values and also check by [`in1d`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html):
```
df3 = df1.assign(v = lambda x: x['a'].isin(np.unique(df2.values.ravel())))
#alternative solution
#df3 = df1.assign(v = lambda x: np.in1d(x['a'], np.unique(df2[['a','b']].values.ravel())))
#if need specify columns in df2 for check
df3 = df1.assign(v = lambda x: x['a'].isin(np.unique(df2[['a','b']].values.ravel())))
print (df3)
a v
0 T11552 True
1 T11559 True
2 T11566 True
3 T11567 False
4 T11569 True
5 T11594 True
6 T11604 True
7 T11625 True
```
Upvotes: 2 |
2018/03/20 | 2,277 | 8,955 | <issue_start>username_0: I have a parent object and a child object. The parent object may include the same child objects multiple times, so I only serialize the child object once and the next instances are only referenced by their ID. The object deserializes without errors when I remove the @JsonIdentityInfo annotation from the child object. To me this feels like a Jackson bug, but maybe someone spots an error in my code. I made a small example which shows the error (Jackson version used is 2.9.4):
The parent class:
```
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.ArrayList;
import java.util.Collection;
import lombok.Getter;
import lombok.Setter;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = TestClassParent.class)
public class TestClassParent {
@Getter
@Setter
private ITestClassChild child1;
@Getter
@Setter
private Collection children;
public TestClassParent(){
child1 = new TestClassChild();
children = new ArrayList<>();
children.add(child1);
}
}
```
The child class:
```
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = TestClassChild.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,
property="id")
public class TestClassChild implements ITestClassChild{
@Getter
private String id;
public TestClassChild(){
id = "1";
}
}
```
The interface:
```
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = ITestClassChild.class)
public interface ITestClassChild {
public String getId();
}
```
The testcase:
```
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import org.junit.Test;
public class TestClassImportExportTest{
@Test
public void test() throws JsonProcessingException, IOException{
ObjectMapper om = new ObjectMapper();
om.registerSubtypes(
TestClassChild.class
);
TestClassParent original = new TestClassParent();
String json = om.writerWithDefaultPrettyPrinter().writeValueAsString(original);
TestClassParent imported = om.readValue(json, TestClassParent.class);
}
}
```
Executing the test results in the following error:
```
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `json.ITestClassChild` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (String)"{
"type" : "TestClassParent",
"child1" : {
"type" : "TestClassChild",
"id" : "1"
},
"children" : [ "1" ]
}"; line: 7, column: 18] (through reference chain: json.TestClassParent["children"]->java.util.ArrayList[0])
at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:265)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedUsingDefaultImpl(AsPropertyTypeDeserializer.java:178)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:88)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:254)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:288)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:245)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:27)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:189)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:130)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1171)
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:68)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
at json.TestClassImportExportTest.test(TestClassImportExportTest.java:18)
```
As already mentioned above, removing the @JsonIdentityInfo annotation from TestClassChild makes the test case pass without errors. However, I need the annotation in order to have correct imports. The error seems to be caused by the use of collection + interface + id, removing either of these seems to work, I am happy for any help!<issue_comment>username_1: Jackson cannot construct Object of `ITestClassChild` since it is a interface as with `JsonIdentityInfo` in place its trying to maintain bidirectional relationship.
You can read here for `JsonIdentityInfo` - [Jackson Relationships](http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
With interface need to specify the Type which is to be used using `@JsonSubTypes`, for example -
`@JsonSubTypes({ @Type(value = TestClassChild.class, name = "child1")})
public interface ITestClassChild`
refer this [blog](http://programmerbruce.blogspot.hk/2011/05/deserialize-json-with-jackson-into.html) for better explanation.
Used - jackson 2.8. Below is my code i still get same exception using input
`{
"type" : "TestClassParent",
"child" : {
"type" : "TestClassChild",
"id" : "1"
}
}`
```
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = TestClassParent.class)
class TestClassParent {
private ITestClassChild child;
/*private Collection children;\*/
public TestClassParent(){
//child = new TestClassChild();
/\*children = new ArrayList<>();
children.add(child1);\*/
}
public ITestClassChild getChild() {
return child;
}
public void setChild(ITestClassChild child) {
this.child = child;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = ITestClassChild.class)
interface ITestClassChild {
public String getId();
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY,
property = "type", defaultImpl = TestClassChild.class)
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,
property="id")
class TestClassChild implements ITestClassChild {
private String id;
public TestClassChild(){
id = "1";
}
@Override
public String getId() {
return id;
}
}
```
But if you use input as below you wont get the exception as it ignores the property.
`{
"type" : "TestClassParent",
}`
Upvotes: 1 <issue_comment>username_2: So the following workaround should work:
I've added a custom deserializer for each child class (annotating the class with @JsonDeserialize(using = TestClassChildDeserializer.class)) and one for the interface (also annotated the same way). Then I deserialize the object (maybe there is a way to use the default deserializer?) and added the object into a static Hashmap in the Interface deserializer.
The deserializer does nothing more than taking the textValue of the node and returning the value in the HashMap for this node. The child deserializers deserialize the object and save it into the HashMap.
It's very ugly, but works for the moment (although I need to empty the HashMap after deserialization and it's also not threadsafe...).
I also tried the solution proposed here: <https://github.com/FasterXML/jackson-databind/issues/1641> to no avail.
Upvotes: 1 [selected_answer] |
2018/03/20 | 403 | 1,310 | <issue_start>username_0: When using python-selenium and loading a web page I can get the source as follows:
```
webdriver.page_source
```
Is there a way to *set* the page source?
I want to 'read' the html from a file and perform a location action on it, i.e. something like this:
```
driver = webdriver.Firefox()
driver.set_source(open('my_file.html'))
driver.find_element((By.XPATH, "//div[@id='create']//input"))
```
Is there a way to do this?<issue_comment>username_1: You can open the file directly.
```
from selenium import webdriver
import os
driver = webdriver.Firefox()
driver.get('file:///' + os.getcwd() +'/my_file.html')
inputElement = driver.find_element_by_xpath("//div[@id='create']//input")
driver.quit()
```
P.S. I recall that this doesn't work on IE. It works fine on Firefox and Chrome.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can try to implement something like below:
```
# Get "html" element
current_html = driver.find_element_by_tag_name("html")
# Get "body" element from saved HTML doc
saved_doc = open("my_file.html")
new_body = saved_doc.read().split("")[-1].split("")[0]
# Replace "body" of current page with "body" of saved page
driver.execute_script("arguments[0].innerHTML = arguments[1]", current_html, new_body)
saved_doc.close()
```
Upvotes: 1 |
2018/03/20 | 365 | 1,443 | <issue_start>username_0: Hi guys I'm working on an exiting Episerver project (my first one) -
One of the issues that we are having is we have three enviroments for our episerver website. Developer / Staging / Live.
All have sepreate DBs. At the moment, we have had lots of media items added to our live enviroment via the CMS, we want to sync this with our staging enviroment.
However when we use the export data feature from live admin section and try to restore it to our staging enviroment, we end up with missing media, duplicate folders etc.
Is there a tool/plugin avalible to manage content/media across mulitple enviroments. Umbraco has something called "courier" (Umbraco being another CMS I have used in the past) looking for the episerver equvilent.
Or is the best way to do this export the live SQL database and over write my staging one? We have diffrent user permissions set in these enviroments how can we manage that?
How is this genreally done in the world of episerver?<issue_comment>username_1: Unfortunately the most common way to handle this is as you say to do it manually. Restore the db, copy the fileshare, and set up the access rights on the stage environment after the restore.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Luc made a nice provider for keeping your local environment in sync. <https://devblog.gosso.se/2017/09/downloadifmissingfileblob-provider-version-1-6-for-episerver/>
Upvotes: 0 |
2018/03/20 | 606 | 2,246 | <issue_start>username_0: I tried to assign currenturl to SiteName(Global variable) but while changing to a new method SiteName(global variable) getting null.
can anyone please help?
```
public string SiteName;
public ActionResult Admin()
{
string currentUrl = HttpContext.Request.Url.Segments.Last();
SiteName = currentUrl;
return View();
}
```<issue_comment>username_1: I don't think you can define global variables, but you can have **static members**.
```
public static class MyStaticValues
{
public static string currentUrl{get;set;}
}
```
And then you can retrieve that from anywhere in the code:
```
String SiteName = MyStaticValues.currentUrl + value.ToString();
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Since you are using asp: there is a [Session](https://msdn.microsoft.com/en-us/library/system.web.httpcontext.session(v=vs.110).aspx) and [Application](https://msdn.microsoft.com/en-us/library/system.web.httpcontext.application(v=vs.110).aspx) object for this purpose:
```
public ActionResult Admin()
{
string currentUrl = HttpContext.Request.Url.Segments.Last();
//per session (let's say: per user)
//you can read and write to this variable
Session["SiteName"] = currentUrl;
//"global" variables: for all users
HttpContext.Application["SiteName"] = currentUrl;
return View();
}
```
You can retrieve it the same way throughout your application where you have access to the httpcontext.
```
public ActionResult Foo()
{
//per session (let's say: per user)
//you can read and write to this variable
var currentUrl = Session["SiteName"];
//or
//"global" variables: for all users
currentUrl = HttpContext.Application["SiteName"];
return View();
}
```
Upvotes: 3 <issue_comment>username_3: To use global variables in an asp.net MVC is not a best practice.
I suggest to use Session variables instead.
```
public ActionResult MyPage(PageData pageData)
{
Session["SiteName"] = HttpContext.Request.Url.Segments.Last();
return View();
}
```
Than you can call it in another ActionResult
```
public ActionResult MyPage2(PageData pageData)
{
var SiteName = Session["SiteName"].ToString();
return View();
}
```
Upvotes: 3 |
2018/03/20 | 556 | 1,817 | <issue_start>username_0: This is my component
```
export class myComponent implements onInit {
private outageCount;
ngOnInit(){
....subscribe((data) => {
this.outageCount = Object.keys(data).length;
})
}
```
I need to pass the outageCount to my css before `CONTENT`
```
:host ::ng-deep app-settings-panel {
&:before{
//content:"4";
content:attr(outageCount);
background: #941313;
position: absolute;
top: 3px;
left: 22px;
border-radius: 50%;
height: 13px;
width: 13px;
border: 1px solid #ffffff;
color: white;
font-size: 8px;
text-align: center;
line-height: 13px;
}
```
How can i pass the outageCount value from my component to css :before `content`.
Any suggestions would be appreciated!<issue_comment>username_1: try using :
>
> document.documentElement.style.setProperty('--contentvalue', this.outageCount);
>
>
>
**css**
```
:root {
--contentvalue: 4;
}
:host ::ng-deep app-settings-panel {
&:before{
//content:"4";
content:attr(--contentvalue);
background: #941313;
position: absolute;
top: 3px;
left: 22px;
border-radius: 50%;
height: 13px;
width: 13px;
border: 1px solid #ffffff;
color: white;
font-size: 8px;
text-align: center;
line-height: 13px;
}
```
Upvotes: 2 <issue_comment>username_2: I'm passing this as attribute in my html like below
```
[attr.outage-count]="outageCount"
```
I css, i updated like this
```
:host ::ng-deep app-settings-panel {
&:before{
content: attr(outage-count);
......
}
}
```
This works for me!! Thanks for all those who tried helping me!
Upvotes: 3 |
2018/03/20 | 968 | 3,611 | <issue_start>username_0: I have highlighted paragraphs in a Word document, from which I have to remove highlighting from 3rd to 5th character of each paragraph.
By searching for highlighted ranges within Set r = ActiveDocument.Range in VBA the segments of text are perfectly found.
The error appears on the line `r(Start:=r_start, End:=r_end).HighlightColorIndex = wdNoHighlight`.
>
> Compile error: Wrong number of arguments or invalid property assignment.
>
>
>
How danI correctly specify the subrange from 3rd to 5th character within the range `r`? Your help is appreciated.
```
Dim r as Range
Dim r_start As Integer
Dim r_end As Integer
r_start = 2
r_end = 5
Set r = ActiveDocument.Range
With r.Find
.Highlight = True
Do While .Execute(FindText:="", Forward:=True) = True
if r.Characters.Count > 7 Then
r(Start:=r_start, End:=r_end).HighlightColorIndex = wdNoHighlight
End If
r.Collapse 0
Loop
End With
```<issue_comment>username_1: You were almost there, I modified the code and tested it and it worked perfectly on my end. It will find any highlighted range in the document and will remove the highlights from character 2 to character 5:
```
Sub GetHighlights()
Dim rng1 As Range
Dim rng2 As Range
Dim r_start As Integer
Dim r_end As Integer
r_start = 2
r_end = 5
Set rng1 = ActiveDocument.Range
With rng1.Find
.Highlight = True
Do While .Execute(FindText:="", Forward:=True) = True
If rng1.Characters.Count > 7 Then
Set rng2 = ActiveDocument.Range(Start:=rng1.Start + r_start, End:=rng1.Start + r_end)
rng2.HighlightColorIndex = wdNoHighlight
End If
rng1.Collapse 0
Loop
End With
End Sub
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: The problem causing the error message is that only the `Range` method (as in `Document.Range`) takes arguments. The `Range` object, since it's not a method, can take no arguments. In order to set the Start and End of a Range object you need the properties of those names. So:
```
r.Start = r.Start + r_start
r.End = r.Start + r_end
```
Your code has a number of other problems which I encountered while testing. For example, if you set the Start position to `r_start` and the End position to `r_end` the Range `r` will be from the second to the fifth characters *of the entire document*, not the second to fifth characters of the Range `r`. That's why the two lines of code, above, have been changed from your original.
The next problem is that the code, as it stands, goes into an infinite loop since the search always begins from within the "found" highlighting. For that reason I've added a variable to capture the end point of the originally Found range and use that as the starting point for the Range to be searched in each loop. The end of the Range to search is set to the end of the document.
Here's my sample code:
```
Sub FindRemoveHighlighting()
Dim r As Range, rDoc As Range
Dim r_foundEnd As Long
Dim r_start As Long
Dim r_end As Long
r_start = 2
r_end = 5
Set rDoc = ActiveDocument.content
Set r = rDoc.Duplicate
With r.Find
.Highlight = True
.Text = ""
.Format = True
.Format = True
Do While .Execute() = True
If r.Characters.Count > 7 Then
rFoundEnd = r.End
r.Start = r.Start + r_start
r.End = r.Start + r_end
r.HighlightColorIndex = wdNoHighlight
End If
r.Start = rFoundEnd
r.End = rDoc.End
Loop
End With
End Sub
```
Upvotes: 1 |
2018/03/20 | 593 | 2,211 | <issue_start>username_0: I am trying out some OpenCV and are on a tutorial for a Canny edge detector [Example](https://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/canny_detector/canny_detector.html).
In this tutorial, there is a function declared like this:
```
void CannyThreshold(int, void*)
```
and then called like this from inside main;
```
CannyThreshold(0, 0);
```
I don't understand the purpose og the (int, void\*) part of the declaration since none of these arguments are used in the CannyThreshold funtion.
Why is it simply not just declared like this?
```
void CannyThreshold();
```<issue_comment>username_1: Note this line in the example:
```
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
```
Here, `CannyThreshold` is passed as a callback argument to `createTrackbar`. The signature of `createTrackbar` requires the callback to accept these two arguments, and so `CannyThreshold` does, even if it has no use for them.
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you declare the function as
```
void CannyThreshold();
```
that is the same as
```
void CannyThreshold(void);
```
In other words, it's a function that takes no argument.
If you want the function to take arguments, but never use those arguments, you must still declare the types of the arguments.
Upvotes: 1 <issue_comment>username_3: This is supposedly because this function is a *callback*, hence its signature is enforced by whatever API is used (here: OpenCV).
A callback is a name given to a function when this function is *registered* into an event system to be called later, when something happens. A function registering a callback is called a *functor*, it takes another function as argument, and do something with it. Exemple:
```
using callback_t = void(*)(int);
void register_callback(callback_t cb);
```
If you want to define a callback to be called (back) by `register_callback`, it needs to be a function taking an `int` and returning `void`, even if you don't need the integer. So the following definition is possible:
```
void my_callback(int) { std::cout << "done\n"; }
register_callback(my_callback);
```
Upvotes: 1 |
2018/03/20 | 636 | 2,226 | <issue_start>username_0: Im Trying to Process below tab csv file line by line .It raising error.Unable to trace where im wrong.
Here is the file :
/tmp/fa.csv
```
1 Close
6 Close
72 Close
99 Close
8 Close
4 Close
3 Close
103 Close
106 Close
107 Close
105 Close
220 Open
```
9.py
```
import csv
with open('/tmp/fa.csv') as f:
rown = csv.reader(f,delimiter='\t')
for row in rown:
print row[1]
```
Output:
```
[root@localhost ~]# python 9.py
File "9.py", line 3
rown = csv.reader(f,delimiter='\t')
^
IndentationError: expected an indented block
```<issue_comment>username_1: Note this line in the example:
```
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
```
Here, `CannyThreshold` is passed as a callback argument to `createTrackbar`. The signature of `createTrackbar` requires the callback to accept these two arguments, and so `CannyThreshold` does, even if it has no use for them.
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you declare the function as
```
void CannyThreshold();
```
that is the same as
```
void CannyThreshold(void);
```
In other words, it's a function that takes no argument.
If you want the function to take arguments, but never use those arguments, you must still declare the types of the arguments.
Upvotes: 1 <issue_comment>username_3: This is supposedly because this function is a *callback*, hence its signature is enforced by whatever API is used (here: OpenCV).
A callback is a name given to a function when this function is *registered* into an event system to be called later, when something happens. A function registering a callback is called a *functor*, it takes another function as argument, and do something with it. Exemple:
```
using callback_t = void(*)(int);
void register_callback(callback_t cb);
```
If you want to define a callback to be called (back) by `register_callback`, it needs to be a function taking an `int` and returning `void`, even if you don't need the integer. So the following definition is possible:
```
void my_callback(int) { std::cout << "done\n"; }
register_callback(my_callback);
```
Upvotes: 1 |
2018/03/20 | 407 | 1,603 | <issue_start>username_0: I am calling the twitch TV API to get users info from one endpoint and I want also to call another endpoint in the same API to check if those users are streaming live or not, **but only if the first ajax call is successful.** Can anyone give me a hint on how to do it?? My first call below:
```
var getUserInfo = $.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/users/?login=ESL_SC2&login=freecodecamp&login=noobs2ninjas",
// contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
headers: {
"Client-ID": "5k4g3q59o69v6p9tudn39v50ro1mux",
},
dataType: "json",
success: function (json) {
console.log(JSON.stringify(json, null, 2));
},
error: function () {
console.log("OOPS!!!");
},
})
```<issue_comment>username_1: The success function only runs if the call was successful.
Trigger the code for the second request from the success function.
Upvotes: 0 <issue_comment>username_2: The jQuery ajax function is built using the callback design to deal with its asynchronicity. You have two callbacks, success and error, one of which will fire when you receive a response from the Twitch API. If you want to make another ajax request depending on if your previous request was successful then you can simply write a very similar ajax request inside your success callback function pointing to the new location you are trying to acccess. I would recommend splitting that off into a separate function to maintain the readability of your code however.
Upvotes: 2 [selected_answer] |
2018/03/20 | 705 | 2,807 | <issue_start>username_0: I am using Retrofit2 to send and receive requests to my server.
Here are my API interface and Model class.
1. Interface
```
public interface ApiInterface {
@POST("/users/")
Call signUp(@Body User user);
@POST("/login\_url/")
Call login(@Body User user);
}
```
2. Retrofit client
```
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getRestClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
```
3. POJO class
```
public class User {
@SerializedName("id")
private Integer id;
@SerializedName("email")
@Expose
private String email;
@SerializedName("first_name")
private String firstName;
@SerializedName("last_name")
private String lastName;
@SerializedName("password")
@Expose
private String password;
}
```
I have exposed email and password so that in login request these 2 parameters will be added.
But for another request like Sign up, I required a first name and last name also to be sent along with email and password.
Can I use same "User" class for both ? because if I expose the first name and last name then, those fields will be also sent in login request.
Is there any other way or should I make different POJO classes for both request ?<issue_comment>username_1: >
> Can I use same `"User"` class for both ?
>
>
>
**Yes** , you can use the same **`Model`** as **`@Body`** for both requests !
Just make sure where you don't need the `required variables` just *omit* them !!
Remove the `@SerializedName` and `@Expose` , these are not required and give the `variable names` according to the **json KEYs**
```
public class User {
private Integer id;
private String email;
private String firstName;
private String lastName;
private String password;
}
```
**Edit**
Suppose for example , for one request you need :-
* 4 params you set the model user as
```
new User(id,email,firstname,lastname); // dont init the password attribute
```
* 5 params you set all values to the `model` like
```
new User(id,email,firstname,lastname,password);
```
Upvotes: 0 <issue_comment>username_2: Instead of sending the whole class , you can use **@Field** annotation , so your login callback will be something like this :
```
@FormUrlEncoded
@POST("/login_url/")
Call login(@field("email")String email,@field("password")String password);
```
**@FormUrlEncoded** denotes that the request body will use form URL encoding. Fields should be declared as parameters and annotated with **@Field**.
Upvotes: 3 [selected_answer] |
2018/03/20 | 520 | 1,906 | <issue_start>username_0: I am trying to create some new env variables in the rhel machine using chef.
The block executes successfully but on trying to echo the value, i am getting black result.
Script-1:
```
execute 'JAVA_HOME' do
command 'export JAVA_HOME='+node['java']['home']
end
```
Script-2:
```
bash 'env_test' do
code <<-EOF
echo $chef
EOF
environment ({ 'chef' => 'chef' })
end
```
Also gave this a shot as it was mentioned in the documentation:
```
ENV['LIBRARY_PATH'] = node['my']['lib']
```
Please let me know where am i going wrong here..<issue_comment>username_1: >
> Can I use same `"User"` class for both ?
>
>
>
**Yes** , you can use the same **`Model`** as **`@Body`** for both requests !
Just make sure where you don't need the `required variables` just *omit* them !!
Remove the `@SerializedName` and `@Expose` , these are not required and give the `variable names` according to the **json KEYs**
```
public class User {
private Integer id;
private String email;
private String firstName;
private String lastName;
private String password;
}
```
**Edit**
Suppose for example , for one request you need :-
* 4 params you set the model user as
```
new User(id,email,firstname,lastname); // dont init the password attribute
```
* 5 params you set all values to the `model` like
```
new User(id,email,firstname,lastname,password);
```
Upvotes: 0 <issue_comment>username_2: Instead of sending the whole class , you can use **@Field** annotation , so your login callback will be something like this :
```
@FormUrlEncoded
@POST("/login_url/")
Call login(@field("email")String email,@field("password")String password);
```
**@FormUrlEncoded** denotes that the request body will use form URL encoding. Fields should be declared as parameters and annotated with **@Field**.
Upvotes: 3 [selected_answer] |
2018/03/20 | 578 | 1,276 | <issue_start>username_0: I need to create a new dictionary comparing the matching values from the dict1 and list1 and passing the keys from the dict1 and values from the list1 to the new dictionary.
```
dict1 = {'F0': (117, 118),
'F1': (227, 118),
'F2': (337, 118),
'F3': (447, 118),
'F4': (557, 118)}
list1 = [(117, 118), (447, 228), (227, 448), (557, 558),(557, 118)]
result:
dict2 = {'F0': (117, 118),'F4': (557, 118)}
```<issue_comment>username_1: This can be achieved using a dictionary comprehension.
```
list1_set = set(list1)
res = {k: v for k, v in dict1.items() if v in list1_set}
```
`list1` is converted to a set for O(1) lookup within the comprehension. This is possible because the elements of `list1` are tuples and therefore hashable.
Result:
```
{'F0': (117, 118), 'F4': (557, 118)}
```
Upvotes: 2 <issue_comment>username_2: ```
dict1 = {'F0': (117, 118),
'F1': (227, 118),
'F2': (337, 118),
'F3': (447, 118),
'F4': (557, 118)}
list1 = [(117, 118), (447, 228), (227, 448), (557, 558),(557, 118)]
print {k:v for k,v in dict1.items() if v in list1} #python dict comprehension
```
**Output:**
```
{'F0': (117, 118), 'F4': (557, 118)}
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 774 | 2,308 | <issue_start>username_0: I have a list of 3 environment variables that I want to bind and encode them (Key +value) in base64.
fro examples,
the 3 Variable now are stored as key-value variables and what i need to have is a base64 encode on this:
{
"VAR1": "313",
"VAR2": "33344",
"VAR3": "rovkssj",
}
I guess that should use the script to create the json and encode it.
appreciate your help
Ronen<issue_comment>username_1: Postman uses the built-in module `CryptoJS`. This *could* be used to get you close to a solution.
If you add this into the `Pre-request Script` or `Tests` tab and send a request, you will see the output of the Base64 conversation in the Postman Console. In the example I'm getting the 'VAR1' `environment variable` and using this as the value to convert.
```
var CryptoJS = require("crypto-js")
//Encrypt
var rawStr = CryptoJS.enc.Utf8.parse(pm.environment.get('VAR1'))
var base64 = CryptoJS.enc.Base64.stringify(rawStr)
console.log(`Encrypted value: ${base64}`)
//Decrypt
var parsedWord = CryptoJS.enc.Base64.parse(base64)
var parsedStr = parsedWord.toString(CryptoJS.enc.Utf8)
console.log(`Decrypted value: ${parsedStr}`)
```
[](https://i.stack.imgur.com/Avk7X.jpg)
Postman Console output:
[](https://i.stack.imgur.com/xhL0R.jpg)
This is probably not the exact solution that you need but hopefully this brings you closer to achieving what you need to do.
Upvotes: 4 <issue_comment>username_2: I see that, in the answer given by @danny-dainton he is importing a JS library. That is unnecessary.
**You can just use the btoa and atob functions.** [Reference](https://www.w3schools.com/jsref/met_win_atob.asp)
In postman this would be (In your `Tests` / `Pre-request Script` tab)
```
var str = "Hello World!";
var encodedValue = btoa(str);
var decodedValue = atob(encodedValue);
```
So in your case to decode `{ "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", }`
you can just do
```
var str = "{ \"VAR1\": \"313\", \"VAR2\": \"33344\", \"VAR3\": \"rovkssj\", }";
var encodedValue = btoa(str);
```
PS: I just want to add that your JSON `{ "VAR1": "313", "VAR2": "33344", "VAR3": "rovkssj", }` is not valid as there is an extra `,` at the end.
Upvotes: 3 |
2018/03/20 | 631 | 1,979 | <issue_start>username_0: In my classification model, I need to maintain uppercase letters, but when I use sklearn countVectorizer to built the vocabulary, uppercase letters convert to lowercase!
To exclude implicit tokinization, I built a tokenizer which just pass the text without any operation ..
my code:
```
co = dict()
def tokenizeManu(txt):
return txt.split()
def corpDict(x):
print('1: ', x)
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu)
countFit = count.fit_transform(x)
vocab = count.get_feature_names()
dist = np.sum(countFit.toarray(), axis=0)
for tag, count in zip(vocab, dist):
co[str(tag)] = count
x = ['I\'m <NAME>', 'We are the only']
corpDict(x)
print(co)
```
the output:
```
1: ["I'm <NAME>", 'We are the only'] #<- before building the vocab.
{'john': 1, 'the': 1, 'we': 1, 'only': 1, 'dev': 1, "i'm": 1, 'are': 1} #<- after
```<issue_comment>username_1: You can set `lowercase` attribute to `False`
```
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu,lowercase=False)
```
Here The Attributes of `CountVectorizer`
```
CountVectorizer(analyzer=u'word', binary=False, charset=None,
charset_error=None, decode_error=u'strict',
dtype=, encoding=u'utf-8', input=u'content',
lowercase=True, max\_df=1.0, max\_features=None, min\_df=0,
ngram\_range=(1, 1), preprocessor=None, stop\_words=None,
strip\_accents=None, token\_pattern=u'(?u)\\b\\w\\w+\\b',
tokenizer=None, vocabulary=None)
```
Upvotes: 1 <issue_comment>username_2: As explained in the documentation, [here](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html). `CountVectorizer` has a parameter `lowercase` that defaults to `True`. In order to disable this behavior, you need to set `lowercase=False` as follows:
```
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu, lowercase=False)
```
Upvotes: 4 [selected_answer] |
2018/03/20 | 391 | 1,324 | <issue_start>username_0: I am creating a multi-tenant rails app for different clubs. I'm using the apartment gem so it creates different databases for each club which has more than 100 tables. now i want to take dump of one tenant and import it to other club tenant<issue_comment>username_1: You can set `lowercase` attribute to `False`
```
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu,lowercase=False)
```
Here The Attributes of `CountVectorizer`
```
CountVectorizer(analyzer=u'word', binary=False, charset=None,
charset_error=None, decode_error=u'strict',
dtype=, encoding=u'utf-8', input=u'content',
lowercase=True, max\_df=1.0, max\_features=None, min\_df=0,
ngram\_range=(1, 1), preprocessor=None, stop\_words=None,
strip\_accents=None, token\_pattern=u'(?u)\\b\\w\\w+\\b',
tokenizer=None, vocabulary=None)
```
Upvotes: 1 <issue_comment>username_2: As explained in the documentation, [here](http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html). `CountVectorizer` has a parameter `lowercase` that defaults to `True`. In order to disable this behavior, you need to set `lowercase=False` as follows:
```
count = CountVectorizer(ngram_range=(1, 1), tokenizer=tokenizeManu, lowercase=False)
```
Upvotes: 4 [selected_answer] |
2018/03/20 | 1,734 | 5,743 | <issue_start>username_0: I am trying to calculate the straight line distance between coordinates. I can successfully do this using with hard coded values, however my problem comes in when I have a list of coordinates. S basically the first set of coordinates will always be my current location which I can successfully get. The second set of coordinates are coming from a JSON file as seen below.
```
[
{
"LocationID": 407,
"LocationName": "Free State",
"CustomerName": "<NAME> - Botshabelo ",
"ContactNo": "051 - 534 4072",
"Address": "75 Blue Street, Botshabelo",
"Zipcode": null,
"Longitude": "26,704671",
"Latitude": "-29,199533",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": "Closed "
},
{
"LocationID": 408,
"LocationName": "Free State",
"CustomerName": "Cashbuild - Thabanchu",
"ContactNo": "051 - 875 1590",
"Address": "Brug St, Thaba Nchu",
"Zipcode": null,
"Longitude": "26,779109",
"Latitude": "-29,196689",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": "Closed "
},
{
"LocationID": 409,
"LocationName": "Free State",
"CustomerName": "<NAME>",
"ContactNo": "082 - 568 5387",
"Address": "17 Joubert St, Ladybrand",
"Zipcode": null,
"Longitude": "27,458835",
"Latitude": "-29,191979",
"Status": 1,
"CreatedDate": "25:29,0",
"CreatedBy": 1,
"ModifiedDate": "25:29,0",
"ModifiedBy": 1,
"ShopType": "Retails",
"Region": null,
"FIELD16": ""
}
]
```
I am looping through the array to get the latitudes and longitudes
```
this.http.get('assets/stores.json').subscribe(data => {
this.places = data;
for(var i = 0; i < this.places.length; i++){
this.placePOS = this.places[i].Latitude, this.places[i].Longitude;
var distance = this.distance(this.currentLat, this.currentLon, this.places[i].Latitude, this.places[i].Longitude, 'K');
}
});
```
The distance function is created here
```
distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1/180
var radlat2 = Math.PI * lat2/180
var radlon1 = Math.PI * lon1/180
var radlon2 = Math.PI * lon2/180
var theta = lon1-lon2
var radtheta = Math.PI * theta/180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI
dist = dist * 60 * 1.1515
if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }
return dist
}
```
When I run the code I get a NaN. Please assist<issue_comment>username_1: You get a NaN, when you try to perform some mathematical operations on variables which are not numbers.
In your problem, the documents array you have, latitude and longitude are in string format and you are not parsing float anywhere. First convert those strings to numbers and then do the mathematical operations, you desire.
PS: I can give you the code but it would be better if you try it out yourself.
Upvotes: 1 <issue_comment>username_2: To my konwledge wenn you read the value for **this.places[i].Latitude** this is not a Number so it would be necessary to convert this String to a number before you send it to the function or within the funktion.
Either with **Number()** or with **parseFloat()**
As pointed out by @username_4 for **parseFloat()** both conversations are not able to handle the comma in the original JSON object. **Number()** would produce again NaN and **parseFloat()** rounds the number to the nearest full number. So it ist necessary to replace the comma from the JSON object with a dot.
thanks @username_4
Upvotes: 3 [selected_answer]<issue_comment>username_3: You were having issue in distance function. you need to use parseFloat for lon(s) and lat(s) to convert them into numbers from string.
I tried to change your code a little bit. <https://jshttps://jsfiddle.net/startsco/z5n7q2zn/10/fiddle.net/startsco/z5n7q2zn/10/>
run it and check your console.
Upvotes: 0 <issue_comment>username_4: Seen as nobody else has spotted it,.. And @eohdev has now gone away thinking the results are correct, just because they are now not giving `NaN`, I'll post the main reason for the problem.
`parseFloat` is good practice, but it's not what was causing the problem.. Javascript can often work out type automatically.. eg. `"20" / 4` will equal `5`, even though `20` was a string. `"20" - "5"` will equal 15,. The one that JS can't work out automatically would be `"20" + "5"` this would be 205.. This is because you can concatenate strings, and add number so it can't automatically choose, this is why parseFloat etc is a good idea.
But back to the problem here, it's the source data..
`"Longitude": "27,458835"`
That number is not a valid floating point number, floating point numbers in JS don't have commas.
So why did it look like parseFloat worked you ask,.. well `parseFloat("27,458835")` will result in `27`.. Oh, dear.. Unless your distance calculation is meant to be truncated to the nearest degree, it's maybe not what your after.
So the problem wasn't parseFloat was missing, but the source data is using commas, instead of full stops for it's decimal's. So if you change the commas to full stops your current code will work, but I would also say keep the parseFloats too for good measure.
Upvotes: 2 |
2018/03/20 | 308 | 799 | <issue_start>username_0: I am trying to create a formula which picks ">" or "<" sign depending upon whether any record has "Higher" or "Lower" against it.
For example, if A1 has "Higher", then formula in B1 should be =0.78>0.59
If A2 has "Lower", then formula in B2 should be =0.78<0.59<issue_comment>username_1: Try,
```
if(a1="higher", 0.78>0.59, 0.78<0.59)
'alternate
=or(and(a1="higher", 0.78>0.59), and(a1="lower", 0.78<0.59))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: use this as formula.
=IF(A1>B1,">","<") in cell C.
than use this formula to get your desired look in next cell. =CONCATENATE(A2,C2,B2)
You can hide Column C if you don't want to show it.
Check it by clicking following link,

Upvotes: 0 |
2018/03/20 | 629 | 2,505 | <issue_start>username_0: Im working on a simple Xamarin Form application after . I created a simple login content page and when i try to run the android emulator im getting this error '**Exception has been thrown by the target of an invocation.**' ,I have Mentioned my code below.Both LoginPage.xaml and LoginPage.xaml.cs
LoginPage.xaml
```
xml version="1.0" encoding="utf-8" ?
40,0,40,0
140,150,140,0
```
LoginPage.xaml.cs
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XLoginApplication.Models;
namespace XLoginApplication.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage ()
{
InitializeComponent ();
Init();
}
void Init()
{
BackgroundColor = Constants.BackgroundColor;
Lbl_Username.TextColor = Constants.MainTextColor;
Lbl_Password.TextColor = Constants.MainTextColor;
ActivitySpinner.IsVisible = false;
LoginIcon.HeightRequest = Constants.LoginIconHeight;
Entry_Username.Completed += (s, e) => Entry_Password.Focus();
Entry_Password.Completed += (s, e) => SignInProcedure(s, e);
}
public void SignInProcedure(object sender ,EventArgs e)
{
User user = new User(Entry_Username.Text ,Entry_Password.Text);
if (user.CheckInformation())
{
DisplayAlert("Login", "Login Success", "Oke");
}
else
{
DisplayAlert("Login", "Login Not Suceesfull User name or Password is empty", "Oke");
}
}
}
}
```<issue_comment>username_1: On the line where the exception is thrown, try to wrap that line in this:
```
Device.BeginInvokeOnMainThread (() => {
// Your line(s) with the exception here
}
```
Upvotes: 0 <issue_comment>username_2: Its mainly xaml issue.
Some property name is given for the control,which is not there.
Implement Try Catch in Initialize Component method & find out.
Upvotes: 0 <issue_comment>username_3: I have tested your code, the problem is caused by the in your xaml.
The number in [Margin](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/margin-and-padding) should be separated by ',' not '.'
For example:
```
```
Upvotes: 1 |
2018/03/20 | 843 | 3,592 | <issue_start>username_0: I have a simple streams application takes one topic as input stream and transforms KeyValues to another like:
```
StoreBuilder> builder =
Stores.keyValueStoreBuilder(Stores.inMemoryKeyValueStore(CategoryTransformer.STORE\_NAME),
Serdes.Long(), CATEGORY\_JSON\_SERDE);
streamsBuilder.addStateStore(builder)
.stream(categoryTopic, Consumed.with(Serdes.Long(), CATEGORY\_JSON\_SERDE))
.transform(CategoryTransformer::new, CategoryTransformer.STORE\_NAME);
static class CategoryTransformer implements Transformer> {
static final String STORE\_NAME = "test-store";
private KeyValueStore store;
@Override
public void init(ProcessorContext context) {
store = (KeyValueStore) context.getStateStore(STORE\_NAME);
}
@Override
public KeyValue transform(Long key, CategoryDto value) {
store.put(key, value);
return KeyValue.pair(key, value);
}
@Override
public KeyValue punctuate(long timestamp) {
return null;
}
@Override
public void close() {
}
}
```
Here i had to use transformer because i need to fetch store and update relevant value.
The question is what is the difference between using local state stores, and just putting values to a simple `HashMap` inside a `ForeachAction`?
What is the advantage of using local state stores in this case?<issue_comment>username_1: Although it is not shown in your code, I'm assuming you somehow read and use the stored state.
Storing your state using a simple (in memory) `HashMap` makes your state not persistent at all, this means your state will be lost when either of the following happens (those are nothing out of the ordinary, assume it will happen quite often):
* your stream processor/applications stops,
* crashes, or
* is partially migrated elsewhere (other JVM) due to rebalancing.
The problem with a non-persistent state is that when any of the above happens, kafka-streams will restart the processing at the last committed offset. As such all records processed before the crash/stop/rebalance will not be reprocessed, this means the content of your `HashMap` will be empty when the processing restarts. This is certainly not what you want.
On the other hand, if you use one of the provided state stores, kafka-streams will ensure that, once the processing restarts after any of the interruptions listed above, the state will be available as if the processing never stopped, without reprocessing any of the previously processed records.
Upvotes: 4 [selected_answer]<issue_comment>username_2: >
> The question is what is the difference between using local state stores, and just putting values to a simple HashMap inside a ForeachAction?
>
>
>
If your input topics are not partitioned and you run a single instance of your Streams application, the value of the local state API is not huge. In such cases—sure: you can use a `HashMap` in your processors, or [some persistent `HashMap`](https://www.google.com/search?q=persistent%20hashmap%20java) if you wanted to survive restarts.
The value of local storage becomes clear when your topics are partitioned and clearer still when you run multiple instances of your Streams application. In such cases, you need to maintain specific state with the processor that's processing a specific partition, and that state needs to be able to move with the processor in case it moves to a different Streams instance. In such cases—AKA scale—the local storage facility is both necessary and invaluable. Imagine having to orchestrate this yourself at scale, vs having this facility part of the core platform (the local state API).
Upvotes: 2 |
2018/03/20 | 1,237 | 5,012 | <issue_start>username_0: I have a tableview which has tableviewcells like so...[](https://i.stack.imgur.com/84bom.png)
On the click of this tableview cell, it expands to show some more buttons like so..
[](https://i.stack.imgur.com/khBSz.png)
But if I make a search in the searchbar above and after I get the results, when I tap on the tableviewcell, it crashes showing some error message like
>
> NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (34) must be equal to the number of rows contained in that section before the update...
>
>
>
What could be the reason..?
Also, this is the code when the cell is tapped..
```
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? ProductListTableViewCell
else { return }
switch cell.isExpanded
{
case true:
self.expandedRows.remove(indexPath.row)
case false:
self.expandedRows.insert(indexPath.row)
}
cell.isExpanded = !cell.isExpanded
tableview.beginUpdates()
tableview.endUpdates()
}
```
**EDIT 1** : This is the code for `numberOfRowsInSection`...
```
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if noSearchChar1 == true {
return filtered.count
}
if filtered.count == 0 && self.appDelegate.searchBarTapFlag == true {
// searchActive = false
if deleteBtnTapped == true {
return filtered.count
}
return newProdDetails.count
}
if(searchActive) {
return filtered.count
}
return newProdDetails.count
}
```
**EDIT 2:** This is the code where the `filtered` array gets some data...
```
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText != "" {
charInSearchBar = true
//filter the results
searchActive = true
filtered = self.newProdDetails.filter({( data : NewProduct) -> Bool in
return (data.name!.lowercased().contains(searchText.lowercased()))
}) //'filtered' array gets data here.
if(filtered.count == 0){
noSearchChar1 = true //this flag is to prevent no data showing on click of back btn.
noSearchChar = true
} else {
searchActive = true;
}
tableview.reloadData() //tableview is reloaded
} else {
noSearchChar1 = false
searchActive = false
self.tableview.reloadData()
}
}
```<issue_comment>username_1: In your switch statement in `didSelectRowAt`, you didnt insert again after you remove the old cell, so the number of cells is not the same.
When you call beginUpdates, compiler expect actions like insertion / deletion of the row, but in your case, you didnt and then just endUpdates, which compiler will treat as no updates and hence your code delete or insert above will trigger the error "number of rows not equal"
Simply put the switch statement inside
```
tableview.beginUpdates()
switch cell.isExpanded
{
case true:
self.expandedRows.remove(indexPath.row)
case false:
self.expandedRows.insert(indexPath.row)
}
tableview.endUpdates()
```
should work
>
> If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid.
> fyi: <https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates>
>
>
>
Upvotes: -1 <issue_comment>username_2: You get a crash because you are changing the number of rows returned by `numberOfRowsInSection:` but you haven't given the table view any reason to expect the number of rows to change.
Somewhere (in code not shown) you put data into `filtered`, which causes `numberOfRowsInSection:` to return `filtered.count` instead of `newProdDetails.count`. This doesn't cause an immediate crash, because the tableview doesn't call `numberOfRowsInSection:` at that point.
When you select a row and call `beginUpdates`/`endUpdates` the tableview does call `numberOfRowsInSection:` and you then get the crash because the number of rows has changed but the tableview doesn't expect the change.
When you switch between the filtered data and the unfiltered data (or make a change in the filtered results) you need to call `reloadData`.
Also, you can't store the `isExpanded` value in the cell, since cell objects will be reused. You need to store it in your data model somewhere. Storing the `indexPath` won't work since the rows numbers will change as you filter the data.
Upvotes: 0 |
2018/03/20 | 669 | 2,607 | <issue_start>username_0: Is it possible to untrack certains lines in `application.properties?`
I want to push `application.properties`, but I don't want to push lines which are for email configuration.
e.g.:
```
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.gmail.com
spring.mail.username=mail
spring.mail.password=<PASSWORD>
spring.mail.port=587
spring.mail.protocol=smtp
spring.mail.test-connection=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```<issue_comment>username_1: In your switch statement in `didSelectRowAt`, you didnt insert again after you remove the old cell, so the number of cells is not the same.
When you call beginUpdates, compiler expect actions like insertion / deletion of the row, but in your case, you didnt and then just endUpdates, which compiler will treat as no updates and hence your code delete or insert above will trigger the error "number of rows not equal"
Simply put the switch statement inside
```
tableview.beginUpdates()
switch cell.isExpanded
{
case true:
self.expandedRows.remove(indexPath.row)
case false:
self.expandedRows.insert(indexPath.row)
}
tableview.endUpdates()
```
should work
>
> If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid.
> fyi: <https://developer.apple.com/documentation/uikit/uitableview/1614908-beginupdates>
>
>
>
Upvotes: -1 <issue_comment>username_2: You get a crash because you are changing the number of rows returned by `numberOfRowsInSection:` but you haven't given the table view any reason to expect the number of rows to change.
Somewhere (in code not shown) you put data into `filtered`, which causes `numberOfRowsInSection:` to return `filtered.count` instead of `newProdDetails.count`. This doesn't cause an immediate crash, because the tableview doesn't call `numberOfRowsInSection:` at that point.
When you select a row and call `beginUpdates`/`endUpdates` the tableview does call `numberOfRowsInSection:` and you then get the crash because the number of rows has changed but the tableview doesn't expect the change.
When you switch between the filtered data and the unfiltered data (or make a change in the filtered results) you need to call `reloadData`.
Also, you can't store the `isExpanded` value in the cell, since cell objects will be reused. You need to store it in your data model somewhere. Storing the `indexPath` won't work since the rows numbers will change as you filter the data.
Upvotes: 0 |
2018/03/20 | 505 | 1,520 | <issue_start>username_0: I wish to stream live video [in my https website](https://www.eoy.ee/metsis/muu) from [this http site.](http://tv.eenet.ee/metsis.html)
Added reference of hls.min.js into my template. Copy-pasted their code:
```
if(Hls.isSupported()) {
var video = document.getElementById('video');
var hls = new Hls();
hls.loadSource('/hls/metsis.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST\_PARSED,function() {
video.play();
});
}
```
into my template, but the player doesn't start to stream.
browser console says:
>
> Uncaught ReferenceError: Hls is not defined
>
>
>
Where exactly is reference error? Here?
```
hls.loadSource('/hls/metsis.m3u8');
```<issue_comment>username_1: You are getting this error as you are trying to access Hls without importing it. Please import it using the following way
```
```
A more detailed example can be seen at Getting Started section of [HLS documentation](https://github.com/video-dev/hls.js/)
Also, Add the correct reference
```
hls.loadSource('https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8');
```
Upvotes: 0 <issue_comment>username_2: correct working code:
```
if(Hls.isSupported()) {
var video = document.getElementById('video');
var hls = new Hls();
hls.loadSource('http://tv.eenet.ee/hls/metsis.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST\_PARSED,function() {
video.play();
});
}
```
but browser blocks it, because `the content must be served over https` if my page is loaded over https.
Upvotes: 2 |
2018/03/20 | 737 | 2,966 | <issue_start>username_0: >
> SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
> update a parent row: a foreign key constraint fails
> (demopurpose\_fundraising.campaign\_product, CONSTRAINT
> campaign\_product\_campaign\_id\_foreign FOREIGN KEY (campaign\_id)
> REFERENCES campaign (id)) (SQL: delete from campaign where id = 60)
>
>
>
campaign table schema :
```
Schema::create('campaign', function (Blueprint $table) {
$table->engine='InnoDB';
$table->increments('id');
$table->integer('users_id')->unsigned();
$table->foreign('users_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('campaign_name');
$table->float('campaign_goal',8,2);
$table->string('discription',400);
$table->string('image');
$table->string('category');
$table->date('start_date');
$table->date('end_date');
$table->float('total_fund',8,2);
});
```
campaign\_product table schema :
```
Schema::create('campaign_product', function (Blueprint $table) {
$table->engine='InnoDB';
$table->increments('id');
$table->integer('campaign_id')->unsigned();
$table->foreign('campaign_id')->references('id')->on('campaign')->onDelete('cascade')->onUpdate('cascade');
$table->integer('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('product')->onDelete('cascade')->onUpdate('cascade');
});
```
campaign\_id is foreign key in campaign\_product delete..
I want to delete campaign ..
How to delete campaign product then campaign ??<issue_comment>username_1: What you are seeing is you cant delete a model because it still has connection in your database. You want to make a function that first deletes all the relations before deleting the model in question.
Try adding this to you `Campaign` Model.
```
protected static function boot() {
parent::boot();
static::deleting(function($campaign) { // before delete() method, call this
$campaign->products()->delete();
// do the rest of the cleanup...
});
}
```
If you follow the process given in the link in the comments you can prevent this issue from happening in the future.
Upvotes: 0 <issue_comment>username_2: You cannot delete it unless you remove those `campaign_id` from `campaign_product` table. Detach products from the `campaign_product` table before you delete a campaign. Example:
```
$campaign = Campaign::query()->findOrFail($id); //find campaign
$campaign->products()->detach($campaign->product); //detach products from `campaign_products` table
$campaign->delete(); //delete the campaign
```
Read more about detaching many-to-many relationship record: <https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships>
Upvotes: 2 [selected_answer] |
2018/03/20 | 1,751 | 5,148 | <issue_start>username_0: Hello I am trying to develop drop-down box list. I am able to develop it. When I click on drop-down all the options will start coming from left side as below
```js
window.onload = function() {
$(".btn-toggle").on("click", function() {
$('.dropdown-menu').toggleClass('open');
});
$(".dropdown-menu li").on("click", function() {
$('.btn-toggle').text($(this).text());
$('.dropdown-menu').removeClass('open');
});
}
```
```css
.dropdown-header {
background: #DCDCDC;
margin-left: 124px;
background: no-repeat;
background-position: right top;
width: 151px;
background-image: url(https://softwareui.abb.com/DOWNLOADS/icons/svgControls/UI_ControlComponent_CaretDown_16.svg);
-webkit-text-fill-color: black;
background-color: lightgrey;
}
.dropdown-menu {
font-family: ABBvoice;
font-weight: normal;
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
min-width: 150px;
max-height: 600px;
overflow-x: visible;
overflow-y: visible;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
font-weight: 500;
text-align: left;
background-color: #FFFFFF;
border-radius: 0;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-webkit-background-clip: padding-box;
background-clip: padding-box;
color: #464646;
transition: all .3s;
transform: translate(-100%);
}
.checkbox-inline:active {
background-color: #2E92FA;
}
.dropdown-menu.open {
transform: translate(0%);
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
```
```html
Select User Role
* Sensors
* Actuators
* Digital inputs
* Outputs
* Converters
```
Whenever i click on drop-down all the options should open immediately just below the button.
Can someone help me to make this work? Any help would be appreciated. Thanks<issue_comment>username_1: The problem is you use `tranform` and `transition` in your css, not sure what you're expect because it's perform transition as it's described.
You can get rid of those transition by remove these 2 lines in `.dropdown-menu`
```
transition: all .3s;
transform: translate(-100%);
```
and change `.dropdown-menu.open` to this
```
.dropdown-menu.open {
display:none
}
```
**update snipped**
```js
window.onload = function() {
$(".btn-toggle").on("click", function() {
$('.dropdown-menu').toggleClass('open');
});
$(".dropdown-menu li").on("click", function() {
$('.btn-toggle').text($(this).text());
$('.dropdown-menu').removeClass('open');
});
}
```
```css
.dropdown-header {
background: #DCDCDC;
margin-left: 124px;
background: no-repeat;
background-position: right top;
width: 151px;
background-image: url(https://softwareui.abb.com/DOWNLOADS/icons/svgControls/UI_ControlComponent_CaretDown_16.svg);
-webkit-text-fill-color: black;
background-color: lightgrey;
}
.dropdown-menu {
font-family: ABBvoice;
font-weight: normal;
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
min-width: 150px;
max-height: 600px;
overflow-x: visible;
overflow-y: visible;
padding: 0;
margin: 0;
list-style: none;
font-size: 13px;
font-weight: 500;
text-align: left;
background-color: #FFFFFF;
border-radius: 0;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
-webkit-background-clip: padding-box;
background-clip: padding-box;
color: #464646;
}
.checkbox-inline:active {
background-color: #2E92FA;
}
.dropdown-menu.open {
display: none
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
```
```html
Select User Role
* Sensors
* Actuators
* Digital inputs
* Outputs
* Converters
```
Upvotes: 1 <issue_comment>username_2: You can directly use bootstrap button group with dropwdown so it will automatically open below the button itself.
<https://getbootstrap.com/docs/3.3/components/#btn-dropdowns-single>
For the sliding animation of dropdown try this code.
```
.open > .dropdown-menu {
-webkit-transform: scale(1, 1);
transform: scale(1, 1);
}
.open > .dropdown-menu li a {
color: #000;
}
.dropdown-menu li a{
color: #fff;
}
.dropdown-menu {
-webkit-transform-origin: top;
transform-origin: top;
-webkit-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-transform: scale(1, 0);
display: block;
transition: all 0.2s ease-out;
-webkit-transition: all 0.2s ease-out;
}
.dropup .dropdown-menu {
-webkit-transform-origin: bottom;
transform-origin: bottom;
}
.navbar .nav > li > .dropdown-menu:after {
}
.dropup > .dropdown-menu:after {
border-bottom: 0;
border-top: 6px solid rgba(39, 45, 51, 0.9);
top: auto;
display: inline-block;
bottom: -6px;
content: '';
position: absolute;
left: 50%;
border-right: 6px solid transparent;
border-left: 6px solid transparent;
}
```
Upvotes: 0 |
2018/03/20 | 1,012 | 3,557 | <issue_start>username_0: I encounted a problem today:
When I started HDP docker container, an error occured:
>
> listen tcp 0.0.0.0:8086: bind: address already in use
>
>
>
According to error message, I know that port 8086 was already in use, so I tried some commands to determine which program was using port 8086.
`lsof -i:8086
lsof -i tcp:8086
lsof | grep 8086`
**But all of commands above make no outputs!**
I felt really confused about that, after some searching on google, I tried another command:
`netstat -pna | grep 8086`
**I got correct output from this command.**
**I know some differences between `lsof` and `netstat`, but I really do not know why I cannot get any output from `lsof -i:8086`?.**
Here are some differences between two commands I searched from google:
netstat(net statistic) is connection based,it shows NW connections (udp/tcp ports), routing tables, interface, multi-cast membership, etc.
lsof(list of open files) is application based, this is kind of like netstat + ps, there you can see all accessed ports, NW connections, etc.
but lsof includes stuff like my local emacs window terminal session (tty dev/pts/n) which is not part of netstat<issue_comment>username_1: As you already mentioned, `lsof` is a very useful command which is used to list files opened by a specific process, while `netstat` is a tool for monitoring network connections.
You should be able to find the PID of the process listening on port 8086 with `netstat`:
```
netstat -tunlp |grep :8086
```
and then use `lsof` to list the files used by the process:
```
lsof -p PID
```
Upvotes: 0 <issue_comment>username_2: I faced a similar issue today. The solution was to run the lsof command with sudo privileges.
```
sudo lsof -i:8086
```
should print the desired output.
Upvotes: 4 [selected_answer]<issue_comment>username_3: >
> **LSOF: List of Open Files. It lists all the open files belonging to all active processes.**
>
>
>
Examples:
```
sudo lsof -n -i
sudo lsof -n -i4
sudo lsof -n -i :80
```
* -n inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster. It is also useful when host
lookup is not working properly
* -i selects the listing of files any of whose Internet address matches the address specified in i. If no address is specified, this option selects the listing of all Internet and x.25 (HP-UX) network files. If -i4 or -i6 is specified with no following address, only files of the indicated IP version, IPv4 or IPv6, are displayed.
>
> **NETSTAT: It is a tool to get the network statistics. By default, netstat displays a list of open sockets. If you don't specify any
> address families, then the active sockets of all configured address
> families will be printed.**
>
>
>
Displays the kernel routing tables:
```
netstat -r
```
Display all listening and established connection for both TCP and UDP with PID data:
```
netstat -plunt
```
***Additionally, You have another command line tool to use which is SS.***
>
> **SS: It is used to dump socket statistics. It allows showing information similar to netstat. It can display more TCP and state
> information than other tools.**
>
>
>
`-plunt` gives data for the TCP and UDP connections which are established and listening with process information:
```
sudo ss -plunt
```
Upvotes: 3 <issue_comment>username_4: You should be root to get proper answers to your `lsof` questions. Your command is fine, assuming something really is listening on that port.
Upvotes: 1 |
2018/03/20 | 609 | 2,233 | <issue_start>username_0: This is a tricky one - I have a java interface that I want to implement in scala:
```
public interface Foo {
public void bar(scala.Array arr);
}
```
Is it even possible to implement in scala? when I try:
```
class FooImpl extends Foo {
override def bar(arr: Array[_]): Unit = ???
}
```
I get:
```
Error:(13, 7) class FooImpl needs to be abstract, since method bar
in trait Foo of type (x$1: Array)Unit is not defined
(Note that Array does not match Array[_]. To implement a raw type, use
Array[_])
class FooImpl extends Foo {
```<issue_comment>username_1: To make the code work you either have to
* Make the `FooImpl` declaration as `abstract` class
* Implement the `bar` method
because "Java interfaces don’t implement behaviour".
For your reference see [this](https://alvinalexander.com/scala/how-to-extend-java-interfaces-like-scala-traits) page.
Upvotes: 0 <issue_comment>username_2: The error message is giving you the answer for any generic type other than `Array` (after replacing the name, of course):
>
> To implement a raw type, use `Array[_]`
>
>
>
"Raw type" is what Java calls a generic type used without a type parameter and e.g. <https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html> explains why you should not use them except to interface with now horribly obsolete pre-Java-5 code. So if it is at all an option, you should fix the Java interface in the first place.
Now, why does this not work for `Array`? It's a special type, which is really built into compiler. Its instances are real JVM arrays, which don't have a common type in Java. So when it's used in Scala code, the compiled bytecode doesn't use `scala.Array` at all. I guess that it only exists as a JVM type (unlike e.g. `scala.Any` or `scala.Null`) to put the static methods there, but all instance methods are defined as `throw new Error()`. It seems the error message didn't take this unique case into account.
So, the answer is: no, it can't be implemented in Scala, as far as I am aware. But it can't be non-trivially implemented in Java either. And even for trivial implementations, you'd run into the same issues when trying to write code *using* it.
Upvotes: 3 [selected_answer] |
2018/03/20 | 736 | 2,120 | <issue_start>username_0: I want to return `False` **only if** the substring has alphabet letter(s) both before AND after it:
e.g. given the target `'at'` and
```
strings = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it']
```
I'd like to return `[True, True, True, False]`.
I have now:
```
def foo(p,i):
if p.findall(i):
return True
return False
pat = re.compile(r'\bat\b')
[foo(pat,i) for i in strings]
```
which returns `[True, False, False, False]`.<issue_comment>username_1: Try below regex
```
def foo(p,i):
if p.findall(i):
return True
return False
pat = re.compile(r'.*([\w]at[\w]).*')
out = [not foo(pat,i) for i in strings]
# [True, True, True, False]
```
Upvotes: 0 <issue_comment>username_2: You may use `re.search` instead of `re.findall` since you only test a string for
a match.
If you only need to match ASCII, `[a-zA-Z]` on both sides of a word will work.
Use
```
import re
strs = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it']
def foo(p,i):
return False if p.search(i) else True
word = 'at'
pat = re.compile(r'[a-zA-Z]{}[a-zA-Z]'.format(word))
print([foo(pat,i) for i in strs])
# => [True, True, True, False]
```
See the [Python demo](https://ideone.com/1NqeEr)
If you plan to work with Unicode letters, replace `[a-zA-Z]` with `[^\W\d_]`. In Python 3, `re.U` is used by default, in Python 2, you would need to add it.
Upvotes: 2 [selected_answer]<issue_comment>username_3: This would be a very very simple solution for your specific Problem.
```
def foo(text):
for x in range(len(text)):
if text[x] == 'a' and text[x+1] == 't':
if text[x-1].isalnum() and text[x+2].isalnum():
return False
return True
```
Upvotes: 0 <issue_comment>username_4: Here is a readable one-line style solution using `re.search` and `map` functions:
```
import re
strings = ['dad at home', 'eat apple', 'he never ate maple', 'because he hate it']
s = list(map(lambda s: not re.search(r'[\w]at[\w]', s), strings))
print(s) # [True, True, True, False]
```
Upvotes: 0 |
2018/03/20 | 416 | 1,297 | <issue_start>username_0: On an AMP page I want to add a reference to my font in the styles tag.
Can we use static to do so?
```
@font-face {
font-family: 'Font Awesome 5 Brands';
font-style: normal;
font-weight: normal;
src: url("{% static '/webfonts/fa-brands-400.eot' %}");
src: url("{% static '/webfonts/fa-brands-400.eot?#iefix' %}") format("embedded-opentype"), url("{% static '/webfonts/fa-brands-400.woff2' %}") format("woff2"), url("{% static '/webfonts/fa-brands-400.woff' %}") format("woff"), url("{% static '/webfonts/fa-brands-400.ttf' %}") format("truetype"), url("{% static '/webfonts/fa-brands-400.svg#fontawesome' %}") format("svg"); }
```
In my body section this works fine for me.
```
```
I am getting the following error:
```
Error during template rendering
In template
C:\users\frank\desktop\test_env\src\templates\fontawesome\fontawesome-all.css, error at line 2702
Invalid block tag on line 2702: 'static'. Did you forget to register or load this tag?
```<issue_comment>username_1: Before you access any file in your Django static directory, you need to load staticfiles with jinja2
Eg:
```
{% load staticfiles %}
```
Upvotes: 2 <issue_comment>username_2: I had to add `{% load staticfiles %}` in my file again even though it was in base.html
Upvotes: 0 |
2018/03/20 | 911 | 3,443 | <issue_start>username_0: There are a ton of tunable settings mentioned on `Spark` [configurations page](https://spark.apache.org/docs/latest/configuration.html). However as told [here](https://jaceklaskowski.gitbooks.io/mastering-apache-spark/content/spark-submit-SparkSubmitOptionParser.html), the `SparkSubmitOptionParser` *attribute-name* for a `Spark` property can be different from that *property's-name*.
For instance, `spark.executor.cores` is passed as `--executor-cores` in `spark-submit`.
---
Where can I find an *exhaustive* list of all tuning parameters of `Spark` (along-with their `SparkSubmitOptionParser` property name) that can be passed with `spark-submit` command?<issue_comment>username_1: In your case, you should actually load your configurations from a file, as mentioned in this [document](https://github.com/apache/spark/blob/master/docs/submitting-applications.md#loading-configuration-from-a-file), instead of passing them as flags to `spark-submit`. This relieves the overhead of mapping `SparkSubmitArguments` to Spark configuration parameters. To quote from the above document:
>
> Loading default Spark configurations this way can obviate the need for certain flags to `spark-submit`. For instance, if the spark.master property is set, you can safely omit the `--master` flag from `spark-submit`. In general, configuration values explicitly set on a `SparkConf` take the highest precedence, then flags passed to `spark-submit`, then values in the defaults file.
>
>
>
Upvotes: 2 <issue_comment>username_2: While **@username_1**'s valuable inputs did solve my problem, I'm answering my own question to directly address my query.
---
* You need not look up for `SparkSubmitOptionParser`'s *attribute-name* for a given `Spark` *property* (configuration setting). Both will do just fine. However, do note that there's a subtle difference between there usage as shown below:
`spark-submit --executor-cores 2`
`spark-submit --conf spark.executor.cores=2`
Both commands shown above will have same effect. The second method takes *configurations* in the format `--conf =`.
* Enclosing values in quotes (correct me if this is incorrect / incomplete)
(i) Values need not be enclosed in quotes (single `''` or double `""`) of any kind (you still can if you want).
(ii) If the value has a `space` character, enclose the entire thing in double quotes `""` like `"="` as shown [here](https://spark.apache.org/docs/latest/configuration.html#dynamically-loading-spark-properties).
* For a *comprehensive* list of all *configurations* that can be passed with `spark-submit`, just run `spark-submit --help`
* In [this link](https://github.com/apache/spark/blob/master/docs/submitting-applications.md#loading-configuration-from-a-file) provided by **@username_1**, they say that:
>
> configuration values explicitly set on a SparkConf take the highest
> precedence, then flags passed to spark-submit, then values in the
> defaults file.
>
>
> If you are ever unclear where configuration options are coming from,
> you can print out fine-grained debugging information by **running
> spark-submit with the --verbose option.**
>
>
>
---
Following two links from `Spark` docs list a lot of *configuration*s:
* [`Spark` Configuration](https://spark.apache.org/docs/latest/configuration.html)
* [Running `Spark` on `YARN`](https://spark.apache.org/docs/latest/running-on-yarn.html)
Upvotes: 4 [selected_answer] |
2018/03/20 | 752 | 2,400 | <issue_start>username_0: Hi I am really new to vuejs. I try to import a picture then call this picture in the methods.
```
import image from '@/assets/svg/xxx.svg'
```
then in the data
```
data () {
return {
image: image
}
},
```
and try to use it
```
li.style.backgroundImage = "url('this.image')";
```
But the image is not showing, and image link show as following
```
http://127.0.0.1:8080/order/detail/29/this.image
```
I really not sure where i get wrong...Please help...<issue_comment>username_1: A another way to doing it using computed property on style attribute :
```
computed : {
liStyle(){
return "background-image : url('" + require('@/assets/svg/xxx.svg') + "')";
}
}
```
Template :
```
-
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I'm pretty sure you can't import an image via the import statement, only modules (<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>).
I would recommend reading up on the [Vue-Webpack-template](https://vuejs-templates.github.io/webpack/) and look at the [static assets section](https://vuejs-templates.github.io/webpack/static.html).
In short you could use Webpack (or Gulp) to move your assets to a fixed location and then use links.
Upvotes: 1 <issue_comment>username_3: I think the better (and scalable) solution it's to have a class which sets the styles you want, and add it to the elements, if it have to be dinamically, just add it with `:class` on some condition.
**note**: i used an external image path, but it's the same with your local path. And use `require()` to import images and html
```js
new Vue({
el: '#example'
})
```
```css
.li-with-bg-image {
background-image: url('http://via.placeholder.com/350x150')
}
```
```html
*
*
*
```
**Another options**
Using inline styles (using v-bind:style)
```js
new Vue({
el: '#example'
})
```
```html
*
```
Using data section or a computed property binded to style
```js
new Vue({
el: '#example',
data: {
myStyles: `background-image: url('http://via.placeholder.com/350x150')`
},
computed: {
anotherStyles () {
return `background-image: url('http://via.placeholder.com/300x150')`
}
}
})
```
```html
*
*
*
```
Resources:
[Class and style bindings Docs](https://v2.vuejs.org/v2/guide/class-and-style.html)
Upvotes: 2 |
2018/03/20 | 908 | 2,306 | <issue_start>username_0: I have a basic flexbox implementation like this
```css
.holder {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
max-width: 500px;
background: wheat;
}
.col img {
max-width: 100%;
}
.col {
width: 20%;
float: left;
text-align: center;
}
```
```html










```
I am trying to add some padding in between each of the items but not at the edges.
Is flexbox the best solution for this and does anybody have an example they can point me at?<issue_comment>username_1: For flex box it is pretty easy. Just make the correct width for the items and set justify-content property of container to space-between. Make sure the sum of widths of items is less than 100% width of container.
Upvotes: 0 <issue_comment>username_2: You can use the `flex-basis` *property* where you set the *initial width* using the `calc()` *function*:
```css
.holder {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
max-width: 500px;
background: wheat;
}
.col img {
max-width: 100%;
}
.col {
/*width: 20%;*/
/*float: left; not necessary*/
flex-basis: calc(20% - 5px);
text-align: center;
}
/* addition, if desired */
img {
display: block; /* removes bottom margin/whitespace; "vertical-align: bottom" does the same */
}
```
```html










```
Upvotes: 3 [selected_answer] |
2018/03/20 | 555 | 1,975 | <issue_start>username_0: I would want to know if i can hide all "core" folders of an angular project, like "e2e" and "node\_modules" and files like "package.json" and "tsconfig.json" under some "support\_files" folder or something, so i can focus only on the src folder which is where i will be working on.
I have tried playing around with the .angular-cli.json as stated on
[Changing directory structure in an angular-cli project](https://stackoverflow.com/questions/40344229/changing-directory-structure-in-an-angular-cli-project) but either it doesn't find the module 'typescript' from x or the path to x/tsconfig.json doesn't exist (but it does)
I'll leave 2 images to show what you get with a default install with angular-cli and what I'm trying to achieve.
[default install structure](https://i.stack.imgur.com/u1pqu.png)
[the structure I want](https://i.stack.imgur.com/cdGRI.png)
Thanks in advance.<issue_comment>username_1: This is relative to your IDE, not to Angular.
For instance, if you use Visual Studio Code, you can hide files following **[this question](https://stackoverflow.com/questions/30140112/how-do-i-hide-certain-files-from-the-sidebar-in-visual-studio-code)**.
Now that I gave you a lead to work on, I'll mark your question as a duplicate, because you probably can find documentation for other IDE. If not, feel free to ask a question relative to your IDE, and not Angular.
Upvotes: 1 <issue_comment>username_2: For this you need to change your Workspace setting (or user settings) in your IDE. Mostly we use VS code (visual studio code) for angular development.
In the newer version of VS Code you will find this settings in below path :
File ->Preferences -> Settings
eg.
```
"files.exclude": {
"node_modules/": true,
"e2e/": true
}
```
similarly, you can hide other core files such as dist, prod etc.
To hide all node\_modules in sub folders you can use:
```
"**/node_modules/**": true
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 717 | 2,620 | <issue_start>username_0: I have Jenkins pipeline Job with parameters (name, group, taskNumber)
I need to write pipeline script which will call groovy script (this one?: <https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-job.groovy>)
I want to create new job (with name name\_group\_taskNamber) every times when I build main Pipeline Job.
I don't understand:
Where do I need to put may groovy script ?
How does Pipeline script should look like? :
```
node{
stage('Build'){
def pipeline = load "CreateJob.groovy"
pipeline.run()
}
}
```<issue_comment>username_1: We do it by using the <https://wiki.jenkins.io/display/JENKINS/Jobcopy+Builder+plugin>, try build another step in pipeline script and pass the parms which are to be considered
Upvotes: 0 <issue_comment>username_2: You can use and configure a [shared library](https://jenkins.io/doc/book/pipeline/shared-libraries/) like here (a git repo): <https://github.com/username_2/shared-library> . You need to configure this in your Jenkins global configuration.
It contains a folder `vars/`. Here you can manage pipelines and groovy scripts like my `slackNotifier.groovy`. The script is just a groovy script to print the build result in Slack.
In the jenkins pipeline job we will import our shared library:
```
@Library('name-of-shared-pipeline-library')_
mavenPipeline {
//define parameters
}
```
In the case above also the pipeline is in the shared library but this isn't necessary.
You can just write your pipeline in the job itself and call only the function from the pipeline like this:
This is the script in the shared library:
```
// vars/sayHello.groovy
def call(String name = 'human') {
echo "Hello, ${name}."
}
```
And in your pipeline:
```
final Lib= library('my-shared-library')
...
stage('stage name'){
echo "output"
Lib.sayHello.groovy('Peter')
}
...
```
**EDIT:**
In new declarative pipelines you can use:
```
pipeline {
agent { node { label 'xxx' } }
options {
buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
}
stages {
stage('test') {
steps {
sh 'echo "execute say hello script:"'
sayHello("Peter")
}
}
}
post {
always {
cleanWs()
}
}
}
def sayHello(String name = 'human') {
echo "Hello, ${name}."
}
```
output:
```
[test] Running shell script
+ echo 'execute say hello script:'
execute say hello script:
[Pipeline] echo
Hello, Peter.
[Pipeline] }
[Pipeline] // stage
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 822 | 2,762 | <issue_start>username_0: I'm trying to implement mutual exclusion using semaphore in Python. The two processes (proc1, proc2) are supposed to be two independent, concurrent processes. They do exactly the same thing: store n in array[n], then increment n.
The purpose of the program is to show that using semaphore we can ensure that the array is filled properly: [0,1,2,3,4,5,6,7,8,9], without skipping any index. However, my code seems to store [0,1,0,0,0,0,0,0,0,0]. I haven't used threads in python before, so I don't know what's going on.
```
import threading
import time
n = 0
array = [0]*10
sem = threading.Semaphore()
def proc1():
global n, array
while True:
sem.acquire()
array[n] = n
n += 1
sem.release()
time.sleep(0.25)
def proc2():
global n, array
while True:
sem.acquire()
array[n] = n
n += 1
sem.release()
time.sleep(0.25)
t = threading.Thread(target = proc1)
t.start()
t2 = threading.Thread(target = proc2)
t2.start()
print (array)
```<issue_comment>username_1: the problem was that the OP tried to print the result before the threads were done.
He should have waited for join.
```
import threading
import time
n = 0
array = [0]*10
sem = threading.Semaphore()
def proc(num):
global n
while True:
sem.acquire()
n = n+1
sem.release()
if n > 9:
break
array[n] = n
print ("Thread {}: {}".format(num,array))
time.sleep(0.25)
t1 = threading.Thread(target = proc, args=[1])
t2 = threading.Thread(target = proc, args=[2])
t1.start()
t2.start()
t1.join()
t2.join()
```
Upvotes: 2 <issue_comment>username_2: Different take on a `Semaphore` pattern, handing the "tasks" within the `Sempahore` itself
```py
class Sempahore:
def __init__(self, max_threads):
self.active_threads = 0
self.max_threads = max_threads
self.tasks = []
def add_task(self, func, args):
self.tasks.append(
Task(
func=func,
args=args
)
)
def run_task(self, task: Task):
_func = task.func
_args = task.args
self.active_threads += 1
_func(*_args)
self.active_threads -= 1
def run(self, blocking=False):
if blocking:
self._run()
else:
t = Thread(target=self._run)
t.start()
def _run(self):
while True:
if self.active_threads < self.max_threads:
task = self.tasks.pop()
logger.info(f'starting task: {task.task_id}')
t = Thread(
target=self.run_task,
args=(task,))
t.start()
if len(self.tasks) == 0:
break
```
Upvotes: 1 |
2018/03/20 | 2,168 | 8,506 | <issue_start>username_0: I'm looking at an application where I'm going to handle several integrations and need them to run in threads. I need the threads to "report back to the mothership (aka the main-loop)". The snippet:
```
class App
{
public delegate void StopHandler();
public event StopHandler OnStop;
private bool keepAlive = true;
public App()
{
OnStop += (() => { keepAlive = false; });
new Thread(() => CheckForStop()).Start();
new Thread(() => Update()).Start();
while (keepAlive) { }
}
private void CheckForStop()
{
while (keepAlive) if (Console.ReadKey().Key.Equals(ConsoleKey.Enter)) OnStop();
}
private void Update()
{
int counter = 0;
while (keepAlive)
{
counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter));
Thread.Sleep(3000);
}
}
}
```
The problem here is variable `keepAlive`. By its use its not thread safe. My question is how can I make it thread safe.
Would it become safe(r) if `Update` used `while(true)` instead of `keepAlive` and event `OnStop` aborted the thread?<issue_comment>username_1: Use an object and [lock it](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement)
```
class App
{
public delegate void StopHandler();
public event StopHandler OnStop;
private object keepAliveLock = new object();
private bool keepAlive = true;
....
private void Update()
{
int counter = 0;
while (true)
{
lock(keepAliveLock)
{
if(!keepAlive)
break;
}
counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter));
Thread.Sleep(3000);
}
}
}
```
Please note, that every access to keepAlive needs to be locked (surround by lock statement). Take care of deadlock situations.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As far as the specific wording of your question and your example code (in regards to `keepAlive`) simply use `volatile` (for simple *Read Access* to `bool`). As to if there are other ways to better your code, this is another story.
```
private volatile bool keepAlive = true;
```
For *Simple Types* and access such as `bool`, then `volatile` is sufficient - this ensures that threads don't cache the value.
Read and writes to `bool` are *Atomic* as found in [C# Language Spec](http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx).
>
> Reads and writes of the following data types are atomic: bool, char,
> byte, sbyte, short, ushort, uint, int, float, and reference types.
>
>
>
**Furthermore**
>
> Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI
> shall guarantee that read and write access to properly aligned memory
> locations no larger than the native word size is atomic when all the
> write accesses to a location are the same size.
>
>
>
Its also worth looking up [volatile (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile)
>
> The volatile keyword indicates that a field might be modified by
> multiple threads that are executing at the same time. Fields that are
> declared volatile are not subject to compiler optimizations that
> assume access by a single thread. This ensures that the most
> up-to-date value is present in the field at all times.
>
>
>
Upvotes: 0 <issue_comment>username_3: I would personally change this from waiting for a bool to become false to use the ManualResetEvent. Also use a System.Timers.Timer for the update rather than a loop:
```
private ManualResetEvent WaitForExit;
private ManualResetEvent WaitForStop;
public App()
{
WaitForExit = new ManualResetEvent(false);
WaitForStop = new ManualResetEvent(false);
new Thread(() => CheckForStop()).Start();
new Thread(() => Update()).Start();
WaitForExit.WaitOne();
}
private void CheckForStop()
{
while (true)
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
WaitForStop.Set();
break;
}
}
private void Update()
{
int counter = 0;
Timer timer = new Timer(3000);
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
WaitForStop.WaitOne();
timer.Stop();
WaitForExit.Set();
}
private int counter = 1;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter++));
}
```
Upvotes: 0 <issue_comment>username_4: As you noticed yourself, it is the mutable `keepAlive` variable that you share between threads that causes your headache. My suggestion is to remove it. More generally:
Stop sharing mutable state between threads
==========================================
Basically all multi-threading problems come from threads sharing mutable state.
Make `keepAlive` a private instance variable on the object that does the printing. Let that class instantiate it's own thread, and let all messages sent to the object be placed on a ConcurrentQueue:
```
class Updater
{
// All messages sent to this object are stored in this concurrent queue
private ConcurrentQueue \_Actions = new ConcurrentQueue();
private Task \_Task;
private bool \_Running;
private int \_Counter = 0;
// This is the constructor. It initializes the first element in the action queue,
// and then starts the thread via the private Run method:
public Updater()
{
\_Running = true;
\_Actions.Enqueue(Print);
Run();
}
private void Run()
{
\_Task = Task.Factory.StartNew(() =>
{
// The while loop below quits when the private \_Running flag
// or if the queue of actions runs out.
Action action;
while (\_Running && \_Actions.TryDequeue(out action))
{
action();
}
});
}
// Stop places an action on the event queue, so that when the Updater
// gets to this action, the private flag is set.
public void Stop()
{
\_Actions.Enqueue(() => \_Running = false);
}
// You can wait for the actor to exit gracefully...
public void Wait()
{
if (\_Running)
\_Task.Wait();
}
// Here's where the printing will happen. Notice that this method
// puts itself unto the queue after the Sleep method returns.
private void Print()
{
\_Counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), \_Counter));
Thread.Sleep(1000);
// Enqueue a new Print action so that the thread doesn't terminate
if (\_Running)
\_Actions.Enqueue(Print);
}
}
```
Now we just need a way to stop the thread:
==========================================
```
class Stopper
{
private readonly Updater _Updater;
private Task _Task;
public Stopper(Updater updater)
{
_Updater = updater;
Run();
}
// Here's where we start yet another thread to listen to the console:
private void Run()
{
// Start a new thread
_Task = Task.Factory.StartNew(() =>
{
while (true)
{
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
_Updater.Stop();
return;
}
}
});
}
// This is the only public method!
// It waits for the user to press enter in the console.
public void Wait()
{
_Task.Wait();
}
}
```
Gluing it all together
======================
All we really need now is a `main` method:
```
class App
{
public static void Main(string[] args)
{
// Instantiate actors
Updater updater = new Updater();
Stopper stopper = new Stopper(updater);
// Wait for the actors to expire
updater.Wait();
stopper.Wait();
Console.WriteLine("Graceful exit");
}
}
```
Further reading:
================
The above method for encapsulating mutable state for a thread is called the [Actor Model](https://en.wikipedia.org/wiki/Actor_model).
The premise is, that all threads are encapsulated by their own class, and only that class can interact with the thread. In the example above, this is done by placing `Action`s on a concurrent queue and then just executing it one by one.
Upvotes: 0 |
2018/03/20 | 2,235 | 8,426 | <issue_start>username_0: i tried the following code i found on the net and is perfectly working.
```
template
std::vector& operator<<(std::vector& v1, T2 t1){
v1.push\_back(T(t1));
return v1;
}
```
but for me the argument t1 must be from type T and not T2.
**so my first question is:** why when i do
```
std::vector& operator<<(std::vector& v1, \*\*\*T t1\*\*\*) //instead of T2 t1
```
i have the following error:
error: no match for 'operator<<' (operand types are 'std::vector >' and 'std::string {aka std::basic\_string}')
**my second question** is a ligne 4 of the code:
what does mean T(t1) ?
thanks a lot !
**EDIT:**
thanks for all your answers!
this is the code i was using to test and try to inderstand the function.
```
using namespace std;
template
std::vector& operator<<(std::vector& v1, T t1){
v1.push\_back(T(t1));
return v1;
}
int main() {
vector s;
string s2(" hello ");
s << s2 ;
cout<< s[0];
return 0;}
```
so the T is string and v1 is of type vector(String) and t1 is of type String
this is why i was wondering why removing typename T2 from template causes error even if the value\_type is string for both<issue_comment>username_1: Use an object and [lock it](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement)
```
class App
{
public delegate void StopHandler();
public event StopHandler OnStop;
private object keepAliveLock = new object();
private bool keepAlive = true;
....
private void Update()
{
int counter = 0;
while (true)
{
lock(keepAliveLock)
{
if(!keepAlive)
break;
}
counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter));
Thread.Sleep(3000);
}
}
}
```
Please note, that every access to keepAlive needs to be locked (surround by lock statement). Take care of deadlock situations.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As far as the specific wording of your question and your example code (in regards to `keepAlive`) simply use `volatile` (for simple *Read Access* to `bool`). As to if there are other ways to better your code, this is another story.
```
private volatile bool keepAlive = true;
```
For *Simple Types* and access such as `bool`, then `volatile` is sufficient - this ensures that threads don't cache the value.
Read and writes to `bool` are *Atomic* as found in [C# Language Spec](http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx).
>
> Reads and writes of the following data types are atomic: bool, char,
> byte, sbyte, short, ushort, uint, int, float, and reference types.
>
>
>
**Furthermore**
>
> Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI
> shall guarantee that read and write access to properly aligned memory
> locations no larger than the native word size is atomic when all the
> write accesses to a location are the same size.
>
>
>
Its also worth looking up [volatile (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile)
>
> The volatile keyword indicates that a field might be modified by
> multiple threads that are executing at the same time. Fields that are
> declared volatile are not subject to compiler optimizations that
> assume access by a single thread. This ensures that the most
> up-to-date value is present in the field at all times.
>
>
>
Upvotes: 0 <issue_comment>username_3: I would personally change this from waiting for a bool to become false to use the ManualResetEvent. Also use a System.Timers.Timer for the update rather than a loop:
```
private ManualResetEvent WaitForExit;
private ManualResetEvent WaitForStop;
public App()
{
WaitForExit = new ManualResetEvent(false);
WaitForStop = new ManualResetEvent(false);
new Thread(() => CheckForStop()).Start();
new Thread(() => Update()).Start();
WaitForExit.WaitOne();
}
private void CheckForStop()
{
while (true)
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
WaitForStop.Set();
break;
}
}
private void Update()
{
int counter = 0;
Timer timer = new Timer(3000);
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
WaitForStop.WaitOne();
timer.Stop();
WaitForExit.Set();
}
private int counter = 1;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter++));
}
```
Upvotes: 0 <issue_comment>username_4: As you noticed yourself, it is the mutable `keepAlive` variable that you share between threads that causes your headache. My suggestion is to remove it. More generally:
Stop sharing mutable state between threads
==========================================
Basically all multi-threading problems come from threads sharing mutable state.
Make `keepAlive` a private instance variable on the object that does the printing. Let that class instantiate it's own thread, and let all messages sent to the object be placed on a ConcurrentQueue:
```
class Updater
{
// All messages sent to this object are stored in this concurrent queue
private ConcurrentQueue \_Actions = new ConcurrentQueue();
private Task \_Task;
private bool \_Running;
private int \_Counter = 0;
// This is the constructor. It initializes the first element in the action queue,
// and then starts the thread via the private Run method:
public Updater()
{
\_Running = true;
\_Actions.Enqueue(Print);
Run();
}
private void Run()
{
\_Task = Task.Factory.StartNew(() =>
{
// The while loop below quits when the private \_Running flag
// or if the queue of actions runs out.
Action action;
while (\_Running && \_Actions.TryDequeue(out action))
{
action();
}
});
}
// Stop places an action on the event queue, so that when the Updater
// gets to this action, the private flag is set.
public void Stop()
{
\_Actions.Enqueue(() => \_Running = false);
}
// You can wait for the actor to exit gracefully...
public void Wait()
{
if (\_Running)
\_Task.Wait();
}
// Here's where the printing will happen. Notice that this method
// puts itself unto the queue after the Sleep method returns.
private void Print()
{
\_Counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), \_Counter));
Thread.Sleep(1000);
// Enqueue a new Print action so that the thread doesn't terminate
if (\_Running)
\_Actions.Enqueue(Print);
}
}
```
Now we just need a way to stop the thread:
==========================================
```
class Stopper
{
private readonly Updater _Updater;
private Task _Task;
public Stopper(Updater updater)
{
_Updater = updater;
Run();
}
// Here's where we start yet another thread to listen to the console:
private void Run()
{
// Start a new thread
_Task = Task.Factory.StartNew(() =>
{
while (true)
{
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
_Updater.Stop();
return;
}
}
});
}
// This is the only public method!
// It waits for the user to press enter in the console.
public void Wait()
{
_Task.Wait();
}
}
```
Gluing it all together
======================
All we really need now is a `main` method:
```
class App
{
public static void Main(string[] args)
{
// Instantiate actors
Updater updater = new Updater();
Stopper stopper = new Stopper(updater);
// Wait for the actors to expire
updater.Wait();
stopper.Wait();
Console.WriteLine("Graceful exit");
}
}
```
Further reading:
================
The above method for encapsulating mutable state for a thread is called the [Actor Model](https://en.wikipedia.org/wiki/Actor_model).
The premise is, that all threads are encapsulated by their own class, and only that class can interact with the thread. In the example above, this is done by placing `Action`s on a concurrent queue and then just executing it one by one.
Upvotes: 0 |
2018/03/20 | 2,369 | 8,622 | <issue_start>username_0: trying to select a value from the data table x and make subtraction within the data table x.
Example:
```
x <- data.table(CountryName = c("Lithuania", "Lithuania", "Latvia", "Latvia", "Estonia", "Estonia"),
Year = c(2000, 2001, 2000, 2001, 2000, 2001),
pop = c(3512, 3486, 2381, 2353, 1401, 1392),
under1 = c(100, 150, 95, 98, 75, 65),
under2 = c(95, 135, 85, 89, 71, 62))
tmp <- data.table(CountryName = "Lithuania", Year = 2000, use.to.adjust = "under1")
setkey(x, CountryName, Year)
```
I'm trying with **tmp** table decide which columns use for subtraction and return just single numeric value.
None of my solutions working. Also, I don't want to create additional values, save them and then subtract.
My tries:
```
x[tmp[, .(CountryName, Year)], pop - tmp$use.to.adjust, with = F ]
Error in eval(jsub, parent.frame(), parent.frame()) :
object 'pop' not found
x[tmp[, .(CountryName, Year)], pop - tmp$use.to.adjust ]
Error in pop - tmp$use.to.adjust :
non-numeric argument to binary operator
x[tmp[, .(CountryName, Year)], "pop" - tmp$use.to.adjust, with = F ]
CountryName Year under1 under2
1: Lithuania 2000 100 9
```
Last example just remove pop column from data table.
want to get:
```
value <- 3512 - 100
```
Thanks for help guys.<issue_comment>username_1: Use an object and [lock it](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement)
```
class App
{
public delegate void StopHandler();
public event StopHandler OnStop;
private object keepAliveLock = new object();
private bool keepAlive = true;
....
private void Update()
{
int counter = 0;
while (true)
{
lock(keepAliveLock)
{
if(!keepAlive)
break;
}
counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter));
Thread.Sleep(3000);
}
}
}
```
Please note, that every access to keepAlive needs to be locked (surround by lock statement). Take care of deadlock situations.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As far as the specific wording of your question and your example code (in regards to `keepAlive`) simply use `volatile` (for simple *Read Access* to `bool`). As to if there are other ways to better your code, this is another story.
```
private volatile bool keepAlive = true;
```
For *Simple Types* and access such as `bool`, then `volatile` is sufficient - this ensures that threads don't cache the value.
Read and writes to `bool` are *Atomic* as found in [C# Language Spec](http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx).
>
> Reads and writes of the following data types are atomic: bool, char,
> byte, sbyte, short, ushort, uint, int, float, and reference types.
>
>
>
**Furthermore**
>
> Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI
> shall guarantee that read and write access to properly aligned memory
> locations no larger than the native word size is atomic when all the
> write accesses to a location are the same size.
>
>
>
Its also worth looking up [volatile (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile)
>
> The volatile keyword indicates that a field might be modified by
> multiple threads that are executing at the same time. Fields that are
> declared volatile are not subject to compiler optimizations that
> assume access by a single thread. This ensures that the most
> up-to-date value is present in the field at all times.
>
>
>
Upvotes: 0 <issue_comment>username_3: I would personally change this from waiting for a bool to become false to use the ManualResetEvent. Also use a System.Timers.Timer for the update rather than a loop:
```
private ManualResetEvent WaitForExit;
private ManualResetEvent WaitForStop;
public App()
{
WaitForExit = new ManualResetEvent(false);
WaitForStop = new ManualResetEvent(false);
new Thread(() => CheckForStop()).Start();
new Thread(() => Update()).Start();
WaitForExit.WaitOne();
}
private void CheckForStop()
{
while (true)
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
WaitForStop.Set();
break;
}
}
private void Update()
{
int counter = 0;
Timer timer = new Timer(3000);
timer.Elapsed += Timer_Elapsed;
timer.AutoReset = true;
timer.Start();
WaitForStop.WaitOne();
timer.Stop();
WaitForExit.Set();
}
private int counter = 1;
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine(string.Format("[{0}] Update #{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), counter++));
}
```
Upvotes: 0 <issue_comment>username_4: As you noticed yourself, it is the mutable `keepAlive` variable that you share between threads that causes your headache. My suggestion is to remove it. More generally:
Stop sharing mutable state between threads
==========================================
Basically all multi-threading problems come from threads sharing mutable state.
Make `keepAlive` a private instance variable on the object that does the printing. Let that class instantiate it's own thread, and let all messages sent to the object be placed on a ConcurrentQueue:
```
class Updater
{
// All messages sent to this object are stored in this concurrent queue
private ConcurrentQueue \_Actions = new ConcurrentQueue();
private Task \_Task;
private bool \_Running;
private int \_Counter = 0;
// This is the constructor. It initializes the first element in the action queue,
// and then starts the thread via the private Run method:
public Updater()
{
\_Running = true;
\_Actions.Enqueue(Print);
Run();
}
private void Run()
{
\_Task = Task.Factory.StartNew(() =>
{
// The while loop below quits when the private \_Running flag
// or if the queue of actions runs out.
Action action;
while (\_Running && \_Actions.TryDequeue(out action))
{
action();
}
});
}
// Stop places an action on the event queue, so that when the Updater
// gets to this action, the private flag is set.
public void Stop()
{
\_Actions.Enqueue(() => \_Running = false);
}
// You can wait for the actor to exit gracefully...
public void Wait()
{
if (\_Running)
\_Task.Wait();
}
// Here's where the printing will happen. Notice that this method
// puts itself unto the queue after the Sleep method returns.
private void Print()
{
\_Counter++;
Console.WriteLine(string.Format("[{0}] Update #{1}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), \_Counter));
Thread.Sleep(1000);
// Enqueue a new Print action so that the thread doesn't terminate
if (\_Running)
\_Actions.Enqueue(Print);
}
}
```
Now we just need a way to stop the thread:
==========================================
```
class Stopper
{
private readonly Updater _Updater;
private Task _Task;
public Stopper(Updater updater)
{
_Updater = updater;
Run();
}
// Here's where we start yet another thread to listen to the console:
private void Run()
{
// Start a new thread
_Task = Task.Factory.StartNew(() =>
{
while (true)
{
if (Console.ReadKey().Key.Equals(ConsoleKey.Enter))
{
_Updater.Stop();
return;
}
}
});
}
// This is the only public method!
// It waits for the user to press enter in the console.
public void Wait()
{
_Task.Wait();
}
}
```
Gluing it all together
======================
All we really need now is a `main` method:
```
class App
{
public static void Main(string[] args)
{
// Instantiate actors
Updater updater = new Updater();
Stopper stopper = new Stopper(updater);
// Wait for the actors to expire
updater.Wait();
stopper.Wait();
Console.WriteLine("Graceful exit");
}
}
```
Further reading:
================
The above method for encapsulating mutable state for a thread is called the [Actor Model](https://en.wikipedia.org/wiki/Actor_model).
The premise is, that all threads are encapsulated by their own class, and only that class can interact with the thread. In the example above, this is done by placing `Action`s on a concurrent queue and then just executing it one by one.
Upvotes: 0 |
2018/03/20 | 1,649 | 4,945 | <issue_start>username_0: What I am trying to do is that,
for example, assuming that there are 6 and 4 for width and height respectively, and the inputs for the 2d array are:
```
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
```
The 2nd row finishes with 1 and the 3rd row starts with 1, hence the number in "count" variable increases its value as it regards the "1s" as duplicate number.
To be more specific,
the overall output for those inputs should be:
1 2 1 (1st row)
1 1 (2nd row)
1 1 (3rd row)
4 (4th row)
The first row has one 1 and two consecutive 2s and one 1, hence it becomes 1 2 1.
The second row has two 1s but they are not linked each other so it becomes 1 1.
The last row has four consecutive 1s so it becomes 4.
```
int main(void) {
int width = 0;
int height = 0;
int input = 0;
int i, j = 0;
int val = 1;
scanf("%d %d", &width, &height);
int board[height][width];
for(i = 0; i < height; i++)
{
for(j = 0; j < width; j++)
{
scanf("%d", &input);
board[i][j] = input;
}
}
for(i = 0; i < height; i ++)
{
val = 1;
for(j = 0; j < width; j++)
{
if(board[i][j]>0)
{
if(board[i][j] == board[i][j+1])
{
val++;
printf("%d ", val);
}
if(board[i][j+1] == 0)
{
val = 1;
}
if(board[i][j] != board[i][j+1] && board[i][j] != board[i][j-1])
{
val = 1;
printf("%d ", val);
}
}
}
printf("\n");
}
return 0;
}
```
This is what I have done so far but there are two problems...
Using the inputs above, this code outputs:
1 2 1
1 2
1
2 3 4
where second row seems to having a problem that I mentioned above and the fourth row prints out all the process of val++, not the final result of val++.<issue_comment>username_1: >
> board[i][j] != board[i][j-1]
>
>
>
You start your j to 0 so you can't do that.
Instead of comparing your current value (board[i][j]) with your previous value [i][j - 1], i think it's easier to store the last value (prev = board[i][j]) at the end of the j loop, and compare your current value with that value. If it's the same, then you can increment your counter.
Before the loop, set your prev to -1 so you don't compare to prev if it's the first column.
Upvotes: 0 <issue_comment>username_2: I slightly modified your code
```
for(i = 0; i < height; i ++)
{
val = 1;
for(j = 0; j < width; j++)
{
if(board[i][j]>0)
{
if(board[i][j] == board[i][j+1]) // same, increase val
{
val++;
}
if(board[i][j+1] == 0 || board[i][j] != board[i][j+1]) // differ to next one, print out and reset val
{
printf("%d ", val);
val = 1;
}
}
}
printf("\n");
}
```
Upvotes: 0 <issue_comment>username_3: Obviously you're going to get it printing out the progress of `val` as you have the `printf` in this part of the code.
```
if(board[i][j] == board[i][j+1])
{
val++;
printf("%d ", val);
}
```
You've made the code overly complicated when all you really need to do is track how many of the last number there are and when the number changes or you reach the end of the row, then you output the count. Something like this maybe:
```
for(i = 0; i < height; i ++)
{
val = 0;
for(j = 0; j < width; j++)
{
if(board[i][j]>0)
{
if((j==0) || (board[i][j] != board[i][j-1]))
{
if(val)
{
printf("%d ", val);
}
val=1;
}
else
{
val++;
}
}
}
if(val)
{
printf("%d ", val);
}
printf("\n");
}
```
Running it with your example input
```
6 4
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
```
gives the output as
```
1 2 1
1 1
1 1
4
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: You jave to print the `val` value in the block `if(board[i][j+1]==0)` before setting `val=1;`
Upvotes: 0 <issue_comment>username_5: ```
#define H 4
#define W 6
int a[H][W] = {
{0,1,2,2,1,0},
{1,0,0,0,0,1},
{1,0,0,0,0,1},
{0,1,1,1,1,0}
};
void PrintRepeat() {
for (int i = 0; i < H; i++) {
int repeat = 0, prev = -1;
for (int j = 0; j < W; j++) {
if (a[i][j]){
if (a[i][j] != prev) {
if (repeat) printf("%d ", repeat);
repeat = 1;
}
else repeat++;
}
prev = a[i][j];
}
if (repeat) printf("%d\n", repeat);
}
}
int main() {
PrintRepeat();
return 0;
}
```
Upvotes: 0 |
2018/03/20 | 1,169 | 3,769 | <issue_start>username_0: I simply want to send login data via https and receive the response. The whole thing runs in Visual Studio 2017. When running the program stops when I click the "Login button". I also get no real error but only an unhandled exception.
I'm new to C # maybe i did something wrong with async? Thanks in advance :)
```
public static async Task GetResponseText(string address)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(address);
}
public void On\_Login\_Listener(Object sender, EventArgs args)
{
string url = "https://localhost/login.php?email=" + email.Text+"&password="+password.Text;
InfoBox.Text = GetResponseText(url).ToString();
}
```<issue_comment>username_1: >
> board[i][j] != board[i][j-1]
>
>
>
You start your j to 0 so you can't do that.
Instead of comparing your current value (board[i][j]) with your previous value [i][j - 1], i think it's easier to store the last value (prev = board[i][j]) at the end of the j loop, and compare your current value with that value. If it's the same, then you can increment your counter.
Before the loop, set your prev to -1 so you don't compare to prev if it's the first column.
Upvotes: 0 <issue_comment>username_2: I slightly modified your code
```
for(i = 0; i < height; i ++)
{
val = 1;
for(j = 0; j < width; j++)
{
if(board[i][j]>0)
{
if(board[i][j] == board[i][j+1]) // same, increase val
{
val++;
}
if(board[i][j+1] == 0 || board[i][j] != board[i][j+1]) // differ to next one, print out and reset val
{
printf("%d ", val);
val = 1;
}
}
}
printf("\n");
}
```
Upvotes: 0 <issue_comment>username_3: Obviously you're going to get it printing out the progress of `val` as you have the `printf` in this part of the code.
```
if(board[i][j] == board[i][j+1])
{
val++;
printf("%d ", val);
}
```
You've made the code overly complicated when all you really need to do is track how many of the last number there are and when the number changes or you reach the end of the row, then you output the count. Something like this maybe:
```
for(i = 0; i < height; i ++)
{
val = 0;
for(j = 0; j < width; j++)
{
if(board[i][j]>0)
{
if((j==0) || (board[i][j] != board[i][j-1]))
{
if(val)
{
printf("%d ", val);
}
val=1;
}
else
{
val++;
}
}
}
if(val)
{
printf("%d ", val);
}
printf("\n");
}
```
Running it with your example input
```
6 4
0 1 2 2 1 0
1 0 0 0 0 1
1 0 0 0 0 1
0 1 1 1 1 0
```
gives the output as
```
1 2 1
1 1
1 1
4
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: You jave to print the `val` value in the block `if(board[i][j+1]==0)` before setting `val=1;`
Upvotes: 0 <issue_comment>username_5: ```
#define H 4
#define W 6
int a[H][W] = {
{0,1,2,2,1,0},
{1,0,0,0,0,1},
{1,0,0,0,0,1},
{0,1,1,1,1,0}
};
void PrintRepeat() {
for (int i = 0; i < H; i++) {
int repeat = 0, prev = -1;
for (int j = 0; j < W; j++) {
if (a[i][j]){
if (a[i][j] != prev) {
if (repeat) printf("%d ", repeat);
repeat = 1;
}
else repeat++;
}
prev = a[i][j];
}
if (repeat) printf("%d\n", repeat);
}
}
int main() {
PrintRepeat();
return 0;
}
```
Upvotes: 0 |
2018/03/20 | 159 | 611 | <issue_start>username_0: The rte\_ckeditor removes the font tag added via sourcecode just after switching back to the rendered view. How can i prevent this?<issue_comment>username_1: The [element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/font) is obsolete. Please use CSS for all styling instead.
In case you need to prepare a design for mails, what you apparently do, you could follow a different approach by adding your
Upvotes: 1 <issue_comment>username_2: Did you try to add this in your Yaml file?
Allow s and u tag
=================
processing:
allowTags:
- s
- yourTag
Upvotes: 0 |
2018/03/20 | 243 | 838 | <issue_start>username_0: I want to get current day for now. Only day. For example today is 20-March i need use it in my queryset
```
query = self.filter(Q(busyrooms__end_date__day=datetime.now().date()),
Q(reservedrooms__end_date__day=datetime.now().date()))
```
Tried to use `datetime.now().date()` but i got error
>
> TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.date'
>
>
><issue_comment>username_1: You can get the current day from datetime\_obj by accessing the `day` attribute of datetimeobj like `datetime.now().day`
Upvotes: 4 [selected_answer]<issue_comment>username_2: In `django` most of the cases we use timezone. so, it's recommended to use `timezone` .
```
from django.utils import timezone
timezone.now().date()
timezone.now().day
```
Upvotes: 3 |
2018/03/20 | 983 | 3,669 | <issue_start>username_0: Given the following XML:
```
```
I can deserialize it like this:
```
[XmlRoot("RESPONSE")]
public class Response
{
[XmlElement(ElementName = "RESULTS")]
public Results Results {get;set;}
}
public class Results
{
[XmlAttribute(AttributeName = "MyAttribute")]
public bool MyAttribute { get; set; }
}
var serializer = new XmlSerializer(typeof(Response));
var result = (Response)serializer.Deserialize(new StringReader(xml));
```
This works and is fine.
The problem however is that I want to deserialize the following XML as well and I don't want to duplicate the Response class, I want to use a generic approach.
```
```
I've tried doing the following:
```
[XmlRoot("Response")]
public class Response
{
public T Data {get;set;}
}
public class SoccerRoot
{
[XmlElement(ElementName = "SOCCER")]
public class Soccer {get;set;}
}
public class Soccer
{
[XmlAttribute(AttributeName = "AnotherAttribute")]
public bool AnotherAttribute {get;set;}
}
var serializer = new XmlSerializer(typeof(Response));
var result = (Response)serializer.Deserialize(new StringReader(xml));
```
But this doesn't work, I've also tried to inherit the Response class but with no luck.
Im getting the following error: `was not expected.`
Am I on the right way here or is it not possible to use a generic approach when deserializing XML files?<issue_comment>username_1: Try to create a common class which contains both the objects RESULTS and SOCCER and then based on the data one will be null and other will contain value.
```
class Program
{
static void Main(string[] args)
{
//
var xml = "";
var serializer = new XmlSerializer(typeof(Response));
var result = (Response)serializer.Deserialize(new StringReader(xml));
xml = "";
result = (Response)serializer.Deserialize(new StringReader(xml));
Console.ReadLine();
}
}
[XmlRoot("RESPONSE")]
public class Response
{
[XmlAttribute(AttributeName = "version")]
public T Version { get; set; }
[XmlElement(ElementName = "SOCCER")]
public SoccerRoot SoccerRoot { get; set; }
[XmlElement(ElementName = "RESULTS")]
public Results Results { get; set; }
}
public class SoccerRoot
{
[XmlAttribute(AttributeName = "AnotherAttribute")]
public int AnotherAttribute { get; set; }
}
public class Results
{
[XmlAttribute(AttributeName = "MyAttribute")]
public bool MyAttribute { get; set; }
}
```
Upvotes: 1 <issue_comment>username_2: With `Response`, the expected xml layout would be:
```
```
which *does not* match what you have. There is no way of customizing the element name of the `T Data` *just* using attributes.
Options:
* have multiple root objects (one each for `SOCCER`, `RESULTS`, etc):
```
[XmlRoot("RESPONSE")]
public class SoccerRoot {
[XmlElement("SOCCER")]
public Soccer Soccer {get;set;}
}
[XmlRoot("RESPONSE")]
public class ResultsRoot {
[XmlElement("RESULTS")]
public Results Results {get;set;}
}
```
* have a single root object that has multiple first-level children (one for `SOCCER`, one for `RESULTS`, etc - each of one type
```
[XmlRoot("RESPONSE")]
public class Response {
[XmlElement("RESULTS")]
public Results Results {get;set;}
[XmlElement("SOCCER")]
public Soccer Soccer {get;set;}
}
```
* use the generics approach, but lose the intermediate object so you have `Response` (delete `SoccerRoot` completely), and use `XmlAttributeOverrides` to customize the element name, *being sure to cache the `XmlSerializer` generated* (otherwise it will leak at an alarming rate)
Frankly, I'd go with either of the first two options and leave the third one alone.
Upvotes: 3 [selected_answer] |
2018/03/20 | 365 | 1,560 | <issue_start>username_0: When we run cucumber tests on forked JVM processes, each test is isolated pretty much immediately, so if we try to use any sort of @before or @after it will run on *every* single jvm instance, and yes we could setup here, it will be executed on every process pointlessly...
How can we get in before the forked JVM processes and execute a single method even to validate the test run before proceeding etc?
The same should go for a run once after all tests on all JVM's have been executed.
Is there a simple solution for this?<issue_comment>username_1: Take a look of [gherkin using qaf](https://qmetry.github.io/qaf/latest/gherkin_client.html). Where you can have different listeners including one that run before suite execution. You also can write method with `@BeforeSuite` annotation.
Upvotes: 0 <issue_comment>username_2: Answer: I ended up writing a single individual test which validated the run and did all runOnce type code, telling surefire to run this test phase before the main one so the main test only continued when validation was a pass.
other alternatives: maven plugin which I also wrote does the same kind of idea.
other alternatives: get the JVM forked number from maven and set it as a system property, do some action(s) where the forked number == 1 for example and pause /sleep the other JVMs until the validation has been done, then continue (will require an external source to be updated, like a properties file with:
canContinue=0
to poll on each JVM until it is 1 to continue
Upvotes: 2 [selected_answer] |
2018/03/20 | 502 | 1,904 | <issue_start>username_0: I want to get the value of an element which changes it type based on some condition.
So, For checking the type of that element I am using the following code:-
```
wait(driver, 15).until(EC.presence_of_element_located((By.ID, "incident.state")))
if( element_type != "text" ):
select = Select(driver.find_element_by_id('incident.state'))
selectval=select.first_selected_option.text
else:
select=driver.find_element_by_id('incident.state')
selectval=select.get_attribute('value')
```
Here the problem is I'm always getting the element as select and not text when sometimes the element is text.
So, I used
```
time.sleep(5)
```
And it's working.But i don't want to use time.sleep as it's not a good practise.
So, I tried with
```
driver.implicitly_wait(10)
```
But it's not waiting
Can you tell me what should i use......<issue_comment>username_1: Take a look of [gherkin using qaf](https://qmetry.github.io/qaf/latest/gherkin_client.html). Where you can have different listeners including one that run before suite execution. You also can write method with `@BeforeSuite` annotation.
Upvotes: 0 <issue_comment>username_2: Answer: I ended up writing a single individual test which validated the run and did all runOnce type code, telling surefire to run this test phase before the main one so the main test only continued when validation was a pass.
other alternatives: maven plugin which I also wrote does the same kind of idea.
other alternatives: get the JVM forked number from maven and set it as a system property, do some action(s) where the forked number == 1 for example and pause /sleep the other JVMs until the validation has been done, then continue (will require an external source to be updated, like a properties file with:
canContinue=0
to poll on each JVM until it is 1 to continue
Upvotes: 2 [selected_answer] |
2018/03/20 | 337 | 1,221 | <issue_start>username_0: My jquery datepicker is looking very strange:
[](https://i.stack.imgur.com/VXvSR.png)
Here are my dependancies loading:
```
```
Here is my HTML:
```
|
```
and here is my js:
```
$( ".datepicker" ).datepicker();
```
Any help would be appreciated.
Thx<issue_comment>username_1: As can see its working perfectly, so somewhere your css has an influence on the `td>input` as you can see the styling is different then mine. I suggest you inspect the input and also the `div` = `#ui-datepicker-div` that contains an `table` that gets pulled from the jQuery because somewhere you are overwriting some style.
```js
$( ".datepicker" ).datepicker();
```
```html
| copy | copy | copy | copy |
| --- | --- | --- | --- |
| data | | data | data |
```
Upvotes: 1 <issue_comment>username_2: I Solved the problem.
I had some css styling that was styling the nth child of the cell. The Jquery code must create some new elements inside the cell and they were therefore inheriting styling as the nth element.
**Bottom line, one cannot use nth element styling in blocks where jquery is going to add its own elements.**
Upvotes: 0 |
2018/03/20 | 2,368 | 11,508 | <issue_start>username_0: I tried to create an authrorization server with its own login page and a resource with Spring Boot 2.0.0 and spring-security-oauth2 2.3.0. Unfortunately, the configuration of the resource server does not seem to work. With
```
curl -v localhost:8080/sample
```
always a redirect 302 to localhost:8080/login with or without token.
My Security Configuration is
```
@Configuration
public class SecurityConfiguration {
@Configuration
@Order(1)
@EnableWebSecurity(debug = true)
protected static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("john").password("{<PASSWORD>").roles("User");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/ping").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginPage("/login")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember")
.and()
.httpBasic().disable()
.logout().permitAll();
}
}
@Configuration
@EnableResourceServer
@Order(10)
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "Sample";
@Override
public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/sample**").authenticated();
}
}
@Configuration
@EnableAuthorizationServer
@Order(Ordered.HIGHEST_PRECEDENCE)
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("ABC").secret("{noop}sec1").autoApprove(true)
.authorizedGrantTypes("authorization_code", "client_credentials", "password", "refresh_token")
.scopes("read", "write")
.redirectUris("http://google.com");
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(new InMemoryTokenStore())
.authenticationManager(authenticationManager);
}
}
}
```
How can I configure the resource server correctly?
[Download Example Project](https://ufile.io/y3h9d)
**UPDATE:**
I tested the follow configuration with Spring Boot 1.5.10, spring-security-oauth2 2.0.14 and Spring Boot 2.0.0, spring-security-oauth2 2.3.0.
With 1.5.10 it works fine but with 2.0.0 i getting *"There was an unexpected error (type=Method Not Allowed, status=405)."* on processing login. I see that *UsernamePasswordAuthenticationFilter* is missing in the security filter chain.
Is there a breaking change in Spring Boot 2.0.0 or Spring Security 5.0.3 that i missed?
```
@Configuration
@EnableWebMvc
@EnableAuthorizationServer
@EnableResourceServer
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfiguration {
@Configuration
protected static class WebMvcConfiguration extends WebMvcConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
@Configuration
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "Sample";
@Override
public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/sample**").authenticated()
;
}
}
@Configuration
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
;
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("ABC")
.secret("{noop}sec1")
.autoApprove(true)
.authorizedGrantTypes("authorization_code", "client_credentials", "password", "refresh_token")
.scopes("read", "write")
.redirectUris("http://google.com")
;
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(new InMemoryTokenStore())
.authenticationManager(authenticationManager);
}
}
@Configuration
protected static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("john")
.password("{<PASSWORD>")
.roles("User");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/ping")
.antMatchers("/login")
.antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/ping").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginPage("/login")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember")
.and()
.httpBasic().disable()
.logout().permitAll();
}
}
}
```<issue_comment>username_1: Thanks to [dur](https://stackoverflow.com/users/5277820/dur)'s comments, the problem is solved.
This configuration is working:
```
@Configuration
@EnableWebMvc
@EnableAuthorizationServer
@EnableResourceServer
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfiguration {
@Configuration
protected static class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
}
@Configuration
@Order(2)
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "Sample";
@Override
public void configure(final ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/sample**").authenticated()
;
}
}
@Configuration
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
;
}
@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("ABC")
.secret("{noop}sec1")
.autoApprove(true)
.authorizedGrantTypes("authorization_code", "client_credentials", "password", "refresh_token")
.scopes("read", "write")
.redirectUris("http://google.com")
;
}
@Override
public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(new InMemoryTokenStore())
.authenticationManager(authenticationManager);
}
}
@Configuration
@Order(1)
protected static class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("john")
.password("{<PASSWORD>")
.roles("User");
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/ping")
.antMatchers("/login")
.antMatchers("/oauth/**")
.and()
.authorizeRequests()
.antMatchers("/ping").permitAll()
.anyRequest().authenticated()
.and()
.csrf()
.and()
.formLogin()
.usernameParameter("username")
.passwordParameter("<PASSWORD>")
.loginPage("/login")
.permitAll()
.and()
.rememberMe()
.rememberMeParameter("remember")
.and()
.httpBasic().disable()
.logout().permitAll();
}
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Wrote a bare-bones spring boot 2 oauth2 resource server with authorization server, putting it here in case anyone is looking for a bootstrap project:
<https://github.com/indrekru/spring-boot-2-oauth2-resource-server>
Upvotes: 0 |
2018/03/20 | 245 | 963 | <issue_start>username_0: I have a autoscheduled script runs everyday and creates a sheet for reporting some data daily. Sheet name is the date with yyyy-MM-dd format and I want to update the spreadsheet name with the date when script runs and creates a new sheet. For example my SpreadSheet name is MY\_SPREAD\_SHEET and once script is executed today then it should be updated as "MY\_SPREAD\_SHEET 2018-03-20" and similar for coming days. How can I do this?<issue_comment>username_1: from the [documentation](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#rename(String))
```
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Hello world");
```
Upvotes: 2 <issue_comment>username_2: I found my questions answer as below:
```
SpreadsheetApp.getActiveSpreadsheet().rename("Renamed Spreadsheet");
```
my intent was renaming the spreadsheet document not the sheets in it.
Thanks for your answers
Upvotes: 4 [selected_answer] |
2018/03/20 | 204 | 853 | <issue_start>username_0: I was wondering is it possible to add a new class using CSS to HTML you dont have access to?
I am working with a survey programme and i can only create custom CSS but i need to separate two divs by giving them different classes.
I know this is obviously possible but Is this possible in CSS without access to the HTML file?<issue_comment>username_1: from the [documentation](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#rename(String))
```
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet("Hello world");
```
Upvotes: 2 <issue_comment>username_2: I found my questions answer as below:
```
SpreadsheetApp.getActiveSpreadsheet().rename("Renamed Spreadsheet");
```
my intent was renaming the spreadsheet document not the sheets in it.
Thanks for your answers
Upvotes: 4 [selected_answer] |
2018/03/20 | 1,866 | 6,001 | <issue_start>username_0: I have need to calculate the sum of the deep elements foreach first level element.
Sample 3-level array:
```
[
1 => [
'A' => ['AA' => 3, 'AB' => 5],
'B' => ['BA' => 2]
],
2 => [
'C' => ['CA' => 4],
'D' => ['DA' => 1, 'DB' => 2]
],
3 => [
'E' => ['EA' => 1, 'EB' => 2, 'EC' => 3],
'F' => ['FA' => 0, 'FB' => 7, 'FC' => 7]
]
]
```
I want to sum the values and this is my expectation:
```
Array(
[1] => 10
[2] => 7
[3] => 20
)
```
Here is my code that I used for summing the value:
```
$total[$country_id][$province_id][$city_id] = $amount;
$result = array();
foreach( $total as $key => $val ){
$total[$key] = array_sum ( $val );
}
```
Can someone explain what is wrong with my code or explain how foreach work? The result of my code is 0 and actually I just studied around 1 week about foreach.<issue_comment>username_1: print the $total,When coming to the foreach, $val is an array. so when calling array\_sum function, it sums the first array and assign the total to a new array's first element. That is how this is working. The reason why you code is not working, there should be a foreach outside the foreach that you have been provided. Remove this foreach from above foreach's scope.
```
php
$x=[0=[1,2,3],1=>[2,3,4]];
$result = array();
foreach( $x as $key => $val ){
$total[$key] = array_sum ( $val );
}
var_dump($total);
?>
```
If your array is 3 dimentional Code is like this,
```
$y=[0=>[0=>[1,2,3],1=>[3,4,5]],1=>[0=>[5,6,7],1=>[8,9,10]]];
$result = array();
foreach( $y as $vals ){
foreach( $vals as $key => $val ){
$total[$key] = array_sum ( $val );
}
}
var_dump($total);
```
Upvotes: 0 <issue_comment>username_2: The problem with your `foreach` is, that your array is three layers deep, while your `foreach` only traverses the first and `array_sum()` only calculates the second layer.
An example of your foreach:
```
$total = [
0 => [
'A' => [
'AA' => 1,
'AB' => 2
],
'B' => [
'BA' => 3,
'BB' => 4
]
]
];
foreach( $total as $key => $val ){
$total[$key] = array_sum ( $val );
}
```
The `foreach` will iterate over the `$total` array. This is the iteraton for the example:
1. `$key = 0`; `$value = ['A'=>['AA'=>1,'AB'=>2], 'B'=>['BA'=>3,'BB'=>4]]`
In your loop, you then call `array_sum()` on `$value`. `array_sum()` adds the children of the provided array together, if they are numeric. Sadly `$value` is a two dimensional array and its children are arrays, so they are not numeric. That is why `0` is returned for it.
---
A solution to your problem would be to use the [`array_walk_recursive()`](http://php.net/manual/en/function.array-walk-recursive.php) function, that traverses inner arrays and calls a function upon them, that you can specify:
```
$sum = 0;
array_walk_recursive($total, function($value) use (&$sum) {
$sum += $value;
});
```
The specified function adds the value of each leaf in your array to the specified variable `$sum`, that is given by reference to the function.
Upvotes: 1 <issue_comment>username_3: As you want to know more about `foreach`, here is a more verbose solution using it :
```
$total = 0;
$totalByCountry = [];
// iterate over each country
foreach ($arr as $countryId => $provinces) {
$totalByCountry[$countryId] = 0;
// iterate over each province
foreach ($provinces as $provinceId => $cities) {
// iterate over each city
foreach ($cities as $cityId => $value) {
$totalByCountry[$countryId] += $value;
$total += $value;
}
}
}
```
Result of `var_dump(totalByCountry)` :
```
array (size=3)
1 => int 10
2 => int 7
3 => int 20
```
Result of `var_dump($total)` :
```
int 37
```
-- edit --
In real world project, you better be less verbose and use php functions made for this kind of situation like [array\_walk\_recursive()](http://php.net/manual/en/function.array-walk-recursive.php), as in [username_2](https://stackoverflow.com/a/49381715/5313715) and [F<NAME>](https://stackoverflow.com/a/49382762/5313715) answers.
Upvotes: 3 [selected_answer]<issue_comment>username_4: To achieve your desired output, you at first should iterate over your array and check if there exists any sub array then, again traverse all array members by using `array_walk_recursive()` function
```
php
$arr = [
[
'A' = [
'AA' => 3,
'BB' => 5,
'CC' => [
'DD' => 4,
'EE' => 5
]
],
'B' => [
'BA' => 2
]
],
[
'C' => [
'CC' => 3,
'CCC' => 2,
],
'D' => [
'DD' => 2
]
],
5,
[
2,
7
]
];
$arrSum = [];
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
$sum = 0;
if(is_array($arr[$i])) {
array_walk_recursive($arr[$i], function ($item, $key) use (&$sum) {
$sum += $item;
});
}
else {
$sum += $arr[$i];
}
$arrSum [] = $sum;
$sum = 0;
}
var_dump($arrSum);
```
Upvotes: 0 <issue_comment>username_5: For a functional-style solution, use `array_map()` to iterate the first level's data sets.
Then flatten the remaining levels in preparation for `array_sum()`.
`array_values()` is currently necessary because PHP does not yet allow the unpacking of non-numerically keyed arrays.
`array_merge(...$variable)` acts to flatten the 2d structure.
Code: ([Demo](https://3v4l.org/qhWXj))
```
var_export(
array_map(
fn($set) => array_sum(array_merge(...array_values($set))),
$array
)
);
```
Upvotes: 0 |
2018/03/20 | 1,863 | 6,181 | <issue_start>username_0: how to replace objects properties without changing other properties and if uneven number of objects are allocated, copy over other properties?
I guess the question might not make any sense. The example will explain everything.
Lets say I have:
```
var oldData = {
fruits: fruits,
veggies: [{
sweet: false,
colour: red,
data: [1, 2, 3]
}]
};
var newData = {
veggies: [{
sweet: true,
data: [99, 100, 101]
},
{
sweet: false,
data: [888, 777, 665],
}]
};
var standardColor = "blue";
```
The goal is to:
* replace old veggies data with new data
* replace old veggies sweet value with new sweet value
* retain old veggies colour value, unless there is a new one in new data, therefore replace it.
* if a following new veggies object does not have colour, use standardColor - "blue"
* leave fruits untouched
Problems:
* newData veggies can have more objects than oldData, therefore I would need to iterate through them somehow?
My poor attempt:
```
function replaceVeggies (newData) {
oldData.veggies = newData.veggies
};
```<issue_comment>username_1: print the $total,When coming to the foreach, $val is an array. so when calling array\_sum function, it sums the first array and assign the total to a new array's first element. That is how this is working. The reason why you code is not working, there should be a foreach outside the foreach that you have been provided. Remove this foreach from above foreach's scope.
```
php
$x=[0=[1,2,3],1=>[2,3,4]];
$result = array();
foreach( $x as $key => $val ){
$total[$key] = array_sum ( $val );
}
var_dump($total);
?>
```
If your array is 3 dimentional Code is like this,
```
$y=[0=>[0=>[1,2,3],1=>[3,4,5]],1=>[0=>[5,6,7],1=>[8,9,10]]];
$result = array();
foreach( $y as $vals ){
foreach( $vals as $key => $val ){
$total[$key] = array_sum ( $val );
}
}
var_dump($total);
```
Upvotes: 0 <issue_comment>username_2: The problem with your `foreach` is, that your array is three layers deep, while your `foreach` only traverses the first and `array_sum()` only calculates the second layer.
An example of your foreach:
```
$total = [
0 => [
'A' => [
'AA' => 1,
'AB' => 2
],
'B' => [
'BA' => 3,
'BB' => 4
]
]
];
foreach( $total as $key => $val ){
$total[$key] = array_sum ( $val );
}
```
The `foreach` will iterate over the `$total` array. This is the iteraton for the example:
1. `$key = 0`; `$value = ['A'=>['AA'=>1,'AB'=>2], 'B'=>['BA'=>3,'BB'=>4]]`
In your loop, you then call `array_sum()` on `$value`. `array_sum()` adds the children of the provided array together, if they are numeric. Sadly `$value` is a two dimensional array and its children are arrays, so they are not numeric. That is why `0` is returned for it.
---
A solution to your problem would be to use the [`array_walk_recursive()`](http://php.net/manual/en/function.array-walk-recursive.php) function, that traverses inner arrays and calls a function upon them, that you can specify:
```
$sum = 0;
array_walk_recursive($total, function($value) use (&$sum) {
$sum += $value;
});
```
The specified function adds the value of each leaf in your array to the specified variable `$sum`, that is given by reference to the function.
Upvotes: 1 <issue_comment>username_3: As you want to know more about `foreach`, here is a more verbose solution using it :
```
$total = 0;
$totalByCountry = [];
// iterate over each country
foreach ($arr as $countryId => $provinces) {
$totalByCountry[$countryId] = 0;
// iterate over each province
foreach ($provinces as $provinceId => $cities) {
// iterate over each city
foreach ($cities as $cityId => $value) {
$totalByCountry[$countryId] += $value;
$total += $value;
}
}
}
```
Result of `var_dump(totalByCountry)` :
```
array (size=3)
1 => int 10
2 => int 7
3 => int 20
```
Result of `var_dump($total)` :
```
int 37
```
-- edit --
In real world project, you better be less verbose and use php functions made for this kind of situation like [array\_walk\_recursive()](http://php.net/manual/en/function.array-walk-recursive.php), as in [username_2](https://stackoverflow.com/a/49381715/5313715) and [Firoz Ahmad](https://stackoverflow.com/a/49382762/5313715) answers.
Upvotes: 3 [selected_answer]<issue_comment>username_4: To achieve your desired output, you at first should iterate over your array and check if there exists any sub array then, again traverse all array members by using `array_walk_recursive()` function
```
php
$arr = [
[
'A' = [
'AA' => 3,
'BB' => 5,
'CC' => [
'DD' => 4,
'EE' => 5
]
],
'B' => [
'BA' => 2
]
],
[
'C' => [
'CC' => 3,
'CCC' => 2,
],
'D' => [
'DD' => 2
]
],
5,
[
2,
7
]
];
$arrSum = [];
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
$sum = 0;
if(is_array($arr[$i])) {
array_walk_recursive($arr[$i], function ($item, $key) use (&$sum) {
$sum += $item;
});
}
else {
$sum += $arr[$i];
}
$arrSum [] = $sum;
$sum = 0;
}
var_dump($arrSum);
```
Upvotes: 0 <issue_comment>username_5: For a functional-style solution, use `array_map()` to iterate the first level's data sets.
Then flatten the remaining levels in preparation for `array_sum()`.
`array_values()` is currently necessary because PHP does not yet allow the unpacking of non-numerically keyed arrays.
`array_merge(...$variable)` acts to flatten the 2d structure.
Code: ([Demo](https://3v4l.org/qhWXj))
```
var_export(
array_map(
fn($set) => array_sum(array_merge(...array_values($set))),
$array
)
);
```
Upvotes: 0 |
2018/03/20 | 1,186 | 3,088 | <issue_start>username_0: I have two dictionaries, I want to merge following two dictionary into one.
How can I merge them efficiently?
**Dict1**
```
{
UUID('id1'): {
'due': datetime.date(2018, 3, 10),
'status': 'Done',
}, UUID('id2'): {
'due_date': datetime.date(2018, 3, 10),
'old_status': 'Done',
}
}
```
**Dict2**
```
{
UUID('id1'): {
'new_val': 'Pass',
'amount': 123.0,
}, UUID('id2'): {
'new_val': 'Fail',
'amount': 0,
}
}
```
**Desired Output**
```
{
UUID('id1'): {
'due': datetime.date(2018, 3, 10),
'status': 'Done',
'new_val': 'Pass',
'amount': 123.0,
}, UUID('id2'): {
'due_date': datetime.date(2018, 3, 10),
'old_status': 'Done',
'new_val': 'Fail',
'amount': 0,
}
}
```<issue_comment>username_1: For dictionaries `x` and `y`, `z` becomes a merged dictionary with values from y replacing those from x.
In Python 3.5 or greater, :
```
z = {**x, **y}
```
In Python 2, (or 3.4 or lower) write a function:
```
def merge_two_dicts(x, y):
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z
```
and
```
z = merge_two_dicts(x, y)
```
Upvotes: 0 <issue_comment>username_2: ```
dict1={
'UUID(id1)': {
'due': 'datetime.date(2018, 3, 10)',
'status': 'Done'
}, 'UUID(id2)': {
'due_date': 'datetime.date(2018, 3, 10)',
'old_status': 'Done'
}
}
dict2={'UUID(id1)':{
'new_val': 'Pass',
'amount': 123.0
},
'UUID(id2)': {
'new_val': 'Fail',
'amount': 0
}
}
finaldict = {key:(dict1[key], dict2[key]) for key in dict1}
print(finaldict)
```
output
```
{
'UUID(id1)': ({'due': 'datetime.date(2018, 3, 10)', 'status': 'Done'},
{'new_val': 'Pass', 'amount': 123.0}),
'UUID(id2)': ({'due_date': 'datetime.date(2018, 3, 10)', 'old_status': 'Done'},
{'new_val': 'Fail', 'amount': 0})
}
```
Upvotes: 0 <issue_comment>username_3: You can use `**` unpacking notation together with `dict.get` default parameter of `{}` to combine your dictionaries.
This will handle cases where keys in one dictionary are not in the other, and allow us to iterate the union of all keys.
```
keys = d1.keys() | d2.keys()
res = {k: {**d1.get(k, {}), **d2.get(k, {})} for k in keys}
```
**Result**
```
{'id1': {'amount': 123.0,
'due': datetime.date(2018, 3, 10),
'new_val': 'Pass',
'status': 'Done'},
'id2': {'amount': 0,
'due_date': datetime.date(2018, 3, 10),
'new_val': 'Fail',
'old_status': 'Done'}}
```
**Setup**
```
import datetime
d1 = {
'id1': {
'due': datetime.date(2018, 3, 10),
'status': 'Done',
}, 'id2': {
'due_date': datetime.date(2018, 3, 10),
'old_status': 'Done',
}
}
d2 = {
'id1': {
'new_val': 'Pass',
'amount': 123.0,
}, 'id2': {
'new_val': 'Fail',
'amount': 0,
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 331 | 1,405 | <issue_start>username_0: I'm using Anychart 8.1 in an Angular 5 project. We are creating a ResourceGantt POC at the moment. And when I'm creating items for the ResourceGantt I noticed that I create Local Time Date objects. But when I pass them as start & end parameters for the items on the datagrid they get transformed to UTC time, and the timeline also shows the data in UTC time. But we want it to be shown in local time.
I couldn't find anything about it in the documentation. And I tried different things already using moment.js to transform the date in different types, but it always remain the same. Please any advice, cause this really is a breaking issue for us.<issue_comment>username_1: After some further looking into it I found out about the inputLocale(), outputLocale() & outputTimezone() functions.
I fixed it by adding following line to my creation code:
```
anychart.format.outputTimezone(-60);
```
It looks like you have to tell the chart how far UTC is away from you instead how far you are away from UTC. But works like a charm now!
Upvotes: 1 <issue_comment>username_2: You were right! anychart.format includes many useful functions to format dateTime, numbers and etc. Also, I may suggest you using the following approach to set the offset automatically:
```
var offset = new Date().getTimezoneOffset();
anychart.format.outputTimezone(offset);
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 325 | 1,197 | <issue_start>username_0: I am struggling with binding to parent DataContext from DataTemplate/ContextMenu control. I've already tried solutions mentioned [here](https://stackoverflow.com/questions/36043659/how-to-bind-a-command-to-a-contextmenu-from-within-an-itemtemplate?lq=1) and [here](https://stackoverflow.com/questions/3668654/relativesource-binding-from-a-tooltip-or-contextmenu?noredirect=1&lq=1) but with no luck. I'm not able to bind to neither to property or command - no exceptions are thrown, but commands are not invoked and properties are set to null.
Here's my code sample (simplified as its possible):
```
```
I've tried to bind Tag property with Window's DataContext via RelativeSource too (and other possible solutions found across other topics), but nothing happens. Something must be clearly wrong in my approach.<issue_comment>username_1: Have you tried this? (note **DataContext** added)
```
```
Upvotes: 0 <issue_comment>username_2: You cannot find PlacementTarget property in Grid. Change your binding like this,
```
```
or like,
```
```
Also To access ViewModel's command, Access DataContext of ListBox not ListBoxItem,
```
```
Upvotes: 4 [selected_answer] |
2018/03/20 | 297 | 1,247 | <issue_start>username_0: I want to add SSL onto the connections to my spring boot server. So far I have an Arduino, an app and a mongodb database connected to the server and making requests to it. All the communication is HTTP. I plan on making everything under HTTPS but I want to know if it'll be possible for the server to handle both http and HTTPS connection simultaneously because I plan on first implementing SSL between the app and the server and leaving the rest under http.
I am using Spring boot.
I'll research how viable it is to add SSL to the arduino but I'd like to know if a server is possible for handling both Https and http requests e.g. arduino sending requests using http and Android sending requests using https.. Because I plan on adding SSL altogether but for the time being, I'll try and have SSL from the Android app to sever will as I think that'll be easier.<issue_comment>username_1: Have you tried this? (note **DataContext** added)
```
```
Upvotes: 0 <issue_comment>username_2: You cannot find PlacementTarget property in Grid. Change your binding like this,
```
```
or like,
```
```
Also To access ViewModel's command, Access DataContext of ListBox not ListBoxItem,
```
```
Upvotes: 4 [selected_answer] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.