问:
Why is picture annotation cropped when displaying or saving figure?
I have been working at producing some boxplots that include an image that shows what the parts of boxplots represent. As shown in the top right here. This is fine.

But, if I remove the green dashed line, which removes the legend, then the little boxplot image is cropped out when I view the plot in jupyter, but also if I save it as image file.e.g.

The solution offered here using 'tight' doesn't work, i.e.:

plt.savefig("test1.jpg", dpi=300,bbox_inches='tight')
```

<p>Nor does: </p>

<pre class="lang-py prettyprint-override"><code>plt.tight_layout()
</code>```

I've also tried using AnnotationBbox but can't find a solution.

Working example code below:

import numpy as np

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
df = pd.DataFrame(np.random.randn(40, 4), columns=list('ABCD'))
df['Class']=list('ADFADAFDADFAFDAADFAFDAFDDFADFAFDADDFDFAD')

assay=df

factor_to_plot='A'
f=factor_to_plot

x_axis_factor='Class'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
plt.rcParams['figure.dpi'] = 300
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

#add dashed line at a value
plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
#ax.set_yscale('log')

#add legend for dashed line
#plt.legend(markerscale=1.5,loc='center left',bbox_to_anchor=(1.0, 0.5))

#plt.title("Assay data")

#add gridlines (use for log plots)
plt.grid(True, which='both')

#plot additional percentiles not included in boxplots
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#next line is important, select a column that has no blanks or nans as the total items are counted to produce
#N= annotations to plot.
assay['value']=assay['B']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax, s = "N=\n" +str(int(j[i])),horizontalalignment='center')
    #plt.text(x = x , y = 102.75, s = "n=",horizontalalignment='center')
    x+=1

#add legend image
img = plt.imread("legend4.jpg")
plt.figimage(img, 3900,1800, zorder=1, alpha=1)

'''xy = [1.1, 0.8]
fn = "legend4.jpg"
arr_img = plt.imread(fn, format='jpg')

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy,
                        boxcoords="figure fraction",

                        )

ax.add_artist(ab)'''

#plt.tight_layout()

#use the section below to adjust the y axis lable format to avoid default of 10^1 etc for log scale plots.
#ylabels = ['{:.1f}'.format(y) for y in ax.get_yticks()]
#ax.set_yticklabels(ylabels)

plt.savefig("test1.jpg", dpi=300,bbox_inches='tight')
```

答:
Using guidance from @ImportanceOfBeingErnest I have got what I required but in saved plots only, the jupyter inline displays are still cropped (not showing annotation box) using the code below:

import numpy as np

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
df = pd.DataFrame(np.random.randn(40, 4), columns=list('ABCD'))
df['Class']=list('ADFADAFDADFAFDAADFAFDAFDDFADFAFDADDFDFAD')

assay=df

factor_to_plot='A'
f=factor_to_plot

x_axis_factor='Class'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
plt.rcParams['figure.dpi'] = 300
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

#add dashed line at a value
#plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
#ax.set_yscale('log')

#add legend for dashed line
#plt.legend(markerscale=1.5,loc='center left',bbox_to_anchor=(1.0, 0.5))

#plt.title("Assay data")

#add gridlines (use for log plots)
plt.grid(True, which='both')

#plot additional percentiles not included in boxplots
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#next line is important, select a column that has no blanks or nans as the total items are counted to produce
#N= annotations to plot.
assay['value']=assay['B']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax, s = "N=\n" +str(int(j[i])),horizontalalignment='center')

    x+=1

#add legend image

fn = plt.imread("legend4.jpg")
arr_img = fn

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy=(1.05, 0.5), xycoords="axes fraction",
                                        boxcoords="offset points",
                    pad=0.5

                    )

ax.add_artist(ab)

plt.savefig('test.png', bbox_extra_artists=[a.offsetbox for a in [ab]])
```

I found that I had to delete the 'bbox_inches='tight' part from the final save statement or I found that my 'N=...' text annotations were being cropped. Can't believe it is this hard to do!

gives:

Body:
I have been working at producing some boxplots that include an image that shows what the parts of boxplots represent. As shown in the top right here. This is fine.

But, if I remove the green dashed line, which removes the legend, then the little boxplot image is cropped out when I view the plot in jupyter, but also if I save it as image file.e.g.

The solution offered here using 'tight' doesn't work, i.e.:

plt.savefig("test1.jpg", dpi=300,bbox_inches='tight')

Nor does:

plt.tight_layout()

I've also tried using AnnotationBbox but can't find a solution.

Working example code below:

import numpy as np

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
df = pd.DataFrame(np.random.randn(40, 4), columns=list('ABCD'))
df['Class']=list('ADFADAFDADFAFDAADFAFDAFDDFADFAFDADDFDFAD')

assay=df

factor_to_plot='A'
f=factor_to_plot

x_axis_factor='Class'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
plt.rcParams['figure.dpi'] = 300
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

#add dashed line at a value
plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
#ax.set_yscale('log')

#add legend for dashed line
#plt.legend(markerscale=1.5,loc='center left',bbox_to_anchor=(1.0, 0.5))

#plt.title("Assay data")

#add gridlines (use for log plots)
plt.grid(True, which='both')

#plot additional percentiles not included in boxplots
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#next line is important, select a column that has no blanks or nans as the total items are counted to produce
#N= annotations to plot.
assay['value']=assay['B']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax, s = "N=\n" +str(int(j[i])),horizontalalignment='center')
    #plt.text(x = x , y = 102.75, s = "n=",horizontalalignment='center')
    x+=1

#add legend image
img = plt.imread("legend4.jpg")
plt.figimage(img, 3900,1800, zorder=1, alpha=1)

'''xy = [1.1, 0.8]
fn = "legend4.jpg"
arr_img = plt.imread(fn, format='jpg')

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy,
                        boxcoords="figure fraction",

                        )

ax.add_artist(ab)'''

#plt.tight_layout()

#use the section below to adjust the y axis lable format to avoid default of 10^1 etc for log scale plots.
#ylabels = ['{:.1f}'.format(y) for y in ax.get_yticks()]
#ax.set_yticklabels(ylabels)

plt.savefig("test1.jpg", dpi=300,bbox_inches='tight')

Body:
Using guidance from @ImportanceOfBeingErnest I have got what I required but in saved plots only, the jupyter inline displays are still cropped (not showing annotation box) using the code below:

import numpy as np

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import (TextArea, DrawingArea, OffsetImage,
                                  AnnotationBbox)
df = pd.DataFrame(np.random.randn(40, 4), columns=list('ABCD'))
df['Class']=list('ADFADAFDADFAFDAADFAFDAFDDFADFAFDADDFDFAD')

assay=df

factor_to_plot='A'
f=factor_to_plot

x_axis_factor='Class'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
plt.rcParams['figure.dpi'] = 300
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

#add dashed line at a value
#plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
#ax.set_yscale('log')

#add legend for dashed line
#plt.legend(markerscale=1.5,loc='center left',bbox_to_anchor=(1.0, 0.5))

#plt.title("Assay data")

#add gridlines (use for log plots)
plt.grid(True, which='both')

#plot additional percentiles not included in boxplots
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#next line is important, select a column that has no blanks or nans as the total items are counted to produce
#N= annotations to plot.
assay['value']=assay['B']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax, s = "N=\n" +str(int(j[i])),horizontalalignment='center')

    x+=1

#add legend image

fn = plt.imread("legend4.jpg")
arr_img = fn

imagebox = OffsetImage(arr_img, zoom=0.2)
imagebox.image.axes = ax

ab = AnnotationBbox(imagebox, xy=(1.05, 0.5), xycoords="axes fraction",
                                        boxcoords="offset points",
                    pad=0.5

                    )

ax.add_artist(ab)

plt.savefig('test.png', bbox_extra_artists=[a.offsetbox for a in [ab]])

I found that I had to delete the 'bbox_inches='tight' part from the final save statement or I found that my 'N=...' text annotations were being cropped. Can't believe it is this hard to do!

gives:


来源: stackexchange

问:
Get BootstrapVue Dropdown (b-dropdown) to show when clicking a button
Using Vue.js 2.6.10 and BootstrapVue 2.0.0-rc.20 and trying to programmatically display a dropdown when clicking a separate button in a single file component.

```<code><template lang='pug'>
div
  b-button(@click='loginShow') Test
  b-dropdown(id='login-dropdown', ref='dropdown', text='Login')
    b-dropdown-item(to='/login') Login
    b-dropdown-item(to='/signup') Sign up
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { BDropdown } from 'bootstrap-vue';

@Component
export default class Login extends Vue {

  private loginShow(e: any): void {
    const dropdown = this.$refs.dropdown as BDropdown;
    dropdown.visible = true;
  }
}
</script>
</code>```

Any idea what's happening?

答:
Oddly, directly setting the visible property using TypeScript didn't work though it worked fine using ES6 per @Riddhi's codepen.

My solution was to update bootstrap-vue to 2.0.0-rc.21 and use the show() method:

```<code><template lang='pug'>
div
  b-button(@click='loginShow') Test
  b-dropdown(id='login-dropdown', ref='dropdown', text='Login')
    b-dropdown-item(to='/login') Login
    b-dropdown-item(to='/signup') Sign up
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { BDropdown } from 'bootstrap-vue';

@Component
export default class Login extends Vue {

  private loginShow(e: any): void {
    const dropdown = this.$refs.dropdown as BDropdown;
    dropdown.show();
  }
}
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using Vue.js 2.6.10 and BootstrapVue 2.0.0-rc.20 and trying to programmatically display a dropdown when clicking a separate button in a single file component.

<template lang='pug'>
div
  b-button(@click='loginShow') Test
  b-dropdown(id='login-dropdown', ref='dropdown', text='Login')
    b-dropdown-item(to='/login') Login
    b-dropdown-item(to='/signup') Sign up
</template>

Any idea what's happening?

Body:
Oddly, directly setting the visible property using TypeScript didn't work though it worked fine using ES6 per @Riddhi's codepen.

My solution was to update bootstrap-vue to 2.0.0-rc.21 and use the show() method:

<template lang='pug'>
div
  b-button(@click='loginShow') Test
  b-dropdown(id='login-dropdown', ref='dropdown', text='Login')
    b-dropdown-item(to='/login') Login
    b-dropdown-item(to='/signup') Sign up
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { BDropdown } from 'bootstrap-vue';

@Component
export default class Login extends Vue {

  private loginShow(e: any): void {
    const dropdown = this.$refs.dropdown as BDropdown;
    dropdown.show();
  }
}
</script>


问:
How to filter object array based on attributes?
I have the following JavaScript array of real estate home objects:

```<code>var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...
    ]
}

var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;
</code>```

What I would like to do is be able to perform a filter on the object to return a subset of "home" objects.

For example, I want to be able to filter based on: price, sqft, num_of_beds, and num_of_baths.

How can I perform something in JavaScript like the pseudo-code below:

```<code>var newArray = homes.filter(
    price <= 1000 &
    sqft >= 500 &
    num_of_beds >=2 &
    num_of_baths >= 2.5 );
</code>```

Note, the syntax does not have to be exactly like above. This is just an example.

答:
I'm surprised no one has posted the one-line response:

```<code>const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);
</code>```

...and just so you can read it easier:

```<code>const filteredHomes = json.homes.filter( x =>
  x.price <= 1000 &&
  x.sqft >= 500 &&
  x.num_of_beds >=2 &&
  x.num_of_baths >= 2.5
);
</code>```

Body:
I have the following JavaScript array of real estate home objects:

var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...
    ]
}

var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;

What I would like to do is be able to perform a filter on the object to return a subset of "home" objects.

For example, I want to be able to filter based on: price, sqft, num_of_beds, and num_of_baths.

How can I perform something in JavaScript like the pseudo-code below:

var newArray = homes.filter(
    price <= 1000 &
    sqft >= 500 &
    num_of_beds >=2 &
    num_of_baths >= 2.5 );

Note, the syntax does not have to be exactly like above. This is just an example.

Body:
I'm surprised no one has posted the one-line response:

const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...and just so you can read it easier:

const filteredHomes = json.homes.filter( x =>
  x.price <= 1000 &&
  x.sqft >= 500 &&
  x.num_of_beds >=2 &&
  x.num_of_baths >= 2.5
);


问:
I am seeing a "GET /emp HTTP/1.1" 404 2159 on my terminal when I try to connect to the django server ...I am receiving a 404 page not found
I feel like my server can't render my views well because of some url configuration issues.It always render the message Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/emp

Here is my project structure

```<code>|--hrdjango
 |--employee
   |--migrations folder
   |--admin.py
   |--urls.py
    ...
   |views.py

|--hrdjango
  ...
 |--settings.py
 |--urls.py
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from .forms import EmployeeForm
from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

</code>```

employee/urls.py

```<code>
from .import views
from django.contrib import admin
from django.urls import path, include
app_name = 'employee'
urlpatterns = [
    path('', views.emp, name='emp'),
    path('show',views.show, name='show'),
    path('edit/<int:id>', views.edit, name='edit'),
    path('update/<int:id>', views.update, name='update'),
    path('delete/<int:id>', views.destroy, name='destroy'),
    ]
</code>```

hrdjango/urls

```<code>
from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
path('', views.emp),
]
</code>```

I was expecting to see the views rendering according to my urls config, but it seems like it can't render my views because it is not seeing it.

答:
You have not any url with this URL pattern http://127.0.0.1:8000/emp, instead of that, have you tried e.g with:

http://127.0.0.1:8000/

http://127.0.0.1:8000/show

Or other URL defined in employee/urls.py

Body:
I feel like my server can't render my views well because of some url configuration issues.It always render the message Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/emp

Here is my project structure

|--hrdjango
 |--employee
   |--migrations folder
   |--admin.py
   |--urls.py
    ...
   |views.py

|--hrdjango
  ...
 |--settings.py
 |--urls.py

views.py

from django.shortcuts import render, redirect
from .forms import EmployeeForm
from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

employee/urls.py

from .import views
from django.contrib import admin
from django.urls import path, include
app_name = 'employee'
urlpatterns = [
    path('', views.emp, name='emp'),
    path('show',views.show, name='show'),
    path('edit/<int:id>', views.edit, name='edit'),
    path('update/<int:id>', views.update, name='update'),
    path('delete/<int:id>', views.destroy, name='destroy'),
    ]

hrdjango/urls

from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
path('', views.emp),
]

I was expecting to see the views rendering according to my urls config, but it seems like it can't render my views because it is not seeing it.


问:
Create style that extends from default style set in application theme
I have set the default button style in my application theme, so that it is applied to every button in the app.

There are few buttons that need to have their text capitalized in addition to default style. So what I'm trying to do is something like this

(the following code snippet doesn't work as I cannot set parent="?attr/materialButtonStyle"):

```<code><style name="capitalizedButton" parent="?attr/materialButtonStyle">
    <item name="android:textAllCaps">true</item>
</style>
</code>```

Is it possible to extend a style defined in theme.xml? I don't want to refer to the local style that I'm setting in theme as that can change later, instead I intend to access it using theme attribute.

答:
If the capitalization happens in addition to your custom default button style, there is no need to make the capitalization style a child of ?attr/materialButtonStyle (This cannot be done anyhow, as ?attr references an attribute in the currently applied theme). You can read more about it here.

styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="buttonStyle">@style/DefaultButton</item>
</style>

<style name="DefaultButton" parent="Widget.AppCompat.Button">
    <item name="android:textColor">@color/white</item>
</style>

<style name="AllCapsButton">
    <item name="android:textAllCaps">true</item>
</style>
</code>```

layout.xml

```<code><Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:theme="@style/AllCapsButton"/>
</code>```

In the code above, button gets the DefaultButton style (white text) applied by the theme, and the AllCapsButton style (capitalized text) applied in the layout file.

Body:
I have set the default button style in my application theme, so that it is applied to every button in the app.

There are few buttons that need to have their text capitalized in addition to default style. So what I'm trying to do is something like this

(the following code snippet doesn't work as I cannot set parent="?attr/materialButtonStyle"):

Is it possible to extend a style defined in theme.xml? I don't want to refer to the local style that I'm setting in theme as that can change later, instead I intend to access it using theme attribute.

Body:
If the capitalization happens in addition to your custom default button style, there is no need to make the capitalization style a child of ?attr/materialButtonStyle (This cannot be done anyhow, as ?attr references an attribute in the currently applied theme). You can read more about it here.

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="buttonStyle">@style/DefaultButton</item>
</style>

<style name="DefaultButton" parent="Widget.AppCompat.Button">
    <item name="android:textColor">@color/white</item>
</style>

<style name="AllCapsButton">
    <item name="android:textAllCaps">true</item>
</style>

layout.xml

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:theme="@style/AllCapsButton"/>

In the code above, button gets the DefaultButton style (white text) applied by the theme, and the AllCapsButton style (capitalized text) applied in the layout file.


问:
Change innerHTML results based on selected "option"
I am trying to have it when I select an option from my dropdown menu it will update the results with the correct info from the data.json file. Right now it will return the stringified data from data[0], but I am wanting it to return based on the selected option id. So if the user selects "Sarah", being option id="4", I am wanting it to take the data from the 4th JSON object.

<select id="options" onchange="myfunction()">
    <option ></option>
    <option id="0">Tyson</option>
    <option id="1">Jessica</option>
    <option id="2">Joshua</option>
    <option id="3">Jennifer</option>
    <option id="4">Sarah</option>
</select>

```

```function myfunction() {
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
    function appendData(data) {
        var mainContainer = document.getElementById("myData");

        var div = document.createElement("div");
        div.innerHTML = JSON.stringify(data[0], null, 4);
        mainContainer.appendChild(div);
    }
}
```

```[
  {
  "id" : 0,
  "first_name": "Tyson",
  "gender": "male",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },

  {
  "id" : 1,
  "first_name": "Jessica",
  "gender": "female",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },
  {
    "id" : 2,
    "first_name": "Joshua",
    "gender": "male",
    "isAlive": true,
    "married": true,
    "has_children": true,
  },

  {
    "id" : 3,
    "first_name": "Jennifer",
    "gender": "female",
    "isAlive": true,
    "married": true,
    "has_children": true,
 },
  {
    "id" : 4,
    "first_name": "Sarah",
    "gender": "female",
    "isAlive": true,
    "married": false,
    "has_children": false,
  }
```

答:
First, move appendData out of myfunction. It doesn't need to be nested.

Secondly, you need to capture the selected value of your dropdown within myfunction, and then filter your data collection based on that. Something like this, perhaps:

```<code>function myfunction() {
    var selectedId = document.getElementById("options").value; // e.g. "4" (string)
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            // let's filter the data
            var person = data.filter(function(p) { return p.id == selectedId; });
            appendData(person);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
}
</code>```

Lastly, you have to slightly adjust your appendData function to not try to index the data object anymore, because it's no longer an array:

```<code>function appendData(data) {
    var mainContainer = document.getElementById("myData");

    var div = document.createElement("div");
    div.innerHTML = JSON.stringify(data, null, 4);
    mainContainer.appendChild(div);
}
</code>```

One final suggestion would be to not put events in your HTML attributes. This is very antiquated. Instead, learn how to attach events to elements via the DOM using addEventListener.

Body:
I am trying to have it when I select an option from my dropdown menu it will update the results with the correct info from the data.json file. Right now it will return the stringified data from data[0], but I am wanting it to return based on the selected option id. So if the user selects "Sarah", being option id="4", I am wanting it to take the data from the 4th JSON object.

<select id="options" onchange="myfunction()">
    <option ></option>
    <option id="0">Tyson</option>
    <option id="1">Jessica</option>
    <option id="2">Joshua</option>
    <option id="3">Jennifer</option>
    <option id="4">Sarah</option>
</select>

function myfunction() {
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
    function appendData(data) {
        var mainContainer = document.getElementById("myData");

        var div = document.createElement("div");
        div.innerHTML = JSON.stringify(data[0], null, 4);
        mainContainer.appendChild(div);
    }
}

[
  {
  "id" : 0,
  "first_name": "Tyson",
  "gender": "male",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },

  {
  "id" : 1,
  "first_name": "Jessica",
  "gender": "female",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },
  {
    "id" : 2,
    "first_name": "Joshua",
    "gender": "male",
    "isAlive": true,
    "married": true,
    "has_children": true,
  },

  {
    "id" : 3,
    "first_name": "Jennifer",
    "gender": "female",
    "isAlive": true,
    "married": true,
    "has_children": true,
 },
  {
    "id" : 4,
    "first_name": "Sarah",
    "gender": "female",
    "isAlive": true,
    "married": false,
    "has_children": false,
  }

Body:
First, move appendData out of myfunction. It doesn't need to be nested.

Secondly, you need to capture the selected value of your dropdown within myfunction, and then filter your data collection based on that. Something like this, perhaps:

function myfunction() {
    var selectedId = document.getElementById("options").value; // e.g. "4" (string)
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            // let's filter the data
            var person = data.filter(function(p) { return p.id == selectedId; });
            appendData(person);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
}

Lastly, you have to slightly adjust your appendData function to not try to index the data object anymore, because it's no longer an array:

function appendData(data) {
    var mainContainer = document.getElementById("myData");

    var div = document.createElement("div");
    div.innerHTML = JSON.stringify(data, null, 4);
    mainContainer.appendChild(div);
}

One final suggestion would be to not put events in your HTML attributes. This is very antiquated. Instead, learn how to attach events to elements via the DOM using addEventListener.


问:
Using Silverlight for an entire website?
We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?

The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.

I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.

Are there any big no-nos from the experience of StackOverflowers? What are the big positives?

答:
The previous comments have dealt with most of the downsides of using Silverlight for a site like this and I agree. If you're determined to have rich-client style development and your audience is small (for admins only) then I'd probably recommend WPF over Silverlight as it currently provides a richer set of tools and controls.

If you stick with ASP.NET have you looked at Dynamic Data - it's ideal for building backend management sites with little effort.

OwnerDisplayName: Sam

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sam

OwnerDisplayName: Simon


问:
Storing word documents
I'm working on job site (using asp.net 3.5) in which a user can upload one or more resumes.
Database is sql server 2005.
Whats the recommendation regarding storage of these documents?
Shall i store it as a blob in the database or just store the path in database and keep the document in the physical folder?
Can someone please mention the pros and cons of each wrt performance and scalability?

Thanks!

答:
Keeping your data in the database will make managing the date much easier. You won't have to make sure the data in the database is in sync with the data (file paths) on the filesystem.

Having said that, it is important to realize there might be a performance hit when storing large blobs in the database. Fortunately, there has been some research done in this area to investigate possible scenarios. I would recommend you take a look at this paper by Microsoft Research on the subject. Hope that helps.

Furthermore, I should mention that Microsoft SharePoint stores its Word documents (as well as other files) in SQL Server databases as blobs. You can read more about this here.

OwnerDisplayName: Patrick

Title: Storing word documents

OwnerDisplayName: fuentesjr

LastEditorDisplayName: fuentesjr


问:
Sales force default access
What is the default access specifier in sfdc?

eg if you declare a class as:

```<code>  class MyClass{
      //Code
   }
</code>```

then by default what will be the access specifier for this class?

答:
You cannot define an outer class without an access modifier, you must specify public or global. If you try you'll get a compile error:

Save error: Top-level type must have
  public or global visibility

Inner classes on the other hand do not require access modifier and are private by default.

ContentLicense: CC BY-SA 3.0

Title: Sales force default access

Body:
What is the default access specifier in sfdc?

eg if you declare a class as:

  class MyClass{
      //Code
   }

then by default what will be the access specifier for this class?


问:
Retrieve access_token from cookie for Azure AD Passport BearerStrategy
I have a webapp which uses OIDCStrategy to authenticate the user. It uses cookies instead of sessions with the useCookieInsteadOfSession flag. My other app is an API protected by BearerStrategy. My webapp, using axios withCredentials: true I'm sending over the browser cookie. But at the API, the BearerStrategy only checks the request header for Authorization. Is there any way to extract the access_token in the cookie?

答: From what i understand (of the technology and from your question) you need to use an Auth library like Passport-Azure-Ad for javascript.</p>


问:
How does php acts in concern of destroyed sessions when it is storing sessions with redis?
I've editted my php configs to save sessions on redis. Everything is working fine but I realized that one day has gone and by running command KEYS * on redis-cli, shows a huge list of php-session entries. My question is if php will remove these keys at any moment or I have to do something for that happen. I got worried with that.</p>

答: I did some tests and can tell you YES, PHP remove entries added by its session manager system into Redis. You can verify that by changing option session.gc_maxlifetime = XX in /etc/php.ini, where XX is the time in seconds to collect the expired sessions.


问:
When to use full system FS vs syscall emulation SE with userland programs in gem5?
Since syscall emulation is much easier to setup, I'm wondering what are the advantages of using the full system emulation when running an userland program.

Or in other words, what interesting aspects are modeled in the full system but not syscall emulation mode, and when are they significant?

It is mentioned in the docs at: http://gem5.org/Splash_benchmarks that full system is

Realistic: you're getting the actual Linux thread scheduler to schedule your threads

Is this the only advantage, or are there any other advantage for users that are optimizing their applications or investigating micro-architecture?

I also suspect that the MMU simulation is another important feature that is only modeled properly in full system mode, and could affect program performance.

答:
Full system mode should be preferred (when it is possible to use it). There are benefits to using it, primarily fidelity in the simulation which is not possible with system call emulation mode. (The kernel interactions with an application can be important depending on the study that a researcher is trying to conduct.) Also, the user does not need to worry about implementing (or debugging) the system call implementation.

With that said, system call emulation mode can be useful under the right conditions. It is faster to run application code because there is no kernel running in the background. There is also no system noise if you want to mitigate it entirely. Arguably, it is easier to bootstrap a new device model as well. You can work on the model without driver support and make magic happen though fake interfaces. (It saves you having to model the bare-metal interface perfectly or having to write your own device driver.)

Your comments about dynamic linking and multi-threading support are related. If dynamic linking is fixed, you should be able to use your system's pthreads library and can forget about linking with m5threads entirely. The pthread library support has existed in the simulator for a while now (the system calls necessary for it to work properly).

However, there's a caveat to the threading implementation. You need to preallocate enough thread contexts at the start of simulation (by invoking with the -n option on the se.py script).

To elaborate, there is no operating system running in the background to schedule threads on the processors. (I use the terms threads and processors very loosely here.) To obviate the scheduling problem, you have to preallocate enough processors so that the threads can be created on calls to clone/execve. There is a constraint that you can never have more threads than processors (unlike a real system where the operating system can schedule them as it pleases).

The configuration scripts probably do not behave how a researcher would want them to behave for a multi-threaded workload. The researcher would need to verify that the caches were configured correctly and that they are sharing certain cache levels like a real machine would do. If the application calls clone/execve many times, it may not be possible to cause the generated configuration to behave realistically.

Your last statement about modeling accelerators is incorrect. The AMD GFX8 model does use system call emulation mode. (Also, we developed a NIC model which was never publicly released.) It involves creating a fake driver and manipulating it through the same ioctl interfaces that a real driver would use. Linux treats everything like a file so the driver is opened through the open system call interface and you can capture it there. There are other things which you might need to do (like map mmio ranges in the configuration), but the driver interface is the main piece. The application interacts with the driver and the driver interacts with the accelerator model.


问:
Ingress-Nginx w/ Kubernetes not getting IP address
I am new to Kubernetes and am attempting to get Ingress-Nginx to work on my local k8s cluster.

I have it installed and running:

```<code>$ kubectl get pods --namespace=ingress-nginx
  NAME                                       READY   STATUS    RESTARTS   AGE
  nginx-ingress-controller-76f97b74b-bbb6h   1/1     Running   0          13h
</code>```

Then I created two nginx services (wanted to test name-based routing):

```<code>$ kubectl get svc
  NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
    kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        20h
    nginx        NodePort    10.102.188.253   <none>        80:32025/TCP   36m
    nginx2       NodePort    10.109.43.89     <none>        80:32458/TCP   35m
</code>```

And I created my ingress:

```<code>$ kubectl get ingress -o yaml
apiVersion: v1
items:
- apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    creationTimestamp: 2018-10-25T12:27:44Z
    generation: 1
    name: test
    namespace: default
    resourceVersion: "98114"
    selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/test
    uid: 5fbc2e9e-d851-11e8-995f-2ae1e5e17bac
  spec:
    rules:
    - host: test-ingress.chbresser.com
      http:
        paths:
        - backend:
            serviceName: nginx
            servicePort: 80
    - host: test-ingress2.chbresser.com
      http:
        paths:
        - backend:
            serviceName: nginx2
            servicePort: 80
  status:
    loadBalancer: {}
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""
</code>```

From my understanding that is all I was supposed to do, but its not getting an IP address:

```<code>$ kubectl get ingress
  NAME   HOSTS                                                    ADDRESS   PORTS   AGE
    test   test-ingress.chbresser.com,test-ingress2.chbresser.com             80      33m
</code>```

What step did I miss? Why am I not getting an IP?

Edit:

kubectl logs nginx-ingress-controller-76f97b74b-bbb6h --namespace=ingress-nginx:

```<code>W1025 05:44:10.003587       9 queue.go:130] requeuing &ObjectMeta{Name:sync status,GenerateName:,Namespace:,SelfLink:,UID:,ResourceVersion:,Generation:0,CreationTimestamp:0001-01-01 00:00:00 +0000 UTC,DeletionTimestamp:<nil>,DeletionGracePeriodSeconds:nil,Labels:map[string]string{},Annotations:map[string]string{},OwnerReferences:[],Finalizers:[],ClusterName:,Initializers:nil,}, err services "ingress-nginx" not found
</code>```

答:
I use Bare-metal and get IP address by using --report-node-internal-ip-address=true
flag in ingress-controller.

Here is my ingress-controller yaml:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-ingress-controller
spec:
  replicas: 1
  revisionHistoryLimit: 3
  template:
    metadata:
      labels:
        k8s-app: ingress-nginx
    spec:
      containers:
        - args:
            - /nginx-ingress-controller
            - "--default-backend-service=default/my-app"
            - "--report-node-internal-ip-address=true"
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          image: "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.15.0"
          name: nginx-ingress-controller
          ports:
            - containerPort: 80
              hostPort: 80
              name: http
              protocol: TCP
```

<p>my <code>ingress</code> yaml:</p>

<pre class="lang-html prettyprint-override"><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-app
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: my-app.example.com
    http:
     paths:
     - path: /
       backend:
        serviceName: my-app
        servicePort: 80
</code>```

and result:

$ kubectl get ing
NAME     HOSTS   ADDRESS        PORTS   AGE
my-app   *       192.168.1.78   80      40h

$ kubectl get svc
NAME              TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes        ClusterIP   10.96.0.1        <none>        443/TCP          8d
my-app            ClusterIP   10.110.152.216   <none>        80/TCP,443/TCP   8d

$ kubectl get po
NAME                                        READY   STATUS    RESTARTS   AGE
my-app-rc-d7lw9                             1/1     Running   0          8d
my-app-rc-spvjb                             1/1     Running   0          8d
my-app-rc-tvkrw                             1/1     Running   0          8d
nginx-ingress-controller-6c6c899467-d9sg6   1/1     Running   0          16m
```

for more detail , see this issues.

Body:
I am new to Kubernetes and am attempting to get Ingress-Nginx to work on my local k8s cluster.

I have it installed and running:

$ kubectl get pods --namespace=ingress-nginx
  NAME                                       READY   STATUS    RESTARTS   AGE
  nginx-ingress-controller-76f97b74b-bbb6h   1/1     Running   0          13h

Then I created two nginx services (wanted to test name-based routing):

$ kubectl get svc
  NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
    kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        20h
    nginx        NodePort    10.102.188.253   <none>        80:32025/TCP   36m
    nginx2       NodePort    10.109.43.89     <none>        80:32458/TCP   35m

And I created my ingress:

$ kubectl get ingress -o yaml
apiVersion: v1
items:
- apiVersion: extensions/v1beta1
  kind: Ingress
  metadata:
    creationTimestamp: 2018-10-25T12:27:44Z
    generation: 1
    name: test
    namespace: default
    resourceVersion: "98114"
    selfLink: /apis/extensions/v1beta1/namespaces/default/ingresses/test
    uid: 5fbc2e9e-d851-11e8-995f-2ae1e5e17bac
  spec:
    rules:
    - host: test-ingress.chbresser.com
      http:
        paths:
        - backend:
            serviceName: nginx
            servicePort: 80
    - host: test-ingress2.chbresser.com
      http:
        paths:
        - backend:
            serviceName: nginx2
            servicePort: 80
  status:
    loadBalancer: {}
kind: List
metadata:
  resourceVersion: ""
  selfLink: ""

From my understanding that is all I was supposed to do, but its not getting an IP address:

$ kubectl get ingress
  NAME   HOSTS                                                    ADDRESS   PORTS   AGE
    test   test-ingress.chbresser.com,test-ingress2.chbresser.com             80      33m

What step did I miss? Why am I not getting an IP?

Edit:

kubectl logs nginx-ingress-controller-76f97b74b-bbb6h --namespace=ingress-nginx:

W1025 05:44:10.003587       9 queue.go:130] requeuing &ObjectMeta{Name:sync status,GenerateName:,Namespace:,SelfLink:,UID:,ResourceVersion:,Generation:0,CreationTimestamp:0001-01-01 00:00:00 +0000 UTC,DeletionTimestamp:<nil>,DeletionGracePeriodSeconds:nil,Labels:map[string]string{},Annotations:map[string]string{},OwnerReferences:[],Finalizers:[],ClusterName:,Initializers:nil,}, err services "ingress-nginx" not found

Body:
I use Bare-metal and get IP address by using --report-node-internal-ip-address=true
flag in ingress-controller.

Here is my ingress-controller yaml:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-ingress-controller
spec:
  replicas: 1
  revisionHistoryLimit: 3
  template:
    metadata:
      labels:
        k8s-app: ingress-nginx
    spec:
      containers:
        - args:
            - /nginx-ingress-controller
            - "--default-backend-service=default/my-app"
            - "--report-node-internal-ip-address=true"
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
          image: "quay.io/kubernetes-ingress-controller/nginx-ingress-controller:0.15.0"
          name: nginx-ingress-controller
          ports:
            - containerPort: 80
              hostPort: 80
              name: http
              protocol: TCP

my ingress yaml:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: my-app
  annotations:
    kubernetes.io/ingress.class: "nginx"
spec:
  rules:
  - host: my-app.example.com
    http:
     paths:
     - path: /
       backend:
        serviceName: my-app
        servicePort: 80

and result:

$ kubectl get ing
NAME     HOSTS   ADDRESS        PORTS   AGE
my-app   *       192.168.1.78   80      40h

$ kubectl get svc
NAME              TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes        ClusterIP   10.96.0.1        <none>        443/TCP          8d
my-app            ClusterIP   10.110.152.216   <none>        80/TCP,443/TCP   8d

$ kubectl get po
NAME                                        READY   STATUS    RESTARTS   AGE
my-app-rc-d7lw9                             1/1     Running   0          8d
my-app-rc-spvjb                             1/1     Running   0          8d
my-app-rc-tvkrw                             1/1     Running   0          8d
nginx-ingress-controller-6c6c899467-d9sg6   1/1     Running   0          16m

for more detail , see this issues.


问:
Multi threading question
I'm trying to make a server program for a game, I need to run 3 extra threads in a windows form app. all the threads needs to be able to access the same variables, (thread1: is going to be pulling user commands from my database and executing them, thread2: is going to be updating all the users data and thread3: is going to be sending all the new variables back to the database.) I've looked into background threads and I'm not sure if thats going to do what i want them todo (they look like they could run my code but it looks like they would have a hard time working with the same variables for the all the threads.)

So i guess my question is, is this possible and what is best way to accomplish this, would background workers and invoke do the trick? what problems would i be looking at doing that, anyone have any better idea.

On a side note i had another question thats related ive tried a bunch of times to accomplish this using just simple threads. Now from what i understand doing all of my work on another thread should not lock up my ui, however it does. maybe im doing thread the wrong way, my code looks something like

```<code>dim newthread as new system.threading.thread(addressof runmycode)
newthread.start()`
</code>```

this code isn't exact but why would using threading like this lock up the UI? Shouldn't it be running separately?

答:
Here's a tutorial I wrote a little while back that walks you through creating a basic multi-threading program in VB2008. With VB2010 you can remove the delegates if you want but the idea is pretty much the same.

Creating a simple multi-threaded VB.Net application

Title: Multi threading question

Body:
I'm trying to make a server program for a game, I need to run 3 extra threads in a windows form app. all the threads needs to be able to access the same variables, (thread1: is going to be pulling user commands from my database and executing them, thread2: is going to be updating all the users data and thread3: is going to be sending all the new variables back to the database.) I've looked into background threads and I'm not sure if thats going to do what i want them todo (they look like they could run my code but it looks like they would have a hard time working with the same variables for the all the threads.)

So i guess my question is, is this possible and what is best way to accomplish this, would background workers and invoke do the trick? what problems would i be looking at doing that, anyone have any better idea.

On a side note i had another question thats related ive tried a bunch of times to accomplish this using just simple threads. Now from what i understand doing all of my work on another thread should not lock up my ui, however it does. maybe im doing thread the wrong way, my code looks something like

dim newthread as new system.threading.thread(addressof runmycode)
newthread.start()`

this code isn't exact but why would using threading like this lock up the UI? Shouldn't it be running separately?


问:
Knn prediction going 100% on y_test
I'm trying to implement K-nearest neighbors on Iris dataset but after doing the predictions, yhat goes 100% without errors, there must have something wrong and i have no idea what it is...

I created a column named class_id, where i changed:

setosa = 1.0

versicolor = 2.0

virginica = 3.0

that column is type float.

Getting X an Y

```<code>
    x = df[['sepal length', 'sepal width', 'petal length', 'petal width']].values

</code>```

type(x) shows nparray

```<code>
    y = df['class_id'].values

</code>```

type(y) shows nparray

Normalizing data

```<code>
    x = preprocessing.StandardScaler().fit(x).transform(x.astype(float))

</code>```

Creating train and test

```<code>
    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 42)

</code>```

Checking best K value:

```<code>
    Ks = 12
    for i in range(1,Ks):
       k = i
       neigh = KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
       yhat = neigh.predict(x_test)
       score = metrics.accuracy_score(y_test,yhat)
       print('K: ', k, ' score: ', score, '\n')

</code>```

Result:

K:  1  score:  0.9666666666666667

K:  2  score:  1.0

K:  3  score:  1.0

K:  4  score:  1.0

K:  5  score:  1.0

K:  6  score:  1.0

K:  7  score:  1.0

K:  8  score:  1.0

K:  9  score:  1.0

K:  10  score:  1.0

K:  11  score:  1.0

Printing y_test and yhat WITH K = 5

```<code>
    print(yhat)
    print(y_test)

</code>```

Result:

yhat: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

y_test: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

all of them shouldn't be 100% correct, there must be something wrong

答:
Try to make a confusion matrix. Test every example of your test data, and check metrics of the specificity, sensibility, accuracy and precision.

where:

```<code>TN = True Negative
FN = False Negative
FP = False Positive
TP = True Positive
</code>```

Here you can check what is the difference between specificity and sensibility
https://dzone.com/articles/ml-metrics-sensitivity-vs-specificity-difference

Here you have one example about how you can get one confusion matrix in python using sklearn.

Also try to make a ROC Curve (optional)
https://en.wikipedia.org/wiki/Receiver_operating_characteristic

Title: Knn prediction going 100% on y_test

Body:
I'm trying to implement K-nearest neighbors on Iris dataset but after doing the predictions, yhat goes 100% without errors, there must have something wrong and i have no idea what it is...

I created a column named class_id, where i changed:

setosa = 1.0

versicolor = 2.0

virginica = 3.0

that column is type float.

Getting X an Y

    x = df[['sepal length', 'sepal width', 'petal length', 'petal width']].values

type(x) shows nparray

    y = df['class_id'].values

type(y) shows nparray

Normalizing data

    x = preprocessing.StandardScaler().fit(x).transform(x.astype(float))

Creating train and test

    x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2, random_state = 42)

Checking best K value:

    Ks = 12
    for i in range(1,Ks):
       k = i
       neigh = KNeighborsClassifier(n_neighbors=k).fit(x_train,y_train)
       yhat = neigh.predict(x_test)
       score = metrics.accuracy_score(y_test,yhat)
       print('K: ', k, ' score: ', score, '\n')

Result:

K:  1  score:  0.9666666666666667

K:  2  score:  1.0

K:  3  score:  1.0

K:  4  score:  1.0

K:  5  score:  1.0

K:  6  score:  1.0

K:  7  score:  1.0

K:  8  score:  1.0

K:  9  score:  1.0

K:  10  score:  1.0

K:  11  score:  1.0

Printing y_test and yhat WITH K = 5

    print(yhat)
    print(y_test)

Result:

yhat: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

y_test: [2. 1. 3. 2. 2. 1. 2. 3. 2. 2. 3. 1. 1. 1. 1. 2. 3. 2. 2. 3. 1. 3. 1. 3.
3. 3. 3. 3. 1. 1.]

all of them shouldn't be 100% correct, there must be something wrong

Body:
Try to make a confusion matrix. Test every example of your test data, and check metrics of the specificity, sensibility, accuracy and precision.

where:

TN = True Negative
FN = False Negative
FP = False Positive
TP = True Positive

Here you can check what is the difference between specificity and sensibility
https://dzone.com/articles/ml-metrics-sensitivity-vs-specificity-difference

Here you have one example about how you can get one confusion matrix in python using sklearn.

Also try to make a ROC Curve (optional)
https://en.wikipedia.org/wiki/Receiver_operating_characteristic


问:
How to get around the ' (quote) problem when saving text using SQL
I've a textbox that I save to a SQL Database using ASP.NET C#.

The problem is using quotes, for instance with words like he's and it's.  When you save it, I get an SQL error.

From experience to get around the issue, I use to use replace command to find all occurances of quotes and replace them with another character.  Then if I was to read the database and the text that was previously saved, I'd replace again.

Is there a better of doing this? Or do you still have to use this 'old' way.

答:
Always use parameterized queries.  Never concatenate strings together (with un-sanitised input information) to create SQL on the fly.  You run the risk of being vulnerable to SQL-injection attacks.

Read the following guide carefully:

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx

And when you understand the following comic strip, you are ready to code:

http://xkcd.com/327/


问:
Trouble Compiling App.Js code using use Effect and use State hooks in React
I am trying to run a web page using useState for Game State and setting game state on a website rendered using React. There are problems compiling with three variables undefined. (Set_GAME_State, SNIPPETS and Snippet Index).

This is based on Daniel Katz's tutorial on using Hooks (useEffect and use State) from the latest version of react: [Link] (https://medium.com/@dtkatz/react-hooks-tutorial-learn-by-building-b90ec4db2b8e)

I tried naming the constant and setting the variable before the hooks but to no avail.

```<code>import React, { useState, useEffect } from 'react';

const [snippet, setSnippet]= useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_Game_State);

setSnippet(SNIPPETS[snippetIndex]);
setGameState({...gameState, startTime: new Date().getTime() });

useEffect (() => {
  if (gameState.victory) document.title = 'Victory!';
});
....
  const chooseSnippet = snippetIndex => () => {
    console.log('setSnippet', snippetIndex);
    setSnippet(SNIPPETS[snippetIndex]);
  };
  const updateUserText = event => {
      setUserText (event.target.value);

    if (event.target.value === snippet) {
      setGameState({
      ...gameState,
      victory: true,
      endTime: new Date().getTime() -gameState.startTime
      });
    }
      console.log('current userText', userText);
    }

  return (
    <div>
      <h2> Type Race</h2>
      <hr />
      <h3> Snippet </h3>
      {snippet}
      <h4> {gameState.victory ? `Done!  Time: ${gameState.endTime}ms` : null}</h4>
     <input value={userText} onChange={updateUserText} />
     <hr />
     {
       SNIPPETS.map((SNIPPET, index) => (
         <button onClick={chooseSnippet(index)} key={index}>
         {SNIPPET.substring(0,10)}...
         </button>
       ))
     }
    </div>
  )
}

export default App;
</code>```

This is the App Css file

```<code>css
.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</code>```

This is the initial game state javascript file.

```<code>const INITIAL_GAME_STATE = { victory: false, startTime: null, endTime: null};
const [snippet, setSnippet]= useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_GAME_STATE);

setSnippet(SNIPPETS[snippetIndex]);
setGameState({...gameState, startTime: new Date().getTime() });
</code>```

Errors Shown:
./src/App.js
  Line 5:  'INITIAL_Game_State' is not defined  no-undef
  Line 7:  'SNIPPETS' is not defined            no-undef
  Line 7:  'snippetIndex' is not defined        no-undef

It should show the website with the game state and other text as written in the javascript code.

答:
In the linked article both SNIPPETS and INTIIAL_Game_State are defined prior to the hooks.

From the article:

```<code>const INITIAL_GAME_STATE = { victory: false, startTime: null, endTime: null };
const [snippet, setSnippet] = useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_GAME_STATE);
</code>```

and for snippets:

```<code>const SNIPPETS = [
  'Bears, beets, battlestar galactica',
  "What's Forrest Gump's password? 1Forrest1",
  'Where do programmers like to hangout? The Foo Bar'
];
const [snippet, setSnippet] = useState('');
const [userText, setUserText] = useState('');
</code>```

Should just be a matter of either including those declarations prior to using them. It looks like they're removed in your example. Just include both above where you use the hooks and you should be set.

His full app.js here

Body:
I am trying to run a web page using useState for Game State and setting game state on a website rendered using React. There are problems compiling with three variables undefined. (Set_GAME_State, SNIPPETS and Snippet Index).

This is based on Daniel Katz's tutorial on using Hooks (useEffect and use State) from the latest version of react: [Link] (https://medium.com/@dtkatz/react-hooks-tutorial-learn-by-building-b90ec4db2b8e)

I tried naming the constant and setting the variable before the hooks but to no avail.

import React, { useState, useEffect } from 'react';

const [snippet, setSnippet]= useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_Game_State);

setSnippet(SNIPPETS[snippetIndex]);
setGameState({...gameState, startTime: new Date().getTime() });

useEffect (() => {
  if (gameState.victory) document.title = 'Victory!';
});
....
  const chooseSnippet = snippetIndex => () => {
    console.log('setSnippet', snippetIndex);
    setSnippet(SNIPPETS[snippetIndex]);
  };
  const updateUserText = event => {
      setUserText (event.target.value);

    if (event.target.value === snippet) {
      setGameState({
      ...gameState,
      victory: true,
      endTime: new Date().getTime() -gameState.startTime
      });
    }
      console.log('current userText', userText);
    }

  return (

 Type Race

 Snippet

      {snippet}

 {gameState.victory ? `Done!  Time: ${gameState.endTime}ms` : null}

     <input value={userText} onChange={updateUserText} />

     {
       SNIPPETS.map((SNIPPET, index) => (
         <button onClick={chooseSnippet(index)} key={index}>
         {SNIPPET.substring(0,10)}...
         </button>
       ))
     }

  )
}

export default App;

This is the App Css file

css
.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
  pointer-events: none;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

This is the initial game state javascript file.

const INITIAL_GAME_STATE = { victory: false, startTime: null, endTime: null};
const [snippet, setSnippet]= useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_GAME_STATE);

setSnippet(SNIPPETS[snippetIndex]);
setGameState({...gameState, startTime: new Date().getTime() });

Errors Shown:
./src/App.js
  Line 5:  'INITIAL_Game_State' is not defined  no-undef
  Line 7:  'SNIPPETS' is not defined            no-undef
  Line 7:  'snippetIndex' is not defined        no-undef

It should show the website with the game state and other text as written in the javascript code.

Body:
In the linked article both SNIPPETS and INTIIAL_Game_State are defined prior to the hooks.

From the article:

const INITIAL_GAME_STATE = { victory: false, startTime: null, endTime: null };
const [snippet, setSnippet] = useState('');
const [userText, setUserText] = useState('');
const [gameState, setGameState] = useState(INITIAL_GAME_STATE);

and for snippets:

const SNIPPETS = [
  'Bears, beets, battlestar galactica',
  "What's Forrest Gump's password? 1Forrest1",
  'Where do programmers like to hangout? The Foo Bar'
];
const [snippet, setSnippet] = useState('');
const [userText, setUserText] = useState('');

Should just be a matter of either including those declarations prior to using them. It looks like they're removed in your example. Just include both above where you use the hooks and you should be set.

His full app.js here


问:
Loading table view with data with 2 different prototype cells
I am trying to populate a tableView with different prototype cells at different times. The problem is any code after let cell = tableView.dequeueReusableCell(withIdentifier: "MeArticlesCell") as? MeArticlesCell else {return UITableViewCell()} isn't being called and I can't figure out why. Im returning the correct amount of rows.

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if(postsSelected){
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //the code in this part loads posts fine

    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //this part never gets called
    }
}
</code>```

答:
You're using dequeueReusableCell(withIdentifier:) method to init cell which return nil if it doesn't find any reusable cell. More here

A UITableViewCell object with the associated identifier or nil if no
  such object exists in the reusable-cell queue.

You should use dequeueReusableCell(withIdentifier:for:) which init a new cell if it doesn't find any cell for reuse. More here

A UITableViewCell object with the associated reuse identifier. This
  method always returns a valid cell.

Body:
I am trying to populate a tableView with different prototype cells at different times. The problem is any code after let cell = tableView.dequeueReusableCell(withIdentifier: "MeArticlesCell") as? MeArticlesCell else {return UITableViewCell()} isn't being called and I can't figure out why. Im returning the correct amount of rows.

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if(postsSelected){
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //the code in this part loads posts fine

    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //this part never gets called
    }
}


问:
Determine whether an IQueryable<T> has been ordered or not
Is there a way to know if an IQueryable<T> has been ordered (using OrderBy or OrderbyDescending)?

So I know whether to call OrderBy or ThenBy on the collection.

```<code>IQueryable<Contact> contacts = Database.GetContacts();
</code>```

I tried contacts is IOrderedQueryable<Contact>, but it's always true.

Edit: I just changed my example, the previous one wasn't really showing my point. Assume that GetContacts uses Entity Framework and simply returns all the records of a table.

Later on, I apply several functions to contacts, I have no knowledge of what those functions do. They can sort or filter the IQueryable<Contact>.

When I get the collection back, I need to sort it once more. To do so, I need to know whether I need to call OrderBy, or ThenBy. So I don't reorder the whole collection if it has already been sorted.

答:
This Works for me.

When IQueryable list is being sorted (Ordered by) it's type is changed to IOrderedQueryable from IQueryable.

```<code>if (iQueryableList.Expression.Type == typeof(IOrderedQueryable<T>))
{
    //IQueryable is sorted
}
else
{
    //IQueryable is sorted
}
</code>```

You can find more details about this on below post.

more details

Body:
Is there a way to know if an IQueryable<T> has been ordered (using OrderBy or OrderbyDescending)?

So I know whether to call OrderBy or ThenBy on the collection.

IQueryable<Contact> contacts = Database.GetContacts();

I tried contacts is IOrderedQueryable<Contact>, but it's always true.

Edit: I just changed my example, the previous one wasn't really showing my point. Assume that GetContacts uses Entity Framework and simply returns all the records of a table.

Later on, I apply several functions to contacts, I have no knowledge of what those functions do. They can sort or filter the IQueryable<Contact>.

When I get the collection back, I need to sort it once more. To do so, I need to know whether I need to call OrderBy, or ThenBy. So I don't reorder the whole collection if it has already been sorted.

Body:
This Works for me.

When IQueryable list is being sorted (Ordered by) it's type is changed to IOrderedQueryable from IQueryable.

if (iQueryableList.Expression.Type == typeof(IOrderedQueryable<T>))
{
    //IQueryable is sorted
}
else
{
    //IQueryable is sorted
}

You can find more details about this on below post.

more details


问:
How to run all threads when getting "the function evaluation requires all threads to run" and the button is missing?
I'm getting the typical error "The function evaluation requires all threads to run." but I don't have the little button that is usually there to do as it suggests -- i.e. run all the threads, as described here.

And yes, I do have this set:

Comments at the link above indicate this feature may have been removed in VS 2015, but I just used it recently in VS 2017 and today is the first time I've noticed it missing.  I restarted VS, no change.

答:
1.Maybe you can trying watching the property in watch window to check if there has difference.

2.And please check if workaround from vapcguy can help. Thanks to him :)

As I found in many issues, adding .ToList() to the end can help fix this issue.


问:
Post back data to api without forcing a render component to do it all
I have a react component for voting things up and down that I am trying to use to post data back with.  For example, button to vote up, button to vote down, changes internal state to record vote up or down.

Now it has come time to post the data changes back to an api.  This component is pretty much a render component:

```<code><Feedbackify up={44} down={23} />
</code>```

So you feed it the current state of votes and it just renders them and currently it modifies it's own internal state when you vote up or down.
I could just POST or PUT to the api from internally in the component, but I'd prefer not to.  What is the most idiomatic way pass some way to post in to the component from the outside?

```<code><Feedbackify up={44} down={23} onChange={someOnChange}/>
</code>```

Or are there alternative approaches in react that are cleaner?

答:
The general approach is to list state up. So parent component has state with up and down votes, pass to Feedbackify only values for votes and someOnChange (as you do). On each vote change (on someOnChange call), state of the parent is changed and updated votes passed as props to Feedbackify. Also parent is responsible for sendeing data to api.

Example

```<code>class Parent extends React.Component {
    constructor (p) {
        super (p);
        this.state = {
            up: 0,
            down: 0
        }
    }

    someOnChange (event) {
        let { up, down } = this.state;
        // Assuming value will be positive for upvote and negative for downvote
        if (event.target.value > 0)
            up += event.target.value;
        else
            down += event.target.value;

        doAsyncPost (up, down); // Post to server API
        this.setState ({ up, down });
    }

    render () {
        return <Feedbackify up={this.state.up} down={this.state.down} onChange={this.someOnChange.bind(this)}/>
    }
}
</code>```

Futher you may consider Redux for managing state centrally for all components

Body:
I have a react component for voting things up and down that I am trying to use to post data back with.  For example, button to vote up, button to vote down, changes internal state to record vote up or down.

Now it has come time to post the data changes back to an api.  This component is pretty much a render component:

<Feedbackify up={44} down={23} />

So you feed it the current state of votes and it just renders them and currently it modifies it's own internal state when you vote up or down.
I could just POST or PUT to the api from internally in the component, but I'd prefer not to.  What is the most idiomatic way pass some way to post in to the component from the outside?

<Feedbackify up={44} down={23} onChange={someOnChange}/>

Or are there alternative approaches in react that are cleaner?

Body:
The general approach is to list state up. So parent component has state with up and down votes, pass to Feedbackify only values for votes and someOnChange (as you do). On each vote change (on someOnChange call), state of the parent is changed and updated votes passed as props to Feedbackify. Also parent is responsible for sendeing data to api.

Example

class Parent extends React.Component {
    constructor (p) {
        super (p);
        this.state = {
            up: 0,
            down: 0
        }
    }

    someOnChange (event) {
        let { up, down } = this.state;
        // Assuming value will be positive for upvote and negative for downvote
        if (event.target.value > 0)
            up += event.target.value;
        else
            down += event.target.value;

        doAsyncPost (up, down); // Post to server API
        this.setState ({ up, down });
    }

    render () {
        return <Feedbackify up={this.state.up} down={this.state.down} onChange={this.someOnChange.bind(this)}/>
    }
}

Futher you may consider Redux for managing state centrally for all components


问:
Request types on iPhone || Android?
Is it possible to send GET, POST, PUT and DELETE requests from iPhone || Android applications to a third party server?

I want to build a web service to reuse on all 3 platforms (3rd being the web app itself).

答: Well, it's all possible on both iOS and Android OS platforms, however while designing web service, you probably may consider a lightweight implementation as mobile platforms are not powerful enough if you for example intend to use SOAP extensively. My most often choice is REST+JSON.</p>

Title: Request types on iPhone || Android?


问:
How to push data from local machine (computer) to Azure Table
I created a simple text file in NotePad, it is a .txt file. I want to push this data to an azure table, but I'm not sure how to go about doing this in c#. Does anyone know how I can push some sample data from my computer to an azure table? Thanks!</p>

答:
There are three basic steps for doing this:

Read the text file into memory.

We can do that with a single line of code:

```<code>string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
</code>```

Authenticate to Azure Tables.

You will need to get the relevant nuget packages for Azure Storage. You could write the code without the SDK, but I don't recommend it.

```<code>CloudStorageAccount storageAccount = new CloudStorageAccount(
    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
        "<name>", "<account-key>"), true);

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Get a reference to a table named "textTable"
CloudTable textTable = tableClient.GetTableReference("textTable");
</code>```

Write to Azure Tables.

We need to make a class that defines the data structure we are uploading into storage. Every entity must have a row key and a partition key.

```<code>public class TextEntity : TableEntity
{
    public TextEntity(string partitionKey, string rowKey)
    {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
    }

    public TextEntity() { }

    public string Text { get; set; }
}
</code>```

We can then use that class to create the object that we will then upload to storage.

```<code>var tableEntry = new TextEntry("partitionKey", "rowKey");
tableEntry.Text = text;

TableOperation insertOperation = TableOperation.Insert(tableEntry);

// Execute the insert operation.
await textTable.ExecuteAsync(insertOperation);
</code>```

Body:
There are three basic steps for doing this:

Read the text file into memory.

We can do that with a single line of code:

string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

Authenticate to Azure Tables.

You will need to get the relevant nuget packages for Azure Storage. You could write the code without the SDK, but I don't recommend it.

CloudStorageAccount storageAccount = new CloudStorageAccount(
    new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
        "<name>", "<account-key>"), true);

// Create the table client.
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

// Get a reference to a table named "textTable"
CloudTable textTable = tableClient.GetTableReference("textTable");

Write to Azure Tables.

We need to make a class that defines the data structure we are uploading into storage. Every entity must have a row key and a partition key.

public class TextEntity : TableEntity
{
    public TextEntity(string partitionKey, string rowKey)
    {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
    }

    public TextEntity() { }

    public string Text { get; set; }
}

We can then use that class to create the object that we will then upload to storage.

var tableEntry = new TextEntry("partitionKey", "rowKey");
tableEntry.Text = text;

TableOperation insertOperation = TableOperation.Insert(tableEntry);

// Execute the insert operation.
await textTable.ExecuteAsync(insertOperation);


问:
How to make view visible in one component from clicking a button from another component?
i have two components
Component A has one button by default that is hidden and another component
B which has search button
how to make button in component A visible when i click button in component B
i m importing component B in A
How to achieve above mention ?</p>

答:
When you activate a button, there are many ways to float other components.

You can change the status value to float it,
OR you can pass the value through the key value to receive the data and execute the button,
 as shown in the example below.

example.js

      <TouchableOpacity
              onPress={() => this.getItems()}
              activeOpacity={0.5}
              style={styles.btn}
              textStyle={styles.txt}
            >Get Products ({productList.length})</TouchableOpacity>
            {
              productList.map((product, i) => {
                return (
                  <View key={i} style={{
                    flexDirection: 'column',
                  }}>
                    <Text style={{
                      marginTop: 20,
                      fontSize: 12,
                      color: 'black',
                      minHeight: 100,
                      alignSelf: 'center',
                      paddingHorizontal: 20,
                    }} >{JSON.stringify(product)}</Text>
                    <TouchableOpacity
                      onPress={() => this.buyItem(product.productId)}
                      activeOpacity={0.5}
                      style={styles.btn}
                      textStyle={styles.txt}
                    >Buy Above Product</TouchableOpacity>
                  </View>
                );
              })
            }
```


问:
When should I use VK_ATTACHMENT_UNUSED when creating subpasses?
If I don't need attachments in a subpass, I would not include the attachment and update the attachment count accordingly in VkSubpassDescription.

I see that VK_ATTACHMENT_UNUSED is a possible value for VkAttachmentReference.attachment. What features does it provide over the original route?

(Originally, I thought it might be a way to preserve the values of attachments between subpasses, but pPreserveAttachments already does that.)

答:
Fragment shader outputs are bound to a Location index. This is an index into the subpass's pColorAttachments array.

If you have a shader that, for whatever reason, writes to locations 0 and 2, then that means pColorAttachments has to have 3 entries. Entry index 1 is VK_ATTACHMENT_UNUSED.

Now, why would your shader do that? Well, it is possible to use the same shader module in different pipelines intended for different subpasses. In one subpass, maybe there are 3 attachments, and this shader simply doesn't write to location 1 (it turns off writes to that attachment as part of the pipeline setup). In another subpass, there are only 2 attachments, but you want to use the same shader.

Yeah, you could theoretically use specialization constants to change the Location index. I wouldn't say this is a widely used or highly useful feature. But there's not reason to not support it.


问:
Unable to sign in with phone number unless phone number is added as an optional testing number
When I try to register as a user using my react-native app I get the following error.

Sing In With Phone Number Error: This app is not authorized to use Firebase Authentication. Please verify that the correct package name and SHA-1 are configured in the Firebase Console. [App validation failed.]

In my Firebase project settings I created a new app, generated a signing report( In android studio) and added the SHA-1 and SHA-256 values from that to Firebase. I then used the new google-services.json file in my project.

Update:
I also tried using keytool and updated the SHA-1 and SHA-256 in Firebase.

keytool.exe -list -v -alias key0 -keystore ks.jks

No luck with any of this so far.

答: I figured out what the issue was. The SHA-1 needs to come from the play console not your local machine. </p>


问:
find max in self join after multiple joins
i'm trying to find the highest number of interviews from each category (month and city) by joining two different tables and doing a self join in sql

```<code>`select distinct table1.event_id, table1.month, table1.city

from

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table1,

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table2

WHERE table1.event_id <> table2.event_id
AND table1.month = table2.month
AND table1.city = table2.city`
</code>```

the above code works that shows a self join after multiple join to compare every event_id for the number of total_interviews, but when i add after where

```<code>AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id)
</code>```

to find the max value, it gives me an error saying there is no such column for table1 and table2.

the reason why i added this is so that i can determine which event_id has the highest number of interviews compared to the rest, but i haven't been able to find out how to do this

答:
You can simply use below query.</p>

```<code>SELECT * FROM (
    SELECT EventID,total_interviews, Month, City, row_number() over(partition by event_ID,month, City order by total_interviews DESC) as RN
    FROM (
       SELECT Company.event_id, count(*) as total_interviews, Events.month, Events.city,
       FROM company, events
       where company.interviewee_id = events.interviewee_id
       GROUP BY Company.event_id, Events.month, Events.city
       ) A
    ) B where RN = 1
</code>```

Body:
i'm trying to find the highest number of interviews from each category (month and city) by joining two different tables and doing a self join in sql

`select distinct table1.event_id, table1.month, table1.city

from

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table1,

(SELECT event_id, count(*) as total_interviews, month, city
FROM company, events
where company.interviewee_id = events.interviewee_id
GROUP BY event_id, month, city) as table2

WHERE table1.event_id <> table2.event_id
AND table1.month = table2.month
AND table1.city = table2.city`

the above code works that shows a self join after multiple join to compare every event_id for the number of total_interviews, but when i add after where

AND table1.total_interviews > all (select table2.total_interviews FROM table2 WHERE table2.event_id <> table1.event_id)

to find the max value, it gives me an error saying there is no such column for table1 and table2.

the reason why i added this is so that i can determine which event_id has the highest number of interviews compared to the rest, but i haven't been able to find out how to do this

Body:
You can simply use below query.

SELECT * FROM (
    SELECT EventID,total_interviews, Month, City, row_number() over(partition by event_ID,month, City order by total_interviews DESC) as RN
    FROM (
       SELECT Company.event_id, count(*) as total_interviews, Events.month, Events.city,
       FROM company, events
       where company.interviewee_id = events.interviewee_id
       GROUP BY Company.event_id, Events.month, Events.city
       ) A
    ) B where RN = 1


问:
is there any difference in the following sort queries
```<code>DECLARE @Table1 TABLE (ID INT IDENTITY(1,1), Field1 INT, FieldSomethingElse VARCHAR(10))

INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (1, 'b')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (2, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (765, 'a')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'd')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'f')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (76, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (3, 'r')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (40, 'b')

declare @flag bit = 0;

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
</code>```

Is there any difference if I write

```<code> 1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc
</code>```

or

```<code> 2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
</code>```

I was advised to use option 1, but for me both options are same because I see the same result. Is there any difference?

how does 1 and 2 options affect the sorting?

答:
For the first clause:

```<code>1. case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc
</code>```

When @flag is not equal to 1 then you'll get 0 returned.
For the second:

```<code>2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc
</code>```

When @flag is not equal to 1 then null will be returned.

Since it's in your order by, no there won't be any difference in functionality.

Body:
DECLARE @Table1 TABLE (ID INT IDENTITY(1,1), Field1 INT, FieldSomethingElse VARCHAR(10))

INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (1, 'b')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (2, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (765, 'a')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'd')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (NULL, 'f')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (76, null)
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (3, 'r')
INSERT INTO @Table1 (Field1, FieldSomethingElse) VALUES (40, 'b')

declare @flag bit = 0;

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc

SELECT *
FROM @Table1
ORDER BY
  case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

Is there any difference if I write

 1. case when @flag = 1 then ISNULL(Field1,0) else 0 end desc, ID desc

or

 2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

I was advised to use option 1, but for me both options are same because I see the same result. Is there any difference?

how does 1 and 2 options affect the sorting?

Body:
For the first clause:

1. case when @flag = 1 then  ISNULL(Field1,0) else 0 end  desc , ID  desc

When @flag is not equal to 1 then you'll get 0 returned.
For the second:

2. case when @flag = 1 then ISNULL(Field1,0) end desc, ID desc

When @flag is not equal to 1 then null will be returned.

Since it's in your order by, no there won't be any difference in functionality.


问:
Get name of currently logged in user
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

```<code>var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}
</code>```

答: The reason is that the user will be available for next request, you could not get the user in this current request,let alone user's name.</p>

Title: Get name of currently logged in user

Body:
I made a simple login using Identity. I logged in with signInManager.PasswordSignInAsync().

If the login was successful, I would like to get the currently logged in user's data using the userManager.

The problem is that I can only get an id from the GetUserAsync and don't know what to do with it.

var result = await mSignInManager.PasswordSignInAsync(username, password, true, false);

if (result.Succeeded)
{
    //var loggedUser = mUserManager.GetUserName(HttpContext.User);
    var userData = mUserManager.GetUserAsync(HttpContext.User);
    var user = await mUserManager.FindByIdAsync(userData.Id.ToString());
    return Redirect("/createpost");
}