问:
getMaximumRange() for Proximity Sensor in Emulator
I try to get a maximum value from getMaximumRange() method for a Proximity sensor in Emulator (not in a real phone!). But I get only value 1.0 instead 10. Why?

My code is simple.

```<code>@Override
protected void onStart() {
    super.onStart();

    if (mProximitySensor != null) {
        mProximitySensorTextView.setText(mProximitySensor.getName());
        mProximityMaxTextView.setText("getMaximumRange: ");
        mProximityMaxTextView.append(String.valueOf(mProximitySensor.getMaximumRange()));
        mSensorManager.registerListener(this, mProximitySensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    } else {
        Log.e("Sensor", "Not available.");
        finish();
    }
}
</code>```

答:
Some proximity sensors only support a binary near or far measurement.
In this case, the sensor should report its maximum range value in the far state and a lesser value in the near state.

This can be confirmed by using the following USSD *#*#0588#*#*

This will Trigger a Proximity Test. Try This on A Real phone or Emulator and Confirm

Body:
I try to get a maximum value from getMaximumRange() method for a Proximity sensor in Emulator (not in a real phone!). But I get only value 1.0 instead 10. Why?

My code is simple.

@Override
protected void onStart() {
    super.onStart();

    if (mProximitySensor != null) {
        mProximitySensorTextView.setText(mProximitySensor.getName());
        mProximityMaxTextView.setText("getMaximumRange: ");
        mProximityMaxTextView.append(String.valueOf(mProximitySensor.getMaximumRange()));
        mSensorManager.registerListener(this, mProximitySensor,
                SensorManager.SENSOR_DELAY_NORMAL);

    } else {
        Log.e("Sensor", "Not available.");
        finish();
    }
}


来源: stackexchange

问:
Syntax error in SQL query: unexpected 'SUM' (sum)

I am trying to run the following query and I am getting the following error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'sum(sl.duration) as duration, sum(sl.quantity_loss) as
  quantity_loss'

```<code>SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(sl.duration * b.marginal_value_downtime) AS value_loss where en.state = 'downtime',
   SUM(sl.quantity_loss * p.marginal_value) as value_loss where en.state != 'downtime',
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM
    sub_losses AS sl
</code>```

Any idea why is this syntax error occurring?

答:
This worked for me. Thanks @HoneyBadger for guiding.</p>

```<code>SELECT
    lr.uid AS loss_reason_uid,
        gl.uid AS gl_uid,
        lt.uid AS lt_uid,
        SUM(CASE WHEN en.state = 'downtime' THEN sl.duration * b.marginal_value_downtime ELSE sl.quantity_loss * p.marginal_value END) AS value_loss,
        SUM(sl.duration) AS duration,
        SUM(sl.quantity_loss) AS quantity_loss,
        COUNT(*) AS count
FROM
    sub_losses AS sl
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run the following query and I am getting the following error:

You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'sum(sl.duration) as duration, sum(sl.quantity_loss) as
  quantity_loss'

SELECT
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(sl.duration * b.marginal_value_downtime) AS value_loss where en.state = 'downtime',
   SUM(sl.quantity_loss * p.marginal_value) as value_loss where en.state != 'downtime',
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM
    sub_losses AS sl

Any idea why is this syntax error occurring?

Body:
This worked for me. Thanks @HoneyBadger for guiding.

SELECT
    lr.uid AS loss_reason_uid,
        gl.uid AS gl_uid,
        lt.uid AS lt_uid,
        SUM(CASE WHEN en.state = 'downtime' THEN sl.duration * b.marginal_value_downtime ELSE sl.quantity_loss * p.marginal_value END) AS value_loss,
        SUM(sl.duration) AS duration,
        SUM(sl.quantity_loss) AS quantity_loss,
        COUNT(*) AS count
FROM
    sub_losses AS sl


问:
Regex expression for a string pattern
Regex newbie here. I need to create a regex expression that will support following strings:

```<code><optional constant string 1><string 2><space><string 3>
</code>```

Here constant string 1 is: ad_

Ex (allowed patterns).

[1]

ad_xyz.qwe.sty blah blah...

string 1: ad_

string 2: xyz.qwe.sty

string 3: blah blah... (free text)

[2]

abc blah ...

string 1: (absent)

string 2: abc

string 3: blah ... (free text)

[3]

sdf.pqr blah blah blah...

string 1: (absent)

string 2: sdf.pqr

string 3: blah blah blah... (free text)

Here is what I'm doing:

(?:[ad_]{0,1})?\-[a-zA-Z.]*\.[a-zA-Z0-9]*

Now this detects only first pattern. Though I have mentioned {0,1}, still string 1 is mandatory.

答:
You can use this regex for an optional match in first group:

```<code>^(ad_)?(\w+(?:\.\w+)*)\s*(.*)$
</code>```

RegEx Demo

In your regex [...] makes it character class where only one character out of several character matches at a time so [ad_] match any one of a or d or _

Title: Regex expression for a string pattern

Body:
Regex newbie here. I need to create a regex expression that will support following strings:

<optional constant string 1><string 2><space><string 3>

Here constant string 1 is: ad_

Ex (allowed patterns).

[1]

ad_xyz.qwe.sty blah blah...

string 1: ad_

string 2: xyz.qwe.sty

string 3: blah blah... (free text)

[2]

abc blah ...

string 1: (absent)

string 2: abc

string 3: blah ... (free text)

[3]

sdf.pqr blah blah blah...

string 1: (absent)

string 2: sdf.pqr

string 3: blah blah blah... (free text)

Here is what I'm doing:

(?:[ad_]{0,1})?\-[a-zA-Z.]*\.[a-zA-Z0-9]*

Now this detects only first pattern. Though I have mentioned {0,1}, still string 1 is mandatory.

Body:
You can use this regex for an optional match in first group:

^(ad_)?(\w+(?:\.\w+)*)\s*(.*)$

RegEx Demo

In your regex [...] makes it character class where only one character out of several character matches at a time so [ad_] match any one of a or d or _


问:
Showing error while installing laravel
have got this error while installing Laravel

```<code>PHP Warning:  require(/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
PHP Fatal error:  require(): Failed opening required '/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php') in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
</code>```

I have tried this source solve this

```<code>composer create-project laravel/laravel laraout "5.2.*" --no-scripts
</code>```

But it is not working for me.

答: Please Run composer install or composer update if you have already run composer install from your terminal inside your project.

Title: Showing error while installing laravel

Body:
have got this error while installing Laravel

PHP Warning:  require(/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16
PHP Fatal error:  require(): Failed opening required '/var/www/html/Laravel/laraout/bootstrap/../vendor/autoload.php' (include_path='.:/usr/share/php') in /var/www/html/Laravel/laraout/bootstrap/autoload.php on line 17
PHP Stack trace:
PHP   1. {main}() /var/www/html/Laravel/laraout/artisan:0
PHP   2. require() /var/www/html/Laravel/laraout/artisan:16

I have tried this source solve this

composer create-project laravel/laravel laraout "5.2.*" --no-scripts

But it is not working for me.


问:
Changing my navigation based on date
I would like my site to display different seasonal projects based on the date. Currently, I call the 'Top Winter Projects' section of my right navigation with the following code:

```<code><?php include (TEMPLATEPATH . '/stub_favorites.php'); ?>
</code>```

Is there a way that I could use a php include based on date? So if its January 14, call /stub_favorites.php, but if its March 10, call stub_favorites1.php? I'm new to php so bear with me.

My website is as followed: http://www.merrimentdesign.com

答:
The most dead easy way to display one include per month:

```<code><?php
   $filename = "month".date("n").".php";
   if (file_exists($filename)) include($filename);
</code>```

then add files:

```<code>month1.php
month2.php
month3.php
</code>```

the right file will be included for each month. The script will fail silently if a month does not exist. To make this work for calendar weeks instead, use date("W");. A full reference of date parameters can be found in the manual.

ContentLicense: CC BY-SA 2.5

Title: Changing my navigation based on date

Body:
I would like my site to display different seasonal projects based on the date. Currently, I call the 'Top Winter Projects' section of my right navigation with the following code:

<?php include (TEMPLATEPATH . '/stub_favorites.php'); ?>

Is there a way that I could use a php include based on date? So if its January 14, call /stub_favorites.php, but if its March 10, call stub_favorites1.php? I'm new to php so bear with me.

My website is as followed: http://www.merrimentdesign.com

Body:
The most dead easy way to display one include per month:

<?php
   $filename = "month".date("n").".php";
   if (file_exists($filename)) include($filename);

then add files:

month1.php
month2.php
month3.php

the right file will be included for each month. The script will fail silently if a month does not exist. To make this work for calendar weeks instead, use date("W");. A full reference of date parameters can be found in the manual.


问:
Side by side view of PDF files in UWP apps
I need the pdf viewer side by side of my app, so that i will be able to view the pdf generated when any changes made in app. In windows 8.1 app the PDF is opened using Reader app and by default it opens PDF side by side.

But the case in Win10 is not the same. In win 10 the reader app is opened seperately pushing back the app screen.Is there any similar viewer as like in win 8.1

Below image is from windows 8.1 app

答:
Here is the solution to open PDF files inside the app

As usual I opened PDF from files as storage file.

```<code>StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/pdffile.pdf"));
Windows.Data.Pdf.PdfDocument doc = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file);
Load(doc);
</code>```

Now the PDF document is read page by page as BitmapImage and added to a list.

```<code>public async void Load(PdfDocument pdfDoc)
    {
        PdfPages.Clear();

        for (uint i = 0; i < pdfDoc.PageCount; i++)
        {
            BitmapImage image = new BitmapImage();

            var page = pdfDoc.GetPage(i);

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await page.RenderToStreamAsync(stream);
                await image.SetSourceAsync(stream);
            }

            PdfPages.Add(image);
        }
    }

    public ObservableCollection<BitmapImage> PdfDocPages
    {
        get;
        set;
    } = new ObservableCollection<BitmapImage>();
</code>```

Binding the ObservableCollection to the ItemsControl we can view the PDF as images.

```<code><ScrollViewer ZoomMode="Enabled" Background="DarkGray" Grid.Column="1">
        <ItemsControl ItemsSource="{Binding PdfDocPages, ElementName=pageRoot}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding}" Margin="0 2" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the solution to open PDF files inside the app

As usual I opened PDF from files as storage file.

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/pdffile.pdf"));
Windows.Data.Pdf.PdfDocument doc = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file);
Load(doc);

Now the PDF document is read page by page as BitmapImage and added to a list.

public async void Load(PdfDocument pdfDoc)
    {
        PdfPages.Clear();

        for (uint i = 0; i < pdfDoc.PageCount; i++)
        {
            BitmapImage image = new BitmapImage();

            var page = pdfDoc.GetPage(i);

            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                await page.RenderToStreamAsync(stream);
                await image.SetSourceAsync(stream);
            }

            PdfPages.Add(image);
        }
    }

    public ObservableCollection<BitmapImage> PdfDocPages
    {
        get;
        set;
    } = new ObservableCollection<BitmapImage>();

Binding the ObservableCollection to the ItemsControl we can view the PDF as images.

<ScrollViewer ZoomMode="Enabled" Background="DarkGray" Grid.Column="1">
        <ItemsControl ItemsSource="{Binding PdfDocPages, ElementName=pageRoot}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding}" Margin="0 2" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>


问:
Need to delete duplicate records from the table using row_number()
I am having a table test having data as follows and I want to delete the trsid 124 and I have millions entry in my DB it is just a scenarion. Concept is to delete the duplicate entry from the table

```<code>--------------------------------------------
TrsId   |   ID  |   Name    |
--------------------------------------------
123     |   1   |   ABC     |
124     |   1   |   ABC     |
</code>```

I am trying something like

```<code>delete from test
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2
</code>```

Even if I update the query which is Ok for me

```<code>update test set id=NULL
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2
</code>```

But if i run both this query it deletes all the records from table test. And if i update it update both the records.
I dont know what I am doing wrong here

答:
To find duplicate records we can write like below query,</p>

```<code>;WITH dup_val
     AS (SELECT a,
                b,
                Row_number()
                  OVER(
                    partition BY a, b
                    ORDER BY b, NAME)AS [RANK]
         FROM   table_name)
SELECT *
FROM   dup_val
WHERE  [rank] <> 1;
</code>```

Body:
I am having a table test having data as follows and I want to delete the trsid 124 and I have millions entry in my DB it is just a scenarion. Concept is to delete the duplicate entry from the table

--------------------------------------------
TrsId   |   ID  |   Name    |
--------------------------------------------
123     |   1   |   ABC     |
124     |   1   |   ABC     |

I am trying something like

delete from test
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2

Even if I update the query which is Ok for me

update test set id=NULL
select T.* from
(
    select ROW_NUMBER() over (partition by ID order by name) as r,
           Trsid,
           ID,
           name
    from test
) t
where r = 2

But if i run both this query it deletes all the records from table test. And if i update it update both the records.
I dont know what I am doing wrong here

Body:
To find duplicate records we can write like below query,

;WITH dup_val
     AS (SELECT a,
                b,
                Row_number()
                  OVER(
                    partition BY a, b
                    ORDER BY b, NAME)AS [RANK]
         FROM   table_name)
SELECT *
FROM   dup_val
WHERE  [rank] <> 1;


问:
Static Code Analysis Tools -
How Many of you use static code analysis tools during development and what is the amount of false positives you experience with the tool you use? This is for a research. </p>

答:
You can try CppDepend, it uses CQLinq a code query language to define the rules.
You can customize easilly the rules to adapt it to your needs and remove the false positives detections.</p>

Title: Static Code Analysis Tools -


问:
Function to check if parameter is still the same
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

```<code>for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}
</code>```

my problem here is to return checkifcurrent(value) if it still the same like this

```<code>function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}
</code>```

I hope you understand tysm for understanding

答:
Alternatively you can use lodash difference function to compare old and new array.

http://devdocs.io/lodash~4/index#difference

For example:

```<code>const _ = require('lodash')
// Save the old array somewhere
let oldArray = ['test1','test1','test1','test2']
let newArray = ['test1','test1','test1','test3']

const areParametersTheSame = !!(_.difference(oldArray, newArray))
</code>```

Body:
I have a loop that has a function inside. my target here is to check if the current data inside the loop are still the same for example my array is like this

var data = ['test1','test1','test1','test2'];

now I will check them if the data on that array inside the loop are currently the same. for example like this.

for (var i = 0; i < data.length; i++) {
    var value = data[i][0];
    console.log(checkifcurrent(value));
}

my problem here is to return checkifcurrent(value) if it still the same like this

function checkifcurrent(value) {
    if (currentvalue is still the same as the last one) {
        console.log(same);
    } else {
        console.log(not same);
    }
}

I hope you understand tysm for understanding

Body:
Alternatively you can use lodash difference function to compare old and new array.

http://devdocs.io/lodash~4/index#difference

For example:

const _ = require('lodash')
// Save the old array somewhere
let oldArray = ['test1','test1','test1','test2']
let newArray = ['test1','test1','test1','test3']

const areParametersTheSame = !!(_.difference(oldArray, newArray))


问:
django url issue using mutiple regular expressions
I am having an issue with an url and regular expression I get the error

```<code>AttributeError: Generic detail view EmployeeDetailView must be called with either an object pk or a slug.
</code>```

What I am to achieve is to get to a user detail page coming from a specific project

```<code>url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
</code>```

my view is :

```<code>Project detail :
class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = Project
    template_name = 'project_details.html'

    def get_context_data(self, **kwargs):
        context = super(ProjectDetailView, self).get_context_data(**kwargs)
        try:
            team_name = Project.objects.get(id=self.kwargs['pk']).team_id.members.all()
            context['team_name'] = team_name
        except AttributeError:
            pass
        return context

class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_context_data(self, **kwargs):
        context = super(EmployeeDetailView, self).get_context_data(**kwargs)
        employee_name = MyUser.objects.get(id=self.kwargs['pk'])
        context['employee_name'] = employee_name
        return context
</code>```

HTML link :

```<code><span class="fa fa-id-card-o" aria-hidden="true"><a href="{% url 'website:EmployeDetails' pk1 = project.id pk2 = member.id %}"> Show Results</a>
</code>```

models:
MyUser models:

```<code>class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=150, blank=True, null=True)
    last_name = models.CharField(max_length=150, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_hr = models.BooleanField(default=False)
    is_candidate = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)
    company = models.CharField(max_length=100, blank=True, null=True)
</code>```

Project model:

```<code>class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
    candidat_answers = models.ManyToManyField('survey.response')
</code>```

Team models:

```<code>class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")
</code>```

could you please help me to figure it ? thx you ;)

答:
Django doesn't know how to use pk1 and pk2 to fetch the object for the view. I would override the get_object method and fetch the object there.

```<code>from django.shortcuts import get_object_or_404

# Note mixin should come first
class EmployeeDetailView(LoginRequiredMixin, generic.DetailView):
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_object(self, queryset=None):
        return get_object_or_404(MyUser, pk=self.kwargs['pk2'], project=self.kwargs['pk1'])

    ...
</code>```

Another option is to set pk_url_kwarg = 'pk2'. This tells Django that pk2 is the primary key of the MyUser object, so there is no need to override get_object. However if you do this, then Django will ignore the pk1 from the URL.

```<code>class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    pk_url_kwarg = 'pk2'
    template_name = 'Employee_Details.html'
</code>```

Body:
I am having an issue with an url and regular expression I get the error

AttributeError: Generic detail view EmployeeDetailView must be called with either an object pk or a slug.

What I am to achieve is to get to a user detail page coming from a specific project

url(r'^project/(?P<pk>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),

my view is :

Project detail :
class ProjectDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = Project
    template_name = 'project_details.html'

    def get_context_data(self, **kwargs):
        context = super(ProjectDetailView, self).get_context_data(**kwargs)
        try:
            team_name = Project.objects.get(id=self.kwargs['pk']).team_id.members.all()
            context['team_name'] = team_name
        except AttributeError:
            pass
        return context

class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_context_data(self, **kwargs):
        context = super(EmployeeDetailView, self).get_context_data(**kwargs)
        employee_name = MyUser.objects.get(id=self.kwargs['pk'])
        context['employee_name'] = employee_name
        return context

HTML link :

 Show Results

models:
MyUser models:

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    first_name = models.CharField(max_length=150, blank=True, null=True)
    last_name = models.CharField(max_length=150, blank=True, null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_hr = models.BooleanField(default=False)
    is_candidate = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=False)
    company = models.CharField(max_length=100, blank=True, null=True)

Project model:

class Project(models.Model):
    name = models.CharField(max_length=250)
    team_id = models.ForeignKey(Team, blank=True, null=True)
    project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
    candidat_answers = models.ManyToManyField('survey.response')

Team models:

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

could you please help me to figure it ? thx you ;)

Body:
Django doesn't know how to use pk1 and pk2 to fetch the object for the view. I would override the get_object method and fetch the object there.

from django.shortcuts import get_object_or_404

# Note mixin should come first
class EmployeeDetailView(LoginRequiredMixin, generic.DetailView):
    model = MyUser
    template_name = 'Employee_Details.html'

    def get_object(self, queryset=None):
        return get_object_or_404(MyUser, pk=self.kwargs['pk2'], project=self.kwargs['pk1'])

    ...

Another option is to set pk_url_kwarg = 'pk2'. This tells Django that pk2 is the primary key of the MyUser object, so there is no need to override get_object. However if you do this, then Django will ignore the pk1 from the URL.

class EmployeeDetailView(generic.DetailView, LoginRequiredMixin):
    #import pdb; pdb.set_trace()
    model = MyUser
    pk_url_kwarg = 'pk2'
    template_name = 'Employee_Details.html'


问:
BackgroundWorker progressBar - Problem implementing ReportProgress when loop occurs in another class
Hi
I am trying to integrate a background worker with a progress bar but cannot get it right.

I am processing some files and all the processing is done in an external class.

My difficulty is that the looping is inside this class,where usually  I do the talking to the backgroundworker.

The good thing is that when processing a file,an event is fired whenever each file has completed processing.

This is my code any suggestions how could this be achieved

```<code>    BackgroundWorker _bw = new BackgroundWorker

    private void RunLongProcess()
    {
        _bw.WorkerReportsProgress = true;
        _bw.WorkerSupportsCancellation = true;
        _bw.DoWork += DoWork;
        _bw.ProgressChanged += ProgressChanged;
        _bw.RunWorkerCompleted += RunWorkerCompleted;

        _bw.RunWorkerAsync();//start the process

        if (_bw.IsBusy)
           _bw.CancelAsync();
    }

     static void DoWork (object sender, DoWorkEventArgs e)
      {

        var files=GetFiles();
        int fileCount=files.Count;

        //usually I do a loop here but all the processing is done inside this class so

        var fileProcessor=new FileProcesser();
        fileProcessor.ProcessFiles(files);

      }
    private void OnFileProcessCompleted(object sender, FileEventArgs e)
    {
        //Event Fired when a file has been processed
        //How do I update progressBar.Problem cross threading here.

                        //What do I do here?????
        _bw.ReportProgress(e.FileProcessedCount, e);
    }

    ProgressChanged (object sender, ProgressChangedEventArgs e)
    {
          // Update the UI
        labelProgress.Text = e.UserState;
        progressBar.Value = e.ProgressPercentage;
    }

    private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
           // Console.WriteLine("You canceled!");
        else if (e.Error != null)
            //Console.WriteLine("Worker exception: " + e.Error.ToString());
        else
           // Console.WriteLine("Complete: " + e.Result);
    }
</code>```

答:
<s>_bw.ReportProgress(e.FileProcessedCount, e); should not go in OnFileProcessCompleted.  This event is fired when DoWork completes.  You should place that in DoWork to update the progress bar.  So it would look something like this:

```<code>private void DoWork (object sender, DoWorkEventArgs e)
{
   BackgroundWorker bg = sender as BackgroundWorker;

   var files = GetFiles();
   int fileCount = files.Count;

   var fileProcessor = new FileProcesser();
   for(int i = 0; i < fileCount; i++)
   {
      fileProcessor.ProcessFile(files[i]);
      bg.ReportProgress( (uint)((i / (double)fileCount) * 100));
   }
}
</code>```

</s>

I would pass in the BackgroundWorker to the FileProcessor like this:

```<code>private void DoWork (object sender, DoWorkEventArgs e)
{
    BackgroundWorker bg = sender as BackgroundWorker;
    var files = GetFiles();
    int fileCount = files.Count;
    var fileProcessor=new FileProcesser(bg);
    fileProcessor.ProcessFiles(files);
}
</code>```

In the FileProcesser, it would look something like this:

```<code>private BackgroundWorker _bg;
public FileProcessor(BackgroundWorker bg)
{
   _bg = bg;
}

public void ProcessFiles(Files files)
{
    // Process files
    // ...
    // Report Progress
    _bg.ReportProgress(e.FileProcessedCount, e);
}
</code>```

Body:
Hi
I am trying to integrate a background worker with a progress bar but cannot get it right.

I am processing some files and all the processing is done in an external class.

My difficulty is that the looping is inside this class,where usually  I do the talking to the backgroundworker.

The good thing is that when processing a file,an event is fired whenever each file has completed processing.

This is my code any suggestions how could this be achieved

    BackgroundWorker _bw = new BackgroundWorker

    private void RunLongProcess()
    {
        _bw.WorkerReportsProgress = true;
        _bw.WorkerSupportsCancellation = true;
        _bw.DoWork += DoWork;
        _bw.ProgressChanged += ProgressChanged;
        _bw.RunWorkerCompleted += RunWorkerCompleted;

        _bw.RunWorkerAsync();//start the process

        if (_bw.IsBusy)
           _bw.CancelAsync();
    }

     static void DoWork (object sender, DoWorkEventArgs e)
      {

        var files=GetFiles();
        int fileCount=files.Count;

        //usually I do a loop here but all the processing is done inside this class so

        var fileProcessor=new FileProcesser();
        fileProcessor.ProcessFiles(files);

      }
    private void OnFileProcessCompleted(object sender, FileEventArgs e)
    {
        //Event Fired when a file has been processed
        //How do I update progressBar.Problem cross threading here.

                        //What do I do here?????
        _bw.ReportProgress(e.FileProcessedCount, e);
    }

    ProgressChanged (object sender, ProgressChangedEventArgs e)
    {
          // Update the UI
        labelProgress.Text = e.UserState;
        progressBar.Value = e.ProgressPercentage;
    }

    private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Cancelled)
           // Console.WriteLine("You canceled!");
        else if (e.Error != null)
            //Console.WriteLine("Worker exception: " + e.Error.ToString());
        else
           // Console.WriteLine("Complete: " + e.Result);
    }

Body:
<s>_bw.ReportProgress(e.FileProcessedCount, e); should not go in OnFileProcessCompleted.  This event is fired when DoWork completes.  You should place that in DoWork to update the progress bar.  So it would look something like this:

private void DoWork (object sender, DoWorkEventArgs e)
{
   BackgroundWorker bg = sender as BackgroundWorker;

   var files = GetFiles();
   int fileCount = files.Count;

   var fileProcessor = new FileProcesser();
   for(int i = 0; i < fileCount; i++)
   {
      fileProcessor.ProcessFile(files[i]);
      bg.ReportProgress( (uint)((i / (double)fileCount) * 100));
   }
}

</s>

I would pass in the BackgroundWorker to the FileProcessor like this:

private void DoWork (object sender, DoWorkEventArgs e)
{
    BackgroundWorker bg = sender as BackgroundWorker;
    var files = GetFiles();
    int fileCount = files.Count;
    var fileProcessor=new FileProcesser(bg);
    fileProcessor.ProcessFiles(files);
}

In the FileProcesser, it would look something like this:

private BackgroundWorker _bg;
public FileProcessor(BackgroundWorker bg)
{
   _bg = bg;
}

public void ProcessFiles(Files files)
{
    // Process files
    // ...
    // Report Progress
    _bg.ReportProgress(e.FileProcessedCount, e);
}


问:
Add link to Abort page
As a follow-up to this answer, I'm trying to add the link after issuing Abort command, but for some reason it does not appear, no trace of it when viewed in Spy++.

The idea is to add the link above the progress bar, but somehow the macro does not work. Is there a reason for this that I'm missing and is it possible to add that link after calling Abort? I've read somewhere that Abort command can have different effect so I'm guessing this is one of it.

I've tried to make this sample script as concise as best I can and would greatly appreciate any help as I'm still learning NSIS.

```<code>!include "MUI2.nsh"

;--------------------------------
;General
ShowInstDetails hide
SetCompressor /SOLID lzma

;Request application privileges for Windows Vista
RequestExecutionLevel user

;--------------------------------
;Interface Configuration

!define MUI_ABORTWARNING
!define MANUAL_DOWNLOAD_TEXT "Automatic download not working? Click here to download manually."

;--------------------------------
;Macros
!macro AddDownloadLink yCoord
    FindWindow $0 "#32770" "" $HWNDPARENT ; Find the inner dialog
    System::Call 'USER32::CreateWindowEx(i0, t "STATIC", t "${MANUAL_DOWNLOAD_TEXT}", i${WS_CHILD}|${WS_VISIBLE}|${SS_NOTIFY}, i 1, i ${yCoord}, i 500, i 50, p $0, i 0x666, p 0, p 0)p.s'
    Pop $0
    SetCtlColors $0 0000ff transparent
    CreateFont $1 "$(^Font)" "$(^FontSize)" "400" /UNDERLINE
    SendMessage $0 ${WM_SETFONT} $1 1

    GetFunctionAddress $1 fnLinkClicked
    ButtonEvent::AddEventHandler 0x666 $1
!macroend

;--------------------------------
;Pages
!insertmacro MUI_PAGE_INSTFILES

;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Installer Sections
Section
    Var /global Filename
    StrCpy $Filename "test100Mb.db"

    Var /global DownloadUrl
    StrCpy $DownloadUrl "http://speedtest.ftp.otenet.gr/files/$Filename"

    !insertmacro AddDownloadLink 70

    inetc::get /caption "Downloading package" $DownloadUrl "$Filename" /end
    Pop $R0 ;Get the return value
    StrCmp $R0 "OK" 0 dlfailed

    Goto quit

dlfailed:
    DetailPrint "Download failed: $R0 $DownloadUrl"
    SetDetailsView show
    Abort

    !insertmacro AddDownloadLink 1

quit:
    Quit
SectionEnd

Function fnLinkClicked
    ExecShell "open" "$DownloadUrl"
FunctionEnd
</code>```

答:
Abort stops executing the section(s) code, you must do whatever you need to do before calling Abort.

Adding controls in a section can be problematic because it executes on a different thread and windows are tied to the thread that created them. If you need the window to stick around longer than the install thread you can create it as a hidden window in the instfiles page show callback and simply call ShowWindow in the section when you need to display it...

Title: Add link to Abort page

Body:
As a follow-up to this answer, I'm trying to add the link after issuing Abort command, but for some reason it does not appear, no trace of it when viewed in Spy++.

The idea is to add the link above the progress bar, but somehow the macro does not work. Is there a reason for this that I'm missing and is it possible to add that link after calling Abort? I've read somewhere that Abort command can have different effect so I'm guessing this is one of it.

I've tried to make this sample script as concise as best I can and would greatly appreciate any help as I'm still learning NSIS.

!include "MUI2.nsh"

;--------------------------------
;General
ShowInstDetails hide
SetCompressor /SOLID lzma

;Request application privileges for Windows Vista
RequestExecutionLevel user

;--------------------------------
;Interface Configuration

!define MUI_ABORTWARNING
!define MANUAL_DOWNLOAD_TEXT "Automatic download not working? Click here to download manually."

;--------------------------------
;Macros
!macro AddDownloadLink yCoord
    FindWindow $0 "#32770" "" $HWNDPARENT ; Find the inner dialog
    System::Call 'USER32::CreateWindowEx(i0, t "STATIC", t "${MANUAL_DOWNLOAD_TEXT}", i${WS_CHILD}|${WS_VISIBLE}|${SS_NOTIFY}, i 1, i ${yCoord}, i 500, i 50, p $0, i 0x666, p 0, p 0)p.s'
    Pop $0
    SetCtlColors $0 0000ff transparent
    CreateFont $1 "$(^Font)" "$(^FontSize)" "400" /UNDERLINE
    SendMessage $0 ${WM_SETFONT} $1 1

    GetFunctionAddress $1 fnLinkClicked
    ButtonEvent::AddEventHandler 0x666 $1
!macroend

;--------------------------------
;Pages
!insertmacro MUI_PAGE_INSTFILES

;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"

;--------------------------------
;Installer Sections
Section
    Var /global Filename
    StrCpy $Filename "test100Mb.db"

    Var /global DownloadUrl
    StrCpy $DownloadUrl "http://speedtest.ftp.otenet.gr/files/$Filename"

    !insertmacro AddDownloadLink 70

    inetc::get /caption "Downloading package" $DownloadUrl "$Filename" /end
    Pop $R0 ;Get the return value
    StrCmp $R0 "OK" 0 dlfailed

    Goto quit

dlfailed:
    DetailPrint "Download failed: $R0 $DownloadUrl"
    SetDetailsView show
    Abort

    !insertmacro AddDownloadLink 1

quit:
    Quit
SectionEnd

Function fnLinkClicked
    ExecShell "open" "$DownloadUrl"
FunctionEnd


问:
Extracting data from array (interpolation)
I need some advice regarding a problem I encountered in MATLAB:

I have 4 variables, I'm not sure what is the best methodology to go about doing this. I initially thought about just computing the GreatCircle distance from each grid point to the specified location and return the corresponding row/column index that has the minimum distance. But doing it this way, I'm not sure how I can compute the interpolation.

I tried reshaping the data into a vector data of 4 columns and running meshgrid to possibly utilize interp2. But I ended up with this error:

Requested 109620x109620 (44.8GB) array exceeds maximum array size preference

What could be the most efficient way to do this?

答:
You are working on large arrays. If interp2 cannot handle it, work on a subarray instead:

```<code>% Create data
format shortG
[Latitude,Longitude] = meshgrid(1:12,1:12);
Altitude = floor(1000+sortrows(rand(12,12))*1000);
Temperature = 10+20*rand(12,12);

Lat = 2.1;
Lon = 11.8;

% Find closest match point
[~,i_Lat] = min(abs(Latitude(1,:)-Lat));
[~,i_Lon] = min(abs(Longitude(:,1)-Lon));

% Select subarrays around this point.
% Minimum size of these matrices depend on the type of interpolation you perform
ia1 = max(1,i_Lat-5);
ia2 = min(size(Latitude,1),i_Lat+5);
io1 = max(1,i_Lon-5);
io2 = min(size(Latitude,2),i_Lon+5);

subLatitude = Latitude(io1:io2,ia1:ia2);
subLongitude = Longitude(io1:io2,ia1:ia2);
subAltitude = Altitude(io1:io2,ia1:ia2);
subTemperature = Temperature(io1:io2,ia1:ia2);

% Interpolate on these small arrays, and evaluate at target (Lat, Lon) point
A_out = interp2(subLatitude, subLongitude, subAltitude, Lat, Lon)
T_out = interp2(subLatitude, subLongitude, subTemperature, Lat, Lon)
</code>```

Body:
You are working on large arrays. If interp2 cannot handle it, work on a subarray instead:

% Create data
format shortG
[Latitude,Longitude] = meshgrid(1:12,1:12);
Altitude = floor(1000+sortrows(rand(12,12))*1000);
Temperature = 10+20*rand(12,12);

Lat = 2.1;
Lon = 11.8;

% Find closest match point
[~,i_Lat] = min(abs(Latitude(1,:)-Lat));
[~,i_Lon] = min(abs(Longitude(:,1)-Lon));

% Select subarrays around this point.
% Minimum size of these matrices depend on the type of interpolation you perform
ia1 = max(1,i_Lat-5);
ia2 = min(size(Latitude,1),i_Lat+5);
io1 = max(1,i_Lon-5);
io2 = min(size(Latitude,2),i_Lon+5);

subLatitude = Latitude(io1:io2,ia1:ia2);
subLongitude = Longitude(io1:io2,ia1:ia2);
subAltitude = Altitude(io1:io2,ia1:ia2);
subTemperature = Temperature(io1:io2,ia1:ia2);

% Interpolate on these small arrays, and evaluate at target (Lat, Lon) point
A_out = interp2(subLatitude, subLongitude, subAltitude, Lat, Lon)
T_out = interp2(subLatitude, subLongitude, subTemperature, Lat, Lon)


问:
why is GAE returning server error when the code works in the local development server?
I'm trying to test the Datastore functionality using Google App Engine and my code works as expected in the local development server:

```<code>// code based on the following guide: https://cloud.google.com/datastore/docs/reference/libraries#client-libraries-install-go
package datastoretest

import (
        "fmt"
        "log"
        "net/http"
        "cloud.google.com/go/datastore"
        "google.golang.org/appengine"
)

type Task struct {
        Description string
}

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)

    // Set Google Cloud Platform project ID.
    projectID := "myProjectID" //note: actual ID is different

    // Creates a client.
    client, err := datastore.NewClient(ctx, projectID)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }

    // Sets the kind for the new entity.
    kind := "Task"
    // Sets the name/ID for the new entity.
    name := "sampletask1"
    // Creates a Key instance.
    taskKey := datastore.NameKey(kind, name, nil)

    // Creates a Task instance.
    task := Task{
            Description: "Buy milk",
    }

    // Saves the new entity.
    if _, err := client.Put(ctx, taskKey, &task); err != nil {
            log.Fatalf("Failed to save task: %v", err)
    }

    fmt.Fprint(w, "Saved ", taskKey, ":", task.Description)

}
</code>```

However, after being deployed to a GAE project, it's returning the following message to the visitor:

```<code>Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.
</code>```

答: I found out that the use of the package "cloud.google.com/go/datastore" was causing the problem. Instead, the solution should have been implemented using the package "google.golang.org/appengine/datastore". It appears that the former package was not compatible with GAE in my implementation. Switching to the latter package led to working code. For Datastore in GAE a better tutorial to follow should have been the following: https://cloud.google.com/appengine/docs/standard/go/getting-started/creating-guestbook</p>

Body:
I'm trying to test the Datastore functionality using Google App Engine and my code works as expected in the local development server:

// code based on the following guide: https://cloud.google.com/datastore/docs/reference/libraries#client-libraries-install-go
package datastoretest

import (
        "fmt"
        "log"
        "net/http"
        "cloud.google.com/go/datastore"
        "google.golang.org/appengine"
)

type Task struct {
        Description string
}

func init() {
    http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)

    // Set Google Cloud Platform project ID.
    projectID := "myProjectID" //note: actual ID is different

    // Creates a client.
    client, err := datastore.NewClient(ctx, projectID)
    if err != nil {
        log.Fatalf("Failed to create client: %v", err)
    }

    // Sets the kind for the new entity.
    kind := "Task"
    // Sets the name/ID for the new entity.
    name := "sampletask1"
    // Creates a Key instance.
    taskKey := datastore.NameKey(kind, name, nil)

    // Creates a Task instance.
    task := Task{
            Description: "Buy milk",
    }

    // Saves the new entity.
    if _, err := client.Put(ctx, taskKey, &task); err != nil {
            log.Fatalf("Failed to save task: %v", err)
    }

    fmt.Fprint(w, "Saved ", taskKey, ":", task.Description)

}

However, after being deployed to a GAE project, it's returning the following message to the visitor:

Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.


问:
get sim serial number in codename one using android native code
I want to get sim serial number in codename one using Android native code, following is my native implementation class, I have also added permission in build hint, code doesn't give any error but return null

```<code>    import com.codename1.impl.android.AndroidNativeUtil;
    import android.telephony.TelephonyManager;

    public class MyNativeImpl {

            public String simID() {
            TelephonyManager tMgr=(TelephonyManager) AndroidNativeUtil.getActivity().getSystemService("phone");
            String SIMSerialNumber=tMgr.getSimSerialNumber();
                 return SIMSerialNumber;
            }

             public boolean isSupported() {
                return true;
            }
    }
</code>```

I have added this code,

if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE, "This should be the description shown to the user...")){ your code here }

but getting error like

error: package Manifest does not exist
                if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE,
  "App requires the permission to work properly"))
                                                                 ^ Note: Some input files use or override a deprecated API. Note: Recompile
  with -Xlint:deprecation for details. Note: Some input files use
  unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked
  for details. 1 error

答:
There's a library written by Fabricio Cabeca a while ago for that.

Search the Codename Extensions Library for Telephony (Right-click project -> Codename One -> CodenameOne Settings -> Extensions). Use this cn1LIb.

If there's still an issue with Android below 6.0,

add android.xpermissions=<uses-permission android:name="android.permission.READ_PHONE_STATE"/> to your build hint.

And also make sure you're not testing on Dual sim device as this could problematic.

Body:
I want to get sim serial number in codename one using Android native code, following is my native implementation class, I have also added permission in build hint, code doesn't give any error but return null

    import com.codename1.impl.android.AndroidNativeUtil;
    import android.telephony.TelephonyManager;

    public class MyNativeImpl {

            public String simID() {
            TelephonyManager tMgr=(TelephonyManager) AndroidNativeUtil.getActivity().getSystemService("phone");
            String SIMSerialNumber=tMgr.getSimSerialNumber();
                 return SIMSerialNumber;
            }

             public boolean isSupported() {
                return true;
            }
    }

I have added this code,

if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE, "This should be the description shown to the user...")){ your code here }

but getting error like

error: package Manifest does not exist
                if(!AndroidNativeUtil.checkForPermission(Manifest.permission.READ_PHONE_STATE,
  "App requires the permission to work properly"))
                                                                 ^ Note: Some input files use or override a deprecated API. Note: Recompile
  with -Xlint:deprecation for details. Note: Some input files use
  unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked
  for details. 1 error


问:
Best way to allow editing of a datetime value in a jeditable environment?
I use Jeditable to allow editing of a table on my page. It updates a MySQL table and it all works fine.

I would like to add the ability to edit a datetime value as well. So I tried using jquery.jeditable.datepicker.js to do the job. But it works only with date values not datetime values.

```<code>$('.editTimeIn').editable('save.php', {
    type        : 'datepicker',
        datepicker: {
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 2
        }
});
</code>```

I need to be able to give the user the ability to pick the date and time. What recommendations do you have for this functionality?
If possible please use examples.

答:
Directly from source file of jeditable. Look at the end of the fie

```<code>  if (settings.datepicker) {
    jQuery.extend(datepicker, settings.datepicker);
  }

  input.datepicker(datepicker);
</code>```

What it's actually doing is applying jquery ui datepicker to your input element.

JQuery ui Datepicker doesn't have the ability to change datetime.
Alternatively you can find another library which support this. or you can request a feature from jeditable developers on github.

I recommend you to find any other library because I doubt that developers would help you because it's been six or seven years since they worked on it. and you shouldn't use depreciated libraries.

Body:
I use Jeditable to allow editing of a table on my page. It updates a MySQL table and it all works fine.

I would like to add the ability to edit a datetime value as well. So I tried using jquery.jeditable.datepicker.js to do the job. But it works only with date values not datetime values.

$('.editTimeIn').editable('save.php', {
    type        : 'datepicker',
        datepicker: {
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 2
        }
});

I need to be able to give the user the ability to pick the date and time. What recommendations do you have for this functionality?
If possible please use examples.

Body:
Directly from source file of jeditable. Look at the end of the fie

  if (settings.datepicker) {
    jQuery.extend(datepicker, settings.datepicker);
  }

  input.datepicker(datepicker);

What it's actually doing is applying jquery ui datepicker to your input element.

JQuery ui Datepicker doesn't have the ability to change datetime.
Alternatively you can find another library which support this. or you can request a feature from jeditable developers on github.

I recommend you to find any other library because I doubt that developers would help you because it's been six or seven years since they worked on it. and you shouldn't use depreciated libraries.


问:
Get textbox value from dynamically created table
I've got a table where I use Ajax to get the data from the database. After each line i've got a number of textboxes. I need the data from each line from the database and the data that is filled in manually in the textboxes. I can't get the data from the textboxes. I keep getting undefined, or an empty result. I've tried it with id's and classes, but without result. Can somebody tell me what i'm doing wrong?

This a what the table looks like

https://www.dropbox.com/s/wvnjkgsx6k1k4es/PastedGraphic-1.png?dl=0

And this is part of my code

```<code>function opslaan() {
    $('#tabelddl tbody tr').each(function() {
        var cijfer1 = $(this).find(".vraag1").val();
    });
}
</code>```

Here is the Ajax call

```<code>   $.ajax({
       url:"../php/zoek_opleiding_cijfer.php",
       type:"POST",
        async: false,
       data :
       {
           'opleidingid' : opleidingid
       },
       success: function(data) {
           var trHTML = '';
           $("#tabelddl tbody").remove();
           $.each(data,function(i,item) {
               trHTML += '<tr><td style="display:none;">' + data[i].opleiding_id +
                 '</td><td style="display:none;">' + data[i].id +
                 '</td><td style="display:none;">' + data[i].inschrijving_id +
                 '</td><td style="display:none;">' + data[i].naam_opleiding +
                 '</td><td>' + data[i].achternaam + '</td><td>' +
                  data[i].tussenvoegsel + '</td><td>' + data[i].voornaam +
                 '</td> <td class= "vraag1" id="vraag1" style="display:none;">' +
                 '<input type="text"></td> </td>' +
                 '</td> <td class= "vraag2" id="vraag2" style="display:none;">' +
                 '<input type="textbox"></td> </td>' +
                 '</td> <td class= "vraag3" id="vraag3" style="display:none;">' +
                 '<input type="textbox"></td> </td>' +
                 '</td> <td class= "vraag4" id="vraag4" style="display:none;">' +
                 '<input type="textbox"></td> </td>' +
                 '</td> <td class= "vraag5" id="vraag5" style="display:none;">' +
                 '<input type="textbox"></td> </tr>';
           });
       $('#tabelddl').append(trHTML);
       },

       complete: function(){
       }
   });
</code>```

And here is the table

```<code><table class="table" id="tabelddl">
<thead>
  <tr>
    <th class="col-lg-1" style="display:none;">opleiding_id</th>
      <th class="col-lg-2" style="display:none;">relatie_id</th>
      <th class="col-lg-2" style="display:none;">inschrijving_id</th>
    <th class="col-lg-1" style="display:none;">naam_opleiding</th>
      <th class="col-lg-1">achternaam</th>
      <th class="col-lg-1">tussenvoegsel</th>
      <th class="col-lg-1">voornaam</th>
      <th class="col-lg-1" style="display:none;">vraag 1</th>
      <th class="col-lg-1" style="display:none;">vraag 2</th>
      <th class="col-lg-1" style="display:none;">vraag 3</th>
      <th class="col-lg-1" style="display:none;">vraag 4</th>
      <th class="col-lg-1" style="display:none;">vraag 5</th>
  </tr>
</thead>
</table>
</code>```

答:
.vraag1 is class name of your td and it dont have val() so you can try like this $(this).find(".vraag1 > input[type=text]").val();

$("document").ready(function(){

   $("#clickMe").click(function(){
       $('#tabelddl tbody tr').each(function() {
           var cijfer1 = $(this).find(".vraag1 > input[type=text]").val();
            alert(cijfer1)
       })
   })

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tabelddl">
<tr>
<td class="vraag1"> <input type="text"/></td>
<td class="vraag2"> <input type="text"/></td>
<td class="vraag3"> <input type="text"/></td>
</tr>
</table>
<input type="button" value="clickMe" id="clickMe"/></code>```

Body:
I've got a table where I use Ajax to get the data from the database. After each line i've got a number of textboxes. I need the data from each line from the database and the data that is filled in manually in the textboxes. I can't get the data from the textboxes. I keep getting undefined, or an empty result. I've tried it with id's and classes, but without result. Can somebody tell me what i'm doing wrong?

This a what the table looks like

https://www.dropbox.com/s/wvnjkgsx6k1k4es/PastedGraphic-1.png?dl=0

And this is part of my code

function opslaan() {
    $('#tabelddl tbody tr').each(function() {
        var cijfer1 = $(this).find(".vraag1").val();
    });
}

Here is the Ajax call

   $.ajax({
       url:"../php/zoek_opleiding_cijfer.php",
       type:"POST",
        async: false,
       data :
       {
           'opleidingid' : opleidingid
       },
       success: function(data) {
           var trHTML = '';
           $("#tabelddl tbody").remove();
           $.each(data,function(i,item) {
               trHTML += '
' + data[i].opleiding_id +
                 '	' + data[i].id +
                 '	' + data[i].inschrijving_id +
                 '	' + data[i].naam_opleiding +
                 '	' + data[i].achternaam + '	' +
                  data[i].tussenvoegsel + '	' + data[i].voornaam +
                 '	 ' +
                 '<input type="text">	 	' +
                 '	 ' +
                 '<input type="textbox">	 	' +
                 '	 ' +
                 '<input type="textbox">	 	' +
                 '	 ' +
                 '<input type="textbox">	 	' +
                 '	 ' +
                 '<input type="textbox">
';
           });
       $('#tabelddl').append(trHTML);
       },

       complete: function(){
       }
   });

And here is the table

    opleiding_id
      relatie_id
      inschrijving_id
    naam_opleiding
      achternaam
      tussenvoegsel
      voornaam
      vraag 1
      vraag 2
      vraag 3
      vraag 4
      vraag 5

Body:
.vraag1 is class name of your td and it dont have val() so you can try like this $(this).find(".vraag1 > input[type=text]").val();

$("document").ready(function(){

   $("#clickMe").click(function(){
       $('#tabelddl tbody tr').each(function() {
           var cijfer1 = $(this).find(".vraag1 > input[type=text]").val();
            alert(cijfer1)
       })
   })

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tabelddl">
<tr>
<td class="vraag1"> <input type="text"/></td>
<td class="vraag2"> <input type="text"/></td>
<td class="vraag3"> <input type="text"/></td>
</tr>
</table>
<input type="button" value="clickMe" id="clickMe"/>


问:
Sitecore Rich Text Editor - Creating tables
We have tried creating tables and it is a difficult and time consuming task creating a beautifully formatted table in Sitecore RTE. There are many content authors working on the website who need to publish financial reports in Sitecore websites which are mostly in the form of data within tables. They face great difficulty building the table fast, copying and pasting does not work sometimes since the formatting gets all wrong. Also, formatting an already built table is difficult and in most cases these tables are not responsive. We understand that the responsiveness can be taken care of by using CSS but there are limitations there since the HTML is not always uniform (sometimes the authors copy and paste from word or PDF documents).

Please let me know the easiest way to build a responsive table in Sitecore with no to minimal HTML knowledge.

答:
Assuming you can make "developer" level changes, I see two options:

Create Customisable Renderings

Given your desire to have the tables responsive and styled well I would create renderings that you can control as a developer. The editors would need to input the data into Sitecore as items and then use a datasource to populate the rendering. If there's a lot of data, you could consider building an importer as it's in a tabulated (organised) format already.

If the styling needs to change, you can either create multiple renderings or use rendering parameters to give the editor options as to how it will look.

HTML Snippets

Sitecore allows you create snippets of HTML which can the be inserted into the RTE by the editor. You would need to create the HTML mark-up with styling/CSS and then create a new Html Editor Snippet item under /system/Settings/Html Editor Profiles/Rich Text Default/Snippets (assuming you're using the default RTE).

The template for the item can be found at /System/Html Editor Profiles/Html Editor Snippet.

The downside to this approach is if you make a change to the mark-up in the snippet item it won't be propagated to previous usages. You would have to manually find and amend those cases.

HTML snippets are really a last resort and not recommended


问:
My app crashes sometimes (AsyncTask should be static)
I have an android app that shows the rss of my website and shows a notification when there is new content.

The problem:
My app crashes sometimes, and this is what i can see in Google play Console:

```<code>java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:318)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)
  at java.util.concurrent.FutureTask.run (FutureTask.java:242)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)
  at java.lang.Thread.run (Thread.java:761)

Caused by: java.lang.NullPointerException:
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:100)
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:92)
  at android.os.AsyncTask$2.call (AsyncTask.java:304)
  at java.util.concurrent.FutureTask.run (FutureTask.java:237)
</code>```

In android studio I see the following  message:

This AsyncTask class should be static or leaks might occur
  (com.mydomain.rss.notification.RssNotificationService.SearchForUpdates)

The following is the java file I need to modify to fix the problem, but I'm not sure what I have to change to fix the problem:

```<code>package com.mydomain.rss.notification;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.mydomain.rss.FeedReaderActivity;
import com.mydomain.rss.R;
import com.mydomain.rss.SettingsActivity;
import com.mydomain.rss.cache.MainActivityContext;
import com.mydomain.rss.cache.RefreshFeed;
import com.mydomain.rss.parser.RSSItem;
import com.mydomain.rss.utility.RSSutility;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.Html;

/**
 * RSS Service Executer
 */

public class RssNotificationService extends Service {

    public static final int NOTIFICATION_ID = 1;
    //public static final String TITLE_ERROR = "Notify Error";

    Handler searchHandler = new Handler();
    Timer searchLoader = new Timer();

     @Override
     public void onCreate() {
         super.onCreate();
         boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
         if (is_notification_on){
             new SearchForUpdates().execute();
         }
     }

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public void onRebind(Intent intent) {
     super.onRebind(intent);
     }

     @Override
     public boolean onUnbind(Intent intent) {
     return true;
     }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public boolean getPrefrenceBoolean(String preference, boolean default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getBoolean (preference, default_value);
    }

    public void savePrefrenceString(String preference, String value){
        SharedPreferences.Editor editor = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE).edit();
        editor.putString(preference, value);
        editor.apply();
    }
    public String getPrefrenceString(String preference, String default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getString(preference, default_value);
    }

    private class SearchForUpdates extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

                String lastest_title = getPrefrenceString ("lastTitle", "No feed");

                List<RSSItem> feeds = RSSutility.getRSSFeed(getString(R.string.rss_url));
                RSSItem feed = feeds.get(0);
                String title = feed.getTitle();

                if (lastest_title.equalsIgnoreCase(title)){
                    //no update
                }else{
                    showNotification(feed);
                    //store last title so next time will not notify for same rss
                    savePrefrenceString("lastTitle", title);
                }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

             boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
             if (is_notification_on){
                //Reload Menu
                long SEARCH_FREQUENCY = Integer.valueOf(getString(R.string.frequency)) * 60 * 1000;

                searchLoader = new Timer();
                searchLoader.schedule(new TimerTask(){
                    public void run() {
                            searchHandler.post(new Runnable(){
                                public void run(){
                                    new SearchForUpdates().execute();
                                    searchLoader.cancel();
                                }
                            });
                }}, SEARCH_FREQUENCY, SEARCH_FREQUENCY);
             }
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private void showNotification(RSSItem feed) {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification);

        Uri alarmSound = null;
        boolean is_notification_sound_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION_SOUND, false);
        if (is_notification_sound_on){
            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }

        String html = feed.getDescription();
        html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        html = html.replaceAll(" ", "");
        html = html.replaceAll("&", "");
        html = html.replaceAll("%20", " ");
        html = html.replaceAll("%2C", ", ");
        html = html.replaceAll("%0A", "");

        String title = feed.getTitle();
        title = title.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        title = title.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        title = title.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        title = title.replaceAll(" ", "");
        title = title.replaceAll("&", "");
        title = title.replaceAll("%20", " ");
        title = title.replaceAll("%2C", ", ");
        title = title.replaceAll("%0A", "");

        //String description = feed.getDescription();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher).setLargeIcon(icon)
                .setContentTitle(feed.getTitle()).setContentText(html)
                .setAutoCancel(true)
                .setSound(alarmSound);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(Html.fromHtml(html));
        bigText.setBigContentTitle(title);
        bigText.setSummaryText(Html.fromHtml(html));
        builder.setStyle(bigText);

        Intent intent = new Intent(this, FeedReaderActivity.class);
        intent.putExtra("NOTIFICATION", true);
        intent.putExtra("title", feed.getTitle());
        intent.putExtra("description", feed.getDescription());
        intent.putExtra("link", feed.getLink());
        intent.putExtra("pubDate", feed.getPubdate());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Send the notification to the system.
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        if (MainActivityContext.instance().activity!=null){
            MainActivityContext.instance().activity.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent broadcast = new Intent();
                            broadcast.setAction("com.rss.RELOAD_URL");
                            sendBroadcast(broadcast);
                            RefreshFeed.instance().refresh = true;
                        }
                    }, 1000);
                }
            });
        }

    }

}
</code>```

So, if you know how to solve my problem, please reply back with the modifications.

答: Make your AsyncTask class static.</p>

Body:
I have an android app that shows the rss of my website and shows a notification when there is new content.

The problem:
My app crashes sometimes, and this is what i can see in Google play Console:

java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:318)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)
  at java.util.concurrent.FutureTask.run (FutureTask.java:242)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)
  at java.lang.Thread.run (Thread.java:761)

Caused by: java.lang.NullPointerException:
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:100)
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:92)
  at android.os.AsyncTask$2.call (AsyncTask.java:304)
  at java.util.concurrent.FutureTask.run (FutureTask.java:237)

In android studio I see the following  message:

This AsyncTask class should be static or leaks might occur
  (com.mydomain.rss.notification.RssNotificationService.SearchForUpdates)

The following is the java file I need to modify to fix the problem, but I'm not sure what I have to change to fix the problem:

package com.mydomain.rss.notification;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.mydomain.rss.FeedReaderActivity;
import com.mydomain.rss.R;
import com.mydomain.rss.SettingsActivity;
import com.mydomain.rss.cache.MainActivityContext;
import com.mydomain.rss.cache.RefreshFeed;
import com.mydomain.rss.parser.RSSItem;
import com.mydomain.rss.utility.RSSutility;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.Html;

/**
 * RSS Service Executer
 */

public class RssNotificationService extends Service {

    public static final int NOTIFICATION_ID = 1;
    //public static final String TITLE_ERROR = "Notify Error";

    Handler searchHandler = new Handler();
    Timer searchLoader = new Timer();

     @Override
     public void onCreate() {
         super.onCreate();
         boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
         if (is_notification_on){
             new SearchForUpdates().execute();
         }
     }

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public void onRebind(Intent intent) {
     super.onRebind(intent);
     }

     @Override
     public boolean onUnbind(Intent intent) {
     return true;
     }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public boolean getPrefrenceBoolean(String preference, boolean default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getBoolean (preference, default_value);
    }

    public void savePrefrenceString(String preference, String value){
        SharedPreferences.Editor editor = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE).edit();
        editor.putString(preference, value);
        editor.apply();
    }
    public String getPrefrenceString(String preference, String default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getString(preference, default_value);
    }

    private class SearchForUpdates extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

                String lastest_title = getPrefrenceString ("lastTitle", "No feed");

                List<RSSItem> feeds = RSSutility.getRSSFeed(getString(R.string.rss_url));
                RSSItem feed = feeds.get(0);
                String title = feed.getTitle();

                if (lastest_title.equalsIgnoreCase(title)){
                    //no update
                }else{
                    showNotification(feed);
                    //store last title so next time will not notify for same rss
                    savePrefrenceString("lastTitle", title);
                }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

             boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
             if (is_notification_on){
                //Reload Menu
                long SEARCH_FREQUENCY = Integer.valueOf(getString(R.string.frequency)) * 60 * 1000;

                searchLoader = new Timer();
                searchLoader.schedule(new TimerTask(){
                    public void run() {
                            searchHandler.post(new Runnable(){
                                public void run(){
                                    new SearchForUpdates().execute();
                                    searchLoader.cancel();
                                }
                            });
                }}, SEARCH_FREQUENCY, SEARCH_FREQUENCY);
             }
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private void showNotification(RSSItem feed) {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification);

        Uri alarmSound = null;
        boolean is_notification_sound_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION_SOUND, false);
        if (is_notification_sound_on){
            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }

        String html = feed.getDescription();
        html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        html = html.replaceAll(" ", "");
        html = html.replaceAll("&", "");
        html = html.replaceAll("%20", " ");
        html = html.replaceAll("%2C", ", ");
        html = html.replaceAll("%0A", "");

        String title = feed.getTitle();
        title = title.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        title = title.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        title = title.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        title = title.replaceAll(" ", "");
        title = title.replaceAll("&", "");
        title = title.replaceAll("%20", " ");
        title = title.replaceAll("%2C", ", ");
        title = title.replaceAll("%0A", "");

        //String description = feed.getDescription();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher).setLargeIcon(icon)
                .setContentTitle(feed.getTitle()).setContentText(html)
                .setAutoCancel(true)
                .setSound(alarmSound);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(Html.fromHtml(html));
        bigText.setBigContentTitle(title);
        bigText.setSummaryText(Html.fromHtml(html));
        builder.setStyle(bigText);

        Intent intent = new Intent(this, FeedReaderActivity.class);
        intent.putExtra("NOTIFICATION", true);
        intent.putExtra("title", feed.getTitle());
        intent.putExtra("description", feed.getDescription());
        intent.putExtra("link", feed.getLink());
        intent.putExtra("pubDate", feed.getPubdate());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Send the notification to the system.
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        if (MainActivityContext.instance().activity!=null){
            MainActivityContext.instance().activity.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent broadcast = new Intent();
                            broadcast.setAction("com.rss.RELOAD_URL");
                            sendBroadcast(broadcast);
                            RefreshFeed.instance().refresh = true;
                        }
                    }, 1000);
                }
            });
        }

    }

}

So, if you know how to solve my problem, please reply back with the modifications.

Body: Make your AsyncTask class static.


问:
How can I give an iframe video different width and height on mobile & pc browsers?
I have a textbox on my website to make the text easier to read. I have an iframe on my website that was placed outside of my box on mobile devices. So I followed this tutorial to fix that. I'm trying to get my iframe video smaller on pc browsers and the current size in my code for mobile devices. It's too big on pc right now. Is there any way to do this?

HTML code:

```<code><div class="video-container"><iframe src="https://www.youtube.com/embed/c0i88t0Kacs"></iframe>
</div>
</code>```

CSS code:

```<code>.video-container {
position:relative;
padding-bottom:56.25%;
padding-top:30px;
height:0;
overflow:hidden; }

.video-container iframe, .video-container object, .video-container embed {
position:absolute;
top:0;
left:0;
width:100%;
height:100%; }
</code>```

答:
Just Add Media Query in your Css

for tablet

```<code>@media only screen and (max-width: 760px) {
.video-container {//set you width and height}

.video-container iframe, .video-container object, .video-container embed
{//set you width and height }
}
</code>```

for Mobile

```<code>@media only screen and (max-width: 480px) {
.video-container {//set you width and height}
.video-container iframe, .video-container object, .video-container embed
{//set you width and height }
</code>```

}

Body:
I have a textbox on my website to make the text easier to read. I have an iframe on my website that was placed outside of my box on mobile devices. So I followed this tutorial to fix that. I'm trying to get my iframe video smaller on pc browsers and the current size in my code for mobile devices. It's too big on pc right now. Is there any way to do this?

HTML code:

CSS code:

.video-container {
position:relative;
padding-bottom:56.25%;
padding-top:30px;
height:0;
overflow:hidden; }

.video-container iframe, .video-container object, .video-container embed {
position:absolute;
top:0;
left:0;
width:100%;
height:100%; }

Body:
Just Add Media Query in your Css

for tablet

@media only screen and (max-width: 760px) {
.video-container {//set you width and height}

.video-container iframe, .video-container object, .video-container embed
{//set you width and height }
}

for Mobile

@media only screen and (max-width: 480px) {
.video-container {//set you width and height}
.video-container iframe, .video-container object, .video-container embed
{//set you width and height }

}


问:
Google Assistant API
Is there some google assistant api guide or tutorial? I cannot find anything related by these keywords. There seems have some Android app integration guide, but I want to integrate with my cloud service, not android app.

I find IFTTT have connected Google Assistant to several services, so I want to add some intents to my custom service.

I have built an Alexa app by using Alexa Skill Kit to handle my customize intent, and want to find something similar in Google Assistant developer playground, but I have no clue.

Thanks!

答:
If you wish to create voice applications for Google Assistant which are called as Google actions you will have to rely on the developers guide posted here

There is also an introductory course on udemy for the same.
I personally have used dialogFlow
and for the backend and I used firebase and have hosted a few apps into the store

Title: Google Assistant API


问:
How to fix: Error device not found with ADB.exe
In cmd when I try to do the command:

adb shell

it shows device not found error. Can someone help me please. It'll be appreciated.

答:
I solved:

Just turn off USB debugging and re-enable debugging it immediately


问:
HTML5 video, fallback to flash if no .ogv file
How can I fallback to a flash video player if the necessary file type is not present.

For example this code:

```<code><video controls width="500">
    <source src="<?= $mov ?>" type="video/mp4" />
    <embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="1024" height="798" allowscriptaccess="always" allowfullscreen="true"></embed>
</video>
</code>```

Does not include an .ogv file, so in Firefox, an empty video player is displayed.

How can I fall back to a Flash player even if the html5 video tag is supported in the browswer?

答:
You can use JavaScript to detect it:</p>

```<code>(function (video) {
    if (!video.canPlayType || !video.canPlayType('video/mp4')) {
        // Flash fallback
    }
}(document.createElement('video')));
</code>```

Body:
How can I fallback to a flash video player if the necessary file type is not present.

For example this code:

<video controls width="500">
    <source src="<?= $mov ?>" type="video/mp4" />
    <embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="1024" height="798" allowscriptaccess="always" allowfullscreen="true"></embed>
</video>

Does not include an .ogv file, so in Firefox, an empty video player is displayed.

How can I fall back to a Flash player even if the html5 video tag is supported in the browswer?

Body:
You can use JavaScript to detect it:

(function (video) {
    if (!video.canPlayType || !video.canPlayType('video/mp4')) {
        // Flash fallback
    }
}(document.createElement('video')));


问:
Access HTML file in maven webapp folder
I have created HTML files that I put into the webapp directory of Maven. My folder structure looks like this:

```<code>/webapp
   /documentation
      /general
             header.png
      /images
          /examples
             image.png
      doc.html
</code>```

Then I access it via the direct link:

```<code>http://localhost:8080/MyApp/documentation/doc.html
</code>```

The HTML page contains the following entries:

```<code><img src='general/header.png' alt='Image' />

<img src='images/examples/image.png' alt='Image' />
</code>```

The first linked image (header.png) is displayed on the HTML page, the second (image.png) one is not. The inspection view in Google Chrome says that the resource could not be found.

How can it happen that one image is found in the folder hierarchy, but not the other? Is there a specific rule on how to integrate HTML pages into the Maven web application?

答: The problem was that the file extension is case sensitive. Since my files have the extension *.PNG, but the extension in the HTML document was *.png , they could not be found.

Title: Access HTML file in maven webapp folder

Body:
I have created HTML files that I put into the webapp directory of Maven. My folder structure looks like this:

/webapp
   /documentation
      /general
             header.png
      /images
          /examples
             image.png
      doc.html

Then I access it via the direct link:

http://localhost:8080/MyApp/documentation/doc.html

The HTML page contains the following entries:

The first linked image (header.png) is displayed on the HTML page, the second (image.png) one is not. The inspection view in Google Chrome says that the resource could not be found.

How can it happen that one image is found in the folder hierarchy, but not the other? Is there a specific rule on how to integrate HTML pages into the Maven web application?


问:
Creating Custom UITableViewCell in Swift Programmatically
I need a cell with a label that takes up the entire contentView. I've done this a bunch of times with a nib but this time I decided to avoid the creating a nib. Below is my code.

```<code>class StackLegendCell: UITableViewCell {

  var title = UILabel()

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(title)

    title.numberOfLines = 1
    title.textAlignment = .center
    title.setContentCompressionResistancePriority(1000, for: .horizontal)
    title.setContentHuggingPriority(1000, for: .horizontal)
    title.text = "??"
    //contentView.translatesAutoresizingMaskIntoConstraints = false

    title.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 1.0).isActive = true
    title.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 1.0).isActive = true
  }
</code>```

The problem is that the label doesn't show anything. A check into view debugger shows that width = height = 0. But I'm setting height and width anchors which should give a size to be the same as the contentView.

What am I missing?

Thanks.

答:
Finally, I found the solution. You missed setting the frame of the titleLabel

title.frame = contentView.frame

add this line of code and build. This should work.

Body:
I need a cell with a label that takes up the entire contentView. I've done this a bunch of times with a nib but this time I decided to avoid the creating a nib. Below is my code.

class StackLegendCell: UITableViewCell {

  var title = UILabel()

  override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubview(title)

    title.numberOfLines = 1
    title.textAlignment = .center
    title.setContentCompressionResistancePriority(1000, for: .horizontal)
    title.setContentHuggingPriority(1000, for: .horizontal)
    title.text = "??"
    //contentView.translatesAutoresizingMaskIntoConstraints = false

    title.widthAnchor.constraint(equalTo: contentView.widthAnchor, multiplier: 1.0).isActive = true
    title.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 1.0).isActive = true
  }

The problem is that the label doesn't show anything. A check into view debugger shows that width = height = 0. But I'm setting height and width anchors which should give a size to be the same as the contentView.

What am I missing?

Thanks.


问:
How to parse the java comments of a groovy file to html format?
I have a set of .groovy files (Java). All of these files have the same comment format.
I developed a tool with which I'm able to read those files and applying a REGEX to get all the comments in a list. (Finally I just have to copy paste these comments to .html file)
I would like to know if it's a correct practice in order to generate a HTML page with the comment (a kind of documentation). If not, what would you recommend?

I read about Doxygen and Javadoc, but I'm not sure about using them (if they can be really useful in my case since the comments are already written)

If you can suggest a library in order to generate easily a HTML Webpage or any other advice.

Any help is appreciated.

答:
There exists Groovydoc which is roughly the equivalent of Javadoc, just for Groovy.

As your setup is not that (you already have comments, probably not in Groovydoc format, and you have half the tooling), there are still multiple ways open to you. As you already extract the documentation from groovy, if I were you, I would do a minimal post-formatting, if necessary, and output the documentation as markdown (e.g., github markdown) or asciidoc (e.g., asciidoctor). Then you can use any preferred tool to convert the post-formatted documentation into HTML.

To answer the question "How to parse the java comments" – you shouldn't. If possible, especially in a new project, stick with the standard tooling. In the case of Groovy that's Groovydoc. The normal (non Java/Groovy-Doc style) comments themselves you should never need to extract from the source code. They should be so much context-specific, that without the corresponding code they are anyways useless.


问:
How to check device compatibility for finger print authentication in android API lower than 23
I am working with finger print authentication using android 5.0 api. My requirement is, if current device is supports finger print authentication, then I will go through finger print authentication else will use normal way, but need to check every device of api 18 and above if they have finger print scanner or not.

So, any one can tell me, how to check device compatibility for finger print authentication in android.

Thanks in advance.

答:
```<code>FingerprintManager fingerprintManager = (FingerprintManager)getSystemService(FINGERPRINT_SERVICE);

if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
          if(!fingerprintManager.isHardwareDetected()){
               //your device doesn't have fingerprint Sensor
          }else{
            // do your code..
          }
    }
</code>```


问:
Enforce all new source code files checked in to have a particular comment
Is there any possibility to enforce all new source code files checked in to a particular repository through Git to have a particular comment, else the push should fail with or without a message.
The source code will be of cpp or cxx or cc extensions.

How do we verify commit messages for a push? is about enforcing something in the commit message but I want to enforce something in the source files that are being checked in.

Say for example, If I am writing a GPL library and anyone who commits into the repository should have the GPL license and author name, something like that.

答: Consider to use Git::Hooks, a Perl framework for implementing Git/Gerrit hooks. Here you have all info needed to install/configure it.</p>


问:
css3 box shadows in one direction only?
I have an element that has inset box shadows, but I want the shadow on only the top.

Is there no way to set only the top shadow? Do I have to resort to creating additional elements to overlay the side shadows?

答:
This is technically the same answer as @ChrisJ, with a few more details on how to make box-shadow do your bidding:

for reference the * items are optional:

```<code>box-shadow: <inset*> <offset-x> <offset-y> <blur-radius*> <spread-radius*> <color*>;
</code>```

The <spread-radius> needs to be negative <blur-radius> (so that none of the other blurred sides show up), and then you need to bump the <offset-y> down by the same amount:

```<code>box-shadow: inset 0 20px 20px -20px #000000;
</code>```

It will give you a single gradient band across the top of the element.

Title: css3 box shadows in one direction only?

Body:
This is technically the same answer as @ChrisJ, with a few more details on how to make box-shadow do your bidding:

for reference the * items are optional:

box-shadow: <inset*> <offset-x> <offset-y> <blur-radius*> <spread-radius*> <color*>;

The <spread-radius> needs to be negative <blur-radius> (so that none of the other blurred sides show up), and then you need to bump the <offset-y> down by the same amount:

box-shadow: inset 0 20px 20px -20px #000000;

It will give you a single gradient band across the top of the element.


问:
How to sort string alphabetically in shell script
String sorting algorithm in shell script.

I have done it for numbers,but not able to do for string.

EX:- I am kohali.
It should be like
am i kohali

答:
Below script will help you

```<code> str='I am kohali'
    for i in `echo $str`; do
        echo $i
    done | sort
</code>```

Below one will accept input from user

```<code>read -p "Enter your string:" str
for i in `echo $str`; do
    echo "$i"
done | sort
</code>```

Output

am I kohali

Body:
Below script will help you

 str='I am kohali'
    for i in `echo $str`; do
        echo $i
    done | sort

Below one will accept input from user

read -p "Enter your string:" str
for i in `echo $str`; do
    echo "$i"
done | sort

Output

am I kohali


问:
HTML won't display 2 images
I want to display 2 images on the same row like this:

```<code>Image  Same Text  Image
</code>```

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

```<code><td colspan="8" >
<h1>
<img src="/home/apps/myapp/dynamic/img/myimage1.png" style="float:left; " alt="This is my mage" height="130" width="455">
<b>Same text</b>
<img src="/home/apps/myapp/dynamic/img/myimage2.png" style="float:right; vertical-align:middle;" alt="My second image" height="130" width="454"></h1>
</td>
</code>```

答:
You can do by creating a nested table.

```<code><td>
  <table width="100%">
    <tr>
      <td>Image 1</td>
      <td>Text</td>
      <td>Image 2</td>
    </tr>
  </table>
</td>
</code>```

or you can do by creating div with float attributes. Do image1 and text to float:left; and image2 to float:right.

Title: HTML won't display 2 images

Body:
I want to display 2 images on the same row like this:

Image  Same Text  Image

If I put one image it works, but if I put both of them I get 404.
I think I am doing something wrong in the code I don't have much experience with HTML and don't know what I am missing.
The files are in same folder.
Here is the code:

Same text

Body:
You can do by creating a nested table.

<td>
  <table width="100%">
    <tr>
      <td>Image 1</td>
      <td>Text</td>
      <td>Image 2</td>
    </tr>
  </table>
</td>

or you can do by creating div with float attributes. Do image1 and text to float:left; and image2 to float:right.