问:
JQuery, load, parse, sum and display from external page
I'm trying to load an external page which contains a table like this:

```<code><table id="uniquedatatable">
 <tr class="row">
  <td class="num col"><a> 1 </a></td>
  <td class="str col"><a>Text</a></td>
  <td class="num col"><a>  7</a></td>
  <td class="str col"><a>Text</a></td>
 </tr>
</table>
</code>```

*Notice the whitespace's in the class names of the td's and around the numbers (1,7).

I need to find all cell's (td's) with class "num col", get the numeric value between the a tag'a and sum all the values. Last I need to display this value on my own page.

So the result I would get from the above table should be: 1 + 7 = 8.

I've gotten this far:

```<code> <script src="http://code.jquery.com/jquery-1.5.1.min.js" type="text/javascript"></script>

 <p id="result"></p>

 <script type="text/javascript">
   var url = "http://someurl";
   var sum = 0;

   $('#result').load('url #uniquedatatable tr td.num col a', function() {
     sum += Number($(this).text());
   });

   _gel('result').innerHTML = sum;
 </script>
</code>```

Realizing something is wrong (close to being correct I hope :)), I need help connecting the "dots" here so that I can:

Calculate the sum (this is the "big" problem :S)

Write the result back.

Any help is appreciated.

答: for calc you can use sum += parseInt($(this).text());

Body:
I'm trying to load an external page which contains a table like this:

   1
  Text
    7
  Text

*Notice the whitespace's in the class names of the td's and around the numbers (1,7).

I need to find all cell's (td's) with class "num col", get the numeric value between the a tag'a and sum all the values. Last I need to display this value on my own page.

So the result I would get from the above table should be: 1 + 7 = 8.

I've gotten this far:

Realizing something is wrong (close to being correct I hope :)), I need help connecting the "dots" here so that I can:

Calculate the sum (this is the "big" problem :S)

Write the result back.

Any help is appreciated.


来源: stackexchange

问:
Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds
In every project I've tried to create in Android Studio, all usages of R are marked in red with the error message "cannot resolve symbol R", but the compilation succeeds and the application runs. This is really annoying, as it blocks auto-completion and shows huge red waved lines all over my code.

I'm running Android Studio 1.7.0 and creating the project with default settings. A screenshot is attached:

This is my build.gradle:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}
</code>```

This is how the Project Structure looks like:

Any idea how to fix this?

答:
Many a times this usually happens when you have changed any of your layout files - where you might have included a new library component (happens generally during copy paste of code). Due to this copy-paste, you might tend to forget adding the dependency in the build.gradle file.

Hence, when you build/compile your project, Android Studio isn't able to understand that newly added component of the library (because the library hasn't become a part of the project yet).

Therefore, make sure you've added the new dependency in the  build.gradle.
Then do a gradle-sync.

ContentLicense: CC BY-SA 3.0

Body:
In every project I've tried to create in Android Studio, all usages of R are marked in red with the error message "cannot resolve symbol R", but the compilation succeeds and the application runs. This is really annoying, as it blocks auto-completion and shows huge red waved lines all over my code.

I'm running Android Studio 1.7.0 and creating the project with default settings. A screenshot is attached:

This is my build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/android-support-v4.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

This is how the Project Structure looks like:

Any idea how to fix this?

ContentLicense: CC BY-SA 4.0


答:
I'm quite sure there is a more elegant way to write this code, but here is a working solution and maybe someone else can build on this: </p>

```<code>library(lubridate)
library(dplyr)
library(tidyr)

df %>%
  mutate(hr1 = paste0("hr_", hour(start_time)),
         min1 = 60 - minute(start_time),
         hr2 = paste0("hr_", hour(end_time)),
         min2 = minute(end_time)) %>%
  gather(hr, hr_val, hr1, hr2) %>%
  mutate(value = ifelse(hr == "hr1", min1, min2)) %>%
  select(user_id, hr_val, value) %>%
  complete(user_id, hr_val = paste0("hr_", 14:23)) %>%
  group_by(user_id) %>%
  mutate(value = case_when(!is.na(value) ~ value,
                           cumsum(!is.na(value)) == 1 ~ 60,
                           TRUE ~ 0)) %>%
  spread(hr_val, value)

# A tibble: 4 x 11
# Groups:   user_id [4]
#   user_id hr_14 hr_15 hr_16 hr_17 hr_18 hr_19 hr_20 hr_21 hr_22 hr_23
#   <fct>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 a          50    60    60    60    30     0     0     0     0     0
# 2 x           0     0     0     0    30    60     0     0     0     0
# 3 y           0     0     0     0     0     0     0    20    60    30
# 4 z           0     0     0     0    50    30     0     0     0     0
</code>```

Title: How to get hours as columns in from-to timestamps (in sparklyr & R)

Body:
I am trying to calculate the time spent (in minutes) by users for each hour . An example is given below. I want to replicate this in sparklyr as well.

df <- data.frame(user_id = c("x", "y", "z", "a"),
                 start_time = c("2019-04-28 18:30:00", "2019-04-28 21:40:00", "2019-04-28 18:10:00", "2019-04-28 14:10:00"),
                 end_time = c("2019-04-28 20:00:00", "2019-04-28 23:30:00", "2019-04-28 19:30:00", "2019-04-28 18:30:00"))

df$start_time <- as.POSIXct(df$start_time, format = "%Y-%m-%d %H:%M:%S")
df$end_time <- as.POSIXct(df$end_time, format = "%Y-%m-%d %H:%M:%S")

df
#   user_id          start_time            end_time
# 1       x 2019-04-28 18:30:00 2019-04-28 20:00:00
# 2       y 2019-04-28 21:40:00 2019-04-28 23:30:00
# 3       z 2019-04-28 18:10:00 2019-04-28 19:30:00
# 4       a 2019-04-28 14:10:00 2019-04-28 18:30:00

The expected output would be in R & Sparklyr

expected_df<-data.frame(user_id=c("x","y","z","a"),hr_14=c(0,0,0,50),hr_15=c(0,0,0,60),hr_16=c(0,0,0,60),hr_17=c(0,0,0,60),hr_18=c(30,0,50,30),hr_19=c(60,0,30,0),hr_20=c(0,0,0,0),hr_21=c(0,20,0,0),hr_22=c(0,60,0,0),hr_23=c(0,30,0,0))

#   user_id hr_14 hr_15 hr_16 hr_17 hr_18 hr_19 hr_20 hr_21 hr_22 hr_23
# 1       x     0     0     0     0    30    60     0     0     0     0
# 2       y     0     0     0     0     0     0     0    20    60    30
# 3       z     0     0     0     0    50    30     0     0     0     0
# 4       a    50    60    60    60    30     0     0     0     0     0

Body:
I'm quite sure there is a more elegant way to write this code, but here is a working solution and maybe someone else can build on this:

library(lubridate)
library(dplyr)
library(tidyr)

df %>%
  mutate(hr1 = paste0("hr_", hour(start_time)),
         min1 = 60 - minute(start_time),
         hr2 = paste0("hr_", hour(end_time)),
         min2 = minute(end_time)) %>%
  gather(hr, hr_val, hr1, hr2) %>%
  mutate(value = ifelse(hr == "hr1", min1, min2)) %>%
  select(user_id, hr_val, value) %>%
  complete(user_id, hr_val = paste0("hr_", 14:23)) %>%
  group_by(user_id) %>%
  mutate(value = case_when(!is.na(value) ~ value,
                           cumsum(!is.na(value)) == 1 ~ 60,
                           TRUE ~ 0)) %>%
  spread(hr_val, value)

# A tibble: 4 x 11
# Groups:   user_id [4]
#   user_id hr_14 hr_15 hr_16 hr_17 hr_18 hr_19 hr_20 hr_21 hr_22 hr_23
#   <fct>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 a          50    60    60    60    30     0     0     0     0     0
# 2 x           0     0     0     0    30    60     0     0     0     0
# 3 y           0     0     0     0     0     0     0    20    60    30
# 4 z           0     0     0     0    50    30     0     0     0     0


问:
How to update same type multiple objects with factory_formset django?
I want to update multiple objects (formset). I have a model and I can to create  multiple objects with this:

```<code>class FormSeguridadView(CreateView):
    v = 0
    insp = 0
    form_class = RespFormSeguridad
    RespFormset = formset_factory(RespFormSeguridad, extra=0)
    template_name = 'formularios/formSeguridad.html'

    def get_context_data(self, **kwargs):
        v = self.v
        insp = self.insp
        context = super(FormSeguridadView, self).get_context_data(**kwargs)
        context['pregDocuObra'] = PRG.objects.filter(PRG_TIP=1)
        context['seguridad_form'] = self.RespFormset(initial=[
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 11},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 12},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 13},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 14},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 19},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 20},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 21},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 22},
        ])

        return context

    def post(self, request, *args, **kwargs):
        resp_formset = self.RespFormset(self.request.POST, self.request.FILES)

        if resp_formset.is_valid():
            for respuestas in resp_formset:
                respuestas.save()

            return HttpResponseRedirect(reverse("index"))
        else:
            print(resp_formset.errors)
            return HttpResponseRedirect(reverse("index"))

</code>```

And this is my part from my form.py:

```<code>class RespFormSeguridad(forms.ModelForm):

    class Meta:
        model = RESP
        fields = '__all__'

    def __init__(self,*args, **kwargs):
       super(RespFormSeguridad, self).__init__(*args, **kwargs)
       self.fields['RESP_FORM'].widget = forms.HiddenInput()
       self.fields['RESP_PRG'].widget = forms.HiddenInput()
       self.fields['RESP_INSP'].widget = forms.HiddenInput()
       self.fields['RESP_RESUL'].widget.attrs['class'] = 'form-control'
</code>```

But i tried to update with this code:

```<code>class FormSeguridadUpdateView(UpdateView):
    form_class = RespFormSeguridad
    template_name = 'formularios/formSeguridadUpdate.html'
    queryset = RESP.objects.all()

    def get_object(self, queryset=None):
        id_ = self.kwargs['pk']
        return get_list_or_404(RESP, RESP_INSP=2)

    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)
</code>```

But it doesn't work. It Throws an error:

```<code>Traceback:

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get
  190.         return super().get(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get
  133.         return self.render_to_response(self.get_context_data())

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get_context_data
  66.             kwargs['form'] = self.get_form()

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get_form
  33.         return form_class(**self.get_form_kwargs())

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\app\forms.py" in __init__
  37.        super(RespFormSeguridad, self).__init__(*args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\forms\models.py" in __init__
  292.             object_data = model_to_dict(instance, opts.fields, opts.exclude)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\forms\models.py" in model_to_dict
  82.     opts = instance._meta

Exception Type: AttributeError at /inspections/1/updateFormSeguridad/
Exception Value: 'list' object has no attribute '_meta'
</code>```

I dont know how to resolve this. Maybe it is not the solution for edit multiple objects. If someone knows to resolve this, please comment here.

答:
The error is being raised because you return a list from the method get_object(), but that method should return a model instance (an instance of a subclass of models.Model).

```<code>def get_object(self, queryset=None):
    ...
    return get_list_or_404(RESP, RESP_INSP=2)   # this causes the ERROR
</code>```

The linked related question mentioned in a comment to the question points this out as well.

I read your comment that you want to update many instances and not just one, but I don't think overriding get_object() is the right way to do it.
That being said, I don't know how to solve your issue, I just added this answer to explain where the error is comming from.

Body:
I want to update multiple objects (formset). I have a model and I can to create  multiple objects with this:

class FormSeguridadView(CreateView):
    v = 0
    insp = 0
    form_class = RespFormSeguridad
    RespFormset = formset_factory(RespFormSeguridad, extra=0)
    template_name = 'formularios/formSeguridad.html'

    def get_context_data(self, **kwargs):
        v = self.v
        insp = self.insp
        context = super(FormSeguridadView, self).get_context_data(**kwargs)
        context['pregDocuObra'] = PRG.objects.filter(PRG_TIP=1)
        context['seguridad_form'] = self.RespFormset(initial=[
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 11},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 12},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 13},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 14},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 19},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 20},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 21},
            {'RESP_INSP': insp, 'RESP_FORM': v, 'RESP_PRG': 22},
        ])

        return context

    def post(self, request, *args, **kwargs):
        resp_formset = self.RespFormset(self.request.POST, self.request.FILES)

        if resp_formset.is_valid():
            for respuestas in resp_formset:
                respuestas.save()

            return HttpResponseRedirect(reverse("index"))
        else:
            print(resp_formset.errors)
            return HttpResponseRedirect(reverse("index"))

And this is my part from my form.py:

class RespFormSeguridad(forms.ModelForm):

    class Meta:
        model = RESP
        fields = '__all__'

    def __init__(self,*args, **kwargs):
       super(RespFormSeguridad, self).__init__(*args, **kwargs)
       self.fields['RESP_FORM'].widget = forms.HiddenInput()
       self.fields['RESP_PRG'].widget = forms.HiddenInput()
       self.fields['RESP_INSP'].widget = forms.HiddenInput()
       self.fields['RESP_RESUL'].widget.attrs['class'] = 'form-control'

But i tried to update with this code:

class FormSeguridadUpdateView(UpdateView):
    form_class = RespFormSeguridad
    template_name = 'formularios/formSeguridadUpdate.html'
    queryset = RESP.objects.all()

    def get_object(self, queryset=None):
        id_ = self.kwargs['pk']
        return get_list_or_404(RESP, RESP_INSP=2)

    def form_valid(self, form):
        print(form.cleaned_data)
        return super().form_valid(form)

But it doesn't work. It Throws an error:

Traceback:

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get
  190.         return super().get(request, *args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get
  133.         return self.render_to_response(self.get_context_data())

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get_context_data
  66.             kwargs['form'] = self.get_form()

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\views\generic\edit.py" in get_form
  33.         return form_class(**self.get_form_kwargs())

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\app\forms.py" in __init__
  37.        super(RespFormSeguridad, self).__init__(*args, **kwargs)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\forms\models.py" in __init__
  292.             object_data = model_to_dict(instance, opts.fields, opts.exclude)

File "C:\Users\usuario\Desktop\Proyectos\inspecciones-moneleg\venv\lib\site-packages\django\forms\models.py" in model_to_dict
  82.     opts = instance._meta

Exception Type: AttributeError at /inspections/1/updateFormSeguridad/
Exception Value: 'list' object has no attribute '_meta'

I dont know how to resolve this. Maybe it is not the solution for edit multiple objects. If someone knows to resolve this, please comment here.

Body:
The error is being raised because you return a list from the method get_object(), but that method should return a model instance (an instance of a subclass of models.Model).

def get_object(self, queryset=None):
    ...
    return get_list_or_404(RESP, RESP_INSP=2)   # this causes the ERROR

The linked related question mentioned in a comment to the question points this out as well.

I read your comment that you want to update many instances and not just one, but I don't think overriding get_object() is the right way to do it.
That being said, I don't know how to solve your issue, I just added this answer to explain where the error is comming from.


问:
Implementing IN /LIKE in MDX
I have a dimension called [Band] and it can have several different values:

```<code>[Band].&[A]&[Under $400]
[Band].&[B]&[$400 - $1,000]
[Band].&[C]&[$1,000 - $2,500]
[Band].&[D]&[$2,500 - $3,500]
...
</code>```

I'm trying to write a query where I can cut by a sublist of these values.

Here's the query that is not working because the .isin function doesn't exist in MDX, but you'll see what I'm trying to do:

```<code>SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].isin(['Under $400', '$400 - $1,000']).ALLMEMBERS)} --fail on .isin(
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)
</code>```

Now, here's a query that is working, but it only gives me one [Band] value:

```<code>SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].&[A]&[Under $400])}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)
</code>```

This returns a valid result of:

```<code>              Measure A    Measure B
Under $400    1795.67%     58.48%
</code>```

But I'd like to see results where it returns the aggregated values of multiple [Band] dimension values. How can this be done in MDX?

As you can probably tell I've never used MDX before, but as I search on this issue I see things like taking the intersect, or using ChildrenSet. But it doesn't seem very intuitive.

Can you point me in the right direction?

答:
So following is a list of how IsIn funcationality can be implemented in MDX

1)you want to filter using in clause and show the members too.
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db

```<code>select
[Measures].[Internet Sales Amount]
on columns,
{[Product].[Category].&[1]
,[Product].[Category].&[3]}
on rows
from
[Adventure Works]
</code>```

Result

2)I want to filter by the IN clause but dont want to show the members
In this example I want to see yearly the internet sales for bikes and clothing category from adventurewroks sample db. The result is to be broken by years.

```<code>select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Year].[Calendar Year]
on rows
from
[Adventure Works]
where
{[Product].[Category].&[1]
,[Product].[Category].&[2]}
</code>```

Result

You achive the same by using subquery

```<code>select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Year].[Calendar Year]
on rows
from
(select {[Product].[Category].&[1],[Product].[Category].&[2]} on 0 from [Adventure Works])
</code>```

Result

3)When you want to implement the IN clause based on name
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db, but in this case I am using the caption

```<code>select
[Measures].[Internet Sales Amount]
on columns,
filter(
[Product].[Category].[Category],
[Product].[Category].currentmember.name='Bikes' or [Product].[Category].currentmember.name='Clothing'
)
on rows
from
[Adventure Works]
</code>```

Result :

4) When you implement IN clause based on name and your condition is looking for a particular text (Like Clause )
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db, but in this case I am searching the the caption name for a piece of string.

```<code>select
[Measures].[Internet Sales Amount]
on columns,
FILTER([Product].[Category].[Category],
Instr([Product].[Category].currentmember.name, 'Bik') > 0
or
Instr([Product].[Category].currentmember.name, 'oth') > 0
)
on rows
from
[Adventure Works]
</code>```

Result

Title: Implementing IN /LIKE in MDX

Body:
I have a dimension called [Band] and it can have several different values:

[Band].&[A]&[Under $400]
[Band].&[B]&[$400 - $1,000]
[Band].&[C]&[$1,000 - $2,500]
[Band].&[D]&[$2,500 - $3,500]
...

I'm trying to write a query where I can cut by a sublist of these values.

Here's the query that is not working because the .isin function doesn't exist in MDX, but you'll see what I'm trying to do:

SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].isin(['Under $400', '$400 - $1,000']).ALLMEMBERS)} --fail on .isin(
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)

Now, here's a query that is working, but it only gives me one [Band] value:

SELECT
  NON EMPTY {[Measure A], [Measure B]} ON COLUMNS,
  NON EMPTY {([Band].&[A]&[Under $400])}
  DIMENSION PROPERTIES MEMBER_CAPTION ON ROWS
FROM (
  SELECT
    ({[Foo].&[Bar]}) ON COLUMNS
  FROM
    [CUBE]
)

This returns a valid result of:

              Measure A    Measure B
Under $400    1795.67%     58.48%

But I'd like to see results where it returns the aggregated values of multiple [Band] dimension values. How can this be done in MDX?

As you can probably tell I've never used MDX before, but as I search on this issue I see things like taking the intersect, or using ChildrenSet. But it doesn't seem very intuitive.

Can you point me in the right direction?

Body:
So following is a list of how IsIn funcationality can be implemented in MDX

1)you want to filter using in clause and show the members too.
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db

select
[Measures].[Internet Sales Amount]
on columns,
{[Product].[Category].&[1]
,[Product].[Category].&[3]}
on rows
from
[Adventure Works]

Result

2)I want to filter by the IN clause but dont want to show the members
In this example I want to see yearly the internet sales for bikes and clothing category from adventurewroks sample db. The result is to be broken by years.

select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Year].[Calendar Year]
on rows
from
[Adventure Works]
where
{[Product].[Category].&[1]
,[Product].[Category].&[2]}

Result

You achive the same by using subquery

select
[Measures].[Internet Sales Amount]
on columns,
non empty
[Date].[Calendar Year].[Calendar Year]
on rows
from
(select {[Product].[Category].&[1],[Product].[Category].&[2]} on 0 from [Adventure Works])

Result

3)When you want to implement the IN clause based on name
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db, but in this case I am using the caption

select
[Measures].[Internet Sales Amount]
on columns,
filter(
[Product].[Category].[Category],
[Product].[Category].currentmember.name='Bikes' or [Product].[Category].currentmember.name='Clothing'
)
on rows
from
[Adventure Works]

Result :

4) When you implement IN clause based on name and your condition is looking for a particular text (Like Clause )
In this example I want to see the internet sales for bikes and clothing category from adventurewroks sample db, but in this case I am searching the the caption name for a piece of string.

select
[Measures].[Internet Sales Amount]
on columns,
FILTER([Product].[Category].[Category],
Instr([Product].[Category].currentmember.name, 'Bik') > 0
or
Instr([Product].[Category].currentmember.name, 'oth') > 0
)
on rows
from
[Adventure Works]

Result


问:
How to get the cell object in tableView:(UITableView *)tableView heightForRowAtIndexPath function?
I wand to know the content of the cell when returning the heightForRowAtIndexPath. In this function how do I get the cell object?

```<code>- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

}
</code>```

If I try this

```<code> [tableView cellForRowAtIndexPath:indexPath]
</code>```

it fails and goes off in an infinite loop.

Any idea?

答:
I don't think you can or you should.
You'll need to determine from indexPath which data you will be displaying in the corresponding cell and thus calculate the needed height of the cell.

So you'll need to write some code to get from indexPath to the right data in your data model.

Body:
I wand to know the content of the cell when returning the heightForRowAtIndexPath. In this function how do I get the cell object?

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

}

If I try this

 [tableView cellForRowAtIndexPath:indexPath]

it fails and goes off in an infinite loop.

Any idea?


问:
How to infer the return type of a function based on an argument that contains a generic?
I don't want to specify the function type every time I call it as I suppose the type can be inferred from the argument somehow. Is it possible?

Here's my current implementation:

```<code>export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}
</code>```

And the errors I'm seeing:

Cannot find name T for Edge<T>

Cannot find name T for T[]

答:
You have to because that's the only way to use a generic type for your parameters, but that doesn't mean you have to type each call. </p>

```<code>getValuesFromEdge({ items: [{ value: 'SomeValue' }]});
</code>```

<p>Would work with </p>

```<code>export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge<T>(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}
</code>```

Body:
I don't want to specify the function type every time I call it as I suppose the type can be inferred from the argument somehow. Is it possible?

Here's my current implementation:

export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}

And the errors I'm seeing:

Cannot find name T for Edge<T>

Cannot find name T for T[]

Body:
You have to because that's the only way to use a generic type for your parameters, but that doesn't mean you have to type each call.

getValuesFromEdge({ items: [{ value: 'SomeValue' }]});

Would work with

export interface Edge<T> {
  items: {
    value: T;
  }[];
}

export function getValuesFromEdge<T>(edge: Edge<T>): T[] {
  return edge.items.map(item => item.value);
}


问:
How to quckly search repeated values in pandas?
I have a column from data frame: 900k rows. Structure of pandas Series:

base['SampleID'] =

```<code>231233
124123
213h213
jkiu12341
213i12i24u
</code>```

I have also a listOfNames contains 84k strings
ex. listOFNames =[jkiu12341,das2123,233213,321n3ju213]

What I need to do?

I need to compare each value from the list to data series (base['SampleID]') rows and check if it contains repetition.

If the script found the same value in Series, should save it (append) to another DataFrame, if not it should just pass.

Problems:

I need to use regex, coz sometimes in the list I would have for example ff5434when in Series: '00ff5434' - and it's should be read as repetition.

I wrote a function in python but it's horribly slow. Compared 900k rows take 35-40 min.

My code:

```<code>found = 0
notfound = 0

for i in range(len(listOfNames)):
    if len(base[base['SampleId'].str.contains(listOfNames[i], regex=False)]) > 0 :
        found += 1
    else:
        notfound+= 1
</code>```

So it's very simple for loop scanning the whole Series. And it's not append founded rows to a data frame yet, just counts how many repeated I have.

Expecting result:

Dataframe with repetition. In the above example it will be: just dataframe or list contains jkiu12341.

Maybe someone knows native pandas function, or any other library helps do it faster and replace my for function?

答:
You can use isin to find the value in a list, you can do the following code:

```<code>df = pd.DataFrame({ 'base': ['231233', '124123', '213h213', 'jkiu12341',
                             '213i12i24u'],})
listOFNames =['jkiu12341','das2123','233213','321n3ju213']
# Result as a list
output=list(df.base[df['base'].isin(listOFNames)])
print(output)
# Result as a DataFrame
df_result=pd.DataFrame(output,columns=['output'])
print(df_result)
</code>```

Output:

```<code>['jkiu12341']

      output
0  jkiu12341
</code>```

time that is needed to execute search operation:

```<code>%timeit output=list(df.base[df['base'].isin(listOFNames)])

585 µs ± 46.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

Body:
I have a column from data frame: 900k rows. Structure of pandas Series:

base['SampleID'] =

231233
124123
213h213
jkiu12341
213i12i24u

I have also a listOfNames contains 84k strings
ex. listOFNames =[jkiu12341,das2123,233213,321n3ju213]

What I need to do?

I need to compare each value from the list to data series (base['SampleID]') rows and check if it contains repetition.

If the script found the same value in Series, should save it (append) to another DataFrame, if not it should just pass.

Problems:

I need to use regex, coz sometimes in the list I would have for example ff5434when in Series: '00ff5434' - and it's should be read as repetition.

I wrote a function in python but it's horribly slow. Compared 900k rows take 35-40 min.

My code:

found = 0
notfound = 0

for i in range(len(listOfNames)):
    if len(base[base['SampleId'].str.contains(listOfNames[i], regex=False)]) > 0 :
        found += 1
    else:
        notfound+= 1

So it's very simple for loop scanning the whole Series. And it's not append founded rows to a data frame yet, just counts how many repeated I have.

Expecting result:

Dataframe with repetition. In the above example it will be: just dataframe or list contains jkiu12341.

Maybe someone knows native pandas function, or any other library helps do it faster and replace my for function?

Body:
You can use isin to find the value in a list, you can do the following code:

df = pd.DataFrame({ 'base': ['231233', '124123', '213h213', 'jkiu12341',
                             '213i12i24u'],})
listOFNames =['jkiu12341','das2123','233213','321n3ju213']
# Result as a list
output=list(df.base[df['base'].isin(listOFNames)])
print(output)
# Result as a DataFrame
df_result=pd.DataFrame(output,columns=['output'])
print(df_result)

Output:

['jkiu12341']

      output
0  jkiu12341

time that is needed to execute search operation:

%timeit output=list(df.base[df['base'].isin(listOFNames)])

585 µs ± 46.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
How to properly make variable Public so it can be accessed by another script?
In Unity I have 2 GameObjects, a sphere and a capsule.

And I have a script attached to each.

Capsule script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CapsuleMesh : MonoBehaviour
{

    public Mesh capsuleMesh;

    void Awake()
    {
        capsuleMesh = GetComponent<MeshFilter>().mesh;
        Debug.Log(capsuleMesh);
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
</code>```

Sphere script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class ChangeMesh : MonoBehaviour
    {

        Mesh mesh;

        void Awake()
        {
            mesh = GetComponent<MeshFilter>().mesh;
            Debug.Log(mesh);
        }
        // Start is called before the first frame update
        void Start()
        {
            mesh = capsuleMesh;

        }

        // Update is called once per frame
        void Update()
        {

        }
    }
</code>```

The mesh = capsuleMesh here is giving me an error about "the name capsuleMesh does not exist in the current context".

I thought that making capsuleMesh public in the other script would make THIS script be able to access it without issue.

What am I doing wrong?

答:
capsuleMesh is a class variable defined in the CapsuleMesh class. It's not a global variable you can use everywhere. You need a reference to the instance of the CapsuleMesh class to retrieve the mesh stored in the capsuleMesh variable.

I've reworked your both scripts to make them work. I've spotted a flaw in your scripts. I guess ChangeMesh is meant to change the mesh of the gameObject? If so, you need to assign a new value to the meshFilter.mesh. Assigning a new reference to the mesh class variable is not enough (it would be pretty long to explain why)

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CapsuleMesh : MonoBehaviour
{
    public Mesh Mesh
    {
       get ; private set;
    }

    void Awake()
    {
        Mesh = GetComponent<MeshFilter>().mesh;
    }
}
</code>```

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeMesh : MonoBehaviour
{
    // Drag & drop in the inspector the gameObject holding the `CapsuleMesh` component
    public CapsuleMesh CapsuleMesh;

    private MeshFilter meshFilter;

    void Awake()
    {
        meshFilter = GetComponent<MeshFilter>();
    }

    void Start()
    {
        meshFilter.mesh = CapsuleMesh.Mesh;
    }
}
</code>```

Body:
In Unity I have 2 GameObjects, a sphere and a capsule.

And I have a script attached to each.

Capsule script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CapsuleMesh : MonoBehaviour
{

    public Mesh capsuleMesh;

    void Awake()
    {
        capsuleMesh = GetComponent<MeshFilter>().mesh;
        Debug.Log(capsuleMesh);
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

Sphere script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class ChangeMesh : MonoBehaviour
    {

        Mesh mesh;

        void Awake()
        {
            mesh = GetComponent<MeshFilter>().mesh;
            Debug.Log(mesh);
        }
        // Start is called before the first frame update
        void Start()
        {
            mesh = capsuleMesh;

        }

        // Update is called once per frame
        void Update()
        {

        }
    }

The mesh = capsuleMesh here is giving me an error about "the name capsuleMesh does not exist in the current context".

I thought that making capsuleMesh public in the other script would make THIS script be able to access it without issue.

What am I doing wrong?

Body:
capsuleMesh is a class variable defined in the CapsuleMesh class. It's not a global variable you can use everywhere. You need a reference to the instance of the CapsuleMesh class to retrieve the mesh stored in the capsuleMesh variable.

I've reworked your both scripts to make them work. I've spotted a flaw in your scripts. I guess ChangeMesh is meant to change the mesh of the gameObject? If so, you need to assign a new value to the meshFilter.mesh. Assigning a new reference to the mesh class variable is not enough (it would be pretty long to explain why)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CapsuleMesh : MonoBehaviour
{
    public Mesh Mesh
    {
       get ; private set;
    }

    void Awake()
    {
        Mesh = GetComponent<MeshFilter>().mesh;
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeMesh : MonoBehaviour
{
    // Drag & drop in the inspector the gameObject holding the `CapsuleMesh` component
    public CapsuleMesh CapsuleMesh;

    private MeshFilter meshFilter;

    void Awake()
    {
        meshFilter = GetComponent<MeshFilter>();
    }

    void Start()
    {
        meshFilter.mesh = CapsuleMesh.Mesh;
    }
}


问:
How to add new label to boxlayout from popup?
I have screen that has two boxlayouts. first one is empty. second one has button to open popup. In popup i have 2 textinputs and checkbox.  I want to add those textinputs as a labels to that boxlayout and checkbox as well.

I can add button to boxlayout if i have button on that screen. but once we go to popup i cant figure out how to do it.

Py.

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager

class MyPopup(Popup):
    pass

class MainScreen(Screen):
    pass

class SecondScreen(Screen):
    def fire_popup(self):
        pops = MyPopup()
        pops.open()

class ScreenManagement(ScreenManager):
    def changescreen(self, value):

        try:
            if value !='main':
                self.current = value
        except:
            print('No Screen named'+ value)

class testiApp(App):
    def build(self):
        self.title = 'Hello'

    def add_more(self):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Button(text='Hello'))

    def remove(self):
        container = self.root.get_screen('Page2').ids.empty
        if len(container.children) > 0:
            container.remove_widget(container.children[0])

testiApp().run()

</code>```

Kv.

```<code>
<MyPopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: False
    title: 'XXX!!'
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'horizontal'
            Label:
                text:'X1'
            TextInput:
                id: X1

            Label:
                text:'X2'
            TextInput:
                id:X2

            CheckBox:
                id:X3

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more()
            Button:
                text: 'Close'
                on_press: pop.dismiss()

ScreenManagement:
    MainScreen:
        name:'Main'
    SecondScreen:
        name:'Page2'

<MainScreen>:
    name:'Main'
    BoxLayout:
        Button:
            text:'Next Page'
            on_release: app.root.current ='Page2'

<SecondScreen>:
    name:'Page2'

    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'vertical'
            Label:
                text:'Popup Test'
            ScrollView:
                GridLayout:
                    orientation: "vertical"
                    size_hint_y: None
                    height: self.minimum_height
                    row_default_height: 60
                    cols:1
                    id:empty
            BoxLayout:
                Button:
                    text:'Open Popup'
                    on_press: root.fire_popup()

                Button:
                    text:'Add'
                    on_release: app.add_more()

                Button:
                    text:'remove'
                    on_release: app.remove()
</code>```

答:
If I understand what you are trying to do, you can get the text from your TextInput by saving a reference to the MyPopup that gets created in your SecondScreen:

```<code>class SecondScreen(Screen):
    def fire_popup(self):
        self.pops = MyPopup()
        self.pops.open()
</code>```

Then use that reference in your add_more() method:

```<code>def add_more(self):
    addbutton = self.root.get_screen('Page2').ids.empty
    addbutton.add_widget(Button(text=self.root.current_screen.pops.ids.X1.text))
</code>```

Of course, you can reference the X2 similarly.

Body:
I have screen that has two boxlayouts. first one is empty. second one has button to open popup. In popup i have 2 textinputs and checkbox.  I want to add those textinputs as a labels to that boxlayout and checkbox as well.

I can add button to boxlayout if i have button on that screen. but once we go to popup i cant figure out how to do it.

Py.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager

class MyPopup(Popup):
    pass

class MainScreen(Screen):
    pass

class SecondScreen(Screen):
    def fire_popup(self):
        pops = MyPopup()
        pops.open()

class ScreenManagement(ScreenManager):
    def changescreen(self, value):

        try:
            if value !='main':
                self.current = value
        except:
            print('No Screen named'+ value)

class testiApp(App):
    def build(self):
        self.title = 'Hello'

    def add_more(self):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Button(text='Hello'))

    def remove(self):
        container = self.root.get_screen('Page2').ids.empty
        if len(container.children) > 0:
            container.remove_widget(container.children[0])

testiApp().run()

Kv.

<MyPopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: False
    title: 'XXX!!'
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'horizontal'
            Label:
                text:'X1'
            TextInput:
                id: X1

            Label:
                text:'X2'
            TextInput:
                id:X2

            CheckBox:
                id:X3

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more()
            Button:
                text: 'Close'
                on_press: pop.dismiss()

ScreenManagement:
    MainScreen:
        name:'Main'
    SecondScreen:
        name:'Page2'

<MainScreen>:
    name:'Main'
    BoxLayout:
        Button:
            text:'Next Page'
            on_release: app.root.current ='Page2'

<SecondScreen>:
    name:'Page2'

    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'vertical'
            Label:
                text:'Popup Test'
            ScrollView:
                GridLayout:
                    orientation: "vertical"
                    size_hint_y: None
                    height: self.minimum_height
                    row_default_height: 60
                    cols:1
                    id:empty
            BoxLayout:
                Button:
                    text:'Open Popup'
                    on_press: root.fire_popup()

                Button:
                    text:'Add'
                    on_release: app.add_more()

                Button:
                    text:'remove'
                    on_release: app.remove()

Body:
If I understand what you are trying to do, you can get the text from your TextInput by saving a reference to the MyPopup that gets created in your SecondScreen:

class SecondScreen(Screen):
    def fire_popup(self):
        self.pops = MyPopup()
        self.pops.open()

Then use that reference in your add_more() method:

def add_more(self):
    addbutton = self.root.get_screen('Page2').ids.empty
    addbutton.add_widget(Button(text=self.root.current_screen.pops.ids.X1.text))

Of course, you can reference the X2 similarly.


问:
Why passing e.target.name is not working here in React
I want to pass the remove method and remove the item from the array.
Here's the code

https://codesandbox.io/embed/heuristic-star-chie9

remove(item,e){
    const x = e.target.name
    console.log(x)
    this.setState((prevState) => {
      return {
        friends : prevState.friends.x.filter((k) => (k.name !== item.name) )
      }
    } )
}
```

<pre class="lang-html prettyprint-override"><code><button name='deactive' onClick={() => {props.remove(item)}}> REMOVE
</button>
</code>```

答:
You have to pass the event like that :</p>

```<code><button name='deactive' onClick={(event) => {props.remove(item, event)}}> REMOVE
</button>
</code>```

Body:
I want to pass the remove method and remove the item from the array.
Here's the code

https://codesandbox.io/embed/heuristic-star-chie9

remove(item,e){
    const x = e.target.name
    console.log(x)
    this.setState((prevState) => {
      return {
        friends : prevState.friends.x.filter((k) => (k.name !== item.name) )
      }
    } )
}

<button name='deactive' onClick={() => {props.remove(item)}}> REMOVE
</button>

Body:
You have to pass the event like that :

<button name='deactive' onClick={(event) => {props.remove(item, event)}}> REMOVE
</button>


问:
Laravel: Pass a variable to a tab without using Javascript
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

```<code><table class="table table-striped table-hover dataTables-example">
    <thead class="thead-dark">
        <tr>
            <th>Id</th>
            <th>Eingang</th>
            <th>Auftrag id</th>
            <th>Ort</th>
        </tr>
    </thead>
    <tbody>
        @foreach($all_ as $element)
        @if($element->status === 'in_progress')
        <tr>
            <td>{{$element->id}}</td>
            <td class="gradeX">{!! $element->created_at->format('D j M Y, G:i:s') !!}</td>
            <td><a href="{{route('orders.show', $element->title)}}">{!! $element->title !!}</a></td>
            <td>{!! $element->address->plz->locality !!}</td>
        </tr>
        @endif
        @endforeach
    </tbody>
</table>
</code>```

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

```<code>....
<div class="tab-content py-3 px-3 px-sm-0" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        <!-- I need to call here the partial and pass status="incoming" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        <!-- I need to call here the partial and pass status="in progress" -->
        @include('dashboard.orders.includes.table_orders')
    </div>

    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">
        <!-- I need to call here the partial and pass status="ready" -->
        @include('dashboard.orders.includes.table_orders')
    </div>
</div>
</code>```

The model looks lilke this:

```<code>$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]
</code>```

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.

答:
Try doing it like this @include('partial_name', $element)

Then you can access the variable as the name you passed to the include

Body:
I am building an index page in whicgh I show the orders separated in three tables: "incoming", "in_progress", "ready"

Essencially is this same table shown three times (and separated into a different tab)

            Id
            Eingang
            Auftrag id
            Ort

        @foreach($all_ as $element)
        @if($element->status === 'in_progress')

            {{$element->id}}
            {!! $element->created_at->format('D j M Y, G:i:s') !!}
            title)}}">{!! $element->title !!}
            {!! $element->address->plz->locality !!}

        @endif
        @endforeach

I saved the table in a different file and I called it like this:  @include('dashboard.orders.includes.table_orders')

....

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

        @include('dashboard.orders.includes.table_orders')

The model looks lilke this:

$element [
    "id" => 1
    "title" => "KFZ_0001_May_2019"
    "details" => "Lorem Ipsums dolor..."
    "status" => "in progress"    // <---or incoming or ready
    "created_at" => "2019-05-31 09:14:02"
    "updated_at" => "2019-05-31 11:16:55"
    "deleted_at" => null
  ]

The question is:

How do I call the external partial and pass the "status" variable in order to show the orders separated each in its corresponding table?

All the three tables are show in the same page!

I would like to avoid using of javascript just for that.


问:
Rowspan and colspan not proper in table
I have created table but its not created as I want. I am using bootstrap. I am created table with row-span and col-span. I am created nearly same but some of rows are not displayed

I am attaching image for the reference.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

     8
    8
     8

     8
     8
    8

    8
    8

```

答:
please try this code:

<!DOCTYPE html>

   <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    8
    8
    8

    8
    8
    8
    8

    8
    8

    8
    8

    8
    8

```

Title: Rowspan and colspan not proper in table

Body:
please try this code:

<!DOCTYPE html>
<html>
<head>

  </head>
 <body>
   <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<table class ="table table-bordered" >

  <tr>
    <th>8</th>
    <th>8</th>
    <th  colspan="2">8</th>
  </tr>
  <tr>
    <td rowspan="2">8</td>
    <td rowspan="2">8</td>
    <td >8</td>
    <td >8</td>
  </tr>
  <tr>
    <td rowspan="2">8</td>
    <td rowspan="2">8</td>
  </tr>
  <tr>
    <td rowspan="2">8</td>
    <td rowspan="2">8</td>
  </tr>
  <tr>
    <td >8</td>
    <td >8</td>
  </tr>
</table>

 </body>
</head>
</html>


问:
How to apply PIXI.js v5 BulgePinchFilter
I'm new to PIXI.js and I would like to use one of the provided filters (BulgePinchFilter) from @pixi/filter-filters.
If I'm correct i can apply these filters to any DisplayObject, but in my example it doesn't work.

index.html

```<code><main>
    <div id="myCanvas"></div>
</main>
</code>```

And here is the app.js file i wrote

```<code>import * as PIXI from "pixi.js";
import { BulgePinchFilter } from 'pixi-filters';
import {Container} from 'pixi.js';

    let app = new PIXI.Application({width: 200, height: 200, transparent:true }),
          container = document.getElementById('myCanvas');

    container.appendChild(app.view);

    const texture = new PIXI.Texture.from(image);
    const bg = PIXI.Sprite.from(texture);
    let appContainer = new Container();

    bg.width = app.screen.width ;
    bg.height = app.screen.height ;

    let x = 40,
        y = 40;

    const myFilter = new BulgePinchFilter([x,y], 20, 0.5);

    appContainer.filters = [ new BulgePinchFilter([app.screen.width/2 ,app.screen.height/2 ], 500, 0.5) ];

    appContainer.addChild(bg);

    app.stage.addChild(appContainer);
</code>```

Right now I can only see the image rendered, but cannot see any Bulge effect on it.

答:
My bad. The X and Y coordinates were bad in my example.
The minimum of these coordinates are 0 and 1 is the maximum.

So if I wanted the filter on the center:

```<code>let x = 0.5,
    y = 0.5;

const myFilter = new BulgePinchFilter([x,y], 20, 0.5);
</code>```

Body:
I'm new to PIXI.js and I would like to use one of the provided filters (BulgePinchFilter) from @pixi/filter-filters.
If I'm correct i can apply these filters to any DisplayObject, but in my example it doesn't work.

index.html

And here is the app.js file i wrote

import * as PIXI from "pixi.js";
import { BulgePinchFilter } from 'pixi-filters';
import {Container} from 'pixi.js';

    let app = new PIXI.Application({width: 200, height: 200, transparent:true }),
          container = document.getElementById('myCanvas');

    container.appendChild(app.view);

    const texture = new PIXI.Texture.from(image);
    const bg = PIXI.Sprite.from(texture);
    let appContainer = new Container();

    bg.width = app.screen.width ;
    bg.height = app.screen.height ;

    let x = 40,
        y = 40;

    const myFilter = new BulgePinchFilter([x,y], 20, 0.5);

    appContainer.filters = [ new BulgePinchFilter([app.screen.width/2 ,app.screen.height/2 ], 500, 0.5) ];

    appContainer.addChild(bg);

    app.stage.addChild(appContainer);

Right now I can only see the image rendered, but cannot see any Bulge effect on it.

Body:
My bad. The X and Y coordinates were bad in my example.
The minimum of these coordinates are 0 and 1 is the maximum.

So if I wanted the filter on the center:

let x = 0.5,
    y = 0.5;

const myFilter = new BulgePinchFilter([x,y], 20, 0.5);


问:
How to format multiple Strings so that they are flush with each other

Description

I want to format multiple strings so that they are flush with each other. (See actual result and expected result)

what i tried

I have implemented this solution: https://stackoverflow.com/a/31613297/11582550
(See code)
It also works, but only if I print the result in the console. I want to save the text in label.text, that doesn't work.

some code

func formattedString(left:String, right:String) -> String {
        let left = (left as NSString).utf8String
        let right = (right as NSString).utf8String
        print(String(format:"%-20s %-20s", left!, right!))
        return String(format:"%-20s %-20s", left!, right!)
    }

label.text += formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")

// actual result

```

<h1>what i expected</h1>

```## actual result (saved in label.text)
Firstname:    Alfred
Lastname:    LongLastname
Note:    private

## expected result (saved in label.text)
Firstname:    Alfred
Lastname:     LongLastname
Note:         private
```

答:
Instead of using low-level C functions and C strings (pointer) in Swift, I suggest using pure Swift string manipulation:

```<code>func formattedString(left: String, right: String, width: Int = 20) -> String {
    // The `max` call returns 0 if `width - left.count` is negative
    let filler = String(repeating: " ", count: max(0, width - left.count))
    return left + filler + right
}

let result = formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")
print(result)

// Firstname:          Alfred
// Lastname:           LongLastname
// Note:               private
</code>```

To cut off long strings, you could do it like this:

```<code>func limit(string: String, length: Int) -> String {
    if string.count <= length {
        return string
    }
    return string.prefix(length) + "…"
}
</code>```

Body:
Description

I want to format multiple strings so that they are flush with each other. (See actual result and expected result)

what i tried

I have implemented this solution: https://stackoverflow.com/a/31613297/11582550
(See code)
It also works, but only if I print the result in the console. I want to save the text in label.text, that doesn't work.

some code

func formattedString(left:String, right:String) -> String {
        let left = (left as NSString).utf8String
        let right = (right as NSString).utf8String
        print(String(format:"%-20s %-20s", left!, right!))
        return String(format:"%-20s %-20s", left!, right!)
    }

label.text += formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")

// actual result

what i expected

## actual result (saved in label.text)
Firstname:    Alfred
Lastname:    LongLastname
Note:    private

## expected result (saved in label.text)
Firstname:    Alfred
Lastname:     LongLastname
Note:         private

Body:
Instead of using low-level C functions and C strings (pointer) in Swift, I suggest using pure Swift string manipulation:

func formattedString(left: String, right: String, width: Int = 20) -> String {
    // The `max` call returns 0 if `width - left.count` is negative
    let filler = String(repeating: " ", count: max(0, width - left.count))
    return left + filler + right
}

let result = formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")
print(result)

// Firstname:          Alfred
// Lastname:           LongLastname
// Note:               private

To cut off long strings, you could do it like this:

func limit(string: String, length: Int) -> String {
    if string.count <= length {
        return string
    }
    return string.prefix(length) + "…"
}


问:
Reactjs - Demo Application is not working
I am trying setup react new setup but it is give me below error

```<code>./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
Error: Cannot find module '@csstools/normalize.css'
</code>```

can anyone suggest me to move forward

thanks in advance

答:
```<code>rm -rf node_modules
npm cache clean --force
npm install
</code>```

now try again to run your scripts, it should work

https://github.com/react-toolbox/react-toolbox-example/issues/28

Body:
I am trying setup react new setup but it is give me below error

./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-3-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
Error: Cannot find module '@csstools/normalize.css'

can anyone suggest me to move forward

thanks in advance

Body:
rm -rf node_modules
npm cache clean --force
npm install

now try again to run your scripts, it should work

https://github.com/react-toolbox/react-toolbox-example/issues/28


问:
Read URL parameters
I have a very basic app and I want to read the request parameter values

http://localhost:3000/submission?issueId=1410&score=3

Page:

```<code>const Submission = () => {
    console.log(this.props.location); // error

    return ();
}

export default Submission;
</code>```

App

```<code>const App = () => (
   <Router>
       <div className='App'>
           <Switch>
               <Route path="/" exact component={Dashboard} />
               <Route path="/submission" component={Submission} />
               <Route path="/test" component={Test} />
           </Switch>
       </div>
   </Router>
);

export default App;
</code>```

答:
The location API provides a search property that allows to get the query parameters of a URL. This can be easily done using the URLSearchParams object. For example, if the url of your page http://localhost:3000/submission?issueId=1410&score=3 the code will look like:

```<code>const searchParams = location.search // location object provided by react-router-dom
const params = new URLSearchParams(searchParams)
const score = params.get('score') // 3
const issueId = params.get('issueId') // 1410
</code>```

Title: Read URL parameters

Body:
I have a very basic app and I want to read the request parameter values

http://localhost:3000/submission?issueId=1410&score=3

Page:

const Submission = () => {
    console.log(this.props.location); // error

    return ();
}

export default Submission;

App

const App = () => (
   <Router>

           <Switch>
               <Route path="/" exact component={Dashboard} />
               <Route path="/submission" component={Submission} />
               <Route path="/test" component={Test} />
           </Switch>

   </Router>
);

export default App;

Body:
The location API provides a search property that allows to get the query parameters of a URL. This can be easily done using the URLSearchParams object. For example, if the url of your page http://localhost:3000/submission?issueId=1410&score=3 the code will look like:

const searchParams = location.search // location object provided by react-router-dom
const params = new URLSearchParams(searchParams)
const score = params.get('score') // 3
const issueId = params.get('issueId') // 1410


问:
Is there a way to validate a .env file?
I'm getting errors when trying to parse a .env file I have, but I have no way of figuring out where it's erring out. Is there an easy way to lint/validate the file, online or otherwise?

Many thanks!

答:
It depends on the syntax you are using. Looking at the Docker and NPM documentation, different tools seem to have a different scope on what they are able to parse.

I use a simple grep to validate if I have a <key>=<value> pattern, where key and value are non-empty. You can adapt the patterns to match your context, ensuring upper case keys for example.

#!/bin/bash

for envfile in $(find . -maxdepth 1 -type f -name '.env.*'); do
    for line in $(cat ${envfile}); do
        # exclude comments
        if [[ "${line:0:1}" == "#" ]]; then
            continue
        fi

        match_line=$(echo ${line} | grep -E "^[A-Za-z0-9_].+=.+$")

        if [[ ${match_line} == "" ]]; then
            echo "Error in file: ${envfile}: line: ${line}"
        fi
    done
done
```

Alternatively, look at your language loadenv library to see if you can catch specific parsing exceptions, if available, to narrow down the specific line that causes the error.

Title: Is there a way to validate a .env file?

Body:
It depends on the syntax you are using. Looking at the Docker and NPM documentation, different tools seem to have a different scope on what they are able to parse.

I use a simple grep to validate if I have a <key>=<value> pattern, where key and value are non-empty. You can adapt the patterns to match your context, ensuring upper case keys for example.

#!/bin/bash

for envfile in $(find . -maxdepth 1 -type f -name '.env.*'); do
    for line in $(cat ${envfile}); do
        # exclude comments
        if [[ "${line:0:1}" == "#" ]]; then
            continue
        fi

        match_line=$(echo ${line} | grep -E "^[A-Za-z0-9_].+=.+$")

        if [[ ${match_line} == "" ]]; then
            echo "Error in file: ${envfile}: line: ${line}"
        fi
    done
done

Alternatively, look at your language loadenv library to see if you can catch specific parsing exceptions, if available, to narrow down the specific line that causes the error.


问:
Using Win32::Env perl module, environment variable not setting permanently in windows
Win32::Env module is used for environment variable set for temporary basis.
I need to set permanently, please help

Please help me to set as permanent .
Because i want it use in another exe.

```<code>use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');
</code>```

By this code, i can set environment variable in windows only as temporary.
when i check with echo command of that variable it is not showing.
because it is set as semi permanent value.

答:
```<code> use Win32::Env;
SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'FALSE');
BroadcastEnv();
print "\n";
DelEnv(ENV_USER, 'AUTO_EXCEL_EXPORT');
print "\n";
SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');
BroadcastEnv();
</code>```

if i run this code its setting only first ENV  ( false ) value, in echo command why??????

Body:
Win32::Env module is used for environment variable set for temporary basis.
I need to set permanently, please help

Please help me to set as permanent .
Because i want it use in another exe.

use Win32::Env;

SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');

By this code, i can set environment variable in windows only as temporary.
when i check with echo command of that variable it is not showing.
because it is set as semi permanent value.

Body:
 use Win32::Env;
SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'FALSE');
BroadcastEnv();
print "\n";
DelEnv(ENV_USER, 'AUTO_EXCEL_EXPORT');
print "\n";
SetEnv(ENV_USER, 'AUTO_EXCEL_EXPORT', 'TRUE');
BroadcastEnv();

if i run this code its setting only first ENV  ( false ) value, in echo command why??????


问:
Apply changes automatically from one azure database to another
I am trying to implement source control for database stored procedures. I am using Azure DevOps and I have added all the stored procedures to an Azure Repo.

I am connecting to the Azure Repo through the team explorer in SSMS. I am working on a branch and once the stored procedure changes are added to the master branch I want the changes to be automatically deployed to the production database.

Is this possible using an Azure pipeline?

答:
Yes you can do it with DACPAC

You can follow the following links,

Use tools that help you integrate and deploy your database along your code. Build better apps on any client OS (Windows, Linux, and macOS) using our graphical user interface and command line tools.

DevOps using SQL Server

Continuous Deployment of SQL


问:
Pandas: how to filter all rows that correlate to a value?
I have a dataframe that looks like this and three lists that contains the information whether the PDB (strucure) is old or new:

```<code>>>> my_df
   PDB1  PDB2  RMSD  Pair
0  A     B     0.2   A-B
1  A     C     0.1   A-C
2  A     D     0.3   A-D
3  B     C     0.3   B-C
4  C     D     0.4   C-D
5  E     F     0.3   E-F
6  E     G     0.4   E-G
7  F     G     0.2   F-G

all_pdb = [A, B, C, D, E, F, G]
old = [A, B, C]
new = [D, E, F, G]
</code>```

The DF compares two structures (PDB1 and PDB2) and has a column for the similarty value (RMSD) and a Pair column.

The  goal is to keep the mimunim representative amount of samples from studied ensemble while keeping the older structures over the newer ones. For example:

Keep A while dropping B, C and D and then keep E while dropping F and G since there is no old structure that represents them.

Using the structures A and E as examples, I've been able to retrieve both structures, while filtering them out of the dataframe, resulting in a dataframe like so:

```<code>>>> my_df
   PDB1  PDB2  RMSD  Pair
0  B     C     0.3   B-C
1  C     D     0.4   C-D
2  F     G     0.2   F-G
</code>```

The problem is that I'm also retrieving B, C and F structures.

This is what the code looks like right now:

pdbs_to_keep = []

all_pdb = [A, B, C, D, E, F, G]

while df.empty == False:

    for x in all_pdb:

#Check whether x is in either column

        if (x in list(df['PDB1']) or x in list(df['PDB2'])):

#Make a filter selecting all rows with x in either column and delete them from the DF

            filter = df[(df['PDB1'] == str(x)) | (df['PDB2'] == str(x))]
            df = df[~df['Pair'].isin(filter['Pair'])]

#Add x to the list of structures to keep

            pdbs_to_keep.append(x)
    break
```

<p>I expect pdbs_to_keep to contain olny A and E, but it contains all of the structures, except for D and G since the row in which they appear (with C and F respectively) are dropped before they can be added.</p>

```Expected result:
>>>pdbs_to_keep
>>>[A, E]

Actual result:
>>>pdbs_to_keep
>>>[A, B, C, E, F]
```

I know that the problem is that I'm only dropping the pairs that contain the analyzed structure (A or E) and not the ones that contain the related structures (B, C, D, F and G) but I can't get it to work like I want it to.

I apologize if the explanation is confusing, english is not my mother tongue. Any help is greatly appreciated.

答:
This should do the trick.

# Logic
for pdb in all_pdb:
    lst = df[df['PDB1'] == pdb]['PDB2'].unique()
    all_pdb = [x for x in all_pdb if x not in lst]
```

<pre class="lang-py prettyprint-override"><code># Result
print(all_pdb)
['A', 'E']
</code>```

Body:
I have a dataframe that looks like this and three lists that contains the information whether the PDB (strucure) is old or new:

>>> my_df
   PDB1  PDB2  RMSD  Pair
0  A     B     0.2   A-B
1  A     C     0.1   A-C
2  A     D     0.3   A-D
3  B     C     0.3   B-C
4  C     D     0.4   C-D
5  E     F     0.3   E-F
6  E     G     0.4   E-G
7  F     G     0.2   F-G

all_pdb = [A, B, C, D, E, F, G]
old = [A, B, C]
new = [D, E, F, G]

The DF compares two structures (PDB1 and PDB2) and has a column for the similarty value (RMSD) and a Pair column.

The  goal is to keep the mimunim representative amount of samples from studied ensemble while keeping the older structures over the newer ones. For example:

Keep A while dropping B, C and D and then keep E while dropping F and G since there is no old structure that represents them.

Using the structures A and E as examples, I've been able to retrieve both structures, while filtering them out of the dataframe, resulting in a dataframe like so:

>>> my_df
   PDB1  PDB2  RMSD  Pair
0  B     C     0.3   B-C
1  C     D     0.4   C-D
2  F     G     0.2   F-G

The problem is that I'm also retrieving B, C and F structures.

This is what the code looks like right now:

pdbs_to_keep = []

all_pdb = [A, B, C, D, E, F, G]

while df.empty == False:

    for x in all_pdb:

#Check whether x is in either column

        if (x in list(df['PDB1']) or x in list(df['PDB2'])):

#Make a filter selecting all rows with x in either column and delete them from the DF

            filter = df[(df['PDB1'] == str(x)) | (df['PDB2'] == str(x))]
            df = df[~df['Pair'].isin(filter['Pair'])]

#Add x to the list of structures to keep

            pdbs_to_keep.append(x)
    break

I expect pdbs_to_keep to contain olny A and E, but it contains all of the structures, except for D and G since the row in which they appear (with C and F respectively) are dropped before they can be added.

Expected result:
>>>pdbs_to_keep
>>>[A, E]

Actual result:
>>>pdbs_to_keep
>>>[A, B, C, E, F]

I know that the problem is that I'm only dropping the pairs that contain the analyzed structure (A or E) and not the ones that contain the related structures (B, C, D, F and G) but I can't get it to work like I want it to.

I apologize if the explanation is confusing, english is not my mother tongue. Any help is greatly appreciated.

Body:
This should do the trick.

# Logic
for pdb in all_pdb:
    lst = df[df['PDB1'] == pdb]['PDB2'].unique()
    all_pdb = [x for x in all_pdb if x not in lst]

# Result
print(all_pdb)
['A', 'E']


问:
img src not working in Django using Bootstrap Carousel
Im trying to add an image to my bootstrap carousel but image is not loading.

```<code>{% extends 'base.html' %}
{% block html %}
{% load static %}

<html lang="en" dir="ltr">
 <head>
<meta charset="utf-8">
 </head>
 <body>
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
 <div class="carousel-inner">
   <div class="carousel-item active">
    <img class="d-block w-100" src="/Users/myname/Documents/django/ldn/static/images/phone.jpg" alt="First slide">
 </div>
 <div class="carousel-item">
  <img class="d-block w-100" src="{% static 'static/images/network.jpg' %}" alt="Second slide">
</div>
<div class="carousel-item">
  <img class="d-block w-100" src="../static/images/phone.jpg" alt="Third slide">
 </div>
</div>
</div>
</body>
</html>
{% endblock %}
</code>```

Ive tried various methods as shown above but none work. My static/images folder is in my project root. Thanks

答:
{% load static %}

    ```

Body:
Im trying to add an image to my bootstrap carousel but image is not loading.

{% extends 'base.html' %}
{% block html %}
{% load static %}

<meta charset="utf-8">

{% endblock %}

Ive tried various methods as shown above but none work. My static/images folder is in my project root. Thanks

Body:
{% load static %}
    <html lang="en">
      <body>
          <img src="{% static 'img/logo.png' %}" >
      </body>
    </html>


问:
Facebook login - LoginManager.getInstance().logInWithReadPermissions never trigger callback
I have followed every steps in https://developers.facebook.com/docs/facebook-login/android/

I implmented using pretty straightforward way

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    android.util.Log.i("CHEOK", "onActivityResult " + requestCode);

    ...
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}

CallbackManager callbackManager;

private void facebook() {
    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            android.util.Log.i("CHEOK", "onSuccess");
            AccessToken accessToken = loginResult.getAccessToken();

            if (accessToken != null) {
                Log.i("CHEOK", "*token --> " + accessToken.getToken());
                Log.i("CHEOK", "*date --> " + accessToken.getExpires());
            } else {
                Log.i("CHEOK", "*no access token");
            }
        }

        @Override
        public void onCancel() {
            android.util.Log.i("CHEOK", "onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            android.util.Log.i("CHEOK", "Error " + error);
        }
    });

    LoginManager.getInstance().logInWithReadPermissions(
            this,
            Arrays.asList("email")
    );
}
</code>```

However, I

Never receive any callback in CallbackManager

Code in onActivityResult not seem to be executed

Didn't see any error log in Android Studio console

May I know what's wrong, and how I can debug this issue?

p/s Note, when the progress dialog of Facebook being dismiss (By pressing back button), I will receive onActivityResult and FacebookCallback's onCancel called.

```<code>onActivityResult 64206
onCancel
</code>```

答:
Try this

Declare a Facebook login button in xml and make it visibility to gone and declare in java class also with click listener

xml file

```<code> <com.facebook.login.widget.LoginButton
        android:id="@+id/flogin_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />
</code>```

Activity or fragment class

```<code>private CallbackManager callbackManager;
    private LoginButton flogin_button;
</code>```

in onCreate()

```<code> flogin_button = (LoginButton) findViewById(R.id.flogin_button);
            callbackManager = CallbackManager.Factory.create();

// facebook login button click listener
login_facebook_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        // App code
        Log.e("onSuccess", "--------" + loginResult.getAccessToken());
        Log.e("Token", "--------" + loginResult.getAccessToken().getToken());
        Log.e("Permision", "--------" + loginResult.getRecentlyGrantedPermissions());
        Profile profile = Profile.getCurrentProfile();
        Log.e("ProfileDataNameF", "--" + profile.getFirstName());
        Log.e("ProfileDataNameL", "--" + profile.getLastName());

        Log.e("Image URI", "--" + profile.getLinkUri());

        Log.e("OnGraph", "------------------------");
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        // Application code
                        Log.e("GraphResponse", "-------------" + response.toString());
                    }
                });
        Bundle parameters = new Bundle();
          parameters.putString("fields", "id,name,first_name,last_name,email,picture.type(large)");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    public void onCancel() {
        // App code
    }

    @Override
    public void onError(FacebookException exception) {
        // App code
    }
});
</code>```

and onActivityResult()

```<code>    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        android.util.Log.i("CHEOK", "onActivityResult " + requestCode);
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }
</code>```

and Finally do this when you want to do facebook login

```<code>flogin_button.performClick();
</code>```

NOTE:-

1) SHOULD HAVE DECLARED CORRECT FACEBOOK KEY IN PROJECT.

2) APP SHOULD BE LIVE IN FACEBOOK CONSOLE.

3) SHOULD HAVE ADDED CORRECT SHA KEY IN FACEBOOK (debug/release)

Body:
I have followed every steps in https://developers.facebook.com/docs/facebook-login/android/

I implmented using pretty straightforward way

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    android.util.Log.i("CHEOK", "onActivityResult " + requestCode);

    ...
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}

CallbackManager callbackManager;

private void facebook() {
    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            android.util.Log.i("CHEOK", "onSuccess");
            AccessToken accessToken = loginResult.getAccessToken();

            if (accessToken != null) {
                Log.i("CHEOK", "*token --> " + accessToken.getToken());
                Log.i("CHEOK", "*date --> " + accessToken.getExpires());
            } else {
                Log.i("CHEOK", "*no access token");
            }
        }

        @Override
        public void onCancel() {
            android.util.Log.i("CHEOK", "onCancel");
        }

        @Override
        public void onError(FacebookException error) {
            android.util.Log.i("CHEOK", "Error " + error);
        }
    });

    LoginManager.getInstance().logInWithReadPermissions(
            this,
            Arrays.asList("email")
    );
}

However, I

Never receive any callback in CallbackManager

Code in onActivityResult not seem to be executed

Didn't see any error log in Android Studio console

May I know what's wrong, and how I can debug this issue?

p/s Note, when the progress dialog of Facebook being dismiss (By pressing back button), I will receive onActivityResult and FacebookCallback's onCancel called.

onActivityResult 64206
onCancel

Body:
Try this

Declare a Facebook login button in xml and make it visibility to gone and declare in java class also with click listener

xml file

 <com.facebook.login.widget.LoginButton
        android:id="@+id/flogin_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

Activity or fragment class

private CallbackManager callbackManager;
    private LoginButton flogin_button;

in onCreate()

 flogin_button = (LoginButton) findViewById(R.id.flogin_button);
            callbackManager = CallbackManager.Factory.create();

// facebook login button click listener
login_facebook_button.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        // App code
        Log.e("onSuccess", "--------" + loginResult.getAccessToken());
        Log.e("Token", "--------" + loginResult.getAccessToken().getToken());
        Log.e("Permision", "--------" + loginResult.getRecentlyGrantedPermissions());
        Profile profile = Profile.getCurrentProfile();
        Log.e("ProfileDataNameF", "--" + profile.getFirstName());
        Log.e("ProfileDataNameL", "--" + profile.getLastName());

        Log.e("Image URI", "--" + profile.getLinkUri());

        Log.e("OnGraph", "------------------------");
        GraphRequest request = GraphRequest.newMeRequest(
                loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(
                            JSONObject object,
                            GraphResponse response) {
                        // Application code
                        Log.e("GraphResponse", "-------------" + response.toString());
                    }
                });
        Bundle parameters = new Bundle();
          parameters.putString("fields", "id,name,first_name,last_name,email,picture.type(large)");
        request.setParameters(parameters);
        request.executeAsync();

    }

    @Override
    public void onCancel() {
        // App code
    }

    @Override
    public void onError(FacebookException exception) {
        // App code
    }
});

and onActivityResult()

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        android.util.Log.i("CHEOK", "onActivityResult " + requestCode);
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);

    }

and Finally do this when you want to do facebook login

flogin_button.performClick();

NOTE:-

1) SHOULD HAVE DECLARED CORRECT FACEBOOK KEY IN PROJECT.

2) APP SHOULD BE LIVE IN FACEBOOK CONSOLE.

3) SHOULD HAVE ADDED CORRECT SHA KEY IN FACEBOOK (debug/release)


问:
MVC 1 Parameter Binding
I'm passing a date to my server in Invariant Culture, the following format

```<code>'mm/dd/yy'
</code>```

The parameter binding in MVC fails to parse this date and returns null for the parameter. This is persumably because IIS is running on a machine using English culture ('dd/mm/yy' works just fine).

I want to override the parsing of all date on my server to use Invariant Culture like so...

```<code>Convert.ChangeType('12/31/11', typeof(DateTime), CultureInfo.InvariantCulture);
</code>```

even when the date is part of another object...

```<code>public class MyObj
{
    public DateTime Date { get; set; }
}
</code>```

My controller method is something like this....

```<code>public ActionResult DoSomethingImportant(MyObj obj)
{
     // use the really important date here
     DoSomethingWithTheDate(obj.Date);
}
</code>```

The date is being sent as Json data like so....

```<code>myobj.Date = '12/31/11'
</code>```

I've tried adding an implementation of IModelBinder to the binderDictionary in the global.asax

```<code>binderDictionary.Add(typeof(DateTime), new DateTimeModelBinder());
</code>```

That doesn't work, and neither does

```<code>ModelBinders.Binders.Add(typeof(DateTime), new DataTimeModelBinder());
</code>```

This seems like some ppl would want to do all the time. I can't see why you would parse dates etc. in the current culture on the server. A client would have to find out the culture of the server just to format dates the server will be able to parse.....

Any help appreciated!

答: Is it possible to pass the date to the server in ISO 8601 format?  I think the server would parse that correctly regardless of its own regional settings.</p>

Title: MVC 1 Parameter Binding

Body:
I'm passing a date to my server in Invariant Culture, the following format

'mm/dd/yy'

The parameter binding in MVC fails to parse this date and returns null for the parameter. This is persumably because IIS is running on a machine using English culture ('dd/mm/yy' works just fine).

I want to override the parsing of all date on my server to use Invariant Culture like so...

Convert.ChangeType('12/31/11', typeof(DateTime), CultureInfo.InvariantCulture);

even when the date is part of another object...

public class MyObj
{
    public DateTime Date { get; set; }
}

My controller method is something like this....

public ActionResult DoSomethingImportant(MyObj obj)
{
     // use the really important date here
     DoSomethingWithTheDate(obj.Date);
}

The date is being sent as Json data like so....

myobj.Date = '12/31/11'

I've tried adding an implementation of IModelBinder to the binderDictionary in the global.asax

binderDictionary.Add(typeof(DateTime), new DateTimeModelBinder());

That doesn't work, and neither does

ModelBinders.Binders.Add(typeof(DateTime), new DataTimeModelBinder());

This seems like some ppl would want to do all the time. I can't see why you would parse dates etc. in the current culture on the server. A client would have to find out the culture of the server just to format dates the server will be able to parse.....

Any help appreciated!


问:
Connection to a spring boot micro-service from a monolithic spring app
So we have a Spring app which runs on localhost:8080

As part of a requirement we need this application to connect to a micro service. The micro service has 2 components.
One running on localhost:8888 - X
Another on localhost:7777 - Y

We have the spring discovery server running on localhost:8761

How can we connect to the micro service X or Y from the monolithic spring application through the discovery server.

We can directly connect to localhost:8888 or localhost:7777

But is there a way to do it through the discover server

答:
There are 3 ways to do the call from the monolithic app to a microservice registered in the discovery-service:

After adding and enabling discovery service dependencies you can
inject eurekaClient bean and get an application url
("round-robinned" or not).

Use the @LoadBalanced restTemplate and send requests to
"http://service-name/url" where ribbon will change "service-name" to
a valid URL automatically

And finally the best option is to rely on feign client. It uses
discovery service implicitly.


问:
How to work with the lists that have different lengths?
The question was started here.

I have an undirected graph g with n<100 vertices. The graph is simple. The coordinates of all vertices are integer (x_i, y_i), i=1, 2,..., n, the set of edges is predefinded, they are line segments with the length 1 unit.
The degree of vertices can be 2, 3 or 4.

```<code>library(igraph)

g <- graph_from_literal(1-2-3-4-5-6-7-8-1, 8-9-4)
B <- t(matrix(c(0,0, 0,1, 0,2, -1,2, -2,2, -2,1, -2,0, -1,0, -1,1), nrow =2));

V(g)$id <- seq_len(vcount(g))

V(g)$x <- B[,1]; V(g)$y <- B[,2]

plot(g, layout=as.matrix(B))
</code>```

I need to set the new attribute for vertex the corner attribute.

We say the vertex i is the corner vertex if its degree is 2 and two incident edges do not lie on the same line. On the plot above vertices 1, 3, 5, 7 are corner vertices while remaining vertices 2, 4, 6, 8, 9 are non-corner.

I have found the list of vertices that have degree equal to 2.

```<code>idv <- V(g)[strength(g)==2]; idv # 1 2 3 5 6 7 9
</code>```

Then the list of neighborhood vertices for i-th vertex was found and new attribur was created:

```<code>neigh<-neighborhood(g, nodes=idv); neigh
V(g)$corner <- 0
</code>```

My attempt

```<code>for(i in idv){
    ifelse(V(g)[neigh[[i]][2]]$x == V(g)[neigh[[i]][3]]$x ||
           V(g)[neigh[[i]][2]]$y == V(g)[neigh[[i]][3]]$y,
    V(g)[neigh[[i]][1]]$corner <- 0,
    V(g)[neigh[[i]][1]]$corner <- 1)}
</code>```

But I have the error Error in neigh[[i]] : subscript out of bounds

In common case the length of neigh is less or equvalent of the length V(g)$id:

```<code>length(neigh)     # 7
length(V(g)$id)   # 9
</code>```

And I cann't compare the coorditates (x_i, y_i).

Question. How to work with the lists that have different lengths?

答:
In this specific case, one solution would be to relate i from idv with an element of neigh. For instance, neigh[[i]][2] could be rewritten as neigh[i == idv][[1]][2]] and in total we have

```<code>for(i in idv){
  ifelse(V(g)[neigh[i == idv][[1]][2]]$x == V(g)[neigh[i == idv][[1]][3]]$x ||
           V(g)[neigh[[i]][2]]$y == V(g)[neigh[i == idv][[1]][3]]$y,
         V(g)[neigh[i == idv][[1]][1]]$corner <- 0,
         V(g)[neigh[i == idv][[1]][1]]$corner <- 1)}
</code>```

However, that is quite convoluted and hard to read. Instead we may exploit the fact that each of idv have the same number of neighbours and neigh can be transformed into a matrix:

```<code>neigh <- do.call(rbind, neigh)
</code>```

Then we simply have

```<code>V(g)$corner[neigh[, 1]] <- V(g)[neigh[, 2]]$x != V(g)[neigh[, 3]]$x &
  V(g)[neigh[, 2]]$y != V(g)[neigh[, 3]]$y
</code>```

Body:
The question was started here.

I have an undirected graph g with n<100 vertices. The graph is simple. The coordinates of all vertices are integer (x_i, y_i), i=1, 2,..., n, the set of edges is predefinded, they are line segments with the length 1 unit.
The degree of vertices can be 2, 3 or 4.

library(igraph)

g <- graph_from_literal(1-2-3-4-5-6-7-8-1, 8-9-4)
B <- t(matrix(c(0,0, 0,1, 0,2, -1,2, -2,2, -2,1, -2,0, -1,0, -1,1), nrow =2));

V(g)$id <- seq_len(vcount(g))

V(g)$x <- B[,1]; V(g)$y <- B[,2]

plot(g, layout=as.matrix(B))

I need to set the new attribute for vertex the corner attribute.

We say the vertex i is the corner vertex if its degree is 2 and two incident edges do not lie on the same line. On the plot above vertices 1, 3, 5, 7 are corner vertices while remaining vertices 2, 4, 6, 8, 9 are non-corner.

I have found the list of vertices that have degree equal to 2.

idv <- V(g)[strength(g)==2]; idv # 1 2 3 5 6 7 9

Then the list of neighborhood vertices for i-th vertex was found and new attribur was created:

neigh<-neighborhood(g, nodes=idv); neigh
V(g)$corner <- 0

My attempt

for(i in idv){
    ifelse(V(g)[neigh[[i]][2]]$x == V(g)[neigh[[i]][3]]$x ||
           V(g)[neigh[[i]][2]]$y == V(g)[neigh[[i]][3]]$y,
    V(g)[neigh[[i]][1]]$corner <- 0,
    V(g)[neigh[[i]][1]]$corner <- 1)}

But I have the error Error in neigh[[i]] : subscript out of bounds

In common case the length of neigh is less or equvalent of the length V(g)$id:

length(neigh)     # 7
length(V(g)$id)   # 9

And I cann't compare the coorditates (x_i, y_i).

Question. How to work with the lists that have different lengths?

Body:
In this specific case, one solution would be to relate i from idv with an element of neigh. For instance, neigh[[i]][2] could be rewritten as neigh[i == idv][[1]][2]] and in total we have

for(i in idv){
  ifelse(V(g)[neigh[i == idv][[1]][2]]$x == V(g)[neigh[i == idv][[1]][3]]$x ||
           V(g)[neigh[[i]][2]]$y == V(g)[neigh[i == idv][[1]][3]]$y,
         V(g)[neigh[i == idv][[1]][1]]$corner <- 0,
         V(g)[neigh[i == idv][[1]][1]]$corner <- 1)}

However, that is quite convoluted and hard to read. Instead we may exploit the fact that each of idv have the same number of neighbours and neigh can be transformed into a matrix:

neigh <- do.call(rbind, neigh)

Then we simply have

V(g)$corner[neigh[, 1]] <- V(g)[neigh[, 2]]$x != V(g)[neigh[, 3]]$x &
  V(g)[neigh[, 2]]$y != V(g)[neigh[, 3]]$y


问:
How to wait visibilityOfElementLocated for sub element?
I am struggling with the syntax of visibilityOfElementLocated

I have an element for a table row, now I need to search an element in this row like row.findElement(xxx)

Below is syntax we use for locating element(parent) directly on page

```<code>WebDriverWait wait = new WebDriverWait(driver, 90L);
WebElement data=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
                ("./td[" + columnIdx + "]");
</code>```

So question is how to use above wait on tableRow ?? (e.g. tableRow.(wait.until))

Thanks!

答:
I was trying to figure out solution for this problem too.

The parameter to wait.Until method is in C# just a method with following signature Func<IWebDriver, IWebElement> (i.e. function with one parameter - the driver - returning the found element.

So instead of trying to hack the Selenium library, I don't have to call the predefined ExpectedConditions (like ExpectedConditions.ElementExists) methods and I can only pass function that does what I need.

```<code>var parent = ... // an element I want to start the search from
// find the element using the XPath expression starting at the parent element
wait.Until(driver => parent.FindElement(By.XPath("..."));
</code>```

Body:
I am struggling with the syntax of visibilityOfElementLocated

I have an element for a table row, now I need to search an element in this row like row.findElement(xxx)

Below is syntax we use for locating element(parent) directly on page

WebDriverWait wait = new WebDriverWait(driver, 90L);
WebElement data=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
                ("./td[" + columnIdx + "]");

So question is how to use above wait on tableRow ?? (e.g. tableRow.(wait.until))

Thanks!

Body:
I was trying to figure out solution for this problem too.

The parameter to wait.Until method is in C# just a method with following signature Func<IWebDriver, IWebElement> (i.e. function with one parameter - the driver - returning the found element.

So instead of trying to hack the Selenium library, I don't have to call the predefined ExpectedConditions (like ExpectedConditions.ElementExists) methods and I can only pass function that does what I need.

var parent = ... // an element I want to start the search from
// find the element using the XPath expression starting at the parent element
wait.Until(driver => parent.FindElement(By.XPath("..."));