问:
How are WPF Buttons and TextBlock styles related?
I have a custom style for my 'default' Buttons, and also created a custom style for TextBlocks. If I remove the TextBlock style entirely, everything works fine, but once the TextBlock styling is added in for some reason the Button style is used on the Button's text 'default' state. It seems like some kind of inheritance is going on here but I can't see where in the msdn docs. What's going on?

I'm using Expression Blend 4-- and also another odd thing is that the preview in Blend looks fine, but when I RUN the application, the button styles are incorrect in their default state. Here's the styles which seem to be conflicting:

```<code>        <ResourceDictionary>

        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver"
                         Value="True">
                    <Setter Property="Foreground">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                <GradientStop Color="White" Offset="0"/>
                                <GradientStop Color="#FFFDFF00" Offset="1"/>
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <TransformGroup>
                                <ScaleTransform ScaleY="1.20" ScaleX="1.20"/>
                                <SkewTransform/>
                                <RotateTransform/>
                                <TranslateTransform/>
                            </TransformGroup>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <ContentPresenter RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
                                <ContentPresenter.Effect>
                                    <DropShadowEffect BlurRadius="3" ShadowDepth="4"/>
                                </ContentPresenter.Effect>
                            </ContentPresenter>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsFocused" Value="True"/>
                            <Trigger Property="IsDefaulted" Value="True"/>
                            <Trigger Property="IsMouseOver" Value="True"/>
                            <Trigger Property="IsPressed" Value="True"/>
                            <Trigger Property="IsEnabled" Value="False"/>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="FontFamily" Value="/Rtk;component/Fonts/#Segoe Print"/>
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="{x:Null}"/>
        </Style>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="TextWrapping" Value="NoWrap"/>
            <Setter Property="TextTrimming" Value="None"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="FontSize" Value="16"/>
            <Setter Property="Effect">
                <Setter.Value>
                    <DropShadowEffect BlurRadius="3" ShadowDepth="4"/>
                </Setter.Value>
            </Setter>
            <Setter Property="FontFamily" Value="/Rtk;component/Fonts/#Segoe Print"/>
        </Style>
    </ResourceDictionary>
</code>```

This is how I am using the Button control itself:

```<code><Button Content="Button Text" FontSize="24"/>
</code>```

(note that this fontsize is different from the size I specified in the default style, 18 - I want to override it in this button's case)

Edit:
The actual button entry looks like this in MainWindow.xaml, there's no other customizations other than the style changes I posed from App.xaml:

```<code><Button Content="Button" HorizontalAlignment="Left" Margin="336,0,0,274.226" VerticalAlignment="Bottom" Width="75"/>
</code>```

To illustrate what I'm seeing:

答:
As people have suggested, your Button contains a Textblock created to hold the content, it is picking up the style from app.xaml, you can work around this in a few ways, here are a couple:

Put an explicit textblock into your button, and apply no style:

```<code>  <Button Margin="272,192,277,0" VerticalAlignment="Top">
        <TextBlock Text="Button" Style="{x:Null}"/>
    </Button>
</code>```

Put a textblock into your button style, also with a null style:

```<code> <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
      <TextBlock Text="{TemplateBinding Content}" Style="{x:Null}">
                       <TextBlock.Effect>
                          <DropShadowEffect BlurRadius="3" ShadowDepth="4"/>
                       </TextBlock.Effect>
      </TextBlock>
         </Grid>
              <ControlTemplate.Triggers>
                  <Trigger Property="IsFocused" Value="True"/>
                  <Trigger Property="IsDefaulted" Value="True"/>
                  <Trigger Property="IsMouseOver" Value="True"/>
                  <Trigger Property="IsPressed" Value="True"/>
                  <Trigger Property="IsEnabled" Value="False"/>
                </ControlTemplate.Triggers>
              </ControlTemplate>
            </Setter.Value>
</code>```

Hopefully one of those 2 will work for you.

Body:
I have a custom style for my 'default' Buttons, and also created a custom style for TextBlocks. If I remove the TextBlock style entirely, everything works fine, but once the TextBlock styling is added in for some reason the Button style is used on the Button's text 'default' state. It seems like some kind of inheritance is going on here but I can't see where in the msdn docs. What's going on?

I'm using Expression Blend 4-- and also another odd thing is that the preview in Blend looks fine, but when I RUN the application, the button styles are incorrect in their default state. Here's the styles which seem to be conflicting:

        <ResourceDictionary>

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid>
                            <ContentPresenter RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
                                <ContentPresenter.Effect>
                                    <DropShadowEffect BlurRadius="3" ShadowDepth="4"/>
                                </ContentPresenter.Effect>
                            </ContentPresenter>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsFocused" Value="True"/>
                            <Trigger Property="IsDefaulted" Value="True"/>
                            <Trigger Property="IsMouseOver" Value="True"/>
                            <Trigger Property="IsPressed" Value="True"/>
                            <Trigger Property="IsEnabled" Value="False"/>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="FontFamily" Value="/Rtk;component/Fonts/#Segoe Print"/>
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="FontSize" Value="18"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="{x:Null}"/>
        </Style>

    </ResourceDictionary>

This is how I am using the Button control itself:

<Button Content="Button Text" FontSize="24"/>

(note that this fontsize is different from the size I specified in the default style, 18 - I want to override it in this button's case)

Edit:
The actual button entry looks like this in MainWindow.xaml, there's no other customizations other than the style changes I posed from App.xaml:

<Button Content="Button" HorizontalAlignment="Left" Margin="336,0,0,274.226" VerticalAlignment="Bottom" Width="75"/>

To illustrate what I'm seeing:

Body:
As people have suggested, your Button contains a Textblock created to hold the content, it is picking up the style from app.xaml, you can work around this in a few ways, here are a couple:

Put an explicit textblock into your button, and apply no style:

  <Button Margin="272,192,277,0" VerticalAlignment="Top">
        <TextBlock Text="Button" Style="{x:Null}"/>
    </Button>

Put a textblock into your button style, also with a null style:

 <Setter Property="Template">
            <Setter.Value>
              <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
      <TextBlock Text="{TemplateBinding Content}" Style="{x:Null}">
                       <TextBlock.Effect>
                          <DropShadowEffect BlurRadius="3" ShadowDepth="4"/>
                       </TextBlock.Effect>
      </TextBlock>
         </Grid>
              <ControlTemplate.Triggers>
                  <Trigger Property="IsFocused" Value="True"/>
                  <Trigger Property="IsDefaulted" Value="True"/>
                  <Trigger Property="IsMouseOver" Value="True"/>
                  <Trigger Property="IsPressed" Value="True"/>
                  <Trigger Property="IsEnabled" Value="False"/>
                </ControlTemplate.Triggers>
              </ControlTemplate>
            </Setter.Value>

Hopefully one of those 2 will work for you.


来源: stackexchange

问:
Why does Foundation recommend adding a tabindex="0" to main content?
In Foundation's docs on creating skip links, they recommend adding tabindex="0" to the element that represents the main content to skip to. I'm a bit confused as to why they would say that. As far as I can see, this results in an extra element receiving focus when tabbing through the document, even though there's not really anything to do with that element focused.

Is the reason perhaps compatibility with older browsers that don't support anchoring to ids? Or is there another reason?

Update: It should soon no longer say the above anymore, but that's because I changed it in response to the answers here :P

答:
It seems to be for the simple reason as to quickly be able to navigate to the most important section of the page. This element will be selected first when pressing tab and the selection will continue from there rather than at the top of the DOM.

Using anchoring ids is for use when the user clicks an internal link or needs otherwise to be triggered though JS. Using tabindex="0" is already built into most browsers.

ContentLicense: CC BY-SA 3.0


问:
Laravel: Compare two dates against today with Eloquent
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

```<code>public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}
</code>```

答:
If I understood your problem correctly, I think this should suffice:

```<code>$today = Carbon::today();
$event = Event::whereDate('startdate', '>', $today->format('Y-m-d'))
    ->whereDate('enddate', '<', $today->format('Y-m-d'))
    ->with('businesses')
    ->get();
</code>```

I hope you did search the internet for this problem in the first place

Body:
So I have events table which has start date and end date.

What I want to do is a comparison between today and start date + end date so if today is between start and end, return that collection which will be displayed on page, if it isn't ignore that event.

Problem is that when I retrieve an event I cannot access it as it is return that it doesn't exist in the collection, but it does after view is returned.

Here's my controller:

public function show($id)
{
    $today = date("Y-m-d");
    $today_dt = new DateTime($today);
    $event = Event::with('businesses')
        ->get();
    $test = $event->startdate;
    $test2 = $event->enddate;
    //something like if $today is not less that start date and not higher than end date, return that collection?
    dd($test);
    return view('events.showEvent', compact('event'));
}

Body:
If I understood your problem correctly, I think this should suffice:

$today = Carbon::today();
$event = Event::whereDate('startdate', '>', $today->format('Y-m-d'))
    ->whereDate('enddate', '<', $today->format('Y-m-d'))
    ->with('businesses')
    ->get();

I hope you did search the internet for this problem in the first place


问:
LocaleMiddleware redirects on a non-i18n url pattern
I'm using Django's LocaleMiddleware to internationalize a part of the website I'm working on.
Here is my project's urls.py:

```<code>from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns

urlpatterns = patterns('',
    url(r'^api/stuff/(?P<stuff_id>)\d+/$', ApiStuff.as_view()),
)

urlpatterns += i18n_patterns('',
    url(r'^stuff/', DoStuff.as_view()),
)
</code>```

The problem is, when ApiStuff.as_view() returns a 404 response (other error codes behave as expected), the LocaleMiddleware operates the request to make it redirect to /en/api/stuff/<stuff_id>, even though the /api namespace is clearly not in the i18n_patterns (at the end, it generates a 404 error too, but the content of my original response is lost).

Here is the code of ApiStuff:

```<code>import django.http
from django.views.generic import View
from project.stuff.models import Stuff

class ApiStuff(View):

    @staticmethod
    def get(request, *args, **kwargs):
        stuff_id = kwargs['stuff_id']

        try:
            stuff = Stuff.objects.get(pk=stuff_id)
        except Stuff.DoesNotExist:
            return response({"error": "stuff not found"}, 404)

        result = stuff.serialize()
        return response(result)

def response(data, status=200):
    data = json.dumps(data)
    return django.http.HttpResponse(data, status=status, content_type='application/json')
</code>```

I'm using django 1.6.10 (I know, it's late, but I can't update the version right now).

Am I missing something?

答:
This is an old bug that has been tracked here:

https://code.djangoproject.com/ticket/17734

The 404 error handler is a default handler of Django. It obviously takes the current language into account in order to translate the "not found" message.

Unless you can upgrade to a newer version you probably need to define your own error handler (including route/url).

EDIT:

As a workaround it might be possible to extend the LocaleMiddleware and maybe also CommonMiddleware. However, it could be that the 404 handler does its magic nevertheless. Might be worth a shot though because it should only require few lines of code.

Citing the ticket:

when you request /api/raising/404/, it is redirecting the user to /en/api/raising/404/ (assuming it detects the language as en). If it tests before redirecting the user if /en/api/raising/404/ is resolvable, it would find out that this would raise a 404 as well and thus would not redirect the user.

EDIT 2:

As an alternative you could simply not use i18n_patterns and just detect/switch the language via browser/cookie/parameter. I did that for a project (which included Django CMS) where I kept running into problems with these URLs. It is definitely not a prerequisite for localized Django sites to use i18n URL patterns. It's just something on top, but not at all necessary. Localization will work just fine without it. If you need help with the middleware for switching languages, drop a comment.

Body:
I'm using Django's LocaleMiddleware to internationalize a part of the website I'm working on.
Here is my project's urls.py:

from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns

urlpatterns = patterns('',
    url(r'^api/stuff/(?P<stuff_id>)\d+/$', ApiStuff.as_view()),
)

urlpatterns += i18n_patterns('',
    url(r'^stuff/', DoStuff.as_view()),
)

The problem is, when ApiStuff.as_view() returns a 404 response (other error codes behave as expected), the LocaleMiddleware operates the request to make it redirect to /en/api/stuff/<stuff_id>, even though the /api namespace is clearly not in the i18n_patterns (at the end, it generates a 404 error too, but the content of my original response is lost).

Here is the code of ApiStuff:

import django.http
from django.views.generic import View
from project.stuff.models import Stuff

class ApiStuff(View):

    @staticmethod
    def get(request, *args, **kwargs):
        stuff_id = kwargs['stuff_id']

        try:
            stuff = Stuff.objects.get(pk=stuff_id)
        except Stuff.DoesNotExist:
            return response({"error": "stuff not found"}, 404)

        result = stuff.serialize()
        return response(result)

def response(data, status=200):
    data = json.dumps(data)
    return django.http.HttpResponse(data, status=status, content_type='application/json')

I'm using django 1.6.10 (I know, it's late, but I can't update the version right now).

Am I missing something?


问:
Windows-1252 to UTF-8 encoding
I've copied certain files from a Windows machine to a Linux machine.

All the files encoded with Windows-1252 need to be converted to
UTF-8.

The files which are already in UTF-8 should not be changed.

I'm planning to use the recode
utility for that.
How can I specify that the recode utility should only convert
windows-1252 encoded files and not the UTF-8 files?

Example usage of recode:

```<code>recode windows-1252.. myfile.txt
</code>```

This would convert myfile.txt from windows-1252 to UTF-8.
Before doing this, I would like to know that myfile.txt is actually
windows-1252 encoded and not UTF-8 encoded.

Otherwise, I believe this would corrupt the file.

答:
If you are sure your files are either UTF-8 or Windows 1252 (or Latin1), you can take advantage of the fact that recode will exit with an error if you try to convert an invalid file.

While utf8 is valid Win-1252, the reverse is not true: win-1252 is NOT valid UTF-8. So:

```<code>recode utf8..utf16 <unknown.txt >/dev/null || recode cp1252..utf8 <unknown.txt >utf8-2.txt
</code>```

Will spit out errors for all cp1252 files, and then proceed to convert them to UTF8.

I would wrap this into a cleaner bash script, keeping a backup of every converted file.

Before doing the charset conversion, you may wish to first ensure you have consistent line-endings in all files. Otherwise, recode will complain because of that, and may convert files which were already UTF8, but just had the wrong line-endings.

ContentLicense: CC BY-SA 4.0

Title: Windows-1252 to UTF-8 encoding

Body:
I've copied certain files from a Windows machine to a Linux machine.

All the files encoded with Windows-1252 need to be converted to
UTF-8.

The files which are already in UTF-8 should not be changed.

I'm planning to use the recode
utility for that.
How can I specify that the recode utility should only convert
windows-1252 encoded files and not the UTF-8 files?

Example usage of recode:

recode windows-1252.. myfile.txt

This would convert myfile.txt from windows-1252 to UTF-8.
Before doing this, I would like to know that myfile.txt is actually
windows-1252 encoded and not UTF-8 encoded.

Otherwise, I believe this would corrupt the file.

Body:
If you are sure your files are either UTF-8 or Windows 1252 (or Latin1), you can take advantage of the fact that recode will exit with an error if you try to convert an invalid file.

While utf8 is valid Win-1252, the reverse is not true: win-1252 is NOT valid UTF-8. So:

recode utf8..utf16 <unknown.txt >/dev/null || recode cp1252..utf8 <unknown.txt >utf8-2.txt

Will spit out errors for all cp1252 files, and then proceed to convert them to UTF8.

I would wrap this into a cleaner bash script, keeping a backup of every converted file.

Before doing the charset conversion, you may wish to first ensure you have consistent line-endings in all files. Otherwise, recode will complain because of that, and may convert files which were already UTF8, but just had the wrong line-endings.

ContentLicense: CC BY-SA 2.5


问:
When to use supervised or unsupervised learning?

Which are the fundamental criterias for using supervised or unsupervised learning?

When is one better than the other?

Is there specific cases when you can only use one of them?

Thanks

答:
Depends on your needs. If you have a set of existing data including the target values that you wish to predict (labels) then you probably need supervised learning (e.g. is something true or false; or does this data represent a fish or cat or a dog? Simply put - you already have examples of right answers and you are just telling the algorithm what to predict). You also need to distinguish whether you need a classification or regression. Classification is when you need to categorize the predicted values into given classes (e.g. is it likely that this person develops a diabetes - yes or no? In other words - discrete values) and regression is when you need to predict continuous values (1,2, 4.56, 12.99, 23 etc.). There are many supervised learning algorithms to choose from (k-nearest neighbors, naive bayes, SVN, ridge..)

On contrary - use the unsupervised learning if you don't have the labels (or target values). You're simply trying to identify the clusters of data as they come. E.g. k-Means, DBScan, spectral clustering..)

So it depends and there's no exact answer but generally speaking you need to:

Collect and see you data. You need to know your data and only then decide which way you choose or what algorithm will best suite your needs.

Train your algorithm. Be sure to have a clean and good data and bear in mind that in case of unsupervised learning you can skip this step as you don't have the target values. You test your algorithm right away

Test your algorithm. Run and see how well your algorithm behaves. In case of supervised learning you can use some training data to evaluate how well is your algorithm doing.

There are many books online about machine learning and many online lectures on the topic as well.


问:
Length of a JavaScript object
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?</p>
```<code>const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
</code>```

答:
A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

```<code>Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});
</code>```

And you can just use it like so:

```<code>var myObj = { 'key': 'value' };
myObj.length;
</code>```

It would give 1.

Title: Length of a JavaScript object

Body:
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

Body:
A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});

And you can just use it like so:

var myObj = { 'key': 'value' };
myObj.length;

It would give 1.


问:
Intent object showing error Android
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

```<code>package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}
</code>```

Image

答:
you have written this inside onClick... try writting MainActivity.this and it should work.. more on using this keyword click here

Intent i = new Intent(MainActivity.this, profile.class);

in your case after watching stacktrace ans should be to bind prof_sub_btn button with xml.

Title: Intent object showing error Android

Body:
I am working with android activities , and trying to launch an activity when a button is clicked on the previous activity, the problem start in intent object, because the first parameter i.e; context parameter of intent constructor doesn't work with "this, MainActivity.this, getApplicationContext(),getBaseContext" i tried all of the parameters in the first parameter of the intent constructor object. Below is my code.

package com.example.nadeemahmad.guitest;

import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Button ma_sub_btn,prof_sub_btn;
    RelativeLayout ma_rel_lay2,ma_rel_lay3,ma_dots_ly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ma_sub_btn = (Button)findViewById(R.id.ma_sub_btn);
        ma_rel_lay2 = (RelativeLayout)findViewById(R.id.ma_rel_lay2);
        ma_rel_lay3 = (RelativeLayout)findViewById(R.id.ma_rel_lay3);
        ma_dots_ly = (RelativeLayout)findViewById(R.id.ma_dots_ly);

        ma_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ma_rel_lay2.setVisibility(View.GONE);
                ma_rel_lay3.setVisibility(View.VISIBLE);
                ma_dots_ly.setVisibility(View.GONE);
            }
        });

        prof_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(this, profile.class);
                startActivity(i);
            }
        });

    }

}

Image


问:
losing fields during validation - nested serializer create()
I don't understand why specific fields are being dropped within validated_data.

When POSTing input to create() a new instance, the following line:
thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)
 throws an error because the identifier attribute is not present:

```<code>AttributeError at /api/v1/policies/
</code>```

'collections.OrderedDict' object has no attribute 'identifier

I have the following serializers within Django REST framework:

serializers.py:

```<code>class ClassificationLabelDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
        read_only_fields = ('identifier', 'lastChanged', 'revision',)

class PolicySerializer(serializers.ModelSerializer):
    labels = ClassificationLabelDetailSerializer(many=True)

    class Meta:
        model = Policy
        fields = ('displayName', 'identifier', 'labels', 'lastChanged', 'description', 'comment')
        read_only_fields = ('identifier', 'lastChanged',)

    def create(self,validated_data):
        labelData = validated_data.pop('labels')
        thisPolicy = Policy.objects.create(**validated_data)
        for label in labelData:
            for k, v in label.items():
                print(k, v)
            thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)#insert organisational filter here
            PolicyMemberClassificationLabel.objects.create(policy=thisPolicy, label=thisLabel, order=index)
        return thisPolicy
</code>```

models.py:

```<code>class ClassificationLabel(models.Model):
    displayName = models.CharField(max_length = 32)
    helpText = models.TextField(max_length = 140, blank=True)
    backgroundColour = models.CharField(max_length=8)
    foregroundColour = models.CharField(max_length=8)
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now=True, editable=False)
    identifier = models.CharField(max_length = 128, blank=True, editable=False)
    revision = models.PositiveIntegerField(default=1, editable=False)

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = ClassificationLabel.objects.filter(identifier=newString).exists()
                if doesStringExist is False:
                    stringCheck = True
            self.identifier = newString
        super(ClassificationLabel, self).save(*args, **kwargs) # Call the "real" save() method.

class Policy(models.Model):
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now =True)
    displayName = models.CharField(max_length = 64)
    identifier = models.CharField(max_length = 128, blank=True)
    labels = models.ManyToManyField(ClassificationLabel, through='PolicyMemberClassificationLabel')
    revision = models.PositiveIntegerField(default=1)

    class Meta:
        verbose_name_plural = 'Policies'

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = Policy.objects.filter(identifier=newString).count()
                if doesStringExist == 0:
                    stringCheck = True
            self.identifier = newString
            super(Policy, self).save() # Call the "real" save() method.

class PolicyMemberClassificationLabel(models.Model):
    label = models.ForeignKey(ClassificationLabel, related_name='memberLabels')
    policy = models.ForeignKey(Policy, related_name='parentPolicy')
    order = models.PositiveSmallIntegerField(blank=True)
</code>```

when sending the following via POST it's dropping the identifier, lastChanged and revision fields from the nested representation within validated_data.

```<code>{
  "labels": [
    {
      "displayName": "Test name",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book. Wayfarers sartorial authentic, small batch readymade disrupt col",
      "identifier": "fa27e9bd-5007-4874-b10c-46b63c7c8a86",
      "backgroundColour": "#808900",
      "foregroundColour": "#000000",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:26:20.450681Z",
      "revision": 2
    },
    {
      "displayName": "Test name 1",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "identifier": "29c968dd-8b83-4374-962d-32b9ef527e1b",
      "backgroundColour": "#9f0500",
      "foregroundColour": "#FFFFFF",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:25:52.955293Z",
      "revision": 2
    }
  ]
}
</code>```

I can see that the serializer .is_valid() is True for the PolicySerializer

when I look at validated_data those three fields are missing (the rest are there)

I've tried commenting out the read_only_fields and that doesn't seem to make any difference

I've been referencing the DRF documentation here

I've ensured that the client's content-type is set correctly, since there was a similar problem here

other people seem to be having similar problems

My question: How do I get the identifier field within the validated_data of the nested representation?

答:
Fields which have editable set to False on the model are read_only by default on serializer. [http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields]

You should use a different serializer for creation where the field will be given explicitly like so:

```<code>class ClassificationLabelDetailSerializer(serializers.ModelSerializer):
    identifier = serializers.CharField()

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
</code>```

Body:
I don't understand why specific fields are being dropped within validated_data.

When POSTing input to create() a new instance, the following line:
thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)
 throws an error because the identifier attribute is not present:

AttributeError at /api/v1/policies/

'collections.OrderedDict' object has no attribute 'identifier

I have the following serializers within Django REST framework:

serializers.py:

class ClassificationLabelDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'identifier', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')
        read_only_fields = ('identifier', 'lastChanged', 'revision',)

class PolicySerializer(serializers.ModelSerializer):
    labels = ClassificationLabelDetailSerializer(many=True)

    class Meta:
        model = Policy
        fields = ('displayName', 'identifier', 'labels', 'lastChanged', 'description', 'comment')
        read_only_fields = ('identifier', 'lastChanged',)

    def create(self,validated_data):
        labelData = validated_data.pop('labels')
        thisPolicy = Policy.objects.create(**validated_data)
        for label in labelData:
            for k, v in label.items():
                print(k, v)
            thisLabel = ClassificationLabel.objects.get(identifier=label.identifier)#insert organisational filter here
            PolicyMemberClassificationLabel.objects.create(policy=thisPolicy, label=thisLabel, order=index)
        return thisPolicy

models.py:

class ClassificationLabel(models.Model):
    displayName = models.CharField(max_length = 32)
    helpText = models.TextField(max_length = 140, blank=True)
    backgroundColour = models.CharField(max_length=8)
    foregroundColour = models.CharField(max_length=8)
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now=True, editable=False)
    identifier = models.CharField(max_length = 128, blank=True, editable=False)
    revision = models.PositiveIntegerField(default=1, editable=False)

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = ClassificationLabel.objects.filter(identifier=newString).exists()
                if doesStringExist is False:
                    stringCheck = True
            self.identifier = newString
        super(ClassificationLabel, self).save(*args, **kwargs) # Call the "real" save() method.

class Policy(models.Model):
    description = models.TextField(max_length = 256, blank=True)
    comment = models.TextField(max_length = 1024, blank=True)
    lastChanged = models.DateTimeField(auto_now =True)
    displayName = models.CharField(max_length = 64)
    identifier = models.CharField(max_length = 128, blank=True)
    labels = models.ManyToManyField(ClassificationLabel, through='PolicyMemberClassificationLabel')
    revision = models.PositiveIntegerField(default=1)

    class Meta:
        verbose_name_plural = 'Policies'

    def __str__(self):
        return self.displayName + " - " + self.identifier

    def save(self, *args, **kwargs):
        self.revision += 1
        #the following code generates a unique identifier and checks it for collisions against existing identifiers
        if not self.identifier:
            stringCheck = False
            while stringCheck is False:
                newString = str(uuid.uuid4())
                newString.replace('-', '')
                doesStringExist = Policy.objects.filter(identifier=newString).count()
                if doesStringExist == 0:
                    stringCheck = True
            self.identifier = newString
            super(Policy, self).save() # Call the "real" save() method.

class PolicyMemberClassificationLabel(models.Model):
    label = models.ForeignKey(ClassificationLabel, related_name='memberLabels')
    policy = models.ForeignKey(Policy, related_name='parentPolicy')
    order = models.PositiveSmallIntegerField(blank=True)

when sending the following via POST it's dropping the identifier, lastChanged and revision fields from the nested representation within validated_data.

{
  "labels": [
    {
      "displayName": "Test name",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book. Wayfarers sartorial authentic, small batch readymade disrupt col",
      "identifier": "fa27e9bd-5007-4874-b10c-46b63c7c8a86",
      "backgroundColour": "#808900",
      "foregroundColour": "#000000",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:26:20.450681Z",
      "revision": 2
    },
    {
      "displayName": "Test name 1",
      "helpText": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "identifier": "29c968dd-8b83-4374-962d-32b9ef527e1b",
      "backgroundColour": "#9f0500",
      "foregroundColour": "#FFFFFF",
      "comment": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "description": "Wayfarers sartorial authentic, small batch readymade disrupt coloring book.",
      "lastChanged": "2017-07-03T09:25:52.955293Z",
      "revision": 2
    }
  ]
}

I can see that the serializer .is_valid() is True for the PolicySerializer

when I look at validated_data those three fields are missing (the rest are there)

I've tried commenting out the read_only_fields and that doesn't seem to make any difference

I've been referencing the DRF documentation here

I've ensured that the client's content-type is set correctly, since there was a similar problem here

other people seem to be having similar problems

My question: How do I get the identifier field within the validated_data of the nested representation?

Body:
Fields which have editable set to False on the model are read_only by default on serializer. [http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields]

You should use a different serializer for creation where the field will be given explicitly like so:

class ClassificationLabelDetailSerializer(serializers.ModelSerializer):
    identifier = serializers.CharField()

    class Meta:
        model = ClassificationLabel
        fields = ('displayName', 'helpText', 'backgroundColour', 'foregroundColour', 'comment', 'description', 'lastChanged', 'revision')


问:
C: read in more than one file
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

```<code>filein = open(argv[1],O_RDONLY,0);
</code>```

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

```<code>j=0;
filein = open(argv[j],O_RDONLY,0);
</code>```

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

答:
argv[0] is the name of the program. argv[1] is the first then you pass on the command line.

Open your output file then each input file. read each input file into the output file then close them all and exit.

Title: C: read in more than one file

Body:
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

filein = open(argv[1],O_RDONLY,0);

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

j=0;
filein = open(argv[j],O_RDONLY,0);

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.


问:
Can threads create sub-threads in Python?
I am familiar with the syntax for creating threads in python.

from threading import Thread
from queue import Queue

task_queue = Queue(maxsize=0)

num_threads=10
for i in range(num_threads):
    thread = Thread(target=work, args=(task_queue,))
    thread.start()

task_queue.join()
```

<p>My question is weather it is ok to open up new threads 'inside' other threads like so:</p>

<pre class="lang-python prettyprint-override"><code>def work(task_queue):
    task = task_queue.get()

    subtasks = task.get_sub_tasks()

    for subtask in subtasks:
        thread = Thread(target=sub_work, args(subtask,))
        thread.start()
</code>```

So

Is this structure ok? or is it to messy to do it this way?

If this is ok, are the sub-thread processes subordinated to the thread that generated it, or do they become children of the parent python process? If the thread that created the sub-thread "dies" with an error, what happens to the sub-thread?

I realize python threads are subject to the interpreter global lock, but my application involves access to a server, so the multi threading is to avoid serialized connections which would take too long.

答:
So regarding your questions:

Q1: It is not a problem to start "subthreads" from a thread

Q2: It is actually an interesting question, my instinct would say "no", but getting a proof sounds better to me

So I created a quick test as below (I would use a gist but I can't access such things from where I am):

```<code>from threading import Thread
import time

def sub_worker(id):
    print("SubWorker started from thread", id)
    while True:
        print("Subworking...")
        time.sleep(5)
def worker(id):
    print("Worker started from thread", id)
    count = 1
    while count < 5:
        print("Working...")
        tmp_thread = Thread(target=sub_worker, args=[count])
        tmp_thread.start()
        count +=1
        time.sleep(1)
    raise EnvironmentError("Tired of working")

main = Thread(target=worker, args=[0])

main.start()
</code>```

Which gives us the output (as expected an error in the parent thread does not stop the "children"):

```<code>Worker started from thread 0
Working...
SubWorker started from thread 1
Subworking...
Working...
SubWorker started from thread 2
Subworking...
Working...
SubWorker started from thread 3
Subworking...
Working...
SubWorker started from thread 4
Subworking...
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Temp\tt\Tools\Anaconda3.4.3.1\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Temp\tt\Tools\Anaconda3.4.3.1\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Temp/tt/Tools/PyCharmWorkspace/xml_parse/test.py", line 18, in worker
    raise EnvironmentError("Tired of working")
OSError: Tired of working

Subworking...
Subworking...
Subworking...
Subworking...
Subworking...
Subworking...
Subworking...
</code>```

I think that htop shows this hierarchy might be due to the fact that threads are treated as processes by the Linux kernel. And since a call to fork is made it can shows this hierarchy. With the concept of threads, I do not believe that a hierarchy makes so much sense as each of them will share the same resources (memory, file descriptors ...etc)

Body:
I am familiar with the syntax for creating threads in python.

from threading import Thread
from queue import Queue

task_queue = Queue(maxsize=0)

num_threads=10
for i in range(num_threads):
    thread = Thread(target=work, args=(task_queue,))
    thread.start()

task_queue.join()

My question is weather it is ok to open up new threads 'inside' other threads like so:

def work(task_queue):
    task = task_queue.get()

    subtasks = task.get_sub_tasks()

    for subtask in subtasks:
        thread = Thread(target=sub_work, args(subtask,))
        thread.start()

So

Is this structure ok? or is it to messy to do it this way?

If this is ok, are the sub-thread processes subordinated to the thread that generated it, or do they become children of the parent python process? If the thread that created the sub-thread "dies" with an error, what happens to the sub-thread?

I realize python threads are subject to the interpreter global lock, but my application involves access to a server, so the multi threading is to avoid serialized connections which would take too long.

Body:
So regarding your questions:

Q1: It is not a problem to start "subthreads" from a thread

Q2: It is actually an interesting question, my instinct would say "no", but getting a proof sounds better to me

So I created a quick test as below (I would use a gist but I can't access such things from where I am):

from threading import Thread
import time

def sub_worker(id):
    print("SubWorker started from thread", id)
    while True:
        print("Subworking...")
        time.sleep(5)
def worker(id):
    print("Worker started from thread", id)
    count = 1
    while count < 5:
        print("Working...")
        tmp_thread = Thread(target=sub_worker, args=[count])
        tmp_thread.start()
        count +=1
        time.sleep(1)
    raise EnvironmentError("Tired of working")

main = Thread(target=worker, args=[0])

main.start()

Which gives us the output (as expected an error in the parent thread does not stop the "children"):

Worker started from thread 0
Working...
SubWorker started from thread 1
Subworking...
Working...
SubWorker started from thread 2
Subworking...
Working...
SubWorker started from thread 3
Subworking...
Working...
SubWorker started from thread 4
Subworking...
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Temp\tt\Tools\Anaconda3.4.3.1\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Temp\tt\Tools\Anaconda3.4.3.1\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Temp/tt/Tools/PyCharmWorkspace/xml_parse/test.py", line 18, in worker
    raise EnvironmentError("Tired of working")
OSError: Tired of working

Subworking...
Subworking...
Subworking...
Subworking...
Subworking...
Subworking...
Subworking...

I think that htop shows this hierarchy might be due to the fact that threads are treated as processes by the Linux kernel. And since a call to fork is made it can shows this hierarchy. With the concept of threads, I do not believe that a hierarchy makes so much sense as each of them will share the same resources (memory, file descriptors ...etc)


问:
Errors when running my first MongoClient scala code with mongo-scala-driver 2.1.0
I followed the instructions at http://mongodb.github.io/mongo-scala-driver/ to install for scala 2.11. But my first class cannot run.

```<code>def main(args: Array[String]): Unit = {
   val mongoClient: MongoClient = if (args.isEmpty) MongoClient() else MongoClient("mongodb://localhost")
}
</code>```

Exception:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.connection.DefaultClusterFactory.create(Lcom/mongodb/connection/ClusterSettings;Lcom/mongodb/connection/ServerSettings;Lcom/mongodb/connection/ConnectionPoolSettings;Lcom/mongodb/connection/StreamFactory;Lcom/mongodb/connection/StreamFactory;Ljava/util/List;Lcom/mongodb/event/ClusterListener;Lcom/mongodb/event/ConnectionPoolListener;Lcom/mongodb/event/ConnectionListener;Lcom/mongodb/event/CommandListener;Ljava/lang/String;Lcom/mongodb/client/MongoDriverInformation;)Lcom/mongodb/connection/Cluster;
    at com.mongodb.async.client.MongoClients.createMongoClient(MongoClients.java:188)
    at com.mongodb.async.client.MongoClients.create(MongoClients.java:181)
    at com.mongodb.async.client.MongoClients.create(MongoClients.java:123)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:102)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:77)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:51)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:43)
    at db.mongo.client.MongoClientExample$.main(MongoClientExample.scala:18)
    at db.mongo.client.MongoClientExample.main(MongoClientExample.scala)
</code>```

答:
I have had the same problem and it was due to a wrong dependency to the underlying Java driver. The Mongo Spark connector had a dependency to version 3.2.2 of the Java driver, which apparently was also used by the Scala driver. I solved the problem by defining the dependencies as follows in sbt:

```<code>val mongoScalaDriver = "org.mongodb.scala" %% "mongo-scala-driver" % "2.1.0"
  val mongoJavaDriver = "org.mongodb" % "mongo-java-driver" % "3.4.2"
  val mongoSpark = Seq(mongoScalaDriver, mongoJavaDriver, "org.mongodb.spark" %% "mongo-spark-connector" % "2.0.0")
</code>```

I use then mongoSpark in my library project. Also, I added explicitly a dependency to version 3.4.2 of the Java driver.

Body:
I followed the instructions at http://mongodb.github.io/mongo-scala-driver/ to install for scala 2.11. But my first class cannot run.

def main(args: Array[String]): Unit = {
   val mongoClient: MongoClient = if (args.isEmpty) MongoClient() else MongoClient("mongodb://localhost")
}

Exception:

Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.connection.DefaultClusterFactory.create(Lcom/mongodb/connection/ClusterSettings;Lcom/mongodb/connection/ServerSettings;Lcom/mongodb/connection/ConnectionPoolSettings;Lcom/mongodb/connection/StreamFactory;Lcom/mongodb/connection/StreamFactory;Ljava/util/List;Lcom/mongodb/event/ClusterListener;Lcom/mongodb/event/ConnectionPoolListener;Lcom/mongodb/event/ConnectionListener;Lcom/mongodb/event/CommandListener;Ljava/lang/String;Lcom/mongodb/client/MongoDriverInformation;)Lcom/mongodb/connection/Cluster;
    at com.mongodb.async.client.MongoClients.createMongoClient(MongoClients.java:188)
    at com.mongodb.async.client.MongoClients.create(MongoClients.java:181)
    at com.mongodb.async.client.MongoClients.create(MongoClients.java:123)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:102)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:77)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:51)
    at org.mongodb.scala.MongoClient$.apply(MongoClient.scala:43)
    at db.mongo.client.MongoClientExample$.main(MongoClientExample.scala:18)
    at db.mongo.client.MongoClientExample.main(MongoClientExample.scala)

Body:
I have had the same problem and it was due to a wrong dependency to the underlying Java driver. The Mongo Spark connector had a dependency to version 3.2.2 of the Java driver, which apparently was also used by the Scala driver. I solved the problem by defining the dependencies as follows in sbt:

val mongoScalaDriver = "org.mongodb.scala" %% "mongo-scala-driver" % "2.1.0"
  val mongoJavaDriver = "org.mongodb" % "mongo-java-driver" % "3.4.2"
  val mongoSpark = Seq(mongoScalaDriver, mongoJavaDriver, "org.mongodb.spark" %% "mongo-spark-connector" % "2.0.0")

I use then mongoSpark in my library project. Also, I added explicitly a dependency to version 3.4.2 of the Java driver.


问:
Functional Programming style growing array loop
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)```
</div>
</div>
</p>

<p>After execution got </p>

```[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]
```

<p>But if I try with an alternative "funcional" mode like forEach the new added elements are not printed</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)</code>```

答:
As Rubens rightfully noticed, functional way assumes that your functions do not mutate source data, but rather transform it and return new values.

In the following example source array is kept untouched and transform iterates through it by calling itself recursively and passing updated arguments:

function transform(array, limit, acc = []) {
    if (limit === 0 || array.length === 0) {
        return acc;
    }

    const head = array[0];
    const tail = array.slice(1);
    return transform(tail.concat(head + "-"), limit - 1, acc.concat(head));
}

transform(["x", "y"], 5).forEach(x => console.log(x))```
</div>
</div>
</p>

<p>Resulting array is limited by the <code>limit</code> argument, <code>limit = 5</code> means that only 5 elements will end up in the result.</p>

<p>If we look at the arguments that are passed to the <code>transform</code> function on each iteration, we would see that <code>limit</code> gets smaller while <code>acc</code> (short for <code>accumulator</code>) receives new elements:</p>

```transform(["x",   "y"],    5, [])
transform(["y",   "x-"],   4, ["x"])
transform(["x-",  "y-"],   3, ["x", "y"])
transform(["y-",  "x--"],  2, ["x", "y", "x-"])
transform(["x--", "y--"],  1, ["x", "y", "x-", "y-"])
transform(["y--", "x---"], 0, ["x", "y", "x-", "y-", "x--"])
```

When limit reaches zero, acc value is returned as a result. Note that no data gets mutated.

It worth mentioning that transform call is in a tail position and since ES6 optimizes tail calls (in strict mode), we don't have to worry about growing call stack.

Note also that the code above only illustrates the idea. It should be used with care as it might be very slow on large amounts of data because of sliceing and concating arrays on each iteration.

Update on tail call optimization: even though tail call optimization is a part of the ES6 specification, it is not widely supported by browsers, so you need to be cautious when using recursion. See compatibility table.

Body:
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)

After execution got

[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]

But if I try with an alternative "funcional" mode like forEach the new added elements are not printed

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)

Body:
As Rubens rightfully noticed, functional way assumes that your functions do not mutate source data, but rather transform it and return new values.

In the following example source array is kept untouched and transform iterates through it by calling itself recursively and passing updated arguments:

function transform(array, limit, acc = []) {
    if (limit === 0 || array.length === 0) {
        return acc;
    }

    const head = array[0];
    const tail = array.slice(1);
    return transform(tail.concat(head + "-"), limit - 1, acc.concat(head));
}

transform(["x", "y"], 5).forEach(x => console.log(x))

Resulting array is limited by the limit argument, limit = 5 means that only 5 elements will end up in the result.

If we look at the arguments that are passed to the transform function on each iteration, we would see that limit gets smaller while acc (short for accumulator) receives new elements:

transform(["x",   "y"],    5, [])
transform(["y",   "x-"],   4, ["x"])
transform(["x-",  "y-"],   3, ["x", "y"])
transform(["y-",  "x--"],  2, ["x", "y", "x-"])
transform(["x--", "y--"],  1, ["x", "y", "x-", "y-"])
transform(["y--", "x---"], 0, ["x", "y", "x-", "y-", "x--"])

When limit reaches zero, acc value is returned as a result. Note that no data gets mutated.

It worth mentioning that transform call is in a tail position and since ES6 optimizes tail calls (in strict mode), we don't have to worry about growing call stack.

Note also that the code above only illustrates the idea. It should be used with care as it might be very slow on large amounts of data because of sliceing and concating arrays on each iteration.

Update on tail call optimization: even though tail call optimization is a part of the ES6 specification, it is not widely supported by browsers, so you need to be cautious when using recursion. See compatibility table.


问:
How do websites code those "What Character Are You" Facebook links?
Here is an example of what I am referring to: Facebook Example

I don't understand how this is coded. Is it simply some code that states if your name begins with the letter "A" then you are this person, "B" then this person, etc... or is it more complex then that. I have seen people whose names both begin with "A" get different results, so could it be just a random result? And how would this all be coded on the website's end, since Facebook just pulls up an image/text preview of the site (which is also another question, how could so many "sites/name" exist for every name possible)

Any insight would be greatly appreciated!

答:
There is many different ways this could be achieved but if you were speaking generally I would assume they where chosen at random for either an object, array, database etc. An example of this would be the following using a JavaScript array

```<code>const la = ["Goofy", "Bugs Bunny", "Yosemite Sam", "Porky Pig"]
const generateRandomCharacter = () => {
    return `Your character is: ${la[Math.floor((Math.random() * la.length} + 0)]}`)
}
alert(generateRandomCharacter) /* would return your random character */
</code>```

running the generateRandomCharacter would return your random character.
Again this could be achieved many other ways this is just an example.

For your question about 'how that many sites could exist' well from my very minimal experience with php I create a site that would write a new file each time a user loaded. I speculate that whenever you were to click the button to generate your character it was writing a file with your randomly chosen character and your facebook name as the filename but again my php knowledge is very minimal.

Hope this helped somehow.

Body:
There is many different ways this could be achieved but if you were speaking generally I would assume they where chosen at random for either an object, array, database etc. An example of this would be the following using a JavaScript array

const la = ["Goofy", "Bugs Bunny", "Yosemite Sam", "Porky Pig"]
const generateRandomCharacter = () => {
    return `Your character is: ${la[Math.floor((Math.random() * la.length} + 0)]}`)
}
alert(generateRandomCharacter) /* would return your random character */

running the generateRandomCharacter would return your random character.
Again this could be achieved many other ways this is just an example.

For your question about 'how that many sites could exist' well from my very minimal experience with php I create a site that would write a new file each time a user loaded. I speculate that whenever you were to click the button to generate your character it was writing a file with your randomly chosen character and your facebook name as the filename but again my php knowledge is very minimal.

Hope this helped somehow.


问:
Error:Execution failed for task when using MQTT dependencies ...paho.android.service:1.0.2
I have just started using MQTT protocol with Android Studio. Using mosquitto broker. The app built successfully with Android Studio if i remove this dependience from grandle :
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2  ,
but the app dosn't start.

When i compile including the string :
complile 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'
the errore is :

*Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;*

I tried many different alternatives but no one worked good.
I have no any ideas

答:
Try to modify your app's build.gradle file (dependencies section) like this:

```<code>compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
    exclude module: 'support-v4'
}
</code>```

The error is throwing (maybe) because you are trying to 'include' the support-v4 module more than once.

Body:
Try to modify your app's build.gradle file (dependencies section) like this:

compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
compile('org.eclipse.paho:org.eclipse.paho.android.service:1.0.2') {
    exclude module: 'support-v4'
}

The error is throwing (maybe) because you are trying to 'include' the support-v4 module more than once.


问:
Post Increment and assigning to same variable
```<code>int b = 2;

c= b++;
System.out.Println("C :"+c+"B"+b);
</code>```

c will be 2 and b will be 3.

```<code>int b = 2;

b= b++;
System.out.Println("B:"+b);
</code>```

Here I wonder what is getting incremented. and where does that incremented value goes.

答:
Well this is tricky. Let's take a look what the post-increment operator does. The JLS states:

The value of the postfix increment expression is the value of the variable before the new value is stored.

So in your code b++ has the value 2, independently from the incrementation of b.

If you do an assignment, the right-hand side expression is evaluated first and then its value is stored into the variable.

It's straightforward if you do c = b++. The expression b++ has the value 2 which gets assigned to c. After that statement b has the incremented value 3. But that's a little simplified. What actually happens is, that b++ is evaluated first, meaning b is incremented before the assignment takes place, not after.

So what happens when you do b = b++? Well, it's just the same: The b++ is evaluated first, meaning b is incremented. After that the assignment takes place and the value of the expression b++ is assigned to b. This is still 2 and overwrites your incremented b.

Fun fact: If I enter your second code in my Eclipse, Findbugs issues the following warning:

Bug: Overwritten increment in MyClass.main(String[])

The code performs an increment operation (e.g., i++) and then immediately overwrites it. For example, i = i++ immediately overwrites the incremented value with the original value.

Body:
int b = 2;

c= b++;
System.out.Println("C :"+c+"B"+b);

c will be 2 and b will be 3.

int b = 2;

b= b++;
System.out.Println("B:"+b);

Here I wonder what is getting incremented. and where does that incremented value goes.


问:
Disable application insights in debug
How can I disable application insights automatically when using a debug configuration and enable it only on release?

Is it possible to do this without creating another instrumentation key only for debug?

I have trackevent statements scattered all over the code, enclosing them inside a debug preprocessor check is not an ideal solution.

My current solution is to set the Build Action of the ApplicationInsights.config file to None so that it's not copied to the project's output directory, but this isn't a process that can be automated based on the active build configuration.

There is a Developer Mode but needs to be changed manually (if it was possible to conditionally set the config file, emptying the instrumentationkey solved problem as well). See http://apmtips.com/blog/2015/02/02/developer-mode/

Reference: http://blogs.msdn.com/b/visualstudioalm/archive/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions.aspx

答:
Slightly different play on some of the other solutions. Put this in your global.asax:

```<code>Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = Debugger.IsAttached;
</code>```

It will turn off app insights debug output when running under the debugger, but allow it under Ctrl+F5 scenarios and debug builds published to test servers

Title: Disable application insights in debug

Body:
Slightly different play on some of the other solutions. Put this in your global.asax:

Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = Debugger.IsAttached;

It will turn off app insights debug output when running under the debugger, but allow it under Ctrl+F5 scenarios and debug builds published to test servers


问:
I am unable to change the directory in cmd
cmd is not able to change the directory using the command

```<code>C:\Windows\system32>CD I:
</code>```

It is going back to same C: directory

The screenshot

答:
Read cd /?  to learn there is a /d switch to change drive and directory at the same time

Keep in mind that a

```<code>cd I:\
</code>```

would have an effect even if the current drive would not change .

An alternative would be

```<code>pushd "I:\"
</code>```

which stores the current location on a stack and can be recalled lateron with

```<code>popd
</code>```

Body:
cmd is not able to change the directory using the command

C:\Windows\system32>CD I:

It is going back to same C: directory

The screenshot

Body:
Read cd /?  to learn there is a /d switch to change drive and directory at the same time

Keep in mind that a

cd I:\

would have an effect even if the current drive would not change .

An alternative would be

pushd "I:\"

which stores the current location on a stack and can be recalled lateron with

popd


问:
Why aren't the co-ordinate variables incrementing and decrementing in my functions in Python?
I'm programming a text based adventure game in Python, where the player moves on a 5x5 grid and picks up items, but I'm having trouble with changing the co-ordinates of the player.
coorx and coory are not incrementing and decrementing within their respective functions.

```<code>coorx = 3 #The beginning x coordinate of the player
coory = 3 #The beginning y coordinate of the player

loop = True
#The dimensions of the map are 5x5.
# __ __ __ __ __
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |><|  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#>< = The player's starting position on the map

def left(coorx):
    if coorx != 1: #This checks if the x co-ordinate is not less than 1 so the player does walk off the map.
        coorx -= 1 #This function moves the player left by decrementing the x co-ordinate.

def right(coorx):
    if coorx != 5: #This checks if the x co-ordinate is not more than 5 so the player does walk off the map.
        coorx += 1 #This function moves the player right by incrementing the x co-ordinate.

def back(coory):
    if coory != 1: #This checks if the y co-ordinate is not less than 1 so the player does walk off the map.
        coory -= 1 #This function moves the player left by decrementing the y co-ordinate.

def forward(coory):
    if coory != 5: #This checks if the y co-ordinate is not more than 5 so the player does walk off the map.
        coory += 1 #This function moves the player right by incrementing the y co-ordinate.

while loop: #This loops as long as the variable "loop" is True, and since "loop" never changes, this is an infinite loop.
    move = input().lower()

    if move == "l":
        left(coorx)
        print("You move left.")
        print(coorx, coory)
    elif move == "r":
        right(coorx)
        print("You move right.")
        print(coorx, coory)
    elif move == "f":
        forward(coory)
        print("You move forward.")
        print(coorx, coory)
    elif move == "b":
        back(coory)
        print("You move backwards.")
        print(coorx, coory)
</code>```

This is what is output.

```<code>>f
>You move forward.
>3 3
>f
>You move forward.
>3 3
>l
>You move left.
>3 3
>l
>You move left.
>3 3
>b
>You move backwards.
>3 3
>b
>You move backwards.
>3 3
>r
>You move right.
>3 3
>r
>You move right.
>3 3
</code>```

As you can see, the co-ordinates do not change from "3 3" throughout. Any assistance with my problem would be greatly appreciated.

答:
Just read something that reminded me of this question. One way to change your co-ordinates without needing to return a value or use global is to use a mutable container type:

```<code>>>> coor = [3, 3]  # x, y
>>>
>>> def left():
...     if coor[0] != 1:
...         coor[0] -= 1
...
>>>
>>> left()
>>> coor
[2, 3]
>>>
</code>```

What's happening here is that the variable coor is only referenced, not assigned to. What you're assigning to is in that container, not the variable coor itself. This uses the implicit existence of the global coor within left() when it's not assigned-to in the same function.

(I guess this is what I had in mind in the first version of my previous answer.)

This will also work with dictionaries, and is a bit more readable:

```<code>>>> coor = dict(x=3, y=3)
>>>
>>> def left():
...     if coor['x'] != 1:
...         coor['x'] -= 1
...
>>>
>>> left()
>>> coor
{'x': 2, 'y': 3}
>>>
</code>```

Body:
I'm programming a text based adventure game in Python, where the player moves on a 5x5 grid and picks up items, but I'm having trouble with changing the co-ordinates of the player.
coorx and coory are not incrementing and decrementing within their respective functions.

coorx = 3 #The beginning x coordinate of the player
coory = 3 #The beginning y coordinate of the player

loop = True
#The dimensions of the map are 5x5.
# __ __ __ __ __
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |><|  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#|  |  |  |  |  |
#|__|__|__|__|__|
#>< = The player's starting position on the map

def left(coorx):
    if coorx != 1: #This checks if the x co-ordinate is not less than 1 so the player does walk off the map.
        coorx -= 1 #This function moves the player left by decrementing the x co-ordinate.

def right(coorx):
    if coorx != 5: #This checks if the x co-ordinate is not more than 5 so the player does walk off the map.
        coorx += 1 #This function moves the player right by incrementing the x co-ordinate.

def back(coory):
    if coory != 1: #This checks if the y co-ordinate is not less than 1 so the player does walk off the map.
        coory -= 1 #This function moves the player left by decrementing the y co-ordinate.

def forward(coory):
    if coory != 5: #This checks if the y co-ordinate is not more than 5 so the player does walk off the map.
        coory += 1 #This function moves the player right by incrementing the y co-ordinate.

while loop: #This loops as long as the variable "loop" is True, and since "loop" never changes, this is an infinite loop.
    move = input().lower()

    if move == "l":
        left(coorx)
        print("You move left.")
        print(coorx, coory)
    elif move == "r":
        right(coorx)
        print("You move right.")
        print(coorx, coory)
    elif move == "f":
        forward(coory)
        print("You move forward.")
        print(coorx, coory)
    elif move == "b":
        back(coory)
        print("You move backwards.")
        print(coorx, coory)

This is what is output.

>f
>You move forward.
>3 3
>f
>You move forward.
>3 3
>l
>You move left.
>3 3
>l
>You move left.
>3 3
>b
>You move backwards.
>3 3
>b
>You move backwards.
>3 3
>r
>You move right.
>3 3
>r
>You move right.
>3 3

As you can see, the co-ordinates do not change from "3 3" throughout. Any assistance with my problem would be greatly appreciated.

Body:
Just read something that reminded me of this question. One way to change your co-ordinates without needing to return a value or use global is to use a mutable container type:

>>> coor = [3, 3]  # x, y
>>>
>>> def left():
...     if coor[0] != 1:
...         coor[0] -= 1
...
>>>
>>> left()
>>> coor
[2, 3]
>>>

What's happening here is that the variable coor is only referenced, not assigned to. What you're assigning to is in that container, not the variable coor itself. This uses the implicit existence of the global coor within left() when it's not assigned-to in the same function.

(I guess this is what I had in mind in the first version of my previous answer.)

This will also work with dictionaries, and is a bit more readable:

>>> coor = dict(x=3, y=3)
>>>
>>> def left():
...     if coor['x'] != 1:
...         coor['x'] -= 1
...
>>>
>>> left()
>>> coor
{'x': 2, 'y': 3}
>>>


问:
CSS 404 Node.JS
I have been trying for a long time to make the CSS file load. I have looked at other stackoverflow  questions and no luck. I have the express.static statements. I have the "standard" file order. It seems that I am doing something very very obvious wrong.</p>

```<code>    <html>
    <head>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <nav>
            <ul>
                <li class="inline"><a class="inline" target="_blank" href="http://instagram.com/blakskyben/?hl=en">My Insta</a></li>
                <li class="inline"><a class="inline" href="/about">About Me</a></li>
                <li class="inline"><a class="inline" href="/">Blogs</a></li>
            </ul>
        </nav>
___________________________________________________________________________
    var express = require("express"),
        app = express(),
        bodyParser = require("body-parser"),
        mongoose = require("mongoose");

    mongoose.connect("mongodb://localhost/blog");

    var blogSchema = new mongoose.Schema({
         title: String,
         content: String
    });

    app.use(express.static("public"));
    app.use(express.static("partials"));

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());

    app.get("/",function(req,res){
        res.redirect("/blogs");
    });

    app.get("/blogs",function(req,res){
        blog.find({},function(err,foundBlogs){
            if(foundBlogs){
                res.render("blogs.ejs",{blogs: foundBlogs});
            } else {
                res.send("Sorry, an error occured retriving the blogs, " + err);
            }
        });
    });

    app.get("/blogs/:id",function(req,res){
        blog.findById(req.params.id,function(err,foundBlog){
            if(foundBlog){
                res.render("show.ejs",{blog: foundBlog});
            } else {
                res.send("Sorry, but there was an error, " + err);
            }
        });
    });

    app.get("/about",function(req,res){
        res.render("about.ejs");
    });

    var blog = mongoose.model("blog",blogSchema);

    //Seed the DB!

    blog.create({
        title: "Camp",
        content: "Blah."
    });

    app.listen(8080);
</code>```

答:
I believe the path to your static directories is wrong. Instead of

```<code>app.use(express.static("public"));
</code>```

try

```<code>app.use(express.static(__dirname + "/public"));
</code>```

Title: CSS 404 Node.JS

Body:
I have been trying for a long time to make the CSS file load. I have looked at other stackoverflow  questions and no luck. I have the express.static statements. I have the "standard" file order. It seems that I am doing something very very obvious wrong.

        <link rel="stylesheet" href="style.css">

My Insta

About Me

Blogs

___________________________________________________________________________
    var express = require("express"),
        app = express(),
        bodyParser = require("body-parser"),
        mongoose = require("mongoose");

    mongoose.connect("mongodb://localhost/blog");

    var blogSchema = new mongoose.Schema({
         title: String,
         content: String
    });

    app.use(express.static("public"));
    app.use(express.static("partials"));

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());

    app.get("/",function(req,res){
        res.redirect("/blogs");
    });

    app.get("/blogs",function(req,res){
        blog.find({},function(err,foundBlogs){
            if(foundBlogs){
                res.render("blogs.ejs",{blogs: foundBlogs});
            } else {
                res.send("Sorry, an error occured retriving the blogs, " + err);
            }
        });
    });

    app.get("/blogs/:id",function(req,res){
        blog.findById(req.params.id,function(err,foundBlog){
            if(foundBlog){
                res.render("show.ejs",{blog: foundBlog});
            } else {
                res.send("Sorry, but there was an error, " + err);
            }
        });
    });

    app.get("/about",function(req,res){
        res.render("about.ejs");
    });

    var blog = mongoose.model("blog",blogSchema);

    //Seed the DB!

    blog.create({
        title: "Camp",
        content: "Blah."
    });

    app.listen(8080);

Body:
I believe the path to your static directories is wrong. Instead of

app.use(express.static("public"));

try

app.use(express.static(__dirname + "/public"));