问:
Oscar offer app override Benefits functions conflicts error
I use Oscar 1.6.4 version. I want to override PercentageDiscountBenefit in oscar.app.offer.benefits.py. But conflict error happens. How can I override this functions?

```<code>from oscar.core.loading import get_classes

CorePercentageDiscountBenefit, CoreAbsoluteDiscountBenefit = get_classes('offer.benefits', ['PercentageDiscountBenefit', 'AbsoluteDiscountBenefit'])

class PercentageDiscountBenefit(CorePercentageDiscountBenefit):

    def apply(self, basket, condition, offer, discount_amount=None,
              max_total_discount=None):

        print(
            "\n\n\n\n",
            "PRINT SOMETHING",
            "\n\n\n\n",
        )
        return super().apply(basket, condition, offer, discount_amount,
              max_total_discount)

class AbsoluteDiscountBenefit(CoreAbsoluteDiscountBenefit):

    def apply(self, basket, condition, offer, discount_amount=None,
              max_total_discount=None):

        print(
            "\n\n\n\n",
            "PRINT SOMETHING",
            "\n\n\n\n",
        )
        return super().apply(basket, condition, offer, discount_amount,
              max_total_discount)
</code>```

Error log

```<code>RuntimeError at /basket/

Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>.

Request Method:     GET
Request URL:    http://localhost:8000/basket/
Django Version:     1.11.9
Exception Type:     RuntimeError
Exception Value:

Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>.

Exception Location:     /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages/django/apps/registry.py in register_model, line 224
Python Executable:  /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/bin/python
Python Version:     3.5.2
Python Path:

['/home/seyidov/PycharmProjects/Backend/embahome-backend',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-x86_64-linux-gnu',
 '/usr/lib/python3.5/lib-dynload',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages',
 '/home/seyidov/Documents/Programs/pycharm-2018.2.4/helpers/pycharm_matplotlib_backend',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend']
</code>```

答:
You can't override benefit classes in this way. If you want to create a custom benefit that applies different logic to the core ones, you need to create your own class which is a proxy for the core Benefit model:

```<code>from oscar.apps.offer import models

class CustomPercentageDiscountBenefit(models.Benefit):

    class Meta:
        proxy = True

    def apply(self, basket, condition, offer, discount_amount=None, max_total_discount=None):
        # Apply your benefit here
</code>```

This is explained in more detail in the documentation.

Body:
I use Oscar 1.6.4 version. I want to override PercentageDiscountBenefit in oscar.app.offer.benefits.py. But conflict error happens. How can I override this functions?

from oscar.core.loading import get_classes

CorePercentageDiscountBenefit, CoreAbsoluteDiscountBenefit = get_classes('offer.benefits', ['PercentageDiscountBenefit', 'AbsoluteDiscountBenefit'])

class PercentageDiscountBenefit(CorePercentageDiscountBenefit):

    def apply(self, basket, condition, offer, discount_amount=None,
              max_total_discount=None):

        print(
            "\n\n\n\n",
            "PRINT SOMETHING",
            "\n\n\n\n",
        )
        return super().apply(basket, condition, offer, discount_amount,
              max_total_discount)

class AbsoluteDiscountBenefit(CoreAbsoluteDiscountBenefit):

    def apply(self, basket, condition, offer, discount_amount=None,
              max_total_discount=None):

        print(
            "\n\n\n\n",
            "PRINT SOMETHING",
            "\n\n\n\n",
        )
        return super().apply(basket, condition, offer, discount_amount,
              max_total_discount)

Error log

RuntimeError at /basket/

Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>.

Request Method:     GET
Request URL:    http://localhost:8000/basket/
Django Version:     1.11.9
Exception Type:     RuntimeError
Exception Value:

Conflicting 'percentagediscountbenefit' models in application 'offer': <class 'oscar.apps.offer.benefits.PercentageDiscountBenefit'> and <class 'oscar_apps.offer.benefits.PercentageDiscountBenefit'>.

Exception Location:     /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages/django/apps/registry.py in register_model, line 224
Python Executable:  /home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/bin/python
Python Version:     3.5.2
Python Path:

['/home/seyidov/PycharmProjects/Backend/embahome-backend',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-x86_64-linux-gnu',
 '/usr/lib/python3.5/lib-dynload',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend/.venv/lib/python3.5/site-packages',
 '/home/seyidov/Documents/Programs/pycharm-2018.2.4/helpers/pycharm_matplotlib_backend',
 '/home/seyidov/PycharmProjects/Backend/embahome-backend']

Body:
You can't override benefit classes in this way. If you want to create a custom benefit that applies different logic to the core ones, you need to create your own class which is a proxy for the core Benefit model:

from oscar.apps.offer import models

class CustomPercentageDiscountBenefit(models.Benefit):

    class Meta:
        proxy = True

    def apply(self, basket, condition, offer, discount_amount=None, max_total_discount=None):
        # Apply your benefit here

This is explained in more detail in the documentation.


来源: stackexchange

问:
How to get the last days from a selected date?
How to get the last days from a selected date?
Given:

```<code>$declation_date  = "2019-01-01"
$lastDays     = date('Y-m-t',$declation_date);
</code>```

I want to display

  $lastDays = 31;

答:
You want to convert the date string to a unix timestamp using the strtotime() function, then use the date() function to convert that timestamp to a readable format, as you only want to get the last day of the month, just put the "t" format as it will display the total days of the month.</p>

```<code>$declation_date = "2019-01-01";
echo date('t', strtotime($declation_date)); // outputs 31
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to get the last days from a selected date?
Given:

$declation_date  = "2019-01-01"
$lastDays     = date('Y-m-t',$declation_date);

I want to display

  $lastDays = 31;

Body:
You want to convert the date string to a unix timestamp using the strtotime() function, then use the date() function to convert that timestamp to a readable format, as you only want to get the last day of the month, just put the "t" format as it will display the total days of the month.

$declation_date = "2019-01-01";
echo date('t', strtotime($declation_date)); // outputs 31


问:
Heroku console weird date issue
I have a cron task that runs once a day, using Heroku's Daily Cron addon. The cron takes values from yesterday's data and creates required objects with today's timestamp. But, I am facing unusual circumstances. This is from Heroku console :

```<code>>> Date.today
=> Thu, 25 Aug 2011
>> Date.yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Thu, 25 Aug 2011 23:31:42 -0700
</code>```

The current time being 23:31, I thought of giving it a try later on. This is what I have now :

```<code>>> Date.today
=> Fri, 26 Aug 2011
>> Date.yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Fri, 26 Aug 2011 00:35:14 -0700
</code>```

Any ideas why Date.today and Date.yesterday provide the same result. Is it due to the timezone or other certain settings ?

Thanks

答:
It's problaby a TimeZone issue.

I'm developing in Spring Boot and I'm using the code below in the main class:

```<code>@PostConstruct
    public void init() {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
</code>```

And when generate a Date, LocalDate, LocalDateTime or Instant use:

```<code>public static Instant getInstantNow() {
        Clock utcClock = Clock.systemUTC();
        return Instant.now(utcClock).minusSeconds(10800);//my local comparing to UTC in seg.
    }

    public static LocalDateTime getLocalDateTimeNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDateTime.from(nowBrasil);
    }

    public static LocalDate getLocalDateNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDate.from(nowBrasil);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Heroku console weird date issue

Body:
I have a cron task that runs once a day, using Heroku's Daily Cron addon. The cron takes values from yesterday's data and creates required objects with today's timestamp. But, I am facing unusual circumstances. This is from Heroku console :

>> Date.today
=> Thu, 25 Aug 2011
>> Date.yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Thu, 25 Aug 2011 23:31:42 -0700

The current time being 23:31, I thought of giving it a try later on. This is what I have now :

>> Date.today
=> Fri, 26 Aug 2011
>> Date.yesterday
=> Thu, 25 Aug 2011
>> DateTime.now
=> Fri, 26 Aug 2011 00:35:14 -0700

Any ideas why Date.today and Date.yesterday provide the same result. Is it due to the timezone or other certain settings ?

Thanks

Body:
It's problaby a TimeZone issue.

I'm developing in Spring Boot and I'm using the code below in the main class:

@PostConstruct
    public void init() {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }

And when generate a Date, LocalDate, LocalDateTime or Instant use:

public static Instant getInstantNow() {
        Clock utcClock = Clock.systemUTC();
        return Instant.now(utcClock).minusSeconds(10800);//my local comparing to UTC in seg.
    }

    public static LocalDateTime getLocalDateTimeNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDateTime.from(nowBrasil);
    }

    public static LocalDate getLocalDateNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDate.from(nowBrasil);
    }


问:
Preserving line breaks in TextField with Firebase
If I want to save line breaks in my <TextField> component so I set whiteSpace: 'pre-wrap'.

I tried some context and printed it out to see what it would look like and I see this:

I typed in:
    asdfasdlkf

```<code>4444
gggg

ghhhhh
</code>```

"asdfasdlkf↵↵4444↵gggg↵↵ghhhhh"

Now my question is if I save "asdfasdlkf↵↵4444↵gggg↵↵ghhhhh" to my Firebase data, will and read it later, will it still preserve the line breaks?

Thanks for your help!

答: Yes, all text is preserved exactly as you wrote it.  This should be pretty easy for you to test for yourself.</p>

Body:
If I want to save line breaks in my <TextField> component so I set whiteSpace: 'pre-wrap'.

I tried some context and printed it out to see what it would look like and I see this:

I typed in:
    asdfasdlkf

4444
gggg

ghhhhh

"asdfasdlkf↵↵4444↵gggg↵↵ghhhhh"

Now my question is if I save "asdfasdlkf↵↵4444↵gggg↵↵ghhhhh" to my Firebase data, will and read it later, will it still preserve the line breaks?

Thanks for your help!


问:
Mutation is not set value no state - Vuex
Mutation is not set value no state.

The problem is that the state is not being updated.

What I'm doing wrong.

Mutation

```<code>function cardValidationSet (state, data) {
  state.cardValided = data
}
</code>```

Getters

```<code>function cardValidationget (state) {
  return state.cardValided
}
</code>```

Component A

```<code>import Store from '../store'

display: function () {
     Store().commit('disponivel/cardValidationSet', valided)
}
</code>```

Component B

```<code>import { mapGetters, mapActions, mapMutations } from 'vuex'

computed: {
    ...mapGetters('disponivel', ['cardValidationget'])
  },
methods: {
onSubmitPay () {
      console.log(this.cardValidationget)
    },
}
</code>```

答:
if you have setup Vuex properly, the right way to commit a mutation is </p>

```<code> this.$store.commit('disponivel/cardValidationSet', valided)
</code>```

Body:
Mutation is not set value no state.

The problem is that the state is not being updated.

What I'm doing wrong.

Mutation

function cardValidationSet (state, data) {
  state.cardValided = data
}

Getters

function cardValidationget (state) {
  return state.cardValided
}

Component A

import Store from '../store'

display: function () {
     Store().commit('disponivel/cardValidationSet', valided)
}

Component B

import { mapGetters, mapActions, mapMutations } from 'vuex'

computed: {
    ...mapGetters('disponivel', ['cardValidationget'])
  },
methods: {
onSubmitPay () {
      console.log(this.cardValidationget)
    },
}

Body:
if you have setup Vuex properly, the right way to commit a mutation is

 this.$store.commit('disponivel/cardValidationSet', valided)


问:
cumulative frequency given certain conditions in R
I am new at R and I do not really know how to count cumulative number of occurrences of a row if it is the same ID but different date.Also, if the first date appears more than once, it should not count in the first attempt.Look at the rows 2 and 3, that is why the column I am trying to build is called "count" and equals to zero. "count" represents the times that the id has appeared but it follows the next two rules:

1.If it is the first appearence of the Id ever, it assigns zero. For example, for Id 1 despite there are two different registers for the very first date of this Id, "count" equals zero.

2.For the next Id 1 appereance (row 3 of Id1 ) it has a different date, that is why "count" equals 2. Because the 01/01/2018 Id1 appeared twice.

This is the DT and the result that I am looking for is in the "count" column:

答:
We can use dplyr to group_by id and return 0 for the first date else return the count of occurrence of 1st date

```<code>library(dplyr)

df %>%
  group_by(id) %>%
  mutate(count = ifelse(date == date[1L], 0, sum(date == date[1L])))

#     id   date       count
#   <dbl> <fct>      <dbl>
#1     1 01/01/2018     0
#2     1 01/01/2018     0
#3     1 02/01/2018     2
#4     2 03/02/2018     0
#5     2 04/04/2018     1
</code>```

Or using base R ave with similar logic

```<code>as.numeric(with(df, ave(date, id, FUN = function(x)
           ifelse(x == x[1L], 0, sum(x == x[1L])))))
#[1] 0 0 2 0 1
</code>```

data

```<code>df <- data.frame(id = c(1, 1, 1, 2, 2), date = c("01/01/2018", "01/01/2018",
     "02/01/2018", "03/02/2018", "04/04/2018"), stringsAsFactors = FALSE)
</code>```

Body:
We can use dplyr to group_by id and return 0 for the first date else return the count of occurrence of 1st date

library(dplyr)

df %>%
  group_by(id) %>%
  mutate(count = ifelse(date == date[1L], 0, sum(date == date[1L])))

#     id   date       count
#   <dbl> <fct>      <dbl>
#1     1 01/01/2018     0
#2     1 01/01/2018     0
#3     1 02/01/2018     2
#4     2 03/02/2018     0
#5     2 04/04/2018     1

Or using base R ave with similar logic

as.numeric(with(df, ave(date, id, FUN = function(x)
           ifelse(x == x[1L], 0, sum(x == x[1L])))))
#[1] 0 0 2 0 1

data

df <- data.frame(id = c(1, 1, 1, 2, 2), date = c("01/01/2018", "01/01/2018",
     "02/01/2018", "03/02/2018", "04/04/2018"), stringsAsFactors = FALSE)


问:
SimpleDateFormat with Timezone set gets correct value but wrong zone
I have a simple test in a Spring application, which has default timezone set to UTC:

```<code>@SpringBootApplication
public class MemberIntegrationApp {

    @Autowired
    private TimeZoneProperties timeZoneProperties;

    @PostConstruct
    void started() {
        TimeZone.setDefault(TimeZone.getTimeZone(timeZoneProperties.getAppDefault()));  // which is UTC
    }

    public static void main(String[] args) {
        SpringApplication.run(MemberIntegrationApp.class, args);
    }

}
</code>```

And, this simple test: (The test class is annotated with @SpringBootTest to load the configuration in main class and @SpringRunner is applied, too)

```<code>/**
 * Test the effect of setting timezone
 */
@Test
public void testTimezoneSettingOnSimpleDateFormat() throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String d = "2018-08-08 12:34:56";
    log.info("Trying to parse the date string: {}", d);
    Date result = f.parse(d);
    log.info("The result should be 12:34 UTC: {}", result);

    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    result = f.parse(d);
    log.info("The result should be 12:34 UTC: {}", result);

    f.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
    result = f.parse(d);
    log.info("The result should be 10:34 CEST: {}", result);
    log.info("Now the offset(depre): {}", result.getTimezoneOffset());
}
</code>```

I have output:

```<code>Trying to parse the date string: 2018-08-08 12:34:56
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 10:34 CEST: Wed Aug 08 10:34:56 UTC 2018
Now the offset(depre): 0
</code>```

Now, why the fourth line has the value correct, but the timezone is wrong? It should be Europe/Madrid. And the offset(which is deprecated in Java 8, OK I can forgive it), it should be +0200, not 0.

It is UTC because when converting to string in log.info(), slf4j is interferring???? Or what? I don't think so because System.out.println() gives me UTC too.

I know I should use OffsetDateTime, but it is legacy and we cannot change all fields of date to that, for now. I want to know why Java parsed it wrongly.

What is the effect of Timezone.getDefault() when parsing with SimpleDateFormat? And what is that of f.getTimezone()? They seem to act in different part of the process.....

I ask this question, because internally Jackson uses SimpleDateFormat to process date string/formatting dates. Does the config on an ObjectMapper affect the SimpleDateFormat that the mapper uses?

答:
```<code>public static Instant getInstantNow() {
        Clock utcClock = Clock.systemUTC();
        //ZoneId myTZ = ZoneId.of("Brazil/East");
        return Instant.now(utcClock).minusSeconds(10800);
        //Instant in = Instant.now(utcClock);
        //return in.atZone(myTZ);
    }

    public static LocalDateTime getLocalDateTimeNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDateTime.from(nowBrasil);
    }

    public static LocalDate getLocalDateNow() {
        ZonedDateTime nowBrasil = ZonedDateTime.now(ZoneId.of("Brazil/East"));
        return LocalDate.from(nowBrasil);
    }
</code>```

Body:
I have a simple test in a Spring application, which has default timezone set to UTC:

@SpringBootApplication
public class MemberIntegrationApp {

    @Autowired
    private TimeZoneProperties timeZoneProperties;

    @PostConstruct
    void started() {
        TimeZone.setDefault(TimeZone.getTimeZone(timeZoneProperties.getAppDefault()));  // which is UTC
    }

    public static void main(String[] args) {
        SpringApplication.run(MemberIntegrationApp.class, args);
    }

}

And, this simple test: (The test class is annotated with @SpringBootTest to load the configuration in main class and @SpringRunner is applied, too)

/**
 * Test the effect of setting timezone
 */
@Test
public void testTimezoneSettingOnSimpleDateFormat() throws ParseException {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String d = "2018-08-08 12:34:56";
    log.info("Trying to parse the date string: {}", d);
    Date result = f.parse(d);
    log.info("The result should be 12:34 UTC: {}", result);

    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    result = f.parse(d);
    log.info("The result should be 12:34 UTC: {}", result);

    f.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
    result = f.parse(d);
    log.info("The result should be 10:34 CEST: {}", result);
    log.info("Now the offset(depre): {}", result.getTimezoneOffset());
}

I have output:

Trying to parse the date string: 2018-08-08 12:34:56
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 12:34 UTC: Wed Aug 08 12:34:56 UTC 2018
The result should be 10:34 CEST: Wed Aug 08 10:34:56 UTC 2018
Now the offset(depre): 0

Now, why the fourth line has the value correct, but the timezone is wrong? It should be Europe/Madrid. And the offset(which is deprecated in Java 8, OK I can forgive it), it should be +0200, not 0.

It is UTC because when converting to string in log.info(), slf4j is interferring???? Or what? I don't think so because System.out.println() gives me UTC too.

I know I should use OffsetDateTime, but it is legacy and we cannot change all fields of date to that, for now. I want to know why Java parsed it wrongly.

What is the effect of Timezone.getDefault() when parsing with SimpleDateFormat? And what is that of f.getTimezone()? They seem to act in different part of the process.....

I ask this question, because internally Jackson uses SimpleDateFormat to process date string/formatting dates. Does the config on an ObjectMapper affect the SimpleDateFormat that the mapper uses?


问:
Why race condition happens in loop?
I have a code to simulate serial vs parallel computing.  However, it seems has a race condition.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *foo(void *para) {
    printf("This is Thread %d running...\n", *(size_t *)para);
    fflush(stdout);
    sleep(2);
}

int main(void)
{
    /* loop version
    for (size_t i = 0; i < 4; i++) {
        foo((void *)&i);
    }
    */

    pthread_t pool[4];
    for (size_t i = 0; i < 4; i++) {
        pthread_create(&pool[i], NULL, foo, (void *)&i);
    }

    for (size_t i = 0; i < 4; i++) {
        pthread_join(pool[i], NULL);
    }

    return 0;
}
```

<p>Output:</p>

```[william@Notebook Downloads]$ time ./a.out
This is Thread 1 running...
This is Thread 2 running...
This is Thread 4 running...
This is Thread 3 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

[william@Notebook Downloads]$ time ./a.out
This is Thread 3 running...
This is Thread 3 running...
This is Thread 2 running...
This is Thread 4 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s
```

Most of examples when race condition happens is whenn you have multiple threads try to write a shared value.  However, there is no write operation in this code at all.  So, why this happens?  Is it because for loop is not excuted in serial order?

答:
While the earlier answer addresses a problem with your code, it's not the cause of the problem you are asking about as its author assumed.

The problem is that you are passing the same argument to every thread. The threads are printing whatever i happens to be at the time, a value you keep changing. i might not even exist at the time the thread tries to access it.

Instead of passing the same pointer each time, you'll need to pass different pointers (e.g. something allocated just for the thread, or pointers to different elements of an array that's guaranteed to outlive the threads). Alternatively, since the pointer itself is copied, you could cast an sufficiently small integer into pointer and have the thread cast the pointer back into an integer.

Title: Why race condition happens in loop?

Body:
I have a code to simulate serial vs parallel computing.  However, it seems has a race condition.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *foo(void *para) {
    printf("This is Thread %d running...\n", *(size_t *)para);
    fflush(stdout);
    sleep(2);
}

int main(void)
{
    /* loop version
    for (size_t i = 0; i < 4; i++) {
        foo((void *)&i);
    }
    */

    pthread_t pool[4];
    for (size_t i = 0; i < 4; i++) {
        pthread_create(&pool[i], NULL, foo, (void *)&i);
    }

    for (size_t i = 0; i < 4; i++) {
        pthread_join(pool[i], NULL);
    }

    return 0;
}

Output:

[william@Notebook Downloads]$ time ./a.out
This is Thread 1 running...
This is Thread 2 running...
This is Thread 4 running...
This is Thread 3 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

[william@Notebook Downloads]$ time ./a.out
This is Thread 3 running...
This is Thread 3 running...
This is Thread 2 running...
This is Thread 4 running...

real    0m2.003s
user    0m0.003s
sys     0m0.000s

Most of examples when race condition happens is whenn you have multiple threads try to write a shared value.  However, there is no write operation in this code at all.  So, why this happens?  Is it because for loop is not excuted in serial order?


问:
Deep recursive array of directory structure in PHP
I'm trying to put some folders on my hard-drive into an array.

For instance, vacation pictures.
Let's say we have this structure:

Set 1

Item 1 of Set 1

Item 2 of Set 1

Item ... of Set 1

Set 2

Subset 1 of Set 2

Item 1 of Subset 1 of Set 2

Item ... of Subset 1 of Set 2

Subset 2 of Set 2

Random file, not a dir.

Set 3

...

I want to have something like that, as an array.

Meaning I have 1 big array and in that array are more arrays. Each set and subset gets its own array.

I'm trying to make it look something like this:

```<code>Array
(
    [Set 1] => Array([0] => Item 1 of Set 1, [1] => Item 1 of Set 1,...)
    [Set 2] => Array([Subnet 1] => Array([0] => Item 1 of Subset 1 of Set 2,[1] => ...), [Subnet 2] => Array([0] => ..., ..., ...), ..., [0] => Random File)
    [set 3] => Array(...)
    ...
)
</code>```

I came across this: http://www.the-art-of-web.com/php/dirlist/

But that's not what I'm looking for. I've been meddling with it but it's giving me nothing but trouble.

Here's an example, view source for larger resolution(no clicking apparently...).

答:
So 6 years later....

I needed a solution like the answers by @tim & @soulmerge. I was trying to do bulk php UnitTest templates for all of the php files in the default codeigniter folders.

This was step one in my process, to get the full recursive contents of a directory / folder as an array. Then recreate the file structure, and inside the directories have files with the proper name, class structure, brackets, methods and comment sections ready to fill in for the php UnitTest.

To summarize: give a directory name, get a single layered array of all directories within it as keys and all files within as values.

I expanded a their answer a bit further and you get the following:

```<code>function getPathContents($path)
{
     // was a file path provided?
     if ($path === null){
        // default file paths in codeigniter 3.0
        $dirs = array(
            './models',
            './controllers'
        );
    } else{
        // file path was provided
        // it can be a comma separated list or singular filepath or file
        $dirs = explode(',', $path);
    }
    // final array
    $contents = array();
    // for each directory / file given
    foreach ($dirs as $dir) {
        // is it a directory?
        if (is_dir($dir)) {
            // scan the directory and for each file inside
            foreach (scandir($dir) as $node) {
                // skip current and parent directory
                if ($node === '.' || $node === '..') {
                    continue;
                } else {
                    // check for sub directories
                    if (is_dir($dir . '/' . $node)) {
                        // recursive check for sub directories
                        $recurseArray = getPathContents($dir . '/' . $node);
                        // merge current and recursive results
                        $contents = array_merge($contents, $recurseArray);
                    } else {
                        // it a file, put it in the array if it's extension is '.php'
                        if (substr($node, -4) === '.php') {
                            // don'r remove periods if current or parent directory was input
                            if ($dir === '.' || $dir === '..') {
                                $contents[$dir][] = $node;
                            } else {
                                // remove period from directory name
                                $contents[str_replace('.', '', $dir)][] = $node;
                            }
                        }
                    }
                }
            }
        } else {
            // file name was given
            $contents[] = $dir;
        }
    }
    return $contents;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to put some folders on my hard-drive into an array.

For instance, vacation pictures.
Let's say we have this structure:

Set 1

Item 1 of Set 1

Item 2 of Set 1

Item ... of Set 1

Set 2

Subset 1 of Set 2

Item 1 of Subset 1 of Set 2

Item ... of Subset 1 of Set 2

Subset 2 of Set 2

Random file, not a dir.

Set 3

...

I want to have something like that, as an array.

Meaning I have 1 big array and in that array are more arrays. Each set and subset gets its own array.

I'm trying to make it look something like this:

Array
(
    [Set 1] => Array([0] => Item 1 of Set 1, [1] => Item 1 of Set 1,...)
    [Set 2] => Array([Subnet 1] => Array([0] => Item 1 of Subset 1 of Set 2,[1] => ...), [Subnet 2] => Array([0] => ..., ..., ...), ..., [0] => Random File)
    [set 3] => Array(...)
    ...
)

I came across this: http://www.the-art-of-web.com/php/dirlist/

But that's not what I'm looking for. I've been meddling with it but it's giving me nothing but trouble.

Here's an example, view source for larger resolution(no clicking apparently...).

Body:
So 6 years later....

I needed a solution like the answers by @tim & @soulmerge. I was trying to do bulk php UnitTest templates for all of the php files in the default codeigniter folders.

This was step one in my process, to get the full recursive contents of a directory / folder as an array. Then recreate the file structure, and inside the directories have files with the proper name, class structure, brackets, methods and comment sections ready to fill in for the php UnitTest.

To summarize: give a directory name, get a single layered array of all directories within it as keys and all files within as values.

I expanded a their answer a bit further and you get the following:

function getPathContents($path)
{
     // was a file path provided?
     if ($path === null){
        // default file paths in codeigniter 3.0
        $dirs = array(
            './models',
            './controllers'
        );
    } else{
        // file path was provided
        // it can be a comma separated list or singular filepath or file
        $dirs = explode(',', $path);
    }
    // final array
    $contents = array();
    // for each directory / file given
    foreach ($dirs as $dir) {
        // is it a directory?
        if (is_dir($dir)) {
            // scan the directory and for each file inside
            foreach (scandir($dir) as $node) {
                // skip current and parent directory
                if ($node === '.' || $node === '..') {
                    continue;
                } else {
                    // check for sub directories
                    if (is_dir($dir . '/' . $node)) {
                        // recursive check for sub directories
                        $recurseArray = getPathContents($dir . '/' . $node);
                        // merge current and recursive results
                        $contents = array_merge($contents, $recurseArray);
                    } else {
                        // it a file, put it in the array if it's extension is '.php'
                        if (substr($node, -4) === '.php') {
                            // don'r remove periods if current or parent directory was input
                            if ($dir === '.' || $dir === '..') {
                                $contents[$dir][] = $node;
                            } else {
                                // remove period from directory name
                                $contents[str_replace('.', '', $dir)][] = $node;
                            }
                        }
                    }
                }
            }
        } else {
            // file name was given
            $contents[] = $dir;
        }
    }
    return $contents;
}


问:
Closest blog engine to Wordpress in ASP.NET
I haven't been very satisfied with all the blog engines I saw in asp.net, I just encountered one which seems better than the other and it's implemented in MVC3, I don't remember which one. Can someone remind me and/or point to me an asp.net blog engine that is closest to Wordpress as for its architecture plugin.</p>

答: You might be thinking of Orchard CMS?  Also check out NBlog (disclaimer: mine) and  FunnelWeb.</p>


问:
Creating POJO/beans dynamically and set values using CGLib
I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.

I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.

```<code>Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
            try {
                Object beanClassObject = beanClass.newInstance();
                lines.forEach(line -> {
                    if (line != null && !line.isEmpty() && !line.equals("null")) {
                        String[] lineData = line.split("\t");
                        System.out.println("LineData length :: " + lineData.length);
                        Method[] methods = beanClass.getMethods();
                        System.out.println("Methods length :: " + methods.length);
                        int index = 0;
                        for (Method m : methods) {
                            m.setAccessible(true);
                            if (m.getName().startsWith("set")) {
                                try {
                                    if ((lineData.length <= index) && lineData[index] != null) {
                                        m.invoke(beanClassObject, lineData[index]);
                                        index++;
                                    } else {
                                        m.invoke(beanClassObject, " ");
                                    }
                                } catch (IllegalAccessException | InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                ObjectMapper om = new ObjectMapper();
                System.out.println(om.writeValueAsString(beanClassObject));
            } catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
                e.printStackTrace();
  }});
</code>```

The problem with the approach is that most of the times all the column values may not have data it can be nulled.

I am wondering if there is an easier way of doing this. Any help is appreciated.

Here is the bean generation method.

```<code>public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
        BeanGenerator beanGenerator = new BeanGenerator();
        beanGenerator.setNamingPolicy(new NamingPolicy() {
            @Override
            public String getClassName(String prefix, String source, Object key, Predicate names) {
                return className;
            }
        });

        BeanGenerator.addProperties(beanGenerator, properties);
        return (Class<?>) beanGenerator.createClass();
    }
</code>```

Here is the sample text file which needs to be converted to the JSON output.

```<code><Data1>
Col1  col2 col3 col4 col5
even    sense   met has
root    greatest    spin    mostly
gentle  held    introduced  palace
cold    equator remember    grandmother
slightly    butter  depth   like
distant second  coast   everyone

<Data2>
Col1  col2 col3 col4 col5 col6 col7 col8
greatest    rope    operation   flies   brown   continent   combination read
slightly    diagram he  grandfather where   party   fifty   pour
well    put plastic anyway  refer   careful correct furniture
how since   army    tongue  birthday    been    clock   official
table   command specific    distant cutting hill    movie   experience
national    though  stopped youth   army    underline   five    know

<Data3>
Col1 col2 col3 col4 col5 col6 col7 col8 col9 col9 col10
vessels characteristic  ship    joy than    tomorrow    high    seven   future  trade
try gray    fourth  advice  week    stream  motion  musical whom    tin
limited daughter    large   rice    came    home    chicken wheat   engine  box
easy    city    pair    strange stage   visitor coach   announced   allow   simple
jet therefore   single  during  construction    flag    bigger  muscle  complex pleasure
income  several coat    range   dull    cattle  damage  jump    present shake
</code>```

JSON output:

```<code>[{
    "<Data1>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        }
    ]

}, {
    "<Data2>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        }
    ]

}]
</code>```

I came up with a solution using the Maps.

```<code>Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new ArrayList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t");
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }
</code>```

答:
I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach.

```<code>public String convert(Map<String, ? extends Metadata> metadataMap) {
        String output = "";
        Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new LinkedList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t",-1);
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

        return output;
    }
</code>```

Body:
I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.

I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.

Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
            try {
                Object beanClassObject = beanClass.newInstance();
                lines.forEach(line -> {
                    if (line != null && !line.isEmpty() && !line.equals("null")) {
                        String[] lineData = line.split("\t");
                        System.out.println("LineData length :: " + lineData.length);
                        Method[] methods = beanClass.getMethods();
                        System.out.println("Methods length :: " + methods.length);
                        int index = 0;
                        for (Method m : methods) {
                            m.setAccessible(true);
                            if (m.getName().startsWith("set")) {
                                try {
                                    if ((lineData.length <= index) && lineData[index] != null) {
                                        m.invoke(beanClassObject, lineData[index]);
                                        index++;
                                    } else {
                                        m.invoke(beanClassObject, " ");
                                    }
                                } catch (IllegalAccessException | InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                ObjectMapper om = new ObjectMapper();
                System.out.println(om.writeValueAsString(beanClassObject));
            } catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
                e.printStackTrace();
  }});

The problem with the approach is that most of the times all the column values may not have data it can be nulled.

I am wondering if there is an easier way of doing this. Any help is appreciated.

Here is the bean generation method.

public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
        BeanGenerator beanGenerator = new BeanGenerator();
        beanGenerator.setNamingPolicy(new NamingPolicy() {
            @Override
            public String getClassName(String prefix, String source, Object key, Predicate names) {
                return className;
            }
        });

        BeanGenerator.addProperties(beanGenerator, properties);
        return (Class<?>) beanGenerator.createClass();
    }

Here is the sample text file which needs to be converted to the JSON output.

<Data1>
Col1  col2 col3 col4 col5
even    sense   met has
root    greatest    spin    mostly
gentle  held    introduced  palace
cold    equator remember    grandmother
slightly    butter  depth   like
distant second  coast   everyone

<Data2>
Col1  col2 col3 col4 col5 col6 col7 col8
greatest    rope    operation   flies   brown   continent   combination read
slightly    diagram he  grandfather where   party   fifty   pour
well    put plastic anyway  refer   careful correct furniture
how since   army    tongue  birthday    been    clock   official
table   command specific    distant cutting hill    movie   experience
national    though  stopped youth   army    underline   five    know

<Data3>
Col1 col2 col3 col4 col5 col6 col7 col8 col9 col9 col10
vessels characteristic  ship    joy than    tomorrow    high    seven   future  trade
try gray    fourth  advice  week    stream  motion  musical whom    tin
limited daughter    large   rice    came    home    chicken wheat   engine  box
easy    city    pair    strange stage   visitor coach   announced   allow   simple
jet therefore   single  during  construction    flag    bigger  muscle  complex pleasure
income  several coat    range   dull    cattle  damage  jump    present shake

JSON output:

[{
    "<Data1>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        }
    ]

}, {
    "<Data2>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        }
    ]

}]

I came up with a solution using the Maps.

Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new ArrayList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t");
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

Body:
I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach.

public String convert(Map<String, ? extends Metadata> metadataMap) {
        String output = "";
        Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new LinkedList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t",-1);
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

        return output;
    }


问:
regex for decimal number validation
I am adding a validation on a text box for decimal number (4,2). i tried below code, it works after the decimal point (meaning it's restricting user inputing more than 2 digits after decimal point) but it doesn't restrict user inputing more than 4 digits before the decimal point.

ng-pattern-restrict="^[0-9]{0,4}+(.[0-9]{0,2})?$"

Valid input: 10.20

Valid input: 1234.23

Invalid input: 123456.23

Invalid input: 1234.23456

答:
The {0,4} means "0 to 4 of the proceeding pattern". The + means "one or more of the proceeding pattern" and the . means "any character".

So it sounds like you need to drop the + (you already have the count specified in {0,4}) and escape the . to match the literal decimal point.

^[0-9]{0,4}(\.[0-9]{0,2})?$

10.20 matches

1234.23 matches

123456.23 no match

1234.23456 no match

Keep in mind this is not a universally acceptable method of validating decimals. Different regions use different symbols for the decimal point, for example.

Title: regex for decimal number validation


问:
Combine several planes, each with its own unique texture into one "model" and keep all of the textures in Unity
In  Unity, I've created a "stack" of planes (programmatically) - each of which has an image on it. I want to be able to take the camera and zoom into the stack, and as it zooms through the stack of planes, see each of the images.

Imagine taking a camera through a Russian Matryoshka doll and seeing each of the smaller dolls as you progress through it.

It's also important to note that in my case, the stack of planes are not perfectly aligned in a stack, and so some of them will intersect slightly - I need to make sure they don't flicker.

I would like to combine these planes, each with its own image into a singular "model" (Mesh is probably the right terminology, but using this video: https://www.youtube.com/watch?v=6APzUgckV7U didn't work - it took all of my planes and simply converted it into a single plane; that being said, I was able combine these planes but it created a single object with a single material). This uses mesh combiners, but I'm not sure this is the right approach.

Here is some code I've written which takes all of the planes out of the slicesHolder and combines them into one "model." It then put that "model" inside of the finalObject but unfortunately, the "model" does not retain any of the materials (images) from the slices. And slicesHolder is destroyed.

```<code>Quaternion oldRot = slicesHolder.transform.rotation;
Vector3 oldPos = slicesHolder.transform.position;

finalObject.transform.rotation = Quaternion.identity;
finalObject.transform.position = Vector3.zero;

MeshFilter[] meshFilters = slicesHolder.GetComponentsInChildren<MeshFilter>();

Debug.Log("Combining " + meshFilters.Length + " meshes");

Mesh finalMesh = new Mesh();
CombineInstance[] combiners = new CombineInstance[meshFilters.Length];

            for(int a = 0; a < meshFilters.Length; a++){
                //if(meshFilters[a].transform == transform)
                //continue;

                combiners[a].subMeshIndex = 0;
                combiners[a].mesh = meshFilters[a].sharedMesh;
                combiners[a].transform = meshFilters[a].transform.localToWorldMatrix;
            }

finalMesh.CombineMeshes(combiners);

finalObject.GetComponent<MeshFilter>().sharedMesh = finalMesh;
finalObject.transform.rotation = oldRot;
finalObject.transform.position = oldPos;

Destroy(slicesHolder);
finalObject.SetActive(true);
</code>```

Is this the correct way of trying to create a singular "model" which has a "stack" of individual images so that I can zoom into this stack and see deeper into the model?

答:
There is no effective way to do this

And the reason for that is the textures. Or more specifically the materials. Because each plane has a unique material instance there is no way to combine it with another plane. You're either going to end up with what you started with or you'll get a combined model using only one of the textures on each face.

You would need a way to map each of the desired textures onto a sprite sheet, create a new material with that sprite sheet, and then figure out what the UV offsets are to convert from one material to the sprite sheet material, assign the sprite sheet material to all the planes, then mesh-combine them.

Body:
In  Unity, I've created a "stack" of planes (programmatically) - each of which has an image on it. I want to be able to take the camera and zoom into the stack, and as it zooms through the stack of planes, see each of the images.

Imagine taking a camera through a Russian Matryoshka doll and seeing each of the smaller dolls as you progress through it.

It's also important to note that in my case, the stack of planes are not perfectly aligned in a stack, and so some of them will intersect slightly - I need to make sure they don't flicker.

I would like to combine these planes, each with its own image into a singular "model" (Mesh is probably the right terminology, but using this video: https://www.youtube.com/watch?v=6APzUgckV7U didn't work - it took all of my planes and simply converted it into a single plane; that being said, I was able combine these planes but it created a single object with a single material). This uses mesh combiners, but I'm not sure this is the right approach.

Here is some code I've written which takes all of the planes out of the slicesHolder and combines them into one "model." It then put that "model" inside of the finalObject but unfortunately, the "model" does not retain any of the materials (images) from the slices. And slicesHolder is destroyed.

Quaternion oldRot = slicesHolder.transform.rotation;
Vector3 oldPos = slicesHolder.transform.position;

finalObject.transform.rotation = Quaternion.identity;
finalObject.transform.position = Vector3.zero;

MeshFilter[] meshFilters = slicesHolder.GetComponentsInChildren<MeshFilter>();

Debug.Log("Combining " + meshFilters.Length + " meshes");

Mesh finalMesh = new Mesh();
CombineInstance[] combiners = new CombineInstance[meshFilters.Length];

            for(int a = 0; a < meshFilters.Length; a++){
                //if(meshFilters[a].transform == transform)
                //continue;

                combiners[a].subMeshIndex = 0;
                combiners[a].mesh = meshFilters[a].sharedMesh;
                combiners[a].transform = meshFilters[a].transform.localToWorldMatrix;
            }

finalMesh.CombineMeshes(combiners);

finalObject.GetComponent<MeshFilter>().sharedMesh = finalMesh;
finalObject.transform.rotation = oldRot;
finalObject.transform.position = oldPos;

Destroy(slicesHolder);
finalObject.SetActive(true);

Is this the correct way of trying to create a singular "model" which has a "stack" of individual images so that I can zoom into this stack and see deeper into the model?


问:
Error when running program with VirtualShellTools from a service
I create a service in Delphi. I need this service to run my program. In Windows 7, I use this code to execute a program :

```<code>procedure ExecuteProcessAsLoggedOnUser(FileName: string);

implementation

function GetShellProcessName: string;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create(KEY_READ);
  try
    Reg.RootKey := HKEY_LOCAL_MACHINE;
    Reg.OpenKeyReadOnly
      ('Software\Microsoft\Windows NT\CurrentVersion\WinLogon');
    Result := Reg.ReadString('Shell');
  finally
    Reg.Free;
  end;
end;

function GetShellProcessPid(const Name: string): Longword;
var
  Snapshot: THandle;
  Process: TProcessEntry32;
  B: Boolean;
begin
  Result := 0;
  Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if Snapshot <> INVALID_HANDLE_VALUE then
    try
      FillChar(Process, SizeOf(Process), 0);
      Process.dwSize := SizeOf(Process);
      B := Process32First(Snapshot, Process);
      while B do
      begin
        if CompareText(Process.szExeFile, Name) = 0 then
        begin
          Result := Process.th32ProcessID;
          Break;
        end;
        B := Process32Next(Snapshot, Process);
      end;
    finally
      CloseHandle(Snapshot);
    end;
end;

function GetShellHandle: THandle;
var
  Pid: Longword;
begin
  Pid := GetShellProcessPid(GetShellProcessName);
  Result := OpenProcess(PROCESS_ALL_ACCESS, False, Pid);
end;

procedure ExecuteProcessAsLoggedOnUser(FileName: string);
var
  ph: THandle;
  hToken, nToken: THandle;
  ProcInfo: TProcessInformation;
  StartInfo: TStartupInfo;
begin
  ph := GetShellHandle;
  if ph > 0 then
  begin
    if OpenProcessToken(ph, TOKEN_DUPLICATE or TOKEN_QUERY, hToken) then
    begin
      if DuplicateTokenEx(hToken, TOKEN_ASSIGN_PRIMARY or TOKEN_DUPLICATE or
        TOKEN_QUERY, nil, SecurityImpersonation, TokenPrimary, nToken) then
      begin
        if ImpersonateLoggedOnUser(nToken) then
        begin
          // Initialize then STARTUPINFO structure
          FillChar(StartInfo, SizeOf(TStartupInfo), 0);
          StartInfo.cb := SizeOf(TStartupInfo);
          // Specify that the process runs in the interactive desktop
          StartInfo.lpDesktop := PChar('WinSta0\Default');

          // Launch the process in the client's logon session
          CreateProcessAsUser(nToken, nil, PChar(FileName), nil, nil, False,
            CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartInfo,
            ProcInfo);

          // End impersonation of client
          RevertToSelf();
        end;
        CloseHandle(nToken);
      end;
      CloseHandle(hToken);
    end;
  end;
end;
</code>```

The code works fine for an "empty" program. So I drop TVirtualExpolorerTreeview onto the form of my program. if I start my service then there will be an error when the program is being called. I guess the program can't enumerate PIDL or blabla (I don't know much about Windows Shell). How do I force the program so it can run normally?

答:
Your WinSta0 might be the cause:

Starting with Windows Vista, the way that services (and processes started by services) can interact with the desktop changed, as services no longer run in the same session as the user at the console.

By default, they cannot interact with the desktop any more.

See this thread for some nice links on this matter.

Body:
I create a service in Delphi. I need this service to run my program. In Windows 7, I use this code to execute a program :

procedure ExecuteProcessAsLoggedOnUser(FileName: string);

implementation

function GetShellProcessName: string;
var
  Reg: TRegistry;
begin
  Reg := TRegistry.Create(KEY_READ);
  try
    Reg.RootKey := HKEY_LOCAL_MACHINE;
    Reg.OpenKeyReadOnly
      ('Software\Microsoft\Windows NT\CurrentVersion\WinLogon');
    Result := Reg.ReadString('Shell');
  finally
    Reg.Free;
  end;
end;

function GetShellProcessPid(const Name: string): Longword;
var
  Snapshot: THandle;
  Process: TProcessEntry32;
  B: Boolean;
begin
  Result := 0;
  Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if Snapshot <> INVALID_HANDLE_VALUE then
    try
      FillChar(Process, SizeOf(Process), 0);
      Process.dwSize := SizeOf(Process);
      B := Process32First(Snapshot, Process);
      while B do
      begin
        if CompareText(Process.szExeFile, Name) = 0 then
        begin
          Result := Process.th32ProcessID;
          Break;
        end;
        B := Process32Next(Snapshot, Process);
      end;
    finally
      CloseHandle(Snapshot);
    end;
end;

function GetShellHandle: THandle;
var
  Pid: Longword;
begin
  Pid := GetShellProcessPid(GetShellProcessName);
  Result := OpenProcess(PROCESS_ALL_ACCESS, False, Pid);
end;

procedure ExecuteProcessAsLoggedOnUser(FileName: string);
var
  ph: THandle;
  hToken, nToken: THandle;
  ProcInfo: TProcessInformation;
  StartInfo: TStartupInfo;
begin
  ph := GetShellHandle;
  if ph > 0 then
  begin
    if OpenProcessToken(ph, TOKEN_DUPLICATE or TOKEN_QUERY, hToken) then
    begin
      if DuplicateTokenEx(hToken, TOKEN_ASSIGN_PRIMARY or TOKEN_DUPLICATE or
        TOKEN_QUERY, nil, SecurityImpersonation, TokenPrimary, nToken) then
      begin
        if ImpersonateLoggedOnUser(nToken) then
        begin
          // Initialize then STARTUPINFO structure
          FillChar(StartInfo, SizeOf(TStartupInfo), 0);
          StartInfo.cb := SizeOf(TStartupInfo);
          // Specify that the process runs in the interactive desktop
          StartInfo.lpDesktop := PChar('WinSta0\Default');

          // Launch the process in the client's logon session
          CreateProcessAsUser(nToken, nil, PChar(FileName), nil, nil, False,
            CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartInfo,
            ProcInfo);

          // End impersonation of client
          RevertToSelf();
        end;
        CloseHandle(nToken);
      end;
      CloseHandle(hToken);
    end;
  end;
end;

The code works fine for an "empty" program. So I drop TVirtualExpolorerTreeview onto the form of my program. if I start my service then there will be an error when the program is being called. I guess the program can't enumerate PIDL or blabla (I don't know much about Windows Shell). How do I force the program so it can run normally?


问:
How to configure an app service that only needs to be up-and-running a few days per month
I have a Web API Core app that only needs to run for a few days per month.  I'd like to only have it incurring costs in Azure for the few days that I run it per month.  How can this be achieved?</p>

答: Even if you "Stop" the App Service, you will be charged as per your plan. So you can have the App Service in the Free Tier. But you cannot have the features like Custom Domain, Backups etc.</p>


问:
How to fix 'ImportError: DLL load failed: The specified procedure could not be found.' while importing tensorflow-gpu?
I cannot import tensorflow-gpu==1.13.1 on python 3.6.0.

What i have already done:

Nvidia's drivers (i have GEFORCE 840M which is cuda supported with compute capability 5.0).

I installed Visual Studio 2017 Professional (did not select any specifications in workload).

I installed CUDA 10.1 (was having issues with Visual studio integration so i disabled it during the installation).

I pasted Cudnn 7.5.0 onto cuda's folders.

Restarted.

Pip installed tensorflow-gpu==1.13.1 on python 3.6.0.

but then i cannot import tensorflow at all it shows the error below.

```<code>>>> import tensorflow as tf
Traceback (most recent call last):
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
>>>
</code>```

Goal:
Obviously being able to import tensorflow and to import keras from the tensorflow library.

答:
In my case this was an issue with detecting the correct CUDA Toolkit/cuDNN version with tensorflow-gpu==1.13.1.

After spending 2 hours on this I installed CUDA Toolkit 10.0 and set TF_CUDA_VERSION environment variable explicitly to 10 in the user env settings (Windows 10).

Body:
I cannot import tensorflow-gpu==1.13.1 on python 3.6.0.

What i have already done:

Nvidia's drivers (i have GEFORCE 840M which is cuda supported with compute capability 5.0).

I installed Visual Studio 2017 Professional (did not select any specifications in workload).

I installed CUDA 10.1 (was having issues with Visual studio integration so i disabled it during the installation).

I pasted Cudnn 7.5.0 onto cuda's folders.

Restarted.

Pip installed tensorflow-gpu==1.13.1 on python 3.6.0.

but then i cannot import tensorflow at all it shows the error below.

>>> import tensorflow as tf
Traceback (most recent call last):
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Users\BenBouali\AppData\Local\Programs\Python\Python36\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
>>>

Goal:
Obviously being able to import tensorflow and to import keras from the tensorflow library.


问:
Do not want to pass all unnecessary parameters in stored Procedure
i have a stroed procedure having two events one is insertion and another one is deletion
using flag. when i have to delete ..i have to pass all parameters which is not actually need while delete.... i need your help to sort it out .

my code is like this..

```<code>ALTER     Proc Proc_Manage_Opening_Leave @ActionFlag int,@SNo int,@LEAVE_ID int,@GIVEN decimal,@GIVENMONTH int,@GIVENYEAR int,@APPROVEDBY int,@IsOpening varchar(6),@EMP_ID int
as
SET NOCOUNT ON
if(@ActionFlag=0)
BEGIN

insert into Tbl_Org_leave_log (EMP_ID,LEAVE_ID,GIVEN,GIVENMONTH,GIVENYEAR,ApprovedBy,OP_FLAG,GIVENDAY)
values(@EMP_ID,@LEAVE_ID,@GIVEN,@GIVENMONTH,@GIVENYEAR,@APPROVEDBY,
(
case
when @IsOpening='False' then 0
when @IsOpening='True' then 1
ELSE NULL
END
),
datepart(day,getdate()))
END

 IF(@ActionFlag=1)
BEGIN

delete from tbl_org_leave_log where SNo=@SNo
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
</code>```

答:
Change your parameters to have default values like so:

```<code>alter     proc Proc_Manage_Opening_Leave
  @ActionFlag int
 ,@SNo int = null
 ,@LEAVE_ID int = null
 ,@GIVEN decimal = null
 ,@GIVENMONTH int = null
 ,@GIVENYEAR int = null
 ,@APPROVEDBY int = null
 ,@IsOpening varchar(6) = null
 ,@EMP_ID int = null
as
</code>```

Then you don't need to provide values for them.

But I agree with Akram that you should make two separate procedures

Body:
i have a stroed procedure having two events one is insertion and another one is deletion
using flag. when i have to delete ..i have to pass all parameters which is not actually need while delete.... i need your help to sort it out .

my code is like this..

ALTER     Proc Proc_Manage_Opening_Leave @ActionFlag int,@SNo int,@LEAVE_ID int,@GIVEN decimal,@GIVENMONTH int,@GIVENYEAR int,@APPROVEDBY int,@IsOpening varchar(6),@EMP_ID int
as
SET NOCOUNT ON
if(@ActionFlag=0)
BEGIN

insert into Tbl_Org_leave_log (EMP_ID,LEAVE_ID,GIVEN,GIVENMONTH,GIVENYEAR,ApprovedBy,OP_FLAG,GIVENDAY)
values(@EMP_ID,@LEAVE_ID,@GIVEN,@GIVENMONTH,@GIVENYEAR,@APPROVEDBY,
(
case
when @IsOpening='False' then 0
when @IsOpening='True' then 1
ELSE NULL
END
),
datepart(day,getdate()))
END

 IF(@ActionFlag=1)
BEGIN

delete from tbl_org_leave_log where SNo=@SNo
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

Body:
Change your parameters to have default values like so:

alter     proc Proc_Manage_Opening_Leave
  @ActionFlag int
 ,@SNo int = null
 ,@LEAVE_ID int = null
 ,@GIVEN decimal = null
 ,@GIVENMONTH int = null
 ,@GIVENYEAR int = null
 ,@APPROVEDBY int = null
 ,@IsOpening varchar(6) = null
 ,@EMP_ID int = null
as

Then you don't need to provide values for them.

But I agree with Akram that you should make two separate procedures


问:
How to update certain tuples after deletion in a table
I am trying to model a music streaming service data base in SQLite and I want to create this trigger: When a song is deleted from a playlist, every song that came after it needs to have its position decremented. I'm not really sure how to write this trigger.

Here is an example of the playlist's table (Sorry for the portuguese names. idMusica = Song ID; posicao = song's position in the playlist)

To further explain what I want here's an example:
If I delete song 6 from playlist 1, the position of song 11 would become 3.

答:
I believe that the following will do as you wish :-

```<code>CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;
</code>```

Note that the table names has been assumed to be playlist

Example

Consider the following test :-

```<code>DROP TABLE IF EXISTS playlist;
CREATE TABLE IF NOT EXISTS playlist (idMusica INTEGER, idPlayList INTEGER, posicao INTEGER);
INSERT INTO playlist (idMusica,idPlayList, posicao) VALUES
    (12,1,1),(5,1,2),(6,1,3),(11,1,4),
    (1,2,1),(2,2,2),(3,2,2),(4,2,4),(9,2,5)
;

CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;
SELECT * FROM playlist;
DELETE FROM playlist WHERE posicao = 3 AND idplayList = 1;
SELECT * FROM playlist;
</code>```

Example results

Before reorder (1st Query) :-

After reorder (2nd Query) :-

Body:
I believe that the following will do as you wish :-

CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;

Note that the table names has been assumed to be playlist

Example

Consider the following test :-

DROP TABLE IF EXISTS playlist;
CREATE TABLE IF NOT EXISTS playlist (idMusica INTEGER, idPlayList INTEGER, posicao INTEGER);
INSERT INTO playlist (idMusica,idPlayList, posicao) VALUES
    (12,1,1),(5,1,2),(6,1,3),(11,1,4),
    (1,2,1),(2,2,2),(3,2,2),(4,2,4),(9,2,5)
;

CREATE TRIGGER IF NOT EXISTS playlistreorder
    AFTER DELETE ON playlist
    BEGIN
        UPDATE playlist SET posicao = posicao -1 WHERE posicao > old.posicao AND idPlayList = old.idPlayList;
    END
;
SELECT * FROM playlist;
DELETE FROM playlist WHERE posicao = 3 AND idplayList = 1;
SELECT * FROM playlist;

Example results

Before reorder (1st Query) :-

After reorder (2nd Query) :-


问:
Best Way to manage AWS Access key ? So that when an employee leave the company . The employ should not be able to access the AWS account
I want to know a way .

Assume there is an organization . There are many team which are using the EC2 resource and all the user have key that is required for the EC2 and now the employee leave the company . But he still have that Access key using which he can access it .

is there any best way to handle . AWS account permission so that when employee leave the company the access to aws account is denied .

答:
The way I see it, only your root user should have root permissions in EC2 and should have to login using Key Pair, for any other employees one way is(and this is what I think is best for everyone)-

Create users for them inside EC2 (Don't give them root permission)

Create keyless entries with password authentication for those users.(Make sure you only allow "PasswordAuthentication yes" for your particular user that you might delete later)

Delete user when they leave

Here's a way to do Key-pair-less login:
SSH to AWS Instance without key pairs


问:
Firebase function, get hashmap data from onCall
I have a problem how i receive and use hashmaps in firebase function. I see the data being sent properly. But using it is a problem.

How i send the data from the Android platform

```<code>fun onStartChatClicked() {
    val functions = FirebaseFunctions.getInstance()
    val map = HashMap<String, String>()

    usersToChatWith.forEach {
        map.put(it.userId!!, it.username!!)
    }

    functions.getHttpsCallable("startChatWithUsers")
        .call(map)
        .continueWith {task ->
               if (task.isSuccessful) {

               } else {

               }
        }
}
</code>```

I have also tried it with hashMapOf() function. Just in case :P

When i just print the receive data in the firebase function. I do get it like some typical Json string

```<code>{ '3SYIpex6u1Mx31j1UUngKAy95hq2': 'user1', JgoKrekU6nNusxeMBr6JAjkCReX2: 'user2' }
</code>```

Simplified firebase function code

```<code>export const startChatWithUsers = functions.https.onCall(async (data , context) => {

        /** A little code */

        for (let [userId, username] of data) {
            /** some code */
        }

       /** Some more code */

    })
</code>```

The problem lies in the function not being able to loop through the data given. Because if i understood it correctly. It does not think the data given is a map.

答:
Based on the code in your question, it looks like you are trying to iterate on an object by getting the key-value pair of each entry in the object.

However, you’ve left out the entries() call that’s needed to turn the object into a collection of key-value pairs.

Try this for your for loop:

```<code>for (let [userId, username] of data.entries()) {
  /** some code */
}
</code>```

Body:
I have a problem how i receive and use hashmaps in firebase function. I see the data being sent properly. But using it is a problem.

How i send the data from the Android platform

fun onStartChatClicked() {
    val functions = FirebaseFunctions.getInstance()
    val map = HashMap<String, String>()

    usersToChatWith.forEach {
        map.put(it.userId!!, it.username!!)
    }

    functions.getHttpsCallable("startChatWithUsers")
        .call(map)
        .continueWith {task ->
               if (task.isSuccessful) {

               } else {

               }
        }
}

I have also tried it with hashMapOf() function. Just in case :P

When i just print the receive data in the firebase function. I do get it like some typical Json string

{ '3SYIpex6u1Mx31j1UUngKAy95hq2': 'user1', JgoKrekU6nNusxeMBr6JAjkCReX2: 'user2' }

Simplified firebase function code

export const startChatWithUsers = functions.https.onCall(async (data , context) => {

        /** A little code */

        for (let [userId, username] of data) {
            /** some code */
        }

       /** Some more code */

    })

The problem lies in the function not being able to loop through the data given. Because if i understood it correctly. It does not think the data given is a map.

Body:
Based on the code in your question, it looks like you are trying to iterate on an object by getting the key-value pair of each entry in the object.

However, you’ve left out the entries() call that’s needed to turn the object into a collection of key-value pairs.

Try this for your for loop:

for (let [userId, username] of data.entries()) {
  /** some code */
}


问:
ng2-smart-table create button not working correctly
I am getting data from firebase and displaying it with ng2-smart-table.

However, the add dialog doesn't close after I add the data. It's still opened with the values that were added.

Here's my code:

settings = {
    pager:{perPage:50},
    add: {
        addButtonContent: '',
        createButtonContent: '',
        cancelButtonContent: '',
        confirmCreate: true,
    },
```

<p>The function to create:</p>

<pre class="lang-ts prettyprint-override"><code>onCreateConfirm(event): any {
    //this service is updating the new data to firebase.
    this.service.createData(event.newData);
    //after that the newdata still on edit mode and not closing it...
}
</code>```

答:
Finally i get the solution by trying many times and this code work for me

First, you read you data once by using firebase or angularfire2 for example

```<code>  this.user.take(1).subscribe(response => {
  response.forEach(item=>{
    this.data.push({
      id:this.i++,
      firstName: item.subs_name,
      lastName: item.subs_info,
      email: item.subs_price,
      username: item.subs_storage
    });
  })
  this.source.load(this.data);
});
</code>```

Second, you update the data in onSaveConfirm method

```<code>onSaveConfirm(event): void  {
 if (window.confirm('Are you sure you want to make a changes?')) {
  event.confirm.resolve();
  this.database.object(`subscription/${event.newData.id}`).update({
    subs_name: event.newData.firstName,
    subs_info: event.newData.lastName,
    subs_price: event.newData.email,
    subs_storage: event.newData.username
   })
  } else {
   event.confirm.reject();
  }
}
</code>```

By doing like this in the system will show you the dummy data while if you make a changes it will save in you firebase

It's work for me i hope it will work for you too

Body:
I am getting data from firebase and displaying it with ng2-smart-table.

However, the add dialog doesn't close after I add the data. It's still opened with the values that were added.

Here's my code:

settings = {
    pager:{perPage:50},
    add: {
        addButtonContent: '',
        createButtonContent: '',
        cancelButtonContent: '',
        confirmCreate: true,
    },

The function to create:

onCreateConfirm(event): any {
    //this service is updating the new data to firebase.
    this.service.createData(event.newData);
    //after that the newdata still on edit mode and not closing it...
}

Body:
Finally i get the solution by trying many times and this code work for me

First, you read you data once by using firebase or angularfire2 for example

  this.user.take(1).subscribe(response => {
  response.forEach(item=>{
    this.data.push({
      id:this.i++,
      firstName: item.subs_name,
      lastName: item.subs_info,
      email: item.subs_price,
      username: item.subs_storage
    });
  })
  this.source.load(this.data);
});

Second, you update the data in onSaveConfirm method

onSaveConfirm(event): void  {
 if (window.confirm('Are you sure you want to make a changes?')) {
  event.confirm.resolve();
  this.database.object(`subscription/${event.newData.id}`).update({
    subs_name: event.newData.firstName,
    subs_info: event.newData.lastName,
    subs_price: event.newData.email,
    subs_storage: event.newData.username
   })
  } else {
   event.confirm.reject();
  }
}

By doing like this in the system will show you the dummy data while if you make a changes it will save in you firebase

It's work for me i hope it will work for you too


问:
How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?
I have a type:

```<code>type tSelectProtected = {
  handleSelector?: string,
  data?: tSelectDataItem[],

  wrapperEle?: HTMLElement,
  inputEle?: HTMLElement,
  listEle?: HTMLElement,
  resultEle?: HTMLElement,

  maxVisibleListItems?: number
}
</code>```

I declare a global module-wise variable:

```<code>var $protected : tSelectProtected = {};
</code>```

I'm assigning proper value in function1() scope:

```<code>$protected.listEle = document.createElement('DIV');
</code>```

Later in function2() scope, I'm calling:

```<code>$protected.listEle.classList.add('visible');
</code>```

I'm getting TypeScript error:

```<code>error TS2533: Object is possibly 'null' or 'undefined'
</code>```

I know that I can do explicit check using if ($protected.listEle) {$protected.listEle} to calm down compiler but this seems to be very unhandy for most non trivial cases.

How this situation can or should be handled without disabling TS compiler checks?

答:
I ran in to this with React when setting state and using map.

In this case I was making an API fetch call and the value of the response wasn't known, but should have a value "Answer". I used a custom type for this, but because the value could be null, I got a TS error anyway. Allowing the type to be null doesn't fix it; alternatively you could use a default parameter value, but this was messy for my case.

I overcame it by providing a default value in the event the response was empty by just using a ternary operator:

this.setState({ record: (response.Answer) ? response.Answer : [{ default: 'default' }] });
```

Body:
I have a type:

type tSelectProtected = {
  handleSelector?: string,
  data?: tSelectDataItem[],

  wrapperEle?: HTMLElement,
  inputEle?: HTMLElement,
  listEle?: HTMLElement,
  resultEle?: HTMLElement,

  maxVisibleListItems?: number
}

I declare a global module-wise variable:

var $protected : tSelectProtected = {};

I'm assigning proper value in function1() scope:

$protected.listEle = document.createElement('DIV');

Later in function2() scope, I'm calling:

$protected.listEle.classList.add('visible');

I'm getting TypeScript error:

error TS2533: Object is possibly 'null' or 'undefined'

I know that I can do explicit check using if ($protected.listEle) {$protected.listEle} to calm down compiler but this seems to be very unhandy for most non trivial cases.

How this situation can or should be handled without disabling TS compiler checks?


问:
How to delete or modify hooks with Bitbucket API? I only see GET and POST
https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/hooks

I only see GET and POST verbs for hook events on Bitbucket. Is there a way to delete or modify them somehow?

答: Yes. Just append /{uid} after /hooks, and you get actions to operate on individual ones. See https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/hooks/%7Buid%7D for documentation on them.


问:
Calling a class having its name as a string
I have a string which specifies the name of the call.
How can i call the particular class by using this string.am trying this in java.
A function will return me a list of strings which are class names.now task is to make a call to a  class by using this string.</p>

答:
You can do this using this code:

```<code>Class clazz = Class.forName(yourString);
</code>```

As the class name you should use the full class name including packages. But you can't call a class. You can initialize a class and then call a method of this class.

http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#forName(java.lang.String

Body:
You can do this using this code:

Class clazz = Class.forName(yourString);

As the class name you should use the full class name including packages. But you can't call a class. You can initialize a class and then call a method of this class.

http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#forName(java.lang.String


问:
What is the advantage of using $"col" over "col" in spark data frames
Let us say I've a DF created as follows

```<code>  val posts = spark.read
    .option("rowTag","row")
    .option("attributePrefix","")
    .schema(Schemas.postSchema)
    .xml("src/main/resources/Posts.xml")
</code>```

What is the advantage of converting it to a Column using posts.select("Id") over posts.select($"Id")

答:
There is not much difference but some functionalities can be used only using $ with the column name.

Example : When we want to sort the value in this column, without using $ prior to column name, it will not work.

Window.orderBy("Id".desc)

But if you use $ before column name, it works.

Window.orderBy($"Id".desc)

Body:
Let us say I've a DF created as follows

  val posts = spark.read
    .option("rowTag","row")
    .option("attributePrefix","")
    .schema(Schemas.postSchema)
    .xml("src/main/resources/Posts.xml")

What is the advantage of converting it to a Column using posts.select("Id") over posts.select($"Id")


问:
Debugging HTTP::Tiny
I am using HTTP::Tiny to interact with rest api below an example :

```<code>my $req = $ua->get('https://myapi.com/user?xyz', {headers =>

     {token => 'xyzzz',
      data => '5343'.

     }});
</code>```

i am using Data::Dumper to see the response header and body

```<code>print Dumper($req); -#i can see the response
</code>```

is there an option to see also the HTTP request i am sending using HTTP::Tiny ,without the need of other tool like wireshark etc..
something like what mojo::useragent achieve with MOJO_CLIENT_DEBUG=1 any idea?

答:
I don't see such a feature mentioned in the HTTP::Tiny documentation, nor do I see it facilitated in the source code for the module. However, you can use a module such as Test::MockModule to get a closer look at what is going on. Here is an example:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

use HTTP::Tiny;
use Test::MockModule;
use Data::Dumper;

my $t = HTTP::Tiny->new();

my $mock = Test::MockModule->new('HTTP::Tiny');

$mock->redefine('_request' => sub {
    warn "In _request: ", Dumper {self => $_[0], method => $_[1], url => $_[2], args => $_[3]};
    return $mock->original('_request')->(@_);
});

print "Response: ", Dumper $t->get('http://localhost:3000');
</code>```

So in this snippet we are mocking _request, but the mock method we install in behalf of _request calls out to the original _request method, so our mocked method becomes a wrapper around the original method, and we can dump the underlying object and args passed into the method. I'm doing the dump prior to the request being made, but I could have done the initial dump, captured the return value of the real request, and then dump the object again afterward if I thought it might contain additional useful information. So long as we return the actual response, the calling code is none the wiser.

Here's an example of the output. The URL I'm hitting is just a default Mojolicious::Lite app.

```<code>In _request: $VAR1 = {
          'method' => 'GET',
          'self' => bless( {
                             'agent' => 'HTTP-Tiny/0.076',
                             'no_proxy' => [],
                             'max_redirect' => 5,
                             'keep_alive' => 1,
                             'verify_SSL' => 0,
                             'timeout' => 60
                           }, 'HTTP::Tiny' ),
          'args' => {},
          'url' => 'http://localhost:3000'
        };
Response: $VAR1 = {
          'headers' => {
                         'content-length' => '146',
                         'content-type' => 'text/html;charset=UTF-8',
                         'server' => 'Mojolicious (Perl)',
                         'date' => 'Sun, 26 May 2019 03:19:57 GMT'
                       },
          'protocol' => 'HTTP/1.1',
          'reason' => 'OK',
          'url' => 'http://localhost:3000',
          'success' => 1,
          'status' => '200',
          'content' => '<!DOCTYPE html>
<html>
  <head><title>Welcome</title></head>
  <body><h1>Welcome to the Mojolicious real-time web framework!</h1>
</body>
</html>
'
        };
</code>```

Before I was able to know that _request was where I wanted to target my mock, I had to look at the source code for HTTP::Tiny. Fortunately the ::Tiny part of the module means there's not a whole lot to look at. It's really a relatively simple module.

You may decide that for your own purposes it makes more sense to introduce your wrapper at some other point in HTTP::Tiny, but wrapping _request seems like a pretty good choice for most cases.

Title: Debugging HTTP::Tiny

Body:
I am using HTTP::Tiny to interact with rest api below an example :

my $req = $ua->get('https://myapi.com/user?xyz', {headers =>

     {token => 'xyzzz',
      data => '5343'.

     }});

i am using Data::Dumper to see the response header and body

print Dumper($req); -#i can see the response

is there an option to see also the HTTP request i am sending using HTTP::Tiny ,without the need of other tool like wireshark etc..
something like what mojo::useragent achieve with MOJO_CLIENT_DEBUG=1 any idea?

Body:
I don't see such a feature mentioned in the HTTP::Tiny documentation, nor do I see it facilitated in the source code for the module. However, you can use a module such as Test::MockModule to get a closer look at what is going on. Here is an example:

#!/usr/bin/env perl

use strict;
use warnings;

use HTTP::Tiny;
use Test::MockModule;
use Data::Dumper;

my $t = HTTP::Tiny->new();

my $mock = Test::MockModule->new('HTTP::Tiny');

$mock->redefine('_request' => sub {
    warn "In _request: ", Dumper {self => $_[0], method => $_[1], url => $_[2], args => $_[3]};
    return $mock->original('_request')->(@_);
});

print "Response: ", Dumper $t->get('http://localhost:3000');

So in this snippet we are mocking _request, but the mock method we install in behalf of _request calls out to the original _request method, so our mocked method becomes a wrapper around the original method, and we can dump the underlying object and args passed into the method. I'm doing the dump prior to the request being made, but I could have done the initial dump, captured the return value of the real request, and then dump the object again afterward if I thought it might contain additional useful information. So long as we return the actual response, the calling code is none the wiser.

Here's an example of the output. The URL I'm hitting is just a default Mojolicious::Lite app.

In _request: $VAR1 = {
          'method' => 'GET',
          'self' => bless( {
                             'agent' => 'HTTP-Tiny/0.076',
                             'no_proxy' => [],
                             'max_redirect' => 5,
                             'keep_alive' => 1,
                             'verify_SSL' => 0,
                             'timeout' => 60
                           }, 'HTTP::Tiny' ),
          'args' => {},
          'url' => 'http://localhost:3000'
        };
Response: $VAR1 = {
          'headers' => {
                         'content-length' => '146',
                         'content-type' => 'text/html;charset=UTF-8',
                         'server' => 'Mojolicious (Perl)',
                         'date' => 'Sun, 26 May 2019 03:19:57 GMT'
                       },
          'protocol' => 'HTTP/1.1',
          'reason' => 'OK',
          'url' => 'http://localhost:3000',
          'success' => 1,
          'status' => '200',
          'content' => '<!DOCTYPE html>
<html>
  <head><title>Welcome</title></head>
  <body><h1>Welcome to the Mojolicious real-time web framework!</h1>
</body>
</html>
'
        };

Before I was able to know that _request was where I wanted to target my mock, I had to look at the source code for HTTP::Tiny. Fortunately the ::Tiny part of the module means there's not a whole lot to look at. It's really a relatively simple module.

You may decide that for your own purposes it makes more sense to introduce your wrapper at some other point in HTTP::Tiny, but wrapping _request seems like a pretty good choice for most cases.


问:
How to check in console selected nav?
How to check the selected navigation by console.log

```<code>export const navItems: NavData[] = [
  {
    name: 'Book #1',
    url: '/book',
    icon: 'fa fa-book',
    children: [{
      name: 'Book #2',
      url: '/book',
      icon: 'fa fa-pencil'
    },{
      name: 'Shopping Plan',
      url: '/plan',
      icon: 'fa fa-shopping-cart',
    }]
  }
]
</code>```

If I click Shopping Plan in sideNav, at console showing "Shopping Plan". Or if I click Book #2, at console showing "Book #2".
In other words, how to console the selected navigation?

This is the HTML:

```<code>  <app-sidebar [fixed]="true" [display]="'lg'">
    <app-sidebar-nav [navItems]="navItems" [perfectScrollbar] [disabled]="sidebarMinimized"></app-sidebar-nav>
    <app-sidebar-minimizer></app-sidebar-minimizer>
  </app-sidebar>
</code>```

答:
I make HTML like below (assign a (click))

```<code><app-sidebar-nav
  [navItems]="navItems"
  [perfectScrollbar]
  [disabled]="sidebarMinimized"
  (click)="onItemClick($event)">
</app-sidebar-nav>
</code>```

And add function in typescript

```<code>  onItemClick(e){
    console.log(e.srcElement.innerText);
  }
</code>```

Title: How to check in console selected nav?

Body:
How to check the selected navigation by console.log

export const navItems: NavData[] = [
  {
    name: 'Book #1',
    url: '/book',
    icon: 'fa fa-book',
    children: [{
      name: 'Book #2',
      url: '/book',
      icon: 'fa fa-pencil'
    },{
      name: 'Shopping Plan',
      url: '/plan',
      icon: 'fa fa-shopping-cart',
    }]
  }
]

If I click Shopping Plan in sideNav, at console showing "Shopping Plan". Or if I click Book #2, at console showing "Book #2".
In other words, how to console the selected navigation?

This is the HTML:

  <app-sidebar [fixed]="true" [display]="'lg'">
    <app-sidebar-nav [navItems]="navItems" [perfectScrollbar] [disabled]="sidebarMinimized"></app-sidebar-nav>
    <app-sidebar-minimizer></app-sidebar-minimizer>
  </app-sidebar>

Body:
I make HTML like below (assign a (click))

<app-sidebar-nav
  [navItems]="navItems"
  [perfectScrollbar]
  [disabled]="sidebarMinimized"
  (click)="onItemClick($event)">
</app-sidebar-nav>

And add function in typescript

  onItemClick(e){
    console.log(e.srcElement.innerText);
  }