问:
Template variables based on calculations using fields from Django Model
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

```<code>class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
</code>```

Here are my views:

```<code>def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})
</code>```

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

```<code><h2 class="title"><a href="{% url 'thing_detail' pk=thing.pk %}">{{ thing.title }}</a></h2>
<p>User: {{ thing.user }}</p>
<div class="date">
    <p>Start Date: {{ thing.start_date }}</p>
</div>
<p>Cost per day: ${{ thing.cost_per_day }}</p>
</code>```

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

```<code><button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>
</code>```

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

```<code>{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}
</code>```

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

```<code>from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day
</code>```

Here is my updated template:

```<code><h4>Here are some calculations for this information...</h4>
    <p>Days since you quit:</p>
    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>
    <hr>
    <p>How much money you have saved:</p>
    <button type="button" class="btn btn-info">{{ thing.savings }}</button>
</code>```

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

答:
This really isn't what template tags are for, at all. They're meant to display variables and call it a day, with some minor functional utility bolted on.

For your equations, best practice would be to implement them in the model.

```<code>from datetime import datetime

class Thing(models.Model):
    quit_date = models.DateTimeField()
    cost_per_day = models.FloatField() ???

    @property
    def timesince(self):
        # Time since last whatever
        elapsed = datetime.now() - self.quit_date
        return elapsed.days

    @property
    def calculate_cost(self):
        return self.timesince * self.cost_per_day
</code>```

Then you can just display each of the values using {{ thing.timesince }} and {{ thing.calculate_cost }} in the template.

Body:
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions.

My model looks like this:

class Thing(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    start_date = models.DateTimeField(
        default=timezone.now)
    cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)

Here are my views:

def something_list(request):
    things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date')
    return render(request, 'myApp/something_list.html', {'things': things})

def thing_detail(request, pk):
    thing = get_object_or_404(Thing, pk=pk)
    return render(request, 'myApp/thing_detail.html', {'thing': thing})

I have two template blocks for each of these views, where I am using template tags to display variables. For example:

{{ thing.title }}

User: {{ thing.user }}

Start Date: {{ thing.start_date }}

Cost per day: ${{ thing.cost_per_day }}

So what is happening here?

Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template.

Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here:

<button type="button" class="btn btn-info">{{ thing.quit_date|timesince }}</button>

This renders how many days and hours have elapsed - lets call it 'time elapsed' - perfectly. The problem lies in my next calculation.

Problem 2) I need to display a calculation of 'time elapsed' (shown above) multiplied by the Cost per Day variable in the current Model instance. Just for clarity, let's say the start date was 30.5 days ago, and the cost per day is $5.00. I need to multiply 30.5 by $5.00. I would love to simply multiply template tags but I understand that's not how it works. For example:

{{ thing.quit_date|timesince }} * {{ thing.cost_per_day }}

Is there a way to capture the result of this timesince calculation... {{ thing.quit_date|timesince }}... as a variable? I may not be able to use the timesince feature for this calculation.

Once again, what I ultimately need to do here is to multiply the "time elapsed" by the cost per day, like this: (Time Now - Start Date) * (Cost Per Day).

I don't know how to do this in models.py or views.py. I'm looking for the best practice way to do this using Django and Python 3.6. I'm a newbie and I have searched all day for an answer to my particular problem.

Thanks in advance and please let me know if I need to provide more information!

UPDATE

Here is my updated model based on suggestions, albeit not working (the timesince property needs work):

from django.db import models
from django.utils import timezone
from datetime import datetime

class Thing(models.Model):
quitter = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
quit_date = models.DateTimeField(default=timezone.now)
cost_per_day = models.DecimalField(max_digits=6, decimal_places=2)
notes = models.TextField()

@property
def timesince(self):
    "Time since quit date"
    now = datetime.now()
    then = self.quit_date
    return (now - then)

@property
def savings(self):
    "Savings since quitting"
    return self.timesince * self.cost_per_day

Here is my updated template:

Here are some calculations for this information...

Days since you quit:

    <button type="button" class="btn btn-info">{{ thing.timesince }}</button>

How much money you have saved:

    <button type="button" class="btn btn-info">{{ thing.savings }}</button>

I'm certain the problem lies in the subtraction of the dates. Any insight into that would be very helpful. The template variables {{ }} are working, but there is a missing piece in the model.

By the way, when I concatenated "days" to any datetime variable, it game me errors saying .days it gave me errors. Perhaps there is an issue using both a DateTimeField and a datetime.now() instance?

Body:
This really isn't what template tags are for, at all. They're meant to display variables and call it a day, with some minor functional utility bolted on.

For your equations, best practice would be to implement them in the model.

from datetime import datetime

class Thing(models.Model):
    quit_date = models.DateTimeField()
    cost_per_day = models.FloatField() ???

    @property
    def timesince(self):
        # Time since last whatever
        elapsed = datetime.now() - self.quit_date
        return elapsed.days

    @property
    def calculate_cost(self):
        return self.timesince * self.cost_per_day

Then you can just display each of the values using {{ thing.timesince }} and {{ thing.calculate_cost }} in the template.


来源: stackexchange

问:
get current date and check if it is "Day X"
I´m wring an App which checks if today is for example if its at the moment sunday.

I have Date today = new Date(); and i want to know if it is a sunday

答:
Date .getDay() is @deprecated so I suggest that you use Calendar</p>

```<code>    Calendar cal = Calendar.getInstance();
    int day = cal.get(Calendar.DAY_OF_WEEK);
    if(Calendar.SUNDAY == day) {
        ...
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Date .getDay() is @deprecated so I suggest that you use Calendar

    Calendar cal = Calendar.getInstance();
    int day = cal.get(Calendar.DAY_OF_WEEK);
    if(Calendar.SUNDAY == day) {
        ...
    }


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
C++ only, unfortunately:

```<code>if ( condition1
     && (condition2.setup(), condition2)
     && (condition3.setup(), condition3) )
{
    dosomething();
}
</code>```

For something java compatible (but I'm still writing C++!) I would fall back to something along the lines of this. (Obviously, some context may need to be passed into CheckConditions().)

```<code>bool CheckConditions()
{
    if (!condition1)
        return false;

    condition2.setup();

    if (!condition2)
        return false;

    condition3.setup();

    if (!condition3)
        return false;

    return true;
}

//...
if (CheckConditions())
{
    dosomething();
}
//...
</code>```

ContentLicense: CC BY-SA 2.5

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
C++ only, unfortunately:

if ( condition1
     && (condition2.setup(), condition2)
     && (condition3.setup(), condition3) )
{
    dosomething();
}

For something java compatible (but I'm still writing C++!) I would fall back to something along the lines of this. (Obviously, some context may need to be passed into CheckConditions().)

bool CheckConditions()
{
    if (!condition1)
        return false;

    condition2.setup();

    if (!condition2)
        return false;

    condition3.setup();

    if (!condition3)
        return false;

    return true;
}

//...
if (CheckConditions())
{
    dosomething();
}
//...


问:
Regarding union and multiple integer values
I'm getting into C and I experimented with union. My code is the following:

```<code>#include <stdio.h>

union date {
 int year  ;
 char month;
 char day  ;
 };

int main() {
 union date birth;
 birth.year = 1984;
 birth.month = 7;
 birth.day = 28;
 printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
 // return 1820,28,28
 return 0;
}
</code>```

1984 is written in binary as 0111 1100 0000

7 is written in binary as 0110

28 is written in binary as 0001 1100

I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.

答:
This entirely misunderstands what a union is. A union is an array of values that all start from at the same memory location; what you need to use if you want to store several separate values in one data type is a struct.

For example, with a union you can do this:

```<code>#include <stdio.h>
#include <stdint.h>

typedef union _myunion
{
    int32_t s;
    uint32_t u;
} myunion;

int main()
{
    myunion u;
    u.s = -1;
    printf("%d %u\n", u.s, u.u);
    return 0;
}
</code>```

Output:

```<code>-1 4294967295
</code>```

Basically, you assign one value and all union members get that value; if it's represented differently in a different type, so be it.

Within a struct, each variable occupies its own memory location, so if you wanted to store a complete date including the year, month, and day as separate variables within the struct, you could do so without any issues.

Body:
I'm getting into C and I experimented with union. My code is the following:

#include <stdio.h>

union date {
 int year  ;
 char month;
 char day  ;
 };

int main() {
 union date birth;
 birth.year = 1984;
 birth.month = 7;
 birth.day = 28;
 printf("%d, %d, %d\n",birth.year, birth.month, birth.day);
 // return 1820,28,28
 return 0;
}

1984 is written in binary as 0111 1100 0000

7 is written in binary as 0110

28 is written in binary as 0001 1100

I understand that because of union, birth.year has the value of 0111 0001 1100 which is 1820. But I do not understand why does birth.month return as value 28.

Body:
This entirely misunderstands what a union is. A union is an array of values that all start from at the same memory location; what you need to use if you want to store several separate values in one data type is a struct.

For example, with a union you can do this:

#include <stdio.h>
#include <stdint.h>

typedef union _myunion
{
    int32_t s;
    uint32_t u;
} myunion;

int main()
{
    myunion u;
    u.s = -1;
    printf("%d %u\n", u.s, u.u);
    return 0;
}

Output:

-1 4294967295

Basically, you assign one value and all union members get that value; if it's represented differently in a different type, so be it.

Within a struct, each variable occupies its own memory location, so if you wanted to store a complete date including the year, month, and day as separate variables within the struct, you could do so without any issues.


问:
Open view controller programatically and dont see navigation bar. Swift 3
On my story board I have a collection view controller embedded in a navigation controller. Now from the cell of the collection view, I programaticly open the second view controller (called TwoPicsViewController), like this:

```<code> let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "TwoPicsViewController") as! TwoPicsViewController

            self.present(nextViewController, animated:true, completion:nil)
</code>```

However when my TwoPicsViewController opens, I don't see the navigation bar at all. On the story board I connected the TwoPicsViewController to the first view controller with a segue show.

Am I missing something else?

Thanks

答:
You are not putting the new vc on the navigation stack, try this:

```<code>performSegue(withIdentifier: "Segue Name", sender: nil)
</code>```

And on Storyboard select the Segue, attributes inspector, identifier = "Segue Name"

Body:
On my story board I have a collection view controller embedded in a navigation controller. Now from the cell of the collection view, I programaticly open the second view controller (called TwoPicsViewController), like this:

 let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "TwoPicsViewController") as! TwoPicsViewController

            self.present(nextViewController, animated:true, completion:nil)

However when my TwoPicsViewController opens, I don't see the navigation bar at all. On the story board I connected the TwoPicsViewController to the first view controller with a segue show.

Am I missing something else?

Thanks

Body:
You are not putting the new vc on the navigation stack, try this:

performSegue(withIdentifier: "Segue Name", sender: nil)

And on Storyboard select the Segue, attributes inspector, identifier = "Segue Name"


问:
Self-documenting WebAPI 2
I have an ASP.NET MVC 5.1 WebAPI 2 with attribute routing project I would like to document. The idea is to add a "describe" path/controller to each API that would create a list of "description" objects.

To make this useful, I would also like to force XML and reference an XML style sheet in the document to display the data.

How do I embed an XML style sheet with a WebAPI?

答:
You can use swagger

It's a great tool to document and test the WebApi and you can also customize the UI.

Title: Self-documenting WebAPI 2


问:
Can't create bucket without authentication
We updated our Couchbase from 4.6 Community edition to 5.0.0-2873 Enterprise Edition for testing purposes and our software using the java-client started throwing InvalidPasswordException when trying to open a bucket.

As I've found, every newly created bucket has authType='sasl' and a randomly generated saslPassword.
I've tried creating a bucket using the CLI instead of the GUI:

```<code>couchbase-cli bucket-create -c localhost:8091 -u Administrator -p password --bucket=general --bucket-ramsize=1300 --bucket-type=couchbase --bucket-password=
</code>```

I got the following error:

```<code>ERROR: unrecognized arguments: --bucket-password=password
</code>```

I also tried the bucket-edit function with the same result.

According to the documentation the argument should be valid.

I also tried using the REST API to change bucket authentication (and similarly password), but even though this didn't throw any erros, the authType and the password remained the same.

```<code>curl -X POST -u Administrator:password -d 'authType=none' http://<host>:8091/pools/default/buckets/general
</code>```

Again, according to the documentation this should work.

If I query the bucket information for the sasl password and provide that for the openBucket function then the connection works, however we really don't want to use this feature in our system.

So, any other ideas how it would be possible to remove the bucket authentication in our 5.0EE Couchbase setup?

答:
In Couchbase 5.0 we no longer support bucket passwords and have moved to using role based access control when connecting to buckets. This means that in 5.0 the standard (pre-production) way to connect to a bucket is by using the Administrator user and password that you created when setting up the cluster. In case you're unsure what the Administrator user is, it is the user you create when you first go through the Couchbase setup wizard or the it is the username and password you specify on the command line when running the couchbase-cli cluster-init command.

One thing to note is that using the Administrator user/password is the standard pre-production workflow. I would recommend that when you go into production you create separate users for your application which only have access to cluster resources they need to access in the cluster. You can do this by going to the Users tab in the Administration Console and creating a new user and giving them the Full Bucket Access role which is the standard role that applications should have.

You might now be saying to yourself that this all sounds great, but when I use the Administrator user/password I still am having issues. If this is the case the reason is because you have Couchbase 5.0, but your SDK is not new enough to handle the new RBAC authentication mechanism in 5.0. The workaround for this is to create a user in the Users tab with the same name as the bucket and give that user the Full Bucket Access role. You can then use this user to authenticate.

One last thing to mention is that during an upgrade from a pre-5.0 cluster to a 5.0 cluster Couchbase will automatically create a user for each bucket. The each user will have the same name as one of the buckets and the password for that user will correspond to the bucket password. This is done mainly to ensure that there is no application downtime during an upgrade. After upgrading the cluster the next step should ideally be to upgrade the Couchbase client library to have it start using RBAC authentication.

Body:
We updated our Couchbase from 4.6 Community edition to 5.0.0-2873 Enterprise Edition for testing purposes and our software using the java-client started throwing InvalidPasswordException when trying to open a bucket.

As I've found, every newly created bucket has authType='sasl' and a randomly generated saslPassword.
I've tried creating a bucket using the CLI instead of the GUI:

couchbase-cli bucket-create -c localhost:8091 -u Administrator -p password --bucket=general --bucket-ramsize=1300 --bucket-type=couchbase --bucket-password=

I got the following error:

ERROR: unrecognized arguments: --bucket-password=password

I also tried the bucket-edit function with the same result.

According to the documentation the argument should be valid.

I also tried using the REST API to change bucket authentication (and similarly password), but even though this didn't throw any erros, the authType and the password remained the same.

curl -X POST -u Administrator:password -d 'authType=none' http://<host>:8091/pools/default/buckets/general

Again, according to the documentation this should work.

If I query the bucket information for the sasl password and provide that for the openBucket function then the connection works, however we really don't want to use this feature in our system.

So, any other ideas how it would be possible to remove the bucket authentication in our 5.0EE Couchbase setup?


问:
how to write custom flume-ng source for creating avro file on hdfs sink ?
I'm trying to write a CustomSource which can create avro files on hdfs sink. But I can't figure it out.

Would like to see some guideline or example.

答:
This will help you to get the details:
https://flume.apache.org/FlumeUserGuide.html

But on a high level to create a custom flume source:
1. Change the Flume config. Here you add your source configuration and point it to the MyCustomSource.java
2. Write the Source logic in MyCustomSource.java and copy the jar to flume nodes and restart.


问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
Network debugging requires Xcode 9.0 or later running on macOS 10.12.4
  or later, and on the device, requires iOS 11.0 or later, or tvOS 11.0
  or later.

iPhone

iOS 11 won't be available for 32bit devices, i.e. iPhone 5 and iPhone 5c and below. The first 64bit iPhone is 5s.

iPad

iPad mini 2 will be the oldest iPad with iOS 11 support.

iPod

iPod needs to be an iPod 6 to be able to run iOS.

If you use your devices not only for developing but also for production, be warned that a beta OS is not for the faint hearted ;-)


问:
Android app Freezing using java
Recently I  started learning java and android to build some android apps. Also im a little new in coding and the first application I code has a problem with high data and also lots of memory usage. What it does is : you enter an exact address of phone and it shows all files and subfiles in the directory. Everything works well until I give it an address with lots of files and everything freezes. Also would be so happy with any feedback, suggestions and anything else. Here is the code:

MainActivity.java:

```<code>package com.mycompany.MagicFiles;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.util.*;
import java.text.*;

public class MainActivity extends Activity
{

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

public void onShowButtonClick(View view)
{
    try
    {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        EditText editText = (EditText)findViewById(R.id.mainEditText1);
        TextView textView = (TextView) findViewById(R.id.mainTextView1);
        String dirName = editText.getText().toString();
        String temp = "";
        double bytes = 0;

        for (File tf : listf(dirName))
        {
            bytes = (tf.length() / 1024);
            temp = temp + tf.getAbsolutePath() + "\nDate: " + sdf.format(tf.lastModified()) + " Size: " + bytes + "KB\n";
        }
        textView.setText(temp);
    }
    catch (Exception e)
    {
        TextView textView = (TextView) findViewById(R.id.mainTextView1);
        textView.setText(e.toString());
    }
}

public static List<File> listf(String directoryName)
{
    File directory = new File(directoryName);

    List<File> resultList = new ArrayList<File>();

    // get all the files from a directory
    File[] fList = directory.listFiles();
    resultList.addAll(Arrays.asList(fList));
    for (File file : fList)
    {
        if (file.isFile())
        {
            System.out.println(file.getAbsolutePath());
        }
        else if (file.isDirectory())
        {
            resultList.addAll(listf(file.getAbsolutePath()));
        }
    }
    return resultList;
 }
}
</code>```

Main.xml:

```<code> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">

<TextView
    android:layout_height="wrap_content"
    android:text="Enter the exact location"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"
    android:layout_marginTop="15dp"/>

<TextView
    android:layout_height="wrap_content"
    android:text="And it shows the files"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"/>

<EditText
    android:layout_height="wrap_content"
    android:ems="10"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    android:id="@+id/mainEditText1"/>

<Button
    android:layout_height="wrap_content"
    android:text="Show"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    android:id="@+id/mainButton1"
    android:onClick="onShowButtonClick"/>

<HorizontalScrollView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">

    <ScrollView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

        <TextView
            android:layout_height="wrap_content"
            android:text="TODO: this gonna show something up :D"
            android:layout_width="match_parent"
            android:id="@+id/mainTextView1"/>

    </ScrollView>

</HorizontalScrollView>
</code>```

AndroidManifest.xml:

```<code> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.MagicFiles" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/the_icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

If anything else (maybe apk ...) is needed tell me.

答:
```<code>                            public void onShowButtonClick(View view) {
                                new Thread() {
                                    @Override
                                    public void run() {
                                        final View progressBar = findViewById(R.id.progressBar);
                                        try {

                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            progressBar.setVisibility(View.VISIBLE);
                                                        }
                                                    });

                                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                                            String dirName = ((EditText) findViewById(R.id.mainEditText1)).getText().toString();
                                            String temp = "";
                                            double bytes = 0;

                                            for (File tf : listf(dirName)) {
                                                bytes = (tf.length() / 1024);
                                                temp = temp + tf.getAbsolutePath() + "\nDate: " + sdf.format(tf.lastModified()) + " Size: " + bytes + "KB\n";
                                            }

                                            final String finalTemp = temp;
                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ((TextView) findViewById(R.id.mainTextView1)).setText(finalTemp);
                                                            progressBar.setVisibility(View.GONE);
                                                        }
                                                    });

                                        } catch (final Exception e) {
                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            progressBar.setVisibility(View.GONE);
                                                            ((TextView) findViewById(R.id.mainTextView1)).setText(e.toString());
                                                        }
                                                    });

                                        }

                                    }
                                }.start();

}
</code>```

And do not forget to add a progress bar to your layout:

```<code><ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:visibility="gone"/>
</code>```

Title: Android app Freezing using java

Body:
Recently I  started learning java and android to build some android apps. Also im a little new in coding and the first application I code has a problem with high data and also lots of memory usage. What it does is : you enter an exact address of phone and it shows all files and subfiles in the directory. Everything works well until I give it an address with lots of files and everything freezes. Also would be so happy with any feedback, suggestions and anything else. Here is the code:

MainActivity.java:

package com.mycompany.MagicFiles;

import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.util.*;
import java.text.*;

public class MainActivity extends Activity
{

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

public void onShowButtonClick(View view)
{
    try
    {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        EditText editText = (EditText)findViewById(R.id.mainEditText1);
        TextView textView = (TextView) findViewById(R.id.mainTextView1);
        String dirName = editText.getText().toString();
        String temp = "";
        double bytes = 0;

        for (File tf : listf(dirName))
        {
            bytes = (tf.length() / 1024);
            temp = temp + tf.getAbsolutePath() + "\nDate: " + sdf.format(tf.lastModified()) + " Size: " + bytes + "KB\n";
        }
        textView.setText(temp);
    }
    catch (Exception e)
    {
        TextView textView = (TextView) findViewById(R.id.mainTextView1);
        textView.setText(e.toString());
    }
}

public static List<File> listf(String directoryName)
{
    File directory = new File(directoryName);

    List<File> resultList = new ArrayList<File>();

    // get all the files from a directory
    File[] fList = directory.listFiles();
    resultList.addAll(Arrays.asList(fList));
    for (File file : fList)
    {
        if (file.isFile())
        {
            System.out.println(file.getAbsolutePath());
        }
        else if (file.isDirectory())
        {
            resultList.addAll(listf(file.getAbsolutePath()));
        }
    }
    return resultList;
 }
}

Main.xml:

 <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">

<TextView
    android:layout_height="wrap_content"
    android:text="Enter the exact location"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"
    android:layout_marginTop="15dp"/>

<TextView
    android:layout_height="wrap_content"
    android:text="And it shows the files"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"/>

<EditText
    android:layout_height="wrap_content"
    android:ems="10"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    android:id="@+id/mainEditText1"/>

<Button
    android:layout_height="wrap_content"
    android:text="Show"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    android:id="@+id/mainButton1"
    android:onClick="onShowButtonClick"/>

<HorizontalScrollView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content">

    <ScrollView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

        <TextView
            android:layout_height="wrap_content"
            android:text="TODO: this gonna show something up :D"
            android:layout_width="match_parent"
            android:id="@+id/mainTextView1"/>

    </ScrollView>

</HorizontalScrollView>

AndroidManifest.xml:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.MagicFiles" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/the_icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

If anything else (maybe apk ...) is needed tell me.

Body:
                            public void onShowButtonClick(View view) {
                                new Thread() {
                                    @Override
                                    public void run() {
                                        final View progressBar = findViewById(R.id.progressBar);
                                        try {

                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            progressBar.setVisibility(View.VISIBLE);
                                                        }
                                                    });

                                            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                                            String dirName = ((EditText) findViewById(R.id.mainEditText1)).getText().toString();
                                            String temp = "";
                                            double bytes = 0;

                                            for (File tf : listf(dirName)) {
                                                bytes = (tf.length() / 1024);
                                                temp = temp + tf.getAbsolutePath() + "\nDate: " + sdf.format(tf.lastModified()) + " Size: " + bytes + "KB\n";
                                            }

                                            final String finalTemp = temp;
                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ((TextView) findViewById(R.id.mainTextView1)).setText(finalTemp);
                                                            progressBar.setVisibility(View.GONE);
                                                        }
                                                    });

                                        } catch (final Exception e) {
                                            runOnUiThread(
                                                    new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            progressBar.setVisibility(View.GONE);
                                                            ((TextView) findViewById(R.id.mainTextView1)).setText(e.toString());
                                                        }
                                                    });

                                        }

                                    }
                                }.start();

}

And do not forget to add a progress bar to your layout:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:visibility="gone"/>


问:
Screen width detection with Javascript / jQuery - Sidebar to Tabbed Pullout
I have a responsive design, with selectable sidebar data drawn from a database. At a screen width less than 751 pixels, that sidebar becomes a pull-out tab on the left of the screen. I cannot feasibly reload the data on state change (sidebar to tab or vice versa) as the amount of data is extensive. So, the solution seems to be using the tabbed state (using MB Extruder - a "hidden" tab utility) as the sidebar, also, and just changing the state of the div. However, that cannot be done without javascript as, in the sidebar state, Extruder needs to be open, whereas it needs to be closed when in the tab state.

So, I am doing the following to set the sidebar/tab:

```<code>$(document).ready(function()
{
    CheckScreen();
},
$(window).resize(function()
{
    CheckScreen();
}));
function CheckScreen()
{
    var ww=$(window).width();
    if(ww < 751)
    {
        $('#extruderLeft').closeMbExtruder();
        $('.extruder.left .flap').css('display', 'block'); // The tab
        $('.site_wrapper').css('padding-left', '30px');
    }
    else
    {
        $('#extruderLeft').openMbExtruder(true);
        $('.extruder.left .flap').css('display', 'none');
        $('.site_wrapper').css('padding-left', '0px');
    }
}
</code>```

This changes the state from a sidebar column to a hidden state with a small tab on the left side of the screen when the screen width is less that 751 pixels. This will work fine at any size screen on document.ready. It will adjust fine when dragging the side of a browser from larger to smaller. However, when dragging back out to a larger width, the div will, rather randomly, switch from one state to another.

Perhaps there is a better way to do this altogether. If worse came to worse, I could have two separate entities (sidebar and tabbed state) holding the same data, and just use CSS, but that would be ridiculously redundant.

答:
The problem seemed to be faulty conditions in the if-clauses (see comments under the question).

This should do the trick:

```<code>$(window).load(function() {
  $(window).resize(function() {
    if ($(window).width() < 751) {
      if ($('.extruder.left .flap').css('display') != 'block') {
        $('#extruderLeft').closeMbExtruder();
        $('.extruder.left .flap').css('display','block'); // The tab
        $('.site_wrapper').css('padding-left','30px');
      }
    } else if ($('.extruder.left .flap').css('display') != 'none') {
      $('#extruderLeft').openMbExtruder(true);
      $('.extruder.left .flap').css('display','none');
      $('.site_wrapper').css('padding-left','0');
    }
  }).resize();
});
</code>```

Notice the extra if-clauses checking the display-state:

if ($('.extruder.left .flap').css('display') != 'block') {

and

} else if ($('.extruder.left .flap').css('display') != 'none') {

This makes sure the sidebar/tab-switch only occurs on the break point of the specified screen-width, and the if-clauses aren't unnecessarily executed.

I also changed your script a bit to make more efficient use of jQuery. This way you don't have to create a named function AND call it twice. (I always put window.resize inside window.load instead of document.ready because if you need to scale things that only works properly after load anyway, but for your purpose both will work.)

Body:
I have a responsive design, with selectable sidebar data drawn from a database. At a screen width less than 751 pixels, that sidebar becomes a pull-out tab on the left of the screen. I cannot feasibly reload the data on state change (sidebar to tab or vice versa) as the amount of data is extensive. So, the solution seems to be using the tabbed state (using MB Extruder - a "hidden" tab utility) as the sidebar, also, and just changing the state of the div. However, that cannot be done without javascript as, in the sidebar state, Extruder needs to be open, whereas it needs to be closed when in the tab state.

So, I am doing the following to set the sidebar/tab:

$(document).ready(function()
{
    CheckScreen();
},
$(window).resize(function()
{
    CheckScreen();
}));
function CheckScreen()
{
    var ww=$(window).width();
    if(ww < 751)
    {
        $('#extruderLeft').closeMbExtruder();
        $('.extruder.left .flap').css('display', 'block'); // The tab
        $('.site_wrapper').css('padding-left', '30px');
    }
    else
    {
        $('#extruderLeft').openMbExtruder(true);
        $('.extruder.left .flap').css('display', 'none');
        $('.site_wrapper').css('padding-left', '0px');
    }
}

This changes the state from a sidebar column to a hidden state with a small tab on the left side of the screen when the screen width is less that 751 pixels. This will work fine at any size screen on document.ready. It will adjust fine when dragging the side of a browser from larger to smaller. However, when dragging back out to a larger width, the div will, rather randomly, switch from one state to another.

Perhaps there is a better way to do this altogether. If worse came to worse, I could have two separate entities (sidebar and tabbed state) holding the same data, and just use CSS, but that would be ridiculously redundant.

Body:
The problem seemed to be faulty conditions in the if-clauses (see comments under the question).

This should do the trick:

$(window).load(function() {
  $(window).resize(function() {
    if ($(window).width() < 751) {
      if ($('.extruder.left .flap').css('display') != 'block') {
        $('#extruderLeft').closeMbExtruder();
        $('.extruder.left .flap').css('display','block'); // The tab
        $('.site_wrapper').css('padding-left','30px');
      }
    } else if ($('.extruder.left .flap').css('display') != 'none') {
      $('#extruderLeft').openMbExtruder(true);
      $('.extruder.left .flap').css('display','none');
      $('.site_wrapper').css('padding-left','0');
    }
  }).resize();
});

Notice the extra if-clauses checking the display-state:

if ($('.extruder.left .flap').css('display') != 'block') {

and

} else if ($('.extruder.left .flap').css('display') != 'none') {

This makes sure the sidebar/tab-switch only occurs on the break point of the specified screen-width, and the if-clauses aren't unnecessarily executed.

I also changed your script a bit to make more efficient use of jQuery. This way you don't have to create a named function AND call it twice. (I always put window.resize inside window.load instead of document.ready because if you need to scale things that only works properly after load anyway, but for your purpose both will work.)


问:
Maintain scroll position in listboxes in updatepanels, NOT the page
I have a listbox inside an update panel.  When I scroll down and select an item, it scrolls back to the top of the listbox.  I heard that the dom does not keep track of the scroll position on a postback.  Does anyone have a solution/example on how to solve this?

Thanks,
XaiSoft

答:
```<code>    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    function BeginRequestHandler(sender, args) {
        if (($get('Panel1')) != null) {
            xPos = $get('Panel1').scrollLeft;
            yPos = $get('Panel1').scrollTop;
        }
    }

    function EndRequestHandler(sender, args) {
        if (($get('Panel1')) != null) {
            $get('Panel1').scrollLeft = xPos;
            $get('Panel1').scrollTop = yPos;
        }
    }
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);

    //Note: "Panel1" Panel or div u want to maintain scroll position
    //Note: This Java Script should be added after Scriptmanager*****
</code>```

<p>//Maintain Scroll Position for Panel/Div with out Update panel</p>

```<code>    window.onload = function() {
        var strCook = document.cookie;
        if (strCook.indexOf("!~") != 0) {
            var intS = strCook.indexOf("!~");
            var intE = strCook.indexOf("~!");
            var strPos = strCook.substring(intS + 2, intE);
            document.getElementById('Panel1').scrollTop = strPos;
        }
    }
    function SetDivPosition() {
        var intY = document.getElementById('Panel1').scrollTop;
        document.title = intY;
        document.cookie = "yPos=!~" + intY + "~!";
    }

   //Note: "Panel1" Panel id or div id for which u want to maintain scroll position
</code>```

OwnerDisplayName: Xaisoft

Body:
    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    function BeginRequestHandler(sender, args) {
        if (($get('Panel1')) != null) {
            xPos = $get('Panel1').scrollLeft;
            yPos = $get('Panel1').scrollTop;
        }
    }

    function EndRequestHandler(sender, args) {
        if (($get('Panel1')) != null) {
            $get('Panel1').scrollLeft = xPos;
            $get('Panel1').scrollTop = yPos;
        }
    }
    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);

    //Note: "Panel1" Panel or div u want to maintain scroll position
    //Note: This Java Script should be added after Scriptmanager*****

//Maintain Scroll Position for Panel/Div with out Update panel

    window.onload = function() {
        var strCook = document.cookie;
        if (strCook.indexOf("!~") != 0) {
            var intS = strCook.indexOf("!~");
            var intE = strCook.indexOf("~!");
            var strPos = strCook.substring(intS + 2, intE);
            document.getElementById('Panel1').scrollTop = strPos;
        }
    }
    function SetDivPosition() {
        var intY = document.getElementById('Panel1').scrollTop;
        document.title = intY;
        document.cookie = "yPos=!~" + intY + "~!";
    }

   //Note: "Panel1" Panel id or div id for which u want to maintain scroll position


问:
Asp.net Core Web API - Current user & Windows Authentication
We have following technical stack in our application
AngularJS2
Asp.Net Core API
SQL Server

Now we need to store User Name for the Logged in User in table during Create/Edit for given item i.e. in Core API.

We have tried with

WindowsIdentity.GetCurrent().Name, it gives IIS APPPOOL\Asp.netCore

HttpContext.User.Identity gives null value

I get User Name with WindowsIdentity while working with Visual Studio, but with IIS, it gives value as Asp.Netcore i.e. pool name

Windows Authentication is enabled and Anonymous Authentication is disabled

Using IIS Version 6.1

Am I missing anything?

答:
On Windows Server 2012 R2/IIS 8.0, even after setting forwardWindowsAuthToken=true in web.config, User.Identity.Name was not returning the user name but IIS APPPOOL so to resolve the issue I made below change;

Go to the web application in IIS

Open Configuration Editor

Change Section to system.webServer/serverRuntime

Change authenticatedUserOverride to UseAuthenticatedUser (for me it was set to UseWorkerProcessUser)

For further details refer to below link;
https://blogs.iis.net/jaroslad/what-does-the-authenticateduseroverrideuser-do


问:
What is the process to reassign a variable to point to another in C#?
At the moment I have the following inside a for loop:

```<code>NewArray.Add(RawDataArray[i].Value);
</code>```

During the course of processing RawDataArray a number of additional arrays will be created, for example NewArray1,NewArray2 etc

At one point I will need NewArray to point to NewArray1 so that the .Add method adds the data to NewArray1 and at another point, I need to point NewArray to another NewArrayX

How do I do this in C#?

Edit

In order to try and clarify here is a relevant section:

```<code>    List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to NewArray1
                    >> Create NewArray1 and "change" NewArray so that it points to NewArray1 <<
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //RawDataArray[i] should be added to NewArray2
                    >> Create NewArray2 and "change" NewArray so that it points to NewArray2 <<
                    NewArray.Add(RawDataArray[i].Value);
                }
            }
</code>```

Additional edit

I guess a little more information is required so you can see the full picture. I have a raw data stream, in this case simulated by RawDataArray (OK terminology of 'array' not correct, accepted!!).

```<code>    struct TypedValue
        {
            private readonly int typeCode;
            private readonly object value;

            public TypedValue(int typeCode, object value)
            {
                this.typeCode = typeCode;
                this.value = value;
            }

            public int TypeCode { get { return typeCode; } }
            public object Value { get { return value; } }

        }

        static readonly IList<TypedValue> RawDataArray = new ReadOnlyCollection<TypedValue>
        (new[] {
            new TypedValue(5005,@"String Value 1"),
            new TypedValue(5005,@"String Value 2"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 3"),
            new TypedValue(5005,@"String Value 4"),
            new TypedValue(5005,@"String Value 5"),
            new TypedValue(5005,@"String Value 6"),
            new TypedValue(5005,@"String Value 7"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 8"),
            new TypedValue(5005,@"String Value 9"),
            new TypedValue(5005,@"String Value 10"),
            new TypedValue(5005,@"String Value 11"),
            new TypedValue(5005,@"String Value 12"),
            new TypedValue(5005,@"String Value 13"),
            new TypedValue(5005,@"String Value 14"),
            new TypedValue(5005,@"String Value 15"),
            new TypedValue(5005,@"String Value 16"),
            new TypedValue(5005,@"String Value 17"),
            new TypedValue(5005,@"String Value 18"),
            new TypedValue(5005,@"String Value 19"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 20"),
            new TypedValue(5005,@"String Value 21"),
            new TypedValue(5005,@"String Value 22"),
            new TypedValue(5005,@"String Value 23"),
            new TypedValue(5005,@"String Value 24"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5005,@"String Value 25"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 26"),
            new TypedValue(5005,@"String Value 27"),
            new TypedValue(5005,@"String Value 28"),
            new TypedValue(5005,@"String Value 29"),
            new TypedValue(5005,@"String Value 30"),
            new TypedValue(5017,@"-1"),
        });
</code>```

The confusing part is that typeCode of 5016 and 5017 form the start and end respectively of a block of data.  That is to say the data between these typeCodes needs to go in to a temporary array (or something) which is then inserted in to NewArray.

So, in pseudo code, I have this working thought:

1) for (int i = 1; i <= RawDataArray.Count; i++)

2) if i.typeCode = 5005 then add i.value to NewArray

3) if i.typeCode = 5016 then create a temporary array and make NewArray point to it so that calls to the Add method now adds to the temporary array.

4) if i.typeCode = 5017 then add temporary array to NewArray and the point NewArray variable to NewArray.

```<code>        List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to temporary array
                    //Create temporary array and "change" NewArray so that it points to temporary array
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //temporary array should be added to NewArray
                    //Add temporary array to NewArray and re-assign NewArray Variable to reference NewArray so that calls to .Add method add to NewArray
                }
            }
</code>```

The idea is this.  As the RawDataArray is iterated through, if it encounters a typeCode of 5005 it adds the value to NewArray.  If the typeCode is 5016 it starts a temporary array and re-assigns the NewArray variable to point to the temporary array. When it next encounters a 5005 typeCode the NewArray variable is pointing to the temporary array so that the add method adds the value to the temporary array.

When the 5017 typeCode is found we know that the temporary array is complete and needs to be added to NewArray and so the process completes. Since the NewArray Variable now points to NewArray and not the temporary array, any subsequent .Add calls will add to NewArray (so typeCode of 5005 outside the 5016 and 5017 data block is added to NewArray.

This image may also help: http://i.xomf.com/myhln.png

I find an image is perhaps sometimes better.

答:
You can clone the array, like so:

```<code>NewArray = List<YourType>(NewArray1);
</code>```

Not sure if that helps, seems like you come from a C++ background and I don't think there's really any way to use it as a pointer.

ContentLicense: CC BY-SA 4.0

Body:
At the moment I have the following inside a for loop:

NewArray.Add(RawDataArray[i].Value);

During the course of processing RawDataArray a number of additional arrays will be created, for example NewArray1,NewArray2 etc

At one point I will need NewArray to point to NewArray1 so that the .Add method adds the data to NewArray1 and at another point, I need to point NewArray to another NewArrayX

How do I do this in C#?

Edit

In order to try and clarify here is a relevant section:

    List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to NewArray1
                    >> Create NewArray1 and "change" NewArray so that it points to NewArray1 <<
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //RawDataArray[i] should be added to NewArray2
                    >> Create NewArray2 and "change" NewArray so that it points to NewArray2 <<
                    NewArray.Add(RawDataArray[i].Value);
                }
            }

Additional edit

I guess a little more information is required so you can see the full picture. I have a raw data stream, in this case simulated by RawDataArray (OK terminology of 'array' not correct, accepted!!).

    struct TypedValue
        {
            private readonly int typeCode;
            private readonly object value;

            public TypedValue(int typeCode, object value)
            {
                this.typeCode = typeCode;
                this.value = value;
            }

            public int TypeCode { get { return typeCode; } }
            public object Value { get { return value; } }

        }

        static readonly IList<TypedValue> RawDataArray = new ReadOnlyCollection<TypedValue>
        (new[] {
            new TypedValue(5005,@"String Value 1"),
            new TypedValue(5005,@"String Value 2"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 3"),
            new TypedValue(5005,@"String Value 4"),
            new TypedValue(5005,@"String Value 5"),
            new TypedValue(5005,@"String Value 6"),
            new TypedValue(5005,@"String Value 7"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 8"),
            new TypedValue(5005,@"String Value 9"),
            new TypedValue(5005,@"String Value 10"),
            new TypedValue(5005,@"String Value 11"),
            new TypedValue(5005,@"String Value 12"),
            new TypedValue(5005,@"String Value 13"),
            new TypedValue(5005,@"String Value 14"),
            new TypedValue(5005,@"String Value 15"),
            new TypedValue(5005,@"String Value 16"),
            new TypedValue(5005,@"String Value 17"),
            new TypedValue(5005,@"String Value 18"),
            new TypedValue(5005,@"String Value 19"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 20"),
            new TypedValue(5005,@"String Value 21"),
            new TypedValue(5005,@"String Value 22"),
            new TypedValue(5005,@"String Value 23"),
            new TypedValue(5005,@"String Value 24"),
            new TypedValue(5017,@"-1"),
            new TypedValue(5005,@"String Value 25"),
            new TypedValue(5016,@"-1"),
            new TypedValue(5005,@"String Value 26"),
            new TypedValue(5005,@"String Value 27"),
            new TypedValue(5005,@"String Value 28"),
            new TypedValue(5005,@"String Value 29"),
            new TypedValue(5005,@"String Value 30"),
            new TypedValue(5017,@"-1"),
        });

The confusing part is that typeCode of 5016 and 5017 form the start and end respectively of a block of data.  That is to say the data between these typeCodes needs to go in to a temporary array (or something) which is then inserted in to NewArray.

So, in pseudo code, I have this working thought:

1) for (int i = 1; i <= RawDataArray.Count; i++)

2) if i.typeCode = 5005 then add i.value to NewArray

3) if i.typeCode = 5016 then create a temporary array and make NewArray point to it so that calls to the Add method now adds to the temporary array.

4) if i.typeCode = 5017 then add temporary array to NewArray and the point NewArray variable to NewArray.

        List<object> NewArray = new List<object>();

            for (int i = 1; i <= RawDataArray.Count; i++)
            {
                if (RawDataArray[i].TypeCode == 5005)
                {
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5016)
                {
                    //RawDataArray[i] should be added to temporary array
                    //Create temporary array and "change" NewArray so that it points to temporary array
                    NewArray.Add(RawDataArray[i].Value);
                }

                if (RawDataArray[i].TypeCode == 5017)
                {
                    //temporary array should be added to NewArray
                    //Add temporary array to NewArray and re-assign NewArray Variable to reference NewArray so that calls to .Add method add to NewArray
                }
            }

The idea is this.  As the RawDataArray is iterated through, if it encounters a typeCode of 5005 it adds the value to NewArray.  If the typeCode is 5016 it starts a temporary array and re-assigns the NewArray variable to point to the temporary array. When it next encounters a 5005 typeCode the NewArray variable is pointing to the temporary array so that the add method adds the value to the temporary array.

When the 5017 typeCode is found we know that the temporary array is complete and needs to be added to NewArray and so the process completes. Since the NewArray Variable now points to NewArray and not the temporary array, any subsequent .Add calls will add to NewArray (so typeCode of 5005 outside the 5016 and 5017 data block is added to NewArray.

This image may also help: http://i.xomf.com/myhln.png

I find an image is perhaps sometimes better.

Body:
You can clone the array, like so:

NewArray = List<YourType>(NewArray1);

Not sure if that helps, seems like you come from a C++ background and I don't think there's really any way to use it as a pointer.


问:
pygame.time.clock() or pygame.clock.tick() error
I have a main loop in my code where it loops everything and when I run my code I get this error:

```<code>    Traceback (most recent call last):
      File "C:\Users\Javier\Documents\Python Pygame\First Game\First
    Game.py", line 17, in <module>
        clock=pygame.time.clock()
    AttributeError: module 'pygame.time' has no attribute 'clock'
</code>```

I understand what the error is: it means it can't find the 'class' clock and in another instance where I used pygame.tick.clock() I got the same error.

```<code>    #import modules here

    import pygame

    #define what colours are
    black=(0,0,0)
    white=(255,255,255)
    turquoise=(64,224,208)
    #initalise pygame
    pygame.init()
    #set up screen
    screen=pygame.display.set_mode((400,400))
    #what the screen is called and backgroud colour
    screen.fill(black)
    pygame.display.set_caption("Snake!")
    #set a variable for how quick the game runs
    clock=pygame.time.clock()

    '''making future references easier
    eval just takes code as a string and runs it
    eg:
    instead of doing print(5+8)
    you can do eval(print(5+8))'''
    def key(key):
        return pygame.ket.get_pressed()[eval("pygame.K_"+key)]
    #draw the snake
    snake=(50,150,150,50)
    #display.flip shows what has been drawn on the screen eg the snake
    while True:
        pygame.draw.rect(screen,turquoise,snake)
        pygame.display.flip()
        clock.tick(60)
</code>```

When I comment the problem code (clock.tick() and pygame.time.clock)  the window opens and displays the turquoise "snake" but it has no limiting factor that slows down the rate of the loop executing.

答:
To use the pygame clock:

```<code>clock = pygame.time.Clock()
</code>```

Then,

```<code>clock.tick(60)
</code>```

Body:
I have a main loop in my code where it loops everything and when I run my code I get this error:

    Traceback (most recent call last):
      File "C:\Users\Javier\Documents\Python Pygame\First Game\First
    Game.py", line 17, in <module>
        clock=pygame.time.clock()
    AttributeError: module 'pygame.time' has no attribute 'clock'

I understand what the error is: it means it can't find the 'class' clock and in another instance where I used pygame.tick.clock() I got the same error.

    #import modules here

    import pygame

    #define what colours are
    black=(0,0,0)
    white=(255,255,255)
    turquoise=(64,224,208)
    #initalise pygame
    pygame.init()
    #set up screen
    screen=pygame.display.set_mode((400,400))
    #what the screen is called and backgroud colour
    screen.fill(black)
    pygame.display.set_caption("Snake!")
    #set a variable for how quick the game runs
    clock=pygame.time.clock()

    '''making future references easier
    eval just takes code as a string and runs it
    eg:
    instead of doing print(5+8)
    you can do eval(print(5+8))'''
    def key(key):
        return pygame.ket.get_pressed()[eval("pygame.K_"+key)]
    #draw the snake
    snake=(50,150,150,50)
    #display.flip shows what has been drawn on the screen eg the snake
    while True:
        pygame.draw.rect(screen,turquoise,snake)
        pygame.display.flip()
        clock.tick(60)

When I comment the problem code (clock.tick() and pygame.time.clock)  the window opens and displays the turquoise "snake" but it has no limiting factor that slows down the rate of the loop executing.

Body:
To use the pygame clock:

clock = pygame.time.Clock()

Then,

clock.tick(60)


问:
Time Series chart X-axis Time display
I am working on TimeSeries in jfreechart and in this chart time is represented as hh:mm:ss. But when I start time from 00:00:00, chart shows the start time 12:00:00 and it rotates after 24 hour, but I do not want rotation of time such I want to see 25:00:00 in place of 1:00:00.
Is there any solution for these problems?

Thanks in advance.

答:
dont know if you still wanna know about that, but you can just use something like this:

```<code>DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setAutoRange(true);
axis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));
</code>```

By using HH instead of hh you force SimpleDateFormat to write the date in 24h format.

Hope it helps!
Cheers

Title: Time Series chart X-axis Time display

Body:
dont know if you still wanna know about that, but you can just use something like this:

DateAxis axis = (DateAxis) plot.getDomainAxis();
axis.setAutoRange(true);
axis.setDateFormatOverride(new SimpleDateFormat("HH:mm"));

By using HH instead of hh you force SimpleDateFormat to write the date in 24h format.

Hope it helps!
Cheers


问:
Drawing latitude, longitude of array elements on canvas
I'm trying to draw rects on a canvas for each element in my array. For the positioning I use the longitude and latitude values of the elements.

My array looks something like this and contains 50.000 elements that are objects:

```<code>var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]
</code>```

EDIT: The solution from @le_m helped me out a lot and I implemented a filter like he suggested:

```<code>const test2 = test.filter(({latitude, longitude}) => latitude != null
              && longitude != null);

function getBoundingRect(test2) {
    let left = Infinity, right  = -Infinity;
    let top  = Infinity, bottom = -Infinity;

    for (let {latitude, longitude} of test2) {
        if (left   > latitude ) left   = latitude;
        if (top    > longitude) top    = longitude;
        if (right  < latitude) right  = latitude;
        if (bottom < longitude) bottom = longitude;
    }
    return {x: left, y: top, width: right - left, height: bottom -
    top};
}

function draw(ctx, test2) {
    let boundingRect = getBoundingRect(test2);
    let scale = Math.min(canvas.width, canvas.height);

    for (let {latitude, longitude} of test2) {
        let x = (latitude  - boundingRect.x) / boundingRect.width  *
        scale;
        let y = (longitude - boundingRect.y) / boundingRect.height *
        scale;
        ctx.fillStyle = "rgba(65,105,225,0.2)";
        ctx.fillRect(x - 5, y - 5, 4, 4);
    }
}

draw(ctx, test2);
</code>```

The filter doesn't seem to work What am I doing wrong?

答:
You may not be initializing your path.
Try plugging in this code and tinkering with the values:

ctx.beginPath();
ctx.lineWidth="10";
ctx.strokeStyle="blue";
ctx.rect(50,50,150,80);
ctx.stroke();```

Body:
I'm trying to draw rects on a canvas for each element in my array. For the positioning I use the longitude and latitude values of the elements.

My array looks something like this and contains 50.000 elements that are objects:

var modified_array =
[{"city":"NYC","longitude":-73.935242,"latitude":40.730610},
 {"city":"NYC","longitude":-74.044502,"latitude":40.689247}]

EDIT: The solution from @le_m helped me out a lot and I implemented a filter like he suggested:

const test2 = test.filter(({latitude, longitude}) => latitude != null
              && longitude != null);

function getBoundingRect(test2) {
    let left = Infinity, right  = -Infinity;
    let top  = Infinity, bottom = -Infinity;

    for (let {latitude, longitude} of test2) {
        if (left   > latitude ) left   = latitude;
        if (top    > longitude) top    = longitude;
        if (right  < latitude) right  = latitude;
        if (bottom < longitude) bottom = longitude;
    }
    return {x: left, y: top, width: right - left, height: bottom -
    top};
}

function draw(ctx, test2) {
    let boundingRect = getBoundingRect(test2);
    let scale = Math.min(canvas.width, canvas.height);

    for (let {latitude, longitude} of test2) {
        let x = (latitude  - boundingRect.x) / boundingRect.width  *
        scale;
        let y = (longitude - boundingRect.y) / boundingRect.height *
        scale;
        ctx.fillStyle = "rgba(65,105,225,0.2)";
        ctx.fillRect(x - 5, y - 5, 4, 4);
    }
}

draw(ctx, test2);

The filter doesn't seem to work What am I doing wrong?


答:
Pointers are very powerfull programming tools, but also quite dangerous ones. So by default no Runtime lets you handle naked pointers.

One of the replacement concepts for pointers (and the one you will need here) are references. You have a instance of a class (Array is a class) in memory. Assigned to one or more references. So something like this:

```<code>//Create a List of List<int>'s
List<List<int>> ListOfLists = new List<List<int>>();

for (int i=0; i < 10){
    List<int> currentList = new List<int>();
    ListOfLists.Add(currentList);
    //Do some work with current list, like filling it with content in a loop.
}

//Do the processing or output of ListOfLists
</code>```

Title: What is the process to reassign a variable to point to another in C#?

Body:
Pointers are very powerfull programming tools, but also quite dangerous ones. So by default no Runtime lets you handle naked pointers.

One of the replacement concepts for pointers (and the one you will need here) are references. You have a instance of a class (Array is a class) in memory. Assigned to one or more references. So something like this:

//Create a List of List<int>'s
List<List<int>> ListOfLists = new List<List<int>>();

for (int i=0; i < 10){
    List<int> currentList = new List<int>();
    ListOfLists.Add(currentList);
    //Do some work with current list, like filling it with content in a loop.
}

//Do the processing or output of ListOfLists


问:
How to store custom objects in Dataset?
According to Introducing Spark Datasets:

As we look forward to Spark 2.0, we plan some exciting improvements to Datasets, specifically:
  ...
  Custom encoders – while we currently autogenerate encoders for a wide variety of types, we’d like to open up an API for custom objects.

and attempts to store custom type in a Dataset lead to following error like:

Unable to find encoder for type stored in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing sqlContext.implicits._ Support for serializing other types will be added in future releases

or:

Java.lang.UnsupportedOperationException: No Encoder found for ....

Are there any existing workarounds?

Note this question exists only as an entry point for a Community Wiki answer. Feel free to update / improve both question and answer.

答:
My examples will be in Java, but I don't imagine it to be difficult adapting to Scala.

I have been quite successful converting RDD<Fruit> to Dataset<Fruit> using spark.createDataset and Encoders.bean as long as Fruit is a simple Java Bean.

Step 1: Create the simple Java Bean.

```<code>public class Fruit implements Serializable {
    private String name  = "default-fruit";
    private String color = "default-color";

    // AllArgsConstructor
    public Fruit(String name, String color) {
        this.name  = name;
        this.color = color;
    }

    // NoArgsConstructor
    public Fruit() {
        this("default-fruit", "default-color");
    }

    // ...create getters and setters for above fields
    // you figure it out
}
</code>```

I'd stick to classes with primitive types and String as fields before the DataBricks folks beef up their Encoders. If you have a class with nested object, create another simple Java Bean with all of its fields flattened, so you can use RDD transformations to map the complex type to the simpler one. Sure it's a little extra work, but I imagine it'll help a lot on performance working with a flat schema.

Step 2: Get your Dataset from the RDD

```<code>SparkSession spark = SparkSession.builder().getOrCreate();
JavaSparkContext jsc = new JavaSparkContext();

List<Fruit> fruitList = ImmutableList.of(
    new Fruit("apple", "red"),
    new Fruit("orange", "orange"),
    new Fruit("grape", "purple"));
JavaRDD<Fruit> fruitJavaRDD = jsc.parallelize(fruitList);

RDD<Fruit> fruitRDD = fruitJavaRDD.rdd();
Encoder<Fruit> fruitBean = Encoders.bean(Fruit.class);
Dataset<Fruit> fruitDataset = spark.createDataset(rdd, bean);
</code>```

And voila! Lather, rinse, repeat.

Title: How to store custom objects in Dataset?

Body:
My examples will be in Java, but I don't imagine it to be difficult adapting to Scala.

I have been quite successful converting RDD<Fruit> to Dataset<Fruit> using spark.createDataset and Encoders.bean as long as Fruit is a simple Java Bean.

Step 1: Create the simple Java Bean.

public class Fruit implements Serializable {
    private String name  = "default-fruit";
    private String color = "default-color";

    // AllArgsConstructor
    public Fruit(String name, String color) {
        this.name  = name;
        this.color = color;
    }

    // NoArgsConstructor
    public Fruit() {
        this("default-fruit", "default-color");
    }

    // ...create getters and setters for above fields
    // you figure it out
}

I'd stick to classes with primitive types and String as fields before the DataBricks folks beef up their Encoders. If you have a class with nested object, create another simple Java Bean with all of its fields flattened, so you can use RDD transformations to map the complex type to the simpler one. Sure it's a little extra work, but I imagine it'll help a lot on performance working with a flat schema.

Step 2: Get your Dataset from the RDD

SparkSession spark = SparkSession.builder().getOrCreate();
JavaSparkContext jsc = new JavaSparkContext();

List<Fruit> fruitList = ImmutableList.of(
    new Fruit("apple", "red"),
    new Fruit("orange", "orange"),
    new Fruit("grape", "purple"));
JavaRDD<Fruit> fruitJavaRDD = jsc.parallelize(fruitList);

RDD<Fruit> fruitRDD = fruitJavaRDD.rdd();
Encoder<Fruit> fruitBean = Encoders.bean(Fruit.class);
Dataset<Fruit> fruitDataset = spark.createDataset(rdd, bean);

And voila! Lather, rinse, repeat.


问:
Implement an Ellipse Structural Element
I want to implement the following using OpenCV (I'll post my attempt at the bottom of the post). I am aware that OpenCV has a function for something like this, but I want to try to write my own.

In an image (Mat) (the coordinate system is at the top left, since it is an image) of width width and height height, I want to display a filled ellipsewith the following properties:

it should be centered at (width/2, height/2)

the image should be binary, so the points corresponding to the ellipse should have a value of 1 and others should be 0

the ellipse should be rotated by angle radians around the origin (or degrees, this does not matter all that much, I can convert)

ellipse: semi-major axis parameter is a and semi-minor axis parameter is b and these two parameters also represent the size of these axes in the picture, so "no matter" the width and height, the ellipse should have a major axis of size 2*a and a minor axis of size 2*b

Ok, so I've found an equation similar to this (https://math.stackexchange.com/a/434482/403961) for my purpose. My code is as follows.. it does seem to do pretty well on the rotation side, but, sadly, depending on the rotation angle, the SIZE (major axis, not sure about the minor) visibly increases/decreases, which is not normal, since I want it to have the same size, independent of the rotation angle.

NOTE The biggest size is seemingly achieved when the angle is 45 or -45 degrees and the smallest for angles like -90, 0, 90.

Code:

```<code>inline double sqr(double x)
{
    return x * x;
}

Mat ellipticalElement(double a, double b, double angle, int width, int height)
{
    // just to make sure I don't use some bad values for my parameters
    assert(2 * a < width);
    assert(2 * b < height);

    Mat element = Mat::zeros(height, width, CV_8UC1);

    Point center(width / 2, height / 2);
    for(int x = 0 ; x < width ; x++)
        for(int y = 0 ; y < height ; y++)
        {
            if (sqr((x - center.x) * cos(angle) - (y - center.y) * sin(angle)) / sqr(a) + sqr((x - center.x) * sin(angle) - (y - center.y) * cos(angle)) / sqr(b) <= 1)
                element.at<uchar>(y, x) = 1;
        }

    return element;
}
</code>```

答:
A pesky typo sneaked in your inequality. The first summand must be

```<code>sqr((x - center.x) * cos(angle) + (y - center.y) * sin(angle)) / sqr(a)
</code>```

Note the plus sign instead of minus.

Title: Implement an Ellipse Structural Element

Body:
I want to implement the following using OpenCV (I'll post my attempt at the bottom of the post). I am aware that OpenCV has a function for something like this, but I want to try to write my own.

In an image (Mat) (the coordinate system is at the top left, since it is an image) of width width and height height, I want to display a filled ellipsewith the following properties:

it should be centered at (width/2, height/2)

the image should be binary, so the points corresponding to the ellipse should have a value of 1 and others should be 0

the ellipse should be rotated by angle radians around the origin (or degrees, this does not matter all that much, I can convert)

ellipse: semi-major axis parameter is a and semi-minor axis parameter is b and these two parameters also represent the size of these axes in the picture, so "no matter" the width and height, the ellipse should have a major axis of size 2*a and a minor axis of size 2*b

Ok, so I've found an equation similar to this (https://math.stackexchange.com/a/434482/403961) for my purpose. My code is as follows.. it does seem to do pretty well on the rotation side, but, sadly, depending on the rotation angle, the SIZE (major axis, not sure about the minor) visibly increases/decreases, which is not normal, since I want it to have the same size, independent of the rotation angle.

NOTE The biggest size is seemingly achieved when the angle is 45 or -45 degrees and the smallest for angles like -90, 0, 90.

Code:

inline double sqr(double x)
{
    return x * x;
}

Mat ellipticalElement(double a, double b, double angle, int width, int height)
{
    // just to make sure I don't use some bad values for my parameters
    assert(2 * a < width);
    assert(2 * b < height);

    Mat element = Mat::zeros(height, width, CV_8UC1);

    Point center(width / 2, height / 2);
    for(int x = 0 ; x < width ; x++)
        for(int y = 0 ; y < height ; y++)
        {
            if (sqr((x - center.x) * cos(angle) - (y - center.y) * sin(angle)) / sqr(a) + sqr((x - center.x) * sin(angle) - (y - center.y) * cos(angle)) / sqr(b) <= 1)
                element.at<uchar>(y, x) = 1;
        }

    return element;
}

Body:
A pesky typo sneaked in your inequality. The first summand must be

sqr((x - center.x) * cos(angle) + (y - center.y) * sin(angle)) / sqr(a)

Note the plus sign instead of minus.