问:
How to avoid query taking long time when adding new node to cluster
I found query (just a simple select query) takes long time when adding a new node to cluster.

My execution time log :

```<code>
17:49:40.008 [ThreadPoolTaskScheduler-14] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 8 ms
17:50:00.010 [ThreadPoolTaskScheduler-3] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 15010 ms
17:50:15.008 [ThreadPoolTaskScheduler-4] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 10008 ms
17:50:20.008 [ThreadPoolTaskScheduler-16] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 7 ms

</code>```

Normally it takes about 10ms, and suddently takes 15000ms when adding node.

And I found it stuck because waiting for new node init data

Cassandra log (the new node):

```<code>INFO  [HANDSHAKE-/194.187.1.52] 2019-05-31 17:49:36,056 OutboundTcpConnection.java:560 - Handshaking version with /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,059 Gossiper.java:1055 - Node /194.187.1.52 is now part of the cluster
INFO  [RequestResponseStage-1] 2019-05-31 17:49:36,069 Gossiper.java:1019 - InetAddress /194.187.1.52 is now UP
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [MigrationStage:1] 2019-05-31 17:49:39,347 ViewManager.java:137 - Not submitting build tasks for views in keyspace system_traces as storage service is not initialized
INFO  [MigrationStage:1] 2019-05-31 17:49:39,352 ColumnFamilyStore.java:411 - Initializing system_traces.events
INFO  [MigrationStage:1] 2019-05-31 17:49:39,382 ColumnFamilyStore.java:411 - Initializing system_traces.sessions

</code>```

Stuck when : Node /194.187.1.52 is now part of the cluster

And client will wait for new node init all data

What I have tried:

```<code>1. I try use consistency with ONE or QUORUM, and is no difference

2. I try turn replication factor to 1, 2 or 3, and still no difference
</code>```

Why new node become part of cluster when that node not init data completely.

Is there a way to solve this.

I expect when I query to old node, the performance is not influenced by just waiting for new node to init data.

.
.
.

I resolved this problem.

I write wrong config, I let all node become seeds even before they joining cluster, this cause read timed-out during adding new node to cluster.

After fix this. all read is normal, but somehow I found insert query timed-out during adding node.

Finally I tune this to avoid insert timed-out:

```<code>/sbin/sysctl -w net.ipv4.tcp_keepalive_time=60 net.ipv4.tcp_keepalive_intvl=60 net.ipv4.tcp_keepalive_probes=5
</code>```

and also change conf to limit throughput

```<code>stream_throughput_outbound_megabits_per_sec : 100
</code>```

Really thanks for help.

答:
That is a behaviour that you can find with too high consistency, or not having enough copies of data (replication factor). When a new node is added to the cluster, a rearrangement of the ownership of tokens occur, once that it is determined what data will the new node be the owner, it will start streaming that data, which may saturate the network.

In your question you don't mention the network setting or if you are using cloud instances, which have a direct impact for these constraints, for example, an AWS m3.large instance will be more restricted in network capabilities than an i3.4xlarge.

Other variable to consider is disk configuration, if you are using your own hardware look for the cap in IO of your drives settings; if you are on the cloud, using the instance storage, when available, will have a better performance than external volumes ( as AWS EBS; if this is the case, ensure that you are enabling the " EBS optimized" option if your instance allows it)

Usually a RF of 3 with consistency level of Quorum should also help you to prevent the issue.

Body:
I found query (just a simple select query) takes long time when adding a new node to cluster.

My execution time log :

17:49:40.008 [ThreadPoolTaskScheduler-14] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 8 ms
17:50:00.010 [ThreadPoolTaskScheduler-3] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 15010 ms
17:50:15.008 [ThreadPoolTaskScheduler-4] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 10008 ms
17:50:20.008 [ThreadPoolTaskScheduler-16] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 7 ms

Normally it takes about 10ms, and suddently takes 15000ms when adding node.

And I found it stuck because waiting for new node init data

Cassandra log (the new node):

INFO  [HANDSHAKE-/194.187.1.52] 2019-05-31 17:49:36,056 OutboundTcpConnection.java:560 - Handshaking version with /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,059 Gossiper.java:1055 - Node /194.187.1.52 is now part of the cluster
INFO  [RequestResponseStage-1] 2019-05-31 17:49:36,069 Gossiper.java:1019 - InetAddress /194.187.1.52 is now UP
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [MigrationStage:1] 2019-05-31 17:49:39,347 ViewManager.java:137 - Not submitting build tasks for views in keyspace system_traces as storage service is not initialized
INFO  [MigrationStage:1] 2019-05-31 17:49:39,352 ColumnFamilyStore.java:411 - Initializing system_traces.events
INFO  [MigrationStage:1] 2019-05-31 17:49:39,382 ColumnFamilyStore.java:411 - Initializing system_traces.sessions

Stuck when : Node /194.187.1.52 is now part of the cluster

And client will wait for new node init all data

What I have tried:

1. I try use consistency with ONE or QUORUM, and is no difference

2. I try turn replication factor to 1, 2 or 3, and still no difference

Why new node become part of cluster when that node not init data completely.

Is there a way to solve this.

I expect when I query to old node, the performance is not influenced by just waiting for new node to init data.

.
.
.

I resolved this problem.

I write wrong config, I let all node become seeds even before they joining cluster, this cause read timed-out during adding new node to cluster.

After fix this. all read is normal, but somehow I found insert query timed-out during adding node.

Finally I tune this to avoid insert timed-out:

/sbin/sysctl -w net.ipv4.tcp_keepalive_time=60 net.ipv4.tcp_keepalive_intvl=60 net.ipv4.tcp_keepalive_probes=5

and also change conf to limit throughput

stream_throughput_outbound_megabits_per_sec : 100

Really thanks for help.


来源: stackexchange

问:
How to lock unwanted hosts out in .htaccess?
Each of the following lines in my .htaccess does not lock out the host hst-123-unwanted.tld

```<code>Require not host unwantedhost.tld
Require not host .unwantedhost.tld
Require not forward-dns unwantedhost.tld
Require not forward-dns .unwantedhost.tld
</code>```

What is wrong?

Thx in advance for your hints.

Additional information to the comment of Bob:

```<code><RequireAll>
        Require any granted
        Require not host amazonaws
        Require not host bezeqint
        Require not host colocrossing
        Require not host metajob
        Require not host drive.dn.ua
        Require not host forthnet
        Require not host hinet
        Require not host kievline
        Require not host kyivstar
</RequireAll>
</code>```

will cause this error message:

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster@my_domain.tld to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache Server at my_domain.tld Port 443

If I change "Require any granted" to "Require all granted" , then the error message disapperars, but the .htaccess does not lock out the unwanted bots.

答:
"require not" cannot be used by itself, it only limits hosts included in a previous require statement.

```<code>Require any granted
Require not host notwanted.tld
</code>```

Should work.

ContentLicense: CC BY-SA 4.0

Body:
Each of the following lines in my .htaccess does not lock out the host hst-123-unwanted.tld

Require not host unwantedhost.tld
Require not host .unwantedhost.tld
Require not forward-dns unwantedhost.tld
Require not forward-dns .unwantedhost.tld

What is wrong?

Thx in advance for your hints.

Additional information to the comment of Bob:

<RequireAll>
        Require any granted
        Require not host amazonaws
        Require not host bezeqint
        Require not host colocrossing
        Require not host metajob
        Require not host drive.dn.ua
        Require not host forthnet
        Require not host hinet
        Require not host kievline
        Require not host kyivstar
</RequireAll>

will cause this error message:

Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at webmaster@my_domain.tld to inform them of the time this error occurred, and the actions you performed just before this error.
More information about this error may be available in the server error log.
Apache Server at my_domain.tld Port 443

If I change "Require any granted" to "Require all granted" , then the error message disapperars, but the .htaccess does not lock out the unwanted bots.

Body:
"require not" cannot be used by itself, it only limits hosts included in a previous require statement.

Require any granted
Require not host notwanted.tld

Should work.


问:
How to do promise.all for array of array of promises?
I am trying to run array of functions parallel and when everybody finishes I want work on that result.
I am using promises. Now, I can put all functions in an array and can do
Promise.all(array of functions)
But I have array like

```<code>[[promise1, promise2], [promise3,promise4], [promise5,promise6]],
</code>```

where each promise is promisified function.
Promise reference document says parameter in Promise.all should be an iterable object and my array is iterable.
But it is not working for me. I think It is executing [promise1, promise2] as a promise but not individual promise.

Can anybody please help me how I can achieve it or is there any better way ?

答:
If you have fixed number of subarrays, I’d suggest to use this simple solution:

const balancePromises = [...];
const symbolPromises = [...];

const [balances, symbols] = await Promise.all([
    Promise.all(balancePromises),
    Promise.all(symbolPromises)
]);
```
<p>Several promises could also be parallelized like this:</p>
<pre class="lang-js prettyprint-override"><code>const [
    balances,
    debt,
    name,
] = await Promise.all([
    this.contract.getBalanceOf(user),
    this.contract.getDebtOf(user),
    this.contract.getNameOf(user),
]);
</code>```

If you have nested arrays of promises - try this:

const nestedResults = await Promise.all(
    nestedPromises.map(promises => Promise.all(promises))
);
```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run array of functions parallel and when everybody finishes I want work on that result.
I am using promises. Now, I can put all functions in an array and can do
Promise.all(array of functions)
But I have array like

[[promise1, promise2], [promise3,promise4], [promise5,promise6]],

where each promise is promisified function.
Promise reference document says parameter in Promise.all should be an iterable object and my array is iterable.
But it is not working for me. I think It is executing [promise1, promise2] as a promise but not individual promise.

Can anybody please help me how I can achieve it or is there any better way ?

Body:
If you have fixed number of subarrays, I’d suggest to use this simple solution:

const balancePromises = [...];
const symbolPromises = [...];

const [balances, symbols] = await Promise.all([
    Promise.all(balancePromises),
    Promise.all(symbolPromises)
]);

Several promises could also be parallelized like this:

const [
    balances,
    debt,
    name,
] = await Promise.all([
    this.contract.getBalanceOf(user),
    this.contract.getDebtOf(user),
    this.contract.getNameOf(user),
]);

If you have nested arrays of promises - try this:

const nestedResults = await Promise.all(
    nestedPromises.map(promises => Promise.all(promises))
);


问:
Parsing time strings like "1h 30min"
Anyone know of a Java library that can parse time strings such as "30min" or "2h 15min" or "2d 15h 30min" as milliseconds (or some kind of Duration object). Can Joda-Time do something like this?

(I have an ugly long method to maintain that does such parsing and would like to get rid of it / replace it with something that does a better job.)

答:
FYI, Just wrote this for hour+ periods, only uses java.time.*, pretty simple to understand and customize for any need;

This version works with strings like; 3d12h, 2y, 9m10d, etc.

import java.time.Duration;
import java.time.Instant;
import java.time.Period;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Locale;
```

<pre class="lang-java prettyprint-override"><code>private static final Pattern periodPattern = Pattern.compile("([0-9]+)([hdwmy])");

public static Long parsePeriod(String period){
    if(period == null) return null;
    period = period.toLowerCase(Locale.ENGLISH);
    Matcher matcher = periodPattern.matcher(period);
    Instant instant=Instant.EPOCH;
    while(matcher.find()){
        int num = Integer.parseInt(matcher.group(1));
        String typ = matcher.group(2);
        switch (typ) {
            case "h":
                instant=instant.plus(Duration.ofHours(num));
                break;
            case "d":
                instant=instant.plus(Duration.ofDays(num));
                break;
            case "w":
                instant=instant.plus(Period.ofWeeks(num));
                break;
            case "m":
                instant=instant.plus(Period.ofMonths(num));
                break;
            case "y":
                instant=instant.plus(Period.ofYears(num));
                break;
        }
    }
    return instant.toEpochMilli();
}

</code>```

Title: Parsing time strings like "1h 30min"

Body:
FYI, Just wrote this for hour+ periods, only uses java.time.*, pretty simple to understand and customize for any need;

This version works with strings like; 3d12h, 2y, 9m10d, etc.

import java.time.Duration;
import java.time.Instant;
import java.time.Period;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Locale;

private static final Pattern periodPattern = Pattern.compile("([0-9]+)([hdwmy])");

public static Long parsePeriod(String period){
    if(period == null) return null;
    period = period.toLowerCase(Locale.ENGLISH);
    Matcher matcher = periodPattern.matcher(period);
    Instant instant=Instant.EPOCH;
    while(matcher.find()){
        int num = Integer.parseInt(matcher.group(1));
        String typ = matcher.group(2);
        switch (typ) {
            case "h":
                instant=instant.plus(Duration.ofHours(num));
                break;
            case "d":
                instant=instant.plus(Duration.ofDays(num));
                break;
            case "w":
                instant=instant.plus(Period.ofWeeks(num));
                break;
            case "m":
                instant=instant.plus(Period.ofMonths(num));
                break;
            case "y":
                instant=instant.plus(Period.ofYears(num));
                break;
        }
    }
    return instant.toEpochMilli();
}


问:
django-import-export assign current user
Trying to assign added_by user while creating an instance and want to create another model instance referring to the current instance

views.py

```<code>class ImportFarmersView(APIView):
    parser_classes = (MultiPartParser,)

    def post(self,request,org_slug=None,format=None,*args,**kwargs):
        serializer=TmpFileUploadSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST)
        entries=serializer.validated_data['file']

        profile_resource=ProfileResource()
        dataset=Dataset()
        imported_data = dataset.load(open(entries.temporary_file_path(),'rb').read(),'xls')
        result = profile_resource.import_data(dataset, dry_run=True)  # Test the data import

        if result.has_errors():
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
        profile_resource.import_data(dataset, dry_run=False)  # Actually import now

        return Response(status=status.HTTP_202_ACCEPTED)
</code>```

resources.py

```<code>class ProfileResource(resources.ModelResource):
    created_at=fields.Field(readonly=True)
    updated_at=fields.Field(readonly=True)
    class Meta:
        model=Profile
        skip_unchange=True
        report_skipped=False
        import_id_fields=('slug','email')
</code>```

Thanks in advance

答:
You can access the current django user in the before_import_row hook on resources.ModelResource. There's a 'user' in **kwarg.

So in your case it would look something like

```<code>class ProfileResource(resources.ModelResource):
    ...
    def before_import_row(self, row, **kwargs):
        row['added_by'] = kwargs['user'].id
</code>```

If you drop a breakpoint() in there and have a look at kwargs you'll see something like this (note that the User record is wrapped in a SimpleLazyObject):

```<code>-> row['added_by'] = kwargs['user'].id
(Pdb) kwargs
{'file_name': 'ImportDatasetWorking.csv', 'user': <SimpleLazyObject: <User:
Kumar>>}
</code>```

Body:
Trying to assign added_by user while creating an instance and want to create another model instance referring to the current instance

views.py

class ImportFarmersView(APIView):
    parser_classes = (MultiPartParser,)

    def post(self,request,org_slug=None,format=None,*args,**kwargs):
        serializer=TmpFileUploadSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(data=serializer.errors,status=status.HTTP_400_BAD_REQUEST)
        entries=serializer.validated_data['file']

        profile_resource=ProfileResource()
        dataset=Dataset()
        imported_data = dataset.load(open(entries.temporary_file_path(),'rb').read(),'xls')
        result = profile_resource.import_data(dataset, dry_run=True)  # Test the data import

        if result.has_errors():
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE)
        profile_resource.import_data(dataset, dry_run=False)  # Actually import now

        return Response(status=status.HTTP_202_ACCEPTED)

resources.py

class ProfileResource(resources.ModelResource):
    created_at=fields.Field(readonly=True)
    updated_at=fields.Field(readonly=True)
    class Meta:
        model=Profile
        skip_unchange=True
        report_skipped=False
        import_id_fields=('slug','email')

Thanks in advance

Body:
You can access the current django user in the before_import_row hook on resources.ModelResource. There's a 'user' in **kwarg.

So in your case it would look something like

class ProfileResource(resources.ModelResource):
    ...
    def before_import_row(self, row, **kwargs):
        row['added_by'] = kwargs['user'].id

If you drop a breakpoint() in there and have a look at kwargs you'll see something like this (note that the User record is wrapped in a SimpleLazyObject):

-> row['added_by'] = kwargs['user'].id
(Pdb) kwargs
{'file_name': 'ImportDatasetWorking.csv', 'user': <SimpleLazyObject: <User:
Kumar>>}


问:
how to fix duplicate entry error in Laravel 5.7?
I am using a user verification system in email with Laravel 5.7 this is working fine. but when I tried to enter the same email with verification form it is generating following massages.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mymail@gmail.com' for key 'users_email_unique' (SQL: insert into `users` (`email`, `name`, `address`, `updated_at`, `created_at`) values (mymail@gmail.com, Banda, Sysney, 2019-05-31 11:32:36, 2019-05-31 11:32:36))

my UserController is like this,

```<code>protected function store(Request $request)
{

    $user = new User;

    $user->email = $request->input('email');
    $user->name = $request->input('name');
    $user->address = $request->input('address');

    $user->save();

    $verifyUser = VerifyUser::create([
        'user_id' => $user->id,
        'token' => str_random(40)
    ]);
}
</code>```

how can fix this problem?

答:
As it seems and also very common, your users table seems to have a UNIQUE INDEX on email so if you try to create an entry with an email which already exists, it is normal to get this error.

I am not sure what exactly you want to do from your question context but I believe if you just want to create a VerifyUser entry, you could use updateOrCreate() for User and go on with VerifyUser logic like so:

```<code>protected function store(Request $request)
{
    $email = $request->input('email');
    $name = $request->input('name');
    $address = $request->input('address');

    $user = User::updateOrCreate(['email' => $email], ['name' => $name, 'address' => $address]);

    $verifyUser = VerifyUser::create([
        'user_id' => $user->id,
        'token' => str_random(40)
    ]);
}
</code>```

I hope it helps

Body:
I am using a user verification system in email with Laravel 5.7 this is working fine. but when I tried to enter the same email with verification form it is generating following massages.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mymail@gmail.com' for key 'users_email_unique' (SQL: insert into `users` (`email`, `name`, `address`, `updated_at`, `created_at`) values (mymail@gmail.com, Banda, Sysney, 2019-05-31 11:32:36, 2019-05-31 11:32:36))

my UserController is like this,

protected function store(Request $request)
{

    $user = new User;

    $user->email = $request->input('email');
    $user->name = $request->input('name');
    $user->address = $request->input('address');

    $user->save();

    $verifyUser = VerifyUser::create([
        'user_id' => $user->id,
        'token' => str_random(40)
    ]);
}

how can fix this problem?

Body:
As it seems and also very common, your users table seems to have a UNIQUE INDEX on email so if you try to create an entry with an email which already exists, it is normal to get this error.

I am not sure what exactly you want to do from your question context but I believe if you just want to create a VerifyUser entry, you could use updateOrCreate() for User and go on with VerifyUser logic like so:

protected function store(Request $request)
{
    $email = $request->input('email');
    $name = $request->input('name');
    $address = $request->input('address');

    $user = User::updateOrCreate(['email' => $email], ['name' => $name, 'address' => $address]);

    $verifyUser = VerifyUser::create([
        'user_id' => $user->id,
        'token' => str_random(40)
    ]);
}

I hope it helps


问:
Is there an easier way to do this in python?
I want to try to find an easier way to do this and I haven't found any way to do it.

This is meant to be a menu that can be written in. I am trying to add personalized messages to the text to further make it human-like, however it seems very long and longer than it should be. sandwich_t is a question asking the user if they want a sandwich, beverage is asking the user if they want a beverage, etc.

if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with no ketchup"
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink no fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink, no fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich, no drink, no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Chasier: You ordered nothing. Why did you come here?"
```

答:
You can not to copy your string dozens of times, but construct it part-by-part:</p>

```<code>string = 'Cashier: In total so far'

if sandwich_t == 'Yes':
    string += ' ordered a '
    string += str(sandwich)
else:
    string += ' you have no sandwich'

if beverage == "Yes":
    string += ' with a '
    string += str(beverage_selection)
    string += ' drink'
else:
    string += 'no drink, '
# ... And another fries, drinks etc etc etc

print string
print "Cashier: In total it will be $", total, "alright?"
print "You: Alright"
</code>```

Body:
You can not to copy your string dozens of times, but construct it part-by-part:

string = 'Cashier: In total so far'

if sandwich_t == 'Yes':
    string += ' ordered a '
    string += str(sandwich)
else:
    string += ' you have no sandwich'

if beverage == "Yes":
    string += ' with a '
    string += str(beverage_selection)
    string += ' drink'
else:
    string += 'no drink, '
# ... And another fries, drinks etc etc etc

print string
print "Cashier: In total it will be $", total, "alright?"
print "You: Alright"


问:
Why/how is an additional variable needed in matching repeated arbitary character with capture groups?
I'm matching a sequence of a repeating arbitrary character, with a minimum length, using a perl6 regex.

After reading through https://docs.perl6.org/language/regexes#Capture_numbers and tweaking the example given, I've come up with this code using an 'external variable':

```<code>#uses an additional variable $c
perl6 -e '$_="bbaaaaawer"; /((.){} :my $c=$0; ($c)**2..*)/ && print $0';

#Output:  aaaaa
</code>```

To aid in illustrating my question only, a similar regex in perl5:

```<code>#No additional variable needed
perl -e ' $_="bbaaaaawer"; /((.)\2{2,})/ && print $1';
</code>```

Could someone enlighten me on the need/benefit of 'saving' $0 into $c and the requirement of the empty {}? Is there an alternative (better/golfed) perl6 regex that will match?

Thanks in advance.

答:
Perl 6 regexes scale up to full grammars, which produce parse trees. Those parse trees are a tree of Match objects. Each capture - named or positional - is either a Match object or, if quantified, an array of Match objects.

This is in general good, but does involve making the trade-off you have observed: once you are on the inside of a nested capturing element, then you are populating a new Match object, with its own set of positional and named captures. For example, if we do:

```<code>say "abab" ~~ /((a)(b))+/
</code>```

Then the result is:

```<code>｢abab｣
 0 => ｢ab｣
  0 => ｢a｣
  1 => ｢b｣
 0 => ｢ab｣
  0 => ｢a｣
  1 => ｢b｣
</code>```

And we can then index:

```<code>say $0;        # The array of the top-level capture, which was quantified
say $0[1];     # The second Match
say $0[1][0];  # The first Match within that Match object (the (a))
</code>```

It is a departure from regex tradition, but also an important part of scaling up to larger parsing challenges.

Body:
I'm matching a sequence of a repeating arbitrary character, with a minimum length, using a perl6 regex.

After reading through https://docs.perl6.org/language/regexes#Capture_numbers and tweaking the example given, I've come up with this code using an 'external variable':

#uses an additional variable $c
perl6 -e '$_="bbaaaaawer"; /((.){} :my $c=$0; ($c)**2..*)/ && print $0';

#Output:  aaaaa

To aid in illustrating my question only, a similar regex in perl5:

#No additional variable needed
perl -e ' $_="bbaaaaawer"; /((.)\2{2,})/ && print $1';

Could someone enlighten me on the need/benefit of 'saving' $0 into $c and the requirement of the empty {}? Is there an alternative (better/golfed) perl6 regex that will match?

Thanks in advance.

Body:
Perl 6 regexes scale up to full grammars, which produce parse trees. Those parse trees are a tree of Match objects. Each capture - named or positional - is either a Match object or, if quantified, an array of Match objects.

This is in general good, but does involve making the trade-off you have observed: once you are on the inside of a nested capturing element, then you are populating a new Match object, with its own set of positional and named captures. For example, if we do:

say "abab" ~~ /((a)(b))+/

Then the result is:

｢abab｣
 0 => ｢ab｣
  0 => ｢a｣
  1 => ｢b｣
 0 => ｢ab｣
  0 => ｢a｣
  1 => ｢b｣

And we can then index:

say $0;        # The array of the top-level capture, which was quantified
say $0[1];     # The second Match
say $0[1][0];  # The first Match within that Match object (the (a))

It is a departure from regex tradition, but also an important part of scaling up to larger parsing challenges.


问:
How do we set state in component while using react final form
I am using react final form to validate my form and it working fine.
I am calling on change handler to set input field state but seems it is not setting the state.How can we achieve it in react final form.

I have tried to pass onchange handler as props in InputType but then react final form validations does not work as intended

```<code>import {Form, Field} from 'react-final-form';
class UserDetails extends Component {

    state = {
      firstName: '',
      lastName: '',
      emailAddress: '',
      password: '',
      confirmPassword: '',
    }

showConsentForm = () =>

     Here I want to get  each field value but they are coming blank.

It looks to me that `setUserDetails` is never getting called using react-final-form

 setUserDetails = (e) => {
      const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
      this.setState({[e.target.name]: value})
    }

render () {
      const {t: translate} = this.props;

      return (
        <Form
          onSubmit={() => this.showConsentForm()}
          render={({handleSubmit, invalid}) => (
            <form onSubmit={handleSubmit}>
              {this.state.showDetailsPage && <div>
                <div className="hw-block hw-block--mb">
                  <h2>{translate('register.heading')}</h2>
                </div>
                <div className="hw-block hw-block--mb">
                  <h4>{translate('register.detailsPageText')}</h4>
                </div>
                <p>{translate('register.firstName')}</p>
                <div className="hw-block hw-block--mb-smaller">
                  <Field type="text" value={this.state.firstName} component={InputType} validate={composeValidators(required, fieldLength(2, 60))}
                    placeholder={translate('register.firstNamePlaceholder')} name="firstName"
                    onChange={(e) => {
                      const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
                      this.setState({[e.target.name]: value})
                    }}/>
                </div>
                <p>{translate('register.surname')}</p>
                <div className="hw-block hw-block--mb-smaller">
                  <Field type="text" value={this.state.lastName}
                    placeholder={translate('register.surnamePlaceHolder')} component={InputType} validate={composeValidators(required, fieldLength(2, 60))}  name="lastName"
                    onChange={(e) => this.setUserDetails(e)}/>
                </div>
                <p>{translate('register.email')}</p>
                <div className="hw-block hw-block--mb-smaller">
                  <Field type="email" value={this.state.emailAddress}
                    placeholder={translate('register.emailPlaceHolder')} component={InputType} validate={composeValidators(required, validateEmail)} name="emailAddress"
                    onChange={(e) => this.setUserDetails(e)}/>
                </div>
                <p>{translate('register.password')}</p>
                <div className="hw-block hw-block--mb-smaller">
                  <div className="hw-password" data-hw-password>
                    <Field type="password" value={this.state.password}
                      placeholder={translate('register.passwordPlaceHolder')} component={InputType} validate={required} name="password"
                      onChange={(e) => this.setUserDetails(e)}/>

                  </div>
                </div>
                <p>{translate('register.confirmPassword')}</p>
                <div className="hw-block hw-block--mb-smaller">
                  <div className="hw-password" data-hw-password>
                    <Field type="password" value={this.state.confirmPassword} component={InputType}
                      placeholder={translate('register.confirmPasswordPlaceHolder')} validate={required}
                      name="confirmPassword" onChange={(e) => this.setUserDetails(e)}/>

                  </div>
                </div>

                <div className="hw-block hw-block--mb-smaller">

                  <label className="hw-checkbox">
                    <p className="hw-text-small">{translate('register.accept')} <a target="_blank"
                      href="https://abcd/etc"
                      className="hw-link">{translate('register.terms')}</a> {translate('register.conditions')}
                    </p>
                    <input type="checkbox" name="acceptTerms" onClick={(e) => this.setUserDetails(e)}/>
                    <i className="hw-checkbox__indicator"></i>
                  </label>
                </div>
                <div className="hw-block hw-block--mb-smaller">
                  <button className="hw-button hw-button--primary" disabled={invalid} >{translate('register.continue')}</button>
                  <button className="hw-button hw-button--secondary secondary-button-margin"
                    onClick={homePage}>{translate('register.cancel')}</button>
                </div>
              </div>}

            </form>)}
        />
      )
    }
}

const InputType = ({
  input,
  type,
  placeholder,
  value,
  meta: { touched, error },
}) => (

  <React.Fragment>
    <input {...input} type={type} value={value} placeholder={placeholder}
      className={(error) ? 'hw-input--error hw-input' : 'hw-input' }/>
    { touched && error &&
        <span className="hw-error">
          {error}
        </span>
    }
  </React.Fragment>
)```
```

答: React Final Form handles all your value storage for you. You shouldn't need to be doing any of this onChange stuff. That's the primary job of React Final Form: to manage your form values so you don't have to be setStateing all the time. It's not really clear to me what you're trying to accomplish, so I can't really help you further. RFF has all of that e.target.type === 'checkbox' logic built in.

Body:
I am using react final form to validate my form and it working fine.
I am calling on change handler to set input field state but seems it is not setting the state.How can we achieve it in react final form.

I have tried to pass onchange handler as props in InputType but then react final form validations does not work as intended

import {Form, Field} from 'react-final-form';
class UserDetails extends Component {

    state = {
      firstName: '',
      lastName: '',
      emailAddress: '',
      password: '',
      confirmPassword: '',
    }

showConsentForm = () =>

     Here I want to get  each field value but they are coming blank.

It looks to me that `setUserDetails` is never getting called using react-final-form

 setUserDetails = (e) => {
      const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
      this.setState({[e.target.name]: value})
    }

render () {
      const {t: translate} = this.props;

      return (
        <Form
          onSubmit={() => this.showConsentForm()}
          render={({handleSubmit, invalid}) => (
            <form onSubmit={handleSubmit}>
              {this.state.showDetailsPage &&

{translate('register.heading')}

{translate('register.detailsPageText')}

{translate('register.firstName')}

                  <Field type="text" value={this.state.firstName} component={InputType} validate={composeValidators(required, fieldLength(2, 60))}
                    placeholder={translate('register.firstNamePlaceholder')} name="firstName"
                    onChange={(e) => {
                      const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
                      this.setState({[e.target.name]: value})
                    }}/>

{translate('register.surname')}

                  <Field type="text" value={this.state.lastName}
                    placeholder={translate('register.surnamePlaceHolder')} component={InputType} validate={composeValidators(required, fieldLength(2, 60))}  name="lastName"
                    onChange={(e) => this.setUserDetails(e)}/>

{translate('register.email')}

                  <Field type="email" value={this.state.emailAddress}
                    placeholder={translate('register.emailPlaceHolder')} component={InputType} validate={composeValidators(required, validateEmail)} name="emailAddress"
                    onChange={(e) => this.setUserDetails(e)}/>

{translate('register.password')}

                    <Field type="password" value={this.state.password}
                      placeholder={translate('register.passwordPlaceHolder')} component={InputType} validate={required} name="password"
                      onChange={(e) => this.setUserDetails(e)}/>

{translate('register.confirmPassword')}

                    <Field type="password" value={this.state.confirmPassword} component={InputType}
                      placeholder={translate('register.confirmPasswordPlaceHolder')} validate={required}
                      name="confirmPassword" onChange={(e) => this.setUserDetails(e)}/>

{translate('register.accept')} {translate('register.terms')} {translate('register.conditions')}

                    <input type="checkbox" name="acceptTerms" onClick={(e) => this.setUserDetails(e)}/>

                  <button className="hw-button hw-button--primary" disabled={invalid} >{translate('register.continue')}</button>
                  <button className="hw-button hw-button--secondary secondary-button-margin"
                    onClick={homePage}>{translate('register.cancel')}</button>

}

            </form>)}
        />
      )
    }
}

const InputType = ({
  input,
  type,
  placeholder,
  value,
  meta: { touched, error },
}) => (

  <React.Fragment>
    <input {...input} type={type} value={value} placeholder={placeholder}
      className={(error) ? 'hw-input--error hw-input' : 'hw-input' }/>
    { touched && error &&

          {error}

    }
  </React.Fragment>
)```


问:
Bootstrap - Progress bar as background in card element
I'm trying to recreate something like the image below (the dark one), that looks like a progress bar in every element of a card. I'm getting close but the problem I have so far is that the text moves with the progress bar.

```<code><div class="card" style="width: 18rem;">
   <ul class="list-group list-group-flush">
    <li class="list-group-item progress-bar bg-success" style="width:40%"><a>Cras justo odio</a></li>
    <li class="list-group-item progress-bar bg-info" style="width:100%">Dapibus ac facilisis in</li>
    <li class="list-group-item progress-bar bg-warning" style="width:10%">Vestibulum at eros</li>
  </ul>
</div>
</code>```

This is the goal, how can I make it?

答:
you just need to add text align to the list item

.list-group-item {
        text-align: left;
    }

Body:
I'm trying to recreate something like the image below (the dark one), that looks like a progress bar in every element of a card. I'm getting close but the problem I have so far is that the text moves with the progress bar.

Cras justo odio

Dapibus ac facilisis in

Vestibulum at eros

This is the goal, how can I make it?


问:
WCF serializing objects with inheritance
Here's what I am trying to do. I have a WCF restful service, and I need to serialize multiple objects that inherit from the same class.

There is nothing in any of the base classes that needs to be serialized.

Here is a minimal demo that shows what I want to get to work:

```<code><DataContract()>
Public Class BaseObj

    <DataMember()>
    Public ID As Integer

    Public Sub New(ByVal idval As Integer)
        ID = idval
    End Sub

End Class

<DataContract()>
Public Class TestObj1
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class

' Different from TestObj1 in real life
<DataContract()>
Public Class TestObj2
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class
</code>```

And here's the code that uses it:

```<code><ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerCall)>
Public Class Service1

    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As List(Of BaseObj)

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))
        Return myObjs

    End Function

End Class
</code>```

If I declare the List to be a list of TestObj1 instead, everything works.

Am I missing some crucial concept here?

EDIT:

The problem gains a new level of confusion by looking at this code:

```<code>    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As BaseObj()

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))

        '   This guy works. Yields correct result of [{"ID":20},{"ID":20}] )
        Dim testStr As String = New JavaScriptSerializer().Serialize(myObjs.ToArray())

        '   But this guy still has problems...
        Return myObjs.ToArray()

    End Function
</code>```

答:
<s>What you are missing is a [KnownType] attribute.</s>

WCF requires a way of knowing all possible types so that it could publish the WSDL.

Have a look here.

UPDATE

The problem is that List<T> is not covariant.

Use IEnumerable<T> instead.

Body:
Here's what I am trying to do. I have a WCF restful service, and I need to serialize multiple objects that inherit from the same class.

There is nothing in any of the base classes that needs to be serialized.

Here is a minimal demo that shows what I want to get to work:

<DataContract()>
Public Class BaseObj

    <DataMember()>
    Public ID As Integer

    Public Sub New(ByVal idval As Integer)
        ID = idval
    End Sub

End Class

<DataContract()>
Public Class TestObj1
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class

' Different from TestObj1 in real life
<DataContract()>
Public Class TestObj2
    Inherits BaseObj

    Public Sub New(ByVal id As Integer)
        MyBase.New(id)
    End Sub

End Class

And here's the code that uses it:

<ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
<ServiceBehavior(InstanceContextMode:=InstanceContextMode.PerCall)>
Public Class Service1

    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As List(Of BaseObj)

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))
        Return myObjs

    End Function

End Class

If I declare the List to be a list of TestObj1 instead, everything works.

Am I missing some crucial concept here?

EDIT:

The problem gains a new level of confusion by looking at this code:

    <WebGet(ResponseFormat:=WebMessageFormat.Json, UriTemplate:="Test?reqReportID={reqReportID}")>
    Public Function GetCollection(ByVal reqReportID As Integer) As BaseObj()

        Dim myObjs As New List(Of BaseObj)
        myObjs.Add(New TestObj1(20))
        myObjs.Add(New TestObj2(20))

        '   This guy works. Yields correct result of [{"ID":20},{"ID":20}] )
        Dim testStr As String = New JavaScriptSerializer().Serialize(myObjs.ToArray())

        '   But this guy still has problems...
        Return myObjs.ToArray()

    End Function


问:
Telling return type of function with multiple possibilities
how could TS know the return type of functions with multiple return type like:

```<code>type VariantA = Variant & {
    a: number,
    b: string,
    c: string[]
}

type VariantB = Variant & {
    e: number,
    f: string,
    g: string[]
}

const CreateObject = (type: 'variantA' | 'variantB') => {
    if (type === 'variantA') {
        return { a: 5, b: 'hello', c: ['a', 'b'] } as VariantA
    } else {
        return { e: 5, f: 'hello', g: ['a', 'b'] } as VariantB
    }
}
</code>```

Here its would be cool if the editor could tell if I pass 'variantA' as type, then the return type is VariantA else VariantB. Is it possible?

答:
You could create two interfaces and the use the Union type a return type.</p>

```<code>interface VariantA{
  a: number,
  b: string,
  c: string[]
}

interface VariantB{
  e: number,
  f: string,
  g: string[]
}

type Variants = VariantA | VariantB;

const createObject = (type: string): Variants => {
  if (type === 'variantA') {
      return { a: 5, b: 'hello im variant A', c: ['a', 'b'] }
  } else {
      return { e: 5, f: 'hello im variant B', g: ['a', 'b'] }
  }
};

const objectA = createObject('variantA');
const objectB = createObject('variantB');
console.log(objectA);
console.log(objectB);
</code>```

Body:
how could TS know the return type of functions with multiple return type like:

type VariantA = Variant & {
    a: number,
    b: string,
    c: string[]
}

type VariantB = Variant & {
    e: number,
    f: string,
    g: string[]
}

const CreateObject = (type: 'variantA' | 'variantB') => {
    if (type === 'variantA') {
        return { a: 5, b: 'hello', c: ['a', 'b'] } as VariantA
    } else {
        return { e: 5, f: 'hello', g: ['a', 'b'] } as VariantB
    }
}

Here its would be cool if the editor could tell if I pass 'variantA' as type, then the return type is VariantA else VariantB. Is it possible?

Body:
You could create two interfaces and the use the Union type a return type.

interface VariantA{
  a: number,
  b: string,
  c: string[]
}

interface VariantB{
  e: number,
  f: string,
  g: string[]
}

type Variants = VariantA | VariantB;

const createObject = (type: string): Variants => {
  if (type === 'variantA') {
      return { a: 5, b: 'hello im variant A', c: ['a', 'b'] }
  } else {
      return { e: 5, f: 'hello im variant B', g: ['a', 'b'] }
  }
};

const objectA = createObject('variantA');
const objectB = createObject('variantB');
console.log(objectA);
console.log(objectB);


问:
Is there a way to pass the object of two different class in one variable in different conditions
I have two classes for language that I want to use at run-time in different conditions.

I want to get both the class's objects in one single variable, as per the condition. However, I am getting an error.

var constantCL = LanguageEnglish()
if languageType == Constants.LoginParameters.LANGUAGE_CODE_ENGLISH {
    constantCL = LanguageEnglish()
} else {
    constantCL = LanguageHindi()
}
```

Getting this error on constantCL = LanguageHindi() in my else:

Cannot assign value of type 'LanguageHindi' to type 'LanguageEnglish'

Screenshot of error:

答:
This is an expected behavior since your language is an actual class, instead of something a bit more flexible.

Possible solutions:

Use a superclass for your languages, e.g.

```<code>class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()
</code>```

Use a protocol instead, and implement it in your language classes (almost the same as above, difference is in implementation and declaration):

```<code>class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()
</code>```

Or maybe use an enum to represent your languages, or a similar more elegant construct if it suits your needs:

```<code>enum Language {
    case english
    case hindi

    // Other useful stuff
}

var constantCL: Language = .english
constantCL = .hindi
</code>```

Body:
I have two classes for language that I want to use at run-time in different conditions.

I want to get both the class's objects in one single variable, as per the condition. However, I am getting an error.

var constantCL = LanguageEnglish()
if languageType == Constants.LoginParameters.LANGUAGE_CODE_ENGLISH {
    constantCL = LanguageEnglish()
} else {
    constantCL = LanguageHindi()
}

Getting this error on constantCL = LanguageHindi() in my else:

Cannot assign value of type 'LanguageHindi' to type 'LanguageEnglish'

Screenshot of error:

Body:
This is an expected behavior since your language is an actual class, instead of something a bit more flexible.

Possible solutions:

Use a superclass for your languages, e.g.

class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()

Use a protocol instead, and implement it in your language classes (almost the same as above, difference is in implementation and declaration):

class LanguageEnglish: Language { }
class LanguageHindi: Language { }

var constantCL: Language = LanguageEnglish()

Or maybe use an enum to represent your languages, or a similar more elegant construct if it suits your needs:

enum Language {
    case english
    case hindi

    // Other useful stuff
}

var constantCL: Language = .english
constantCL = .hindi


问:
Hidden text animation is not working properly
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}</code>```

  <button>
</button>

some text

```

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

答:
You seem to be getting confused between javascript and jquery. However, I don't think ($button.hover) would be a valid condition in either.

button = document.querySelector('button');
textcontent = document.querySelector('.textcontent');
button.addEventListener('mouseover', handlerIn)
button.addEventListener('mouseout', handlerOut)

function handlerIn() {
  textcontent.classList.add('active')
}

function handlerOut() {
  textcontent.classList.remove('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  opacity: 0;
  transition: opacity  0.2s linear;
}

.active {
  opacity: 1;
}</code>```

  <button>
</button>

some text

```

Body:
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}

button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}

  <button>
</button>

some text

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

Body:
You seem to be getting confused between javascript and jquery. However, I don't think ($button.hover) would be a valid condition in either.

button = document.querySelector('button');
textcontent = document.querySelector('.textcontent');
button.addEventListener('mouseover', handlerIn)
button.addEventListener('mouseout', handlerOut)

function handlerIn() {
  textcontent.classList.add('active')
}

function handlerOut() {
  textcontent.classList.remove('active')
}

button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  opacity: 0;
  transition: opacity  0.2s linear;
}

.active {
  opacity: 1;
}

<div>
  <button>
</button>
  <div class="textcontent">
    <p>some text</p>
  </div>
</div>


问:
android c++ undefined reference to eglGetCurrentContext
i am trying to get the current OpenGL context on android in c++.

but i get a compile time error, how can i get the current context?

the error:

```<code>undefined reference to eglGetCurrentContext()
</code>```

the code:

```<code>#include <GLES2/gl2.h>
#include <EGL/egl.h>

void foo()
{
    EGLContext ctx = eglGetCurrentContext();
}
</code>```

答:
You are missing libEGL from your make file library list.

Assuming you are using CMake files, you need something like this in your make file:

```<code># Include libraries needed
target_link_libraries(
            GLESv2
            EGL)
</code>```

Note GLESv2 not needed for this error, but given you include the GLES2 header, it's likely you'll need the GLESv2 library at some point ...

Body:
i am trying to get the current OpenGL context on android in c++.

but i get a compile time error, how can i get the current context?

the error:

undefined reference to eglGetCurrentContext()

the code:

#include <GLES2/gl2.h>
#include <EGL/egl.h>

void foo()
{
    EGLContext ctx = eglGetCurrentContext();
}

Body:
You are missing libEGL from your make file library list.

Assuming you are using CMake files, you need something like this in your make file:

# Include libraries needed
target_link_libraries(
            GLESv2
            EGL)

Note GLESv2 not needed for this error, but given you include the GLES2 header, it's likely you'll need the GLESv2 library at some point ...


问:
constructor overloading between template specialized classes
In the following code I have a class template and its specialization.

template<size_t U>
struct Foo
{
    Foo(double(&u)[U]) : u{ u } {}
    double(&u)[U];
};

template<>
struct Foo<1>
{
    double &u;
    bool specialized = true;
    Foo(double &u) : u{ u } {}
};
```

<p>If I attempt to create an instance with deduced template arguments, then the constructor arguments will only be matched against the generic <code>Foo</code> object.</p>

<pre class="lang-cpp prettyprint-override"><code>double s[7] = { 1, 2, 3, 4, 5, 6, 7 };
Foo f(s); // will deduce s is of type Foo<7>

double t = 5.;
Foo g(t); // no instance matches the argument list!
Foo<1> g(t); // I must explicitly tell it I'm using the specialization
</code>```

Of course, if the specialized class had the same constructor parameters, and I did something like Foo g(t) where t is type double[1], the instance would be of the specialized type.

So, how come the specialized constructor is also not resolved (or otherwise part of the set of constructors) in this case?

答:
Only primary template is considered for Implicitly-generated deduction guides, but you can add deduction guide yourself:

```<code>Foo(double &u) -> Foo<1>;
</code>```

Demo

Notice also that

```<code>double t[1] = {5.};
Foo g(t); // deduce Foo<1>, but fails as specialization doesn't have compatible constructor
</code>```

Body:
In the following code I have a class template and its specialization.

template<size_t U>
struct Foo
{
    Foo(double(&u)[U]) : u{ u } {}
    double(&u)[U];
};

template<>
struct Foo<1>
{
    double &u;
    bool specialized = true;
    Foo(double &u) : u{ u } {}
};

If I attempt to create an instance with deduced template arguments, then the constructor arguments will only be matched against the generic Foo object.

double s[7] = { 1, 2, 3, 4, 5, 6, 7 };
Foo f(s); // will deduce s is of type Foo<7>

double t = 5.;
Foo g(t); // no instance matches the argument list!
Foo<1> g(t); // I must explicitly tell it I'm using the specialization

Of course, if the specialized class had the same constructor parameters, and I did something like Foo g(t) where t is type double[1], the instance would be of the specialized type.

So, how come the specialized constructor is also not resolved (or otherwise part of the set of constructors) in this case?

Body:
Only primary template is considered for Implicitly-generated deduction guides, but you can add deduction guide yourself:

Foo(double &u) -> Foo<1>;

Demo

Notice also that

double t[1] = {5.};
Foo g(t); // deduce Foo<1>, but fails as specialization doesn't have compatible constructor


问:
Searchable JS/Next.js site text extraction
I have a Next.js documentation site at https://logary.tech source, and would like to implement the document search, e.g. with Lunr.

How do I program babel/webpack/nextjs to also extract text (perhaps as a pre-compilation step/babel plugin), into a json file, that I can use for input to Lunr?

答:
I chose to use hgtmlparser2 as part of the build pipeline against the dev server; this if found in the buildIndex.js file.

It outputs pages.json (in this commit you see the stub; browse forward in history for impl) — which is then compiled into the web app.

Then I use LunR to perform the search.

From this commit: https://github.com/logary/logary/commit/d824089e29c8d40624758431f4f58d3ae1433d97


问:
Iterators in C++ (stl) vs Java, is there a conceptual difference?
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

```<code>//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}
</code>```

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

```<code>vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}
</code>```

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

答: Iterators are only equivalent to pointers in the trivial case of iterating over the contents of an array in sequence. An iterator could be supplying objects from any number of other sources: from a database, from a file, from the network, from some other calculation, etc.</p>

OwnerDisplayName: Jeff V

Body:
I'm returning to c++ after being away for a bit and trying to dust off the old melon.

In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed.

//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
    System.out.println(iter.next());
}

In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.

vector<int> vec;
vector<int>::iterator iter;

// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);

for (iter= v.begin(); iter != v.end(); iter++)
{
    cout << *i << " "; //Should output 1 4 8
}

The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.

It there any further subtlety to this that I am missing?

OwnerDisplayName: sadie

ContentLicense: CC BY-SA 2.5


问:
C#, calling an instance of a class from a string
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

```<code>        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;
</code>```

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

答:
First I also thought you mean reflection but you want to use your class StandardVehicle always. Just the properties should be set by a single string you receive from the user.

Write yourself a constructor. You define the format of the single string, for example fixed position within that string:

```<code>public StandardVehicle(String data)
{
    this.Model = data.Substring(0, 1);
    this.HorsePower = Int32.Parse(data.Substring(1, 4);
}
</code>```

Not very comfortable but might work. Add some error handling. Or XML loading or other formats.

Body:
I've been struggling for a while to find a way of calling an instance of a class from a user defined input.

Essentially I want to call an instance from my StandardVehicle class that has already been defined, however the problem is that the name of the instance that I'm calling is defined by a users selection on a combo box on a form.

This is how I assumed it would be formatted, however I get an error when I try calling the instance saying that I cannot complicitly convert from string to StandardVehicle.

        StandardVehicle VauxhallB = new StandardVehicle();
        VauxhallB.Model = "B";
        VauxhallB.Manufacturer = "Vauxhall";
        VauxhallB.Doors = 5;
        VauxhallB.HorsePower = 200;
        VauxhallB.Transmission = "Manual";
        VauxhallB.Year = 2009;
        VauxhallB.Cylinders = 6;
        VauxhallB.Seats = 7;
        VauxhallB.Price = 17000;
        VauxhallB.Registration = "abc1243";

        StandardVehicle objname = comboBox1.Text;

I'm assuming it's just a case of formatting the string, but I've been searching for hours and can't figure out what format it needs to be in to define it as an instance.

Any help would be appreciated.

Regards,
S.

Body:
First I also thought you mean reflection but you want to use your class StandardVehicle always. Just the properties should be set by a single string you receive from the user.

Write yourself a constructor. You define the format of the single string, for example fixed position within that string:

public StandardVehicle(String data)
{
    this.Model = data.Substring(0, 1);
    this.HorsePower = Int32.Parse(data.Substring(1, 4);
}

Not very comfortable but might work. Add some error handling. Or XML loading or other formats.


问:
How to handle users managements with node js and mysql
Is working with node js and mysql is reasonable in android app development ?
because all the tutorials I found is with mongodb and I can't use it because apparently my country is restrict from access it

what I want in my app is  user management and upload images

am coming from php so the user management can easily done with session but how it done here

so will mysql do this for me our should I use something else !?

答:
Ok, MongoDB is a no SQL database you will have some flexibilities there but SQL is more structured and it can be used with nodejs.

The use case is something you should think about. To give you an example suppose the data you are storing is not same for every user then NoSQL(Mongo DB) is preferred but there are ways around to do such things in SQL(MySQL) by normalizing the data.

So, You can use MySQL... In my opinion.

Here is one example you can try...

https://www.w3schools.com/nodejs/nodejs_mysql.asp


问:
Use attribute selector for selecting by class instead of proper class selector
I'm just working on a email html template and I came across this:

*[class=width100pc] { width: 100% !important; }

I've never seen something like this before. Is there a reason of using this syntax for selecting by class instead of just using

.width100pc {width: 100% !important;}

I know that CSS is kind of limited in email clients, is it somehow related to it?

答:
You would use *[class=width100pc] to style any element where width100pc is the only class.

*[class=width100pc] { color: red; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="width100pc">Hello</div>

<div class="width100pc another-class">world!</div></code>```

A standard class selector will apply regardless of other classes.

.width100pc { color: red; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="width100pc">Hello</div>

<div class="width100pc another-class">world!</div></code>```

Body:
You would use *[class=width100pc] to style any element where width100pc is the only class.

*[class=width100pc] { color: red; }

<div class="width100pc">Hello</div>

<div class="width100pc another-class">world!</div>

A standard class selector will apply regardless of other classes.

.width100pc { color: red; }

<div class="width100pc">Hello</div>

<div class="width100pc another-class">world!</div>


问:
Why I get more then one window per key in flink session window
My requirements is to check if both begin and success events in a session. I use session window, of course.But it seems there're overlapped windows per key. I've searched online and couldn't know why.

Data format: myForm(timestamp, roomId, role, sessionId, event), for example:

```<code>myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
myform(1559129977, 456, kid, 38239, begin) # timestamp equals to 2019-05-29 19:39:37
...
</code>```

session may have only one pair of begin and success events, may also several pairs of events of begin and sucess events.

event may arrive late, and is allowed late to maxinum 3 minutes.

My key is roomId + role + sessionId like '123_kid_37890', seesionGap is 60s

// use event time
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val stream = ... // from kafka, steam of myform
val sessionStream = stream
    .assignTimestampsAndWatermarks(new MyFormEventWatermarks(0L))
    .keyBy(mf => mf.roomId + "_" + mf.role + "_" + mf.sessionId)
 .window(EventTimeSessionWindows.withGap(Time.milliseconds(60 * 1000L))
.allowedLateness(Time.minutes(3))
.apply(myFormWindowFunction)

//MyFormEventWatermarks is :
class MyFormEventWatermarks[T <: AbstractForm](dely: Long) extends AssignerWithPeriodicWatermarks[T] {

  private var currentMaxTimestamp = Long.MinValue
  val maxOutOfOrderness = dely

  @transient
  var waterMark : Watermark = null

  override def getCurrentWatermark: Watermark = {
    if (currentMaxTimestamp == Long.MinValue){
      waterMark = new Watermark(Long.MinValue)
      waterMark
    }
    else{
      waterMark = new Watermark(currentMaxTimestamp - maxOutOfOrderness)
      waterMark
    }
  }

  override def extractTimestamp(data: T, previousElementTimestamp: Long): Long = {
    val timestamp = data.timestamp
    currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp)
    timestamp
  }

}

//window func is
class myFormWindowFunction extends RichWindowFunction ... {
    ...
    override def apply(key: String, window: TimeWindow, input: Iterable[myForm], out: Collector[List[myForm]]): Unit = {
        println("window is " + window.getStart() + "-" + window.getEnd() + "|" + data.tostring)

    }
    ...

}
```

<p>In method <code>apply</code> of <code>myFormWindowFunction</code>, results of <code>println</code> like:</p>

```// like this session data:
myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
```

I got a window of 2019-05-29 19:22:22.605- 2019-05-29 19:23:22.605,data is myform(1559128942, 123, kid, 37890, begin), then I got a second window of 2019-05-29 19:22:22.605 - 2019-05-29 19:23:24.844and data is myform(1559128942, 123, kid, 37890, begin), myform(1559128944, 123, kid, 37890, success).
It looks like window initalize to (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605) and (2019-05-29 19:22:24.844, 2019-05-29 19:23:24.844), and onMerge method merged but not 'droped' window (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605). I've looked up the source function of EventTimeSessionWindows and examples of flink session window, and still don't known where program goes wrong?

答:
The default behavior for events assigned to a window during the allowed lateness interval is to trigger the window as each late event is added to the window -- but it's also possible to implement a custom trigger that fires at the expiration of the allowed lateness, either instead of, or in addition to the other firings.

Note that with session windows, an event that arrives late may cause a late merge.

You may want to think about the tradeoffs between the watermarking delay and the allowed lateness. Because your watermark delay is zero, you are likely to have quite a few late events (every time the event stream isn't perfectly in order by timestamp). If instead, for example, you used 3 minutes as the watermark delay and set allowed lateness to zero, then you would produce the same final results, but with no late triggerings and no late merges -- but with 3 minutes of latency before the initial triggering of each window.

Body:
My requirements is to check if both begin and success events in a session. I use session window, of course.But it seems there're overlapped windows per key. I've searched online and couldn't know why.

Data format: myForm(timestamp, roomId, role, sessionId, event), for example:

myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844
myform(1559129977, 456, kid, 38239, begin) # timestamp equals to 2019-05-29 19:39:37
...

session may have only one pair of begin and success events, may also several pairs of events of begin and sucess events.

event may arrive late, and is allowed late to maxinum 3 minutes.

My key is roomId + role + sessionId like '123_kid_37890', seesionGap is 60s

// use event time
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val stream = ... // from kafka, steam of myform
val sessionStream = stream
    .assignTimestampsAndWatermarks(new MyFormEventWatermarks(0L))
    .keyBy(mf => mf.roomId + "_" + mf.role + "_" + mf.sessionId)
 .window(EventTimeSessionWindows.withGap(Time.milliseconds(60 * 1000L))
.allowedLateness(Time.minutes(3))
.apply(myFormWindowFunction)

//MyFormEventWatermarks is :
class MyFormEventWatermarks[T <: AbstractForm](dely: Long) extends AssignerWithPeriodicWatermarks[T] {

  private var currentMaxTimestamp = Long.MinValue
  val maxOutOfOrderness = dely

  @transient
  var waterMark : Watermark = null

  override def getCurrentWatermark: Watermark = {
    if (currentMaxTimestamp == Long.MinValue){
      waterMark = new Watermark(Long.MinValue)
      waterMark
    }
    else{
      waterMark = new Watermark(currentMaxTimestamp - maxOutOfOrderness)
      waterMark
    }
  }

  override def extractTimestamp(data: T, previousElementTimestamp: Long): Long = {
    val timestamp = data.timestamp
    currentMaxTimestamp = Math.max(timestamp, currentMaxTimestamp)
    timestamp
  }

}

//window func is
class myFormWindowFunction extends RichWindowFunction ... {
    ...
    override def apply(key: String, window: TimeWindow, input: Iterable[myForm], out: Collector[List[myForm]]): Unit = {
        println("window is " + window.getStart() + "-" + window.getEnd() + "|" + data.tostring)

    }
    ...

}

In method apply of myFormWindowFunction, results of println like:

// like this session data:
myform(1559128942, 123, kid, 37890, begin) # timestamp equals to 2019-05-29 19:22:22.605
myform(1559128944, 123, kid, 37890, success) # timestamp equals to 2019-05-29 19:22:24.844

I got a window of 2019-05-29 19:22:22.605- 2019-05-29 19:23:22.605,data is myform(1559128942, 123, kid, 37890, begin), then I got a second window of 2019-05-29 19:22:22.605 - 2019-05-29 19:23:24.844and data is myform(1559128942, 123, kid, 37890, begin), myform(1559128944, 123, kid, 37890, success).
It looks like window initalize to (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605) and (2019-05-29 19:22:24.844, 2019-05-29 19:23:24.844), and onMerge method merged but not 'droped' window (2019-05-29 19:22:22.605, 2019-05-29 19:23:22.605). I've looked up the source function of EventTimeSessionWindows and examples of flink session window, and still don't known where program goes wrong?


问:
Using single ngOnDestroy in parent component
In our application we have some components that inherit from a BaseComponent.

The base component implements OnDestroy interface and emits with a Subject to notify the children to unsubscribe from eventual open streams.

Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation? From this article I read that Lifecycle hooks are not inherited.

BaseComponent

```<code>export abstract class ComponentBase implements OnDestroy {
  protected destroy$ = new Subject<boolean>();

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}
</code>```

ChildComponent

```<code>export class ChildComponent extends ComponentBase implements OnInit {

 ngOnInit() {
    this.service
      .getById(userId)
      .pipe(takeUntil(this.destroy$)) // this is emitted by the parent
      .subscribe(user => { ...}
 }
}
</code>```

答: Its a valid approach but its better to use async pipe instead of subscribe and add onPushStrategy for better performance if that is you want to achieve https://blog.angular-university.io/onpush-change-detection-how-it-works/.</p>

Body:
In our application we have some components that inherit from a BaseComponent.

The base component implements OnDestroy interface and emits with a Subject to notify the children to unsubscribe from eventual open streams.

Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation? From this article I read that Lifecycle hooks are not inherited.

BaseComponent

export abstract class ComponentBase implements OnDestroy {
  protected destroy$ = new Subject<boolean>();

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

ChildComponent

export class ChildComponent extends ComponentBase implements OnInit {

 ngOnInit() {
    this.service
      .getById(userId)
      .pipe(takeUntil(this.destroy$)) // this is emitted by the parent
      .subscribe(user => { ...}
 }
}


问:
Retrieving data in Ascending order In PHP5 MySQL
```<code>if($limit== '400'){
    $sql="SELECT * FROM report ORDER BY reportID ASC LIMIT $limit WHERE userID='$reportID'";}
</code>```

says "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE userID='147'' at line 1".

Anybody who can help me. I'm a beginner in php programming language.

答:
Where clause should be come before the Order By

Try this:

```<code>if($limit== '400'){
    $sql="SELECT * FROM report WHERE userID='$reportID' ORDER BY reportID ASC LIMIT $limit";
}
</code>```

Body:
if($limit== '400'){
    $sql="SELECT * FROM report ORDER BY reportID ASC LIMIT $limit WHERE userID='$reportID'";}

says "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE userID='147'' at line 1".

Anybody who can help me. I'm a beginner in php programming language.

Body:
Where clause should be come before the Order By

Try this:

if($limit== '400'){
    $sql="SELECT * FROM report WHERE userID='$reportID' ORDER BY reportID ASC LIMIT $limit";
}


问:
mklink permission on windows 8
I need to create symbolic links via mklink as an user, not as an administrator. I have set via secpol.msc and Security Settings → Local Policies → User Rights Assignment rule Create Symbolic links to user, that is currently logged in. After that I have restarted my laptop and tried to create symlink.

I still get the error:
You do not have sufficient privilege to perform this operation.

The strange thing is that when I create junction (mklink /d /j ...) it works fine. For other mklink operations does not.

So the question is simple, how can I need to set permissions in windows 8 to get mklink work properly under user, not administrator?

Thank you for help.

答:
I found this way works:

Find 'Command Prompt'.

Right click on it.

On the menu that comes up, click 'Run as Administrator'.

Now type in the command.

The command is mklink /d "{the link where you want the symlink to be}\{the name of the symlink}" "{link to the actual folder}"

Title: mklink permission on windows 8


问:
jQuery Dialog - animate dialog to move from center to top-right
I have a form with the validation plugin setup. When the form is submitted and has errors, I am showing the error'ed fields in a dialog box (not modal).

The form could get really long really quick (business requirements keep adding fields) and I  made the errore'd fields in the dialog box clickable to scroll the window to the field in the from and highlight the fields. The dialog box is not dismissed at this point.

This dialog box is centered to start with and once the user starts clicking on the links, I need to move the dialog box out of the user's way and highlight (jQuery effect) the fields below.

To do this, I've come up with the following code and the dialog seems to animate to the top but not to the right. When I change 'right' to 'left' it works fine.

Below is the code and a jsbin to play with - http://jsbin.com/avigi3/4/

```<code>$('a.field').click(function(){
    $(this).closest('.ui-dialog').animate( {
        right : '0', /*left:'0' works fine here*/
        top : $(window).scrollTop()
    }, 'slow');
});
</code>```

I debugged the jQuery.animate code and here are my notes:

jQuery.animate() 'starts' with the property's current value and gradually animates to the destination value as passed in. For ex: in the call, top starts with whatever the current top value of the dialog is and reduces to the scrollTop of the window (which is the visible top of the browser's viewport).

Now, here lies the problem. Even though the dialog is center-aligned, its 'right' property doesn't exist as jQuery-ui uses the 'left' property to center (absolutely position) the dialog. And since 'right' doesn't exist, the animation sequence for 'right' doesn't seem to work.

Did anyone face this issue? Any way I possibly could reset the 'right' position of the dialog so that it has 'some' value? Or can I configure jQuery dialog such that it animates when the position is changed programmatically and not manually by dragging.

Thanks,

-Syam

答:
For future readers, Shrikant's answer would be a quicker fix and specific to the call and it works fine. Just change width to use offsetWidth() to consider the paddings/margins.

I ended up following through the jQuery UI code to the end and have found a generic implementation. This is for jquery-ui 1.8.10.

Once it figures out where to move the dialog box by calculating {left:xxx, top:xxx}, jQuery-dialog uses the Position utility to position and re-position the ui-dialog div. One of the options for Position is the 'using' function. If 'using' is defined, it triggers that function and passes in an object of {left:xxx, top:xxx}. If it is not defined, it just updates the css on ui-dialog. Here's a snippet of the code:

```<code>line number 9977 in jquery-ui version 1.8.10:
            if ( 'using' in options ) {
                options.using.call( elem, props );
            } else {
                curElem.css( props );
            }
</code>```

You can override the 'using' property on the Position defaults, but since my usage is only for dialogs, I overwrote it on the dialog prototype:

```<code>$.extend($.ui.dialog.prototype.options, {
    position : {
        using : function(props) {
            $(this).animate( {
                left : props.left,
                top : props.top
            }, 'slow');
        }
    }
});
</code>```

I hope this helps!

Thanks,
-Syam

Body:
I have a form with the validation plugin setup. When the form is submitted and has errors, I am showing the error'ed fields in a dialog box (not modal).

The form could get really long really quick (business requirements keep adding fields) and I  made the errore'd fields in the dialog box clickable to scroll the window to the field in the from and highlight the fields. The dialog box is not dismissed at this point.

This dialog box is centered to start with and once the user starts clicking on the links, I need to move the dialog box out of the user's way and highlight (jQuery effect) the fields below.

To do this, I've come up with the following code and the dialog seems to animate to the top but not to the right. When I change 'right' to 'left' it works fine.

Below is the code and a jsbin to play with - http://jsbin.com/avigi3/4/

$('a.field').click(function(){
    $(this).closest('.ui-dialog').animate( {
        right : '0', /*left:'0' works fine here*/
        top : $(window).scrollTop()
    }, 'slow');
});

I debugged the jQuery.animate code and here are my notes:

jQuery.animate() 'starts' with the property's current value and gradually animates to the destination value as passed in. For ex: in the call, top starts with whatever the current top value of the dialog is and reduces to the scrollTop of the window (which is the visible top of the browser's viewport).

Now, here lies the problem. Even though the dialog is center-aligned, its 'right' property doesn't exist as jQuery-ui uses the 'left' property to center (absolutely position) the dialog. And since 'right' doesn't exist, the animation sequence for 'right' doesn't seem to work.

Did anyone face this issue? Any way I possibly could reset the 'right' position of the dialog so that it has 'some' value? Or can I configure jQuery dialog such that it animates when the position is changed programmatically and not manually by dragging.

Thanks,

-Syam

Body:
For future readers, Shrikant's answer would be a quicker fix and specific to the call and it works fine. Just change width to use offsetWidth() to consider the paddings/margins.

I ended up following through the jQuery UI code to the end and have found a generic implementation. This is for jquery-ui 1.8.10.

Once it figures out where to move the dialog box by calculating {left:xxx, top:xxx}, jQuery-dialog uses the Position utility to position and re-position the ui-dialog div. One of the options for Position is the 'using' function. If 'using' is defined, it triggers that function and passes in an object of {left:xxx, top:xxx}. If it is not defined, it just updates the css on ui-dialog. Here's a snippet of the code:

line number 9977 in jquery-ui version 1.8.10:
            if ( 'using' in options ) {
                options.using.call( elem, props );
            } else {
                curElem.css( props );
            }

You can override the 'using' property on the Position defaults, but since my usage is only for dialogs, I overwrote it on the dialog prototype:

$.extend($.ui.dialog.prototype.options, {
    position : {
        using : function(props) {
            $(this).animate( {
                left : props.left,
                top : props.top
            }, 'slow');
        }
    }
});

I hope this helps!

Thanks,
-Syam


问:
How to read all characters from file and store it in 2d array without \n?
I am trying to read a file and store each of its character in 2d array(of size 7 by 7) without special characters like '\n' and than print that 2d array.

I write a code but it does not store and print the last line characters in 2d array.

```<code>#include<stdio.h>
#include<stdlib.h>
int main()
{
     char ar[7][7],c;
    int i,j;
    FILE *fp;
    fp=fopen("B11.txt","r");
    if(fp==NULL)
        printf("File not Found");

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {

         fscanf(fp,"%c",&ar[i][j]);
        }

    }

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            printf("%c",ar[i][j]);
        }

    }
fclose(fp);
}
</code>```

This the output of the my code:

```<code>abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
</code>```

But the file contains,

```<code>abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
comsats
</code>```

Here the file contains the word 'comsats' also, that is not printed. Why this word comsats is not printed?

答:
The \n character is causing the last line to be skipped.

Change this:

```<code>     fscanf(fp,"%c",&ar[i][j]);
</code>```

To this:

```<code>     fscanf(fp," %c",&ar[i][j]);
                ^
</code>```

The space consumes the newline character when using scanf() format specifiers such as %c %lf %d etc.  The space is not needed however for reading strings, ( %s ).

Regarding your statement: without special characters like '\n'

If by this you are referring characters such as:

space (" ")

horizontal tab ("\t")

formfeed ("\f")

carriage return ("\r")

vertical tab ("\v")

and of course newline ("\n")

Consider replacing the fscanf() construct with one using fgetc() in conjunction with the white-space test function: isspace(). (which checks for those characters listed above.)  Example:

```<code>#define ROW 7
#define COL 7
int main(void)
{
    int row = 0;
    int col = 0;
    char ar[COL][ROW];
    int byte;

    FILE *fp = fopen(filename, "r");
    if(fp)
    {
        byte = fgetc(fp);
        while(byte != EOF)
        {
            if(!isspace(byte))
            {   //populate array only if not white-space
                ar[col][row++] = (char)byte;
                if(row == ROW)
                {
                    row = 0;
                    col++;
                }
                if(col == COL) break;
            }
            byte = fgetc(fp);
        }
        fclose(fp);
    }
    // print results as in your original post...

    return 0;
}
</code>```

Body:
I am trying to read a file and store each of its character in 2d array(of size 7 by 7) without special characters like '\n' and than print that 2d array.

I write a code but it does not store and print the last line characters in 2d array.

#include<stdio.h>
#include<stdlib.h>
int main()
{
     char ar[7][7],c;
    int i,j;
    FILE *fp;
    fp=fopen("B11.txt","r");
    if(fp==NULL)
        printf("File not Found");

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {

         fscanf(fp,"%c",&ar[i][j]);
        }

    }

for(i=0; i<7; i++)
    {
        for(j=0; j<7; j++)
        {
            printf("%c",ar[i][j]);
        }

    }
fclose(fp);
}

This the output of the my code:

abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh

But the file contains,

abtvelo
camerag
bhtollp
qeryvxq
appboyl
awerfgh
comsats

Here the file contains the word 'comsats' also, that is not printed. Why this word comsats is not printed?

Body:
The \n character is causing the last line to be skipped.

Change this:

     fscanf(fp,"%c",&ar[i][j]);

To this:

     fscanf(fp," %c",&ar[i][j]);
                ^

The space consumes the newline character when using scanf() format specifiers such as %c %lf %d etc.  The space is not needed however for reading strings, ( %s ).

Regarding your statement: without special characters like '\n'

If by this you are referring characters such as:

space (" ")

horizontal tab ("\t")

formfeed ("\f")

carriage return ("\r")

vertical tab ("\v")

and of course newline ("\n")

Consider replacing the fscanf() construct with one using fgetc() in conjunction with the white-space test function: isspace(). (which checks for those characters listed above.)  Example:

#define ROW 7
#define COL 7
int main(void)
{
    int row = 0;
    int col = 0;
    char ar[COL][ROW];
    int byte;

    FILE *fp = fopen(filename, "r");
    if(fp)
    {
        byte = fgetc(fp);
        while(byte != EOF)
        {
            if(!isspace(byte))
            {   //populate array only if not white-space
                ar[col][row++] = (char)byte;
                if(row == ROW)
                {
                    row = 0;
                    col++;
                }
                if(col == COL) break;
            }
            byte = fgetc(fp);
        }
        fclose(fp);
    }
    // print results as in your original post...

    return 0;
}


问:
How to get rid of automatic fill in html?
i want to get rid of the auto fill in

i am new to html and i cant ix my problem. if you dont understand me ill be more than happy to send a screenshot using gmail.

```<code><FORM action="Database.php" method="GET">
<LABEL>First Name</LABEL>
<input type="text" name="firstName">
<br>
</code>```

Last Name

答:
just use autocomplete="off" in your tag like this

<input type="text" name="firstName" autocomplete="off">

to know more visit this

Body:
i want to get rid of the auto fill in

i am new to html and i cant ix my problem. if you dont understand me ill be more than happy to send a screenshot using gmail.

<FORM action="Database.php" method="GET">
First Name
<input type="text" name="firstName">

Last Name