问:
How to fix such an error in Django url-routing, get_object_or_404and Slug?
How to get exactly the series that is specified in the URL, but the name of all series is the same, and they should be the same, but it takes only the URL of the series itself, that is, it searches only for the URL series, but not how, so that this series was in The series which is specified in the URL and also was in the season exactly the volume that is specified in the URL here is url

Url works fine but I can not go to the right series!

```<code>urlpatterns = [
   url(r'^$', homeview, name='homeview'),
   url(r'^subscribe/$', validate_email, name='subscribe'),   # /series/
   url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'),  # /series/Prison_Break/
   url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'),  # /series/Prison_Break/season_5/
   url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'),  # /series/Prison_Break/season_5/2/

]
</code>```

Models

```<code>class Series(models.Model):
    id                                          = models.AutoField(primary_key=True)
    rus_name                                    = models.CharField(max_length=60)
    eng_name                                    = models.CharField(max_length=60)
    slug                                        = models.SlugField(unique=False)
    serial_of_this_series                       = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
    season_of_this_series                       = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
    number_of_series                            = models.IntegerField(default=0, blank=True, null=True)
    description                                 = models.TextField(max_length=700, blank=True, default=None)
    size_of_torent_file                         = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_360p     = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_720p     = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_1080p    = models.CharField(max_length=60, default=None)
    rating                                      = models.FloatField(default=0, blank=True)
    is_active                                   = models.BooleanField(default=True)
    timestamp_rus                               = models.DateField(auto_now_add=True, auto_now=False)
    updated                                     = models.DateTimeField(auto_now_add=False, auto_now=True)
    timestamp_eng                               = models.CharField(max_length=60)
    time_of_series                              = models.DecimalField(max_digits=10, decimal_places=2, default=42)

    def get_absolute_url(self):
        return reverse('series:post_of_serie', kwargs=
                      {'serial_slug': self.serial_of_this_series.slug,
                       'season_slug': self.season_of_this_series.slug,
                       'series_slug': self.slug})

    def __str__(self):
        return "%s | %s" % (self.rus_name, self.number_of_series)

    class Meta:
        ordering                                = ["-timestamp_rus"]
        verbose_name                            = 'Series'
        verbose_name_plural                     = 'Series'
</code>```

views.py

```<code>def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, serial_of_this_series=serial_slug, season_of_this_series=season_slug, slug=series_slug)
    #series_2                       = Series.objects.filter(serial_of_this_series=serial_slug, season_of_this_series=season_slug, slug=series_slug )
    context                         = {"serie":serie,}
    return render(request, 'series.html', context)
</code>```

Error on the version above

```<code>ValueError at /series/Colony/Season_1/episode_1/

invalid literal for int() with base 10: 'Colony'
</code>```

There was also such an option but there comes an error from such that such a name already exists. In fact the fact that the name of the series and seasons should be the same!

```<code>def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, slug=series_slug)
    context                         = {"serie":serie,}
    return render(request, 'series.html', context)
</code>```

答:
Try editing your views like this,

```<code>def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    context = {"serie":serie,}
    return render(request, 'series.html', context)
</code>```

The serial_of_this_series is a ForeignKey to another table, so when accessing the field, django automatically provides the primary_key of the corresponding table. By looking at your error, it seems that you haven't explicitly specified the slug field as primary_key, then the auto-incrementing integer field which is provided by the django automatically is trying to match with the slug you just provided. I'd recommend to access the corresponding field in the table, like serial_of_this_series__slug, ie, slug field(or whatever the field name is) in Serial table for query filterings.

Body:
How to get exactly the series that is specified in the URL, but the name of all series is the same, and they should be the same, but it takes only the URL of the series itself, that is, it searches only for the URL series, but not how, so that this series was in The series which is specified in the URL and also was in the season exactly the volume that is specified in the URL here is url

Url works fine but I can not go to the right series!

urlpatterns = [
   url(r'^$', homeview, name='homeview'),
   url(r'^subscribe/$', validate_email, name='subscribe'),   # /series/
   url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'),  # /series/Prison_Break/
   url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'),  # /series/Prison_Break/season_5/
   url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'),  # /series/Prison_Break/season_5/2/

]

Models

class Series(models.Model):
    id                                          = models.AutoField(primary_key=True)
    rus_name                                    = models.CharField(max_length=60)
    eng_name                                    = models.CharField(max_length=60)
    slug                                        = models.SlugField(unique=False)
    serial_of_this_series                       = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
    season_of_this_series                       = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
    number_of_series                            = models.IntegerField(default=0, blank=True, null=True)
    description                                 = models.TextField(max_length=700, blank=True, default=None)
    size_of_torent_file                         = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_360p     = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_720p     = models.CharField(max_length=60, default=None)
    link_for_dowloand_serie_in_quality_1080p    = models.CharField(max_length=60, default=None)
    rating                                      = models.FloatField(default=0, blank=True)
    is_active                                   = models.BooleanField(default=True)
    timestamp_rus                               = models.DateField(auto_now_add=True, auto_now=False)
    updated                                     = models.DateTimeField(auto_now_add=False, auto_now=True)
    timestamp_eng                               = models.CharField(max_length=60)
    time_of_series                              = models.DecimalField(max_digits=10, decimal_places=2, default=42)

    def get_absolute_url(self):
        return reverse('series:post_of_serie', kwargs=
                      {'serial_slug': self.serial_of_this_series.slug,
                       'season_slug': self.season_of_this_series.slug,
                       'series_slug': self.slug})

    def __str__(self):
        return "%s | %s" % (self.rus_name, self.number_of_series)

    class Meta:
        ordering                                = ["-timestamp_rus"]
        verbose_name                            = 'Series'
        verbose_name_plural                     = 'Series'

views.py

def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, serial_of_this_series=serial_slug, season_of_this_series=season_slug, slug=series_slug)
    #series_2                       = Series.objects.filter(serial_of_this_series=serial_slug, season_of_this_series=season_slug, slug=series_slug )
    context                         = {"serie":serie,}
    return render(request, 'series.html', context)

Error on the version above

ValueError at /series/Colony/Season_1/episode_1/

invalid literal for int() with base 10: 'Colony'

There was also such an option but there comes an error from such that such a name already exists. In fact the fact that the name of the series and seasons should be the same!

def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, slug=series_slug)
    context                         = {"serie":serie,}
    return render(request, 'series.html', context)

Body:
Try editing your views like this,

def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    context = {"serie":serie,}
    return render(request, 'series.html', context)

The serial_of_this_series is a ForeignKey to another table, so when accessing the field, django automatically provides the primary_key of the corresponding table. By looking at your error, it seems that you haven't explicitly specified the slug field as primary_key, then the auto-incrementing integer field which is provided by the django automatically is trying to match with the slug you just provided. I'd recommend to access the corresponding field in the table, like serial_of_this_series__slug, ie, slug field(or whatever the field name is) in Serial table for query filterings.


来源: stackexchange

问:
Calling A Method With null param
In java we can call a method aMethod(val1 , val2)

with classObject.aMethod(null_if_Val1_NotAvailable,val2)
And inside the Method i will check that if val1 is null
i will initialize that

How to do the same in Kotlin.
I tried but its saying Null Cannot be value of Non-null type

答:
You can use default values:

```<code>fun aMethod(val1: String = "default value", val2: String)
</code>```

You can now use the default method like so:

```<code>classObject.aMethod(val2 = "val2")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Calling A Method With null param

Body:
You can use default values:

fun aMethod(val1: String = "default value", val2: String)

You can now use the default method like so:

classObject.aMethod(val2 = "val2")


答:
Try it this way

```<code>fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello ${name}")
    else
        println("Hi there!")
    // `return Unit` or `return` is optional
}
</code>```

Return type as your wish.

Refrence from kotlin langauge function tutorial

? after the datatype allows you to have null. refer this link

Title: Calling A Method With null param

Body:
In java we can call a method aMethod(val1 , val2)

with classObject.aMethod(null_if_Val1_NotAvailable,val2)
And inside the Method i will check that if val1 is null
i will initialize that

How to do the same in Kotlin.
I tried but its saying Null Cannot be value of Non-null type

Body:
Try it this way

fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello ${name}")
    else
        println("Hi there!")
    // `return Unit` or `return` is optional
}

Return type as your wish.

Refrence from kotlin langauge function tutorial

? after the datatype allows you to have null. refer this link


问:
Python Error: PermissionError: [WinError 5] Access is denied
So I am currently trying to use Tesseract (pytesseract wrapper) in Python 3.5. Now Im at the office so my guess is that there are some goofy permissions not set and thats why I get this error trying to run some pretty simple code. Now I do have admnin permissions on this machine and can change file permissions... any idea what I can do to get this to run?

If anything it will help me wrap my head around system permissions in general as I work with different OS.

```<code>   import pytesseract
from PIL import Image
test = Image.open('test.png')
print (pytesseract.image_to_string(test))

    Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
========= RESTART: C:\Users\dmartin\CheckScanScript\TextFromImage.py =========
Traceback (most recent call last):
  File "C:\Users\dmartin\CheckScanScript\TextFromImage.py", line 4, in <module>
    print (pytesseract.image_to_string(test))
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pytesseract\pytesseract.py", line 161, in image_to_string
    config=config)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pytesseract\pytesseract.py", line 94, in run_tesseract
    stderr=subprocess.PIPE)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access is denied
</code>```

答:
I solved it by give Permission to the file by code:</p>

```<code>import stat
import os

os.chmod("file",stat.S_IRUSR|stat.S_IRGRP|stat.S_IROTH|stat.S_IXUSR|stat.S_IRUSR|stat.S_IWUSR|stat.S_IWGRP|stat.S_IXGRP)
os.remove("file")
</code>```

Body:
So I am currently trying to use Tesseract (pytesseract wrapper) in Python 3.5. Now Im at the office so my guess is that there are some goofy permissions not set and thats why I get this error trying to run some pretty simple code. Now I do have admnin permissions on this machine and can change file permissions... any idea what I can do to get this to run?

If anything it will help me wrap my head around system permissions in general as I work with different OS.

   import pytesseract
from PIL import Image
test = Image.open('test.png')
print (pytesseract.image_to_string(test))

    Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
========= RESTART: C:\Users\dmartin\CheckScanScript\TextFromImage.py =========
Traceback (most recent call last):
  File "C:\Users\dmartin\CheckScanScript\TextFromImage.py", line 4, in <module>
    print (pytesseract.image_to_string(test))
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pytesseract\pytesseract.py", line 161, in image_to_string
    config=config)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pytesseract\pytesseract.py", line 94, in run_tesseract
    stderr=subprocess.PIPE)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
    restore_signals, start_new_session)
  File "C:\Users\dmartin\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child
    startupinfo)
PermissionError: [WinError 5] Access is denied

Body:
I solved it by give Permission to the file by code:

import stat
import os

os.chmod("file",stat.S_IRUSR|stat.S_IRGRP|stat.S_IROTH|stat.S_IXUSR|stat.S_IRUSR|stat.S_IWUSR|stat.S_IWGRP|stat.S_IXGRP)
os.remove("file")


问:
How to get each NSPoint from NSView, subview on NSWindow?
I have mac application, I want to display sheet from particular nspoint, I have multiple views with hierarchy, So, I want selected nspoint on (upper level view i.e. sub view of sun view)view, get it in nswindow & present sheet from that point in objective c. How to achieve this?</p>

答:
I got answer : just in upper sub view or any subview in window
 -> NSPoint point =  [self.window.contentView convertPoint:[NSApp currentEvent].locationInWindow fromView:nil]; get mouse clicked point on view.

Post notification from this subview with value of this point , listen notification in its parent window, get same point value. save it.

& in window - use this point to to present sheet, use - willPositionSheet:this method to change presented sheet's frame.


问:
Java parse string as date "2017-06-12T14:45:00+05:30"
How do I parse this String in Java as date
"2017-06-12T14:45:00+05:30"
I've tried using SimpleDateFormat but it is throwing exception.
Thanks</p>

答:
```<code>DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date date = format.parse(string);
</code>```

date is your solution

Body:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ENGLISH);
Date date = format.parse(string);

date is your solution


答:
Kotlin emphasis on null safety. If you want a property/return type/parameter/local variable to be null, you will have to use nullable types, by appending a question mark to the end of your type.

e.g.

```<code>Foo foo = null // doesn't compile
Foo? foo = null // compiles

fun foo(foo: Foo)
foo(null) // doesn't compile

fun bar(foo: Foo?)
bar(null) // compiles

fun foo(): Foo = null // doesn't compile
fun foo(): Foo? = null // compiles
</code>```

So in order to make your code works, all you need is to specify that function aMethod takes a nullable type:

```<code>fun aMethod(val1: SomeType?, val2) {
    //...
}
</code>```

However, in kotlin, it's not suggested to use null here. We have a better way to deal with your situation. We use default parameters, as suggested by nhaarman.

```<code>fun aMethod(val1: SomeType = someDefaultValue, val2: OtherType) {
    //...
}
aMethod(val2 = OtherType())
</code>```

Title: Calling A Method With null param

Body:
Kotlin emphasis on null safety. If you want a property/return type/parameter/local variable to be null, you will have to use nullable types, by appending a question mark to the end of your type.

e.g.

Foo foo = null // doesn't compile
Foo? foo = null // compiles

fun foo(foo: Foo)
foo(null) // doesn't compile

fun bar(foo: Foo?)
bar(null) // compiles

fun foo(): Foo = null // doesn't compile
fun foo(): Foo? = null // compiles

So in order to make your code works, all you need is to specify that function aMethod takes a nullable type:

fun aMethod(val1: SomeType?, val2) {
    //...
}

However, in kotlin, it's not suggested to use null here. We have a better way to deal with your situation. We use default parameters, as suggested by nhaarman.

fun aMethod(val1: SomeType = someDefaultValue, val2: OtherType) {
    //...
}
aMethod(val2 = OtherType())


答:
It seems to be a valid ISO offset date time format, so this should work without requiring a formatter:

```<code>OffsetDateTime date = OffsetDateTime.parse(input);
</code>```

If you really need a java.util.Date, you can then use:

```<code>Date legacyDate = Date.from(date.toInstant());
</code>```

Title: Java parse string as date "2017-06-12T14:45:00+05:30"

Body:
How do I parse this String in Java as date
"2017-06-12T14:45:00+05:30"
I've tried using SimpleDateFormat but it is throwing exception.
Thanks

Body:
It seems to be a valid ISO offset date time format, so this should work without requiring a formatter:

OffsetDateTime date = OffsetDateTime.parse(input);

If you really need a java.util.Date, you can then use:

Date legacyDate = Date.from(date.toInstant());


问:
Android Keystore KeyPairGeneratorSpec Where do I get X500Principal
I am building a keystore that I will hide my authorization and refresh tokens in. I am on API 19. Looking at the examples for KeyPairGeneratorSpec. Most of the examples use a dummy certificate (X500Principal). I haven't worked much with certificates. I am not sure where I get this "subject." Is this the certificate used in the generation of a signed APK?  IE https://developer.android.com/studio/publish/app-signing.html

Or do I get a certificate from a group like CA?

That said once I have this data, how do I transform it into this X500? How do I map the data to the x500?

The former will be problematic due to the way my company is handling app signing.  I am not sure I will have access to it.

Following

```<code>KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(this)
                        .setAlias(k)
                        .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                        .setSerialNumber(BigInteger.ONE)
                        .setStartDate(start.getTime())
                        .setEndDate(end.getTime())
                        .build();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
</code>```

答:
Signing your .apk for distribution on the Google Play Store and encrypting sensitive user data using the AndroidKeyStore are distinct. The former takes place using the Java Key Store (jks) on your dev machine (i.e. your laptop or desktop computer) while the other takes place on the handset where your app is installed.

You don't need to obtain a certificate authority for the X500Principal. The example code you quoted is correct and you would just substitute it with, for example, your application name and organisation:

```<code>new X500Principal("CN=StarWind, O=StarWindOrganization");
</code>```

If you want to understand what the different abbreviations mean, please refer to the Wikipedia entry for Lightweight Directory Access Protocol but just for instance, "CN" means "common name" and "O" means organisation. The attributes you supply here are merely to form a unique entry much in the same way you form a unique package name in Java like com.starwind.myapp.

If you are finding it confusing you can have a look at Scytale which is a wrapper around the Android KeyStore. Even if you don't end up using the library, the code there is quite useful for working out how to use the KeyStore.

Body:
I am building a keystore that I will hide my authorization and refresh tokens in. I am on API 19. Looking at the examples for KeyPairGeneratorSpec. Most of the examples use a dummy certificate (X500Principal). I haven't worked much with certificates. I am not sure where I get this "subject." Is this the certificate used in the generation of a signed APK?  IE https://developer.android.com/studio/publish/app-signing.html

Or do I get a certificate from a group like CA?

That said once I have this data, how do I transform it into this X500? How do I map the data to the x500?

The former will be problematic due to the way my company is handling app signing.  I am not sure I will have access to it.

Following

KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(this)
                        .setAlias(k)
                        .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                        .setSerialNumber(BigInteger.ONE)
                        .setStartDate(start.getTime())
                        .setEndDate(end.getTime())
                        .build();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

Body:
Signing your .apk for distribution on the Google Play Store and encrypting sensitive user data using the AndroidKeyStore are distinct. The former takes place using the Java Key Store (jks) on your dev machine (i.e. your laptop or desktop computer) while the other takes place on the handset where your app is installed.

You don't need to obtain a certificate authority for the X500Principal. The example code you quoted is correct and you would just substitute it with, for example, your application name and organisation:

new X500Principal("CN=StarWind, O=StarWindOrganization");

If you want to understand what the different abbreviations mean, please refer to the Wikipedia entry for Lightweight Directory Access Protocol but just for instance, "CN" means "common name" and "O" means organisation. The attributes you supply here are merely to form a unique entry much in the same way you form a unique package name in Java like com.starwind.myapp.

If you are finding it confusing you can have a look at Scytale which is a wrapper around the Android KeyStore. Even if you don't end up using the library, the code there is quite useful for working out how to use the KeyStore.


问:
Which windows vm allowed to upload to azure?
In Azure, I can upload VM from my local vhd. I find Linux VM List, but I can't find the Windows list.</p>

答:
I can't find the list too.

As far as I know, we can upload those windows version to Azure:

```<code>Server:
Windows server 2003
Windows server 2003 R2
Windows server 2008
Windows server 2008 R2
Windows server 2012
Windows server 2012 R2
Windows server 2016
Client:
Windows 7
Windows 8.1
Windows 10
</code>```

Windows Server

Windows Server 2003 and later versions are supported for deployment in
  Microsoft Azure.

Client

Certain versions of Windows 7, Windows 8.1, and Windows 10 are
  available to MSDN Azure

More information please refer to this link.

Body:
I can't find the list too.

As far as I know, we can upload those windows version to Azure:

Server:
Windows server 2003
Windows server 2003 R2
Windows server 2008
Windows server 2008 R2
Windows server 2012
Windows server 2012 R2
Windows server 2016
Client:
Windows 7
Windows 8.1
Windows 10

Windows Server

Windows Server 2003 and later versions are supported for deployment in
  Microsoft Azure.

Client

Certain versions of Windows 7, Windows 8.1, and Windows 10 are
  available to MSDN Azure

More information please refer to this link.


问:
Good books on Silverlight and WCF
Can anyone suggest some good books that practically describe Silverlight and WCF?</p>

答:
Wcf stuff:

Good and easy books/tutorials to learn WCF latest stuff

ContentLicense: CC BY-SA 2.5

Title: Good books on Silverlight and WCF


问:
How would I use enum on my project?
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

```<code>public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3
</code>```

}

答:
@eldix_ you can use enums when you know that some of the Constant data in your code can't be changed by the user.
For example.
if you want to show some data in a drop down on the screen like below

as shown in the example, where the drop down values are constants, which client has to select.

we can change this at one place use it any where, without data being changed.

Title: How would I use enum on my project?

Body:
I have a class with an instance field lockAction, value 1 is lock and 3 is unlock. I'd like to introduce enum on to my EJB project. How do I got about that?

public enum lockUnlock {
    LOCK, //1
    UNLOCK, //3

}


问:
Yii2 - Integrity constraint violation – yii\db\IntegrityException
I have a rather weired error on trying to add data to my database. It keeps telling me that there is an Integrity violation, i.e.

```<code>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ticketing_system`.`parcels`, CONSTRAINT `FK_parcels_customers_customer_id` FOREIGN KEY (`sender_id`) REFERENCES `customers` (`customer_id`))
The SQL being executed was: INSERT INTO `parcels` (`parcel_id`) VALUES (DEFAULT)
</code>```

I have checked the values being inserted and all of them are picked from the referenced table. Funny bit is that when I echo the values and use them to update the database directly via SQL query on the PHPMyAdmin, the database is populated well without any problem. Again, when I try to change the order of the foreign keys as they appear on the SQL query being performed, the first one fails, meaning all the foreign keys of the model are failing.

EDITED

Here is my actionCreate in the ParcelsController

```<code>public function actionCreate()
{
    $model = new Parcels();
    $customerModel = new Customers();

    //checking whether we are getting the logged in user id value
    Yii::info("User id=".Yii::$app->user->id);

    $model->received_by_id = Yii::$app->user->id;

    if (Yii::$app->request->post()) {

        $data = Yii::$app->request->post('Customers');

        $sender_id = Customers::create([
            'name' => $data['name'],
            'mobile_number' => $data['mobile_number'],
            'sex' => $data['sex'],
            'address' => $data['address'],
            'registered_by_id' => $model->received_by_id,
        ]);

        $data = Yii::$app->request->post('Parcels');

        $receiver_id = Customers::create([
            'name' => $data['name'],
            'mobile_number' => $data['mobile_number'],
            'sex' => $data['sex'],
            'address' => $data['address'],
            'registered_by_id' => $model->received_by_id,
        ]);

        $model->consignment_number = $model->generateUniqueRandomString("consignment_number");
        $model->source_id = $model->receivedBy->station_id;

        $model->parcel_id = Parcels::create([
            'consignment_number' => $model->consignment_number,
            'sender_id' => $sender_id,
            'receiver_id' => $receiver_id,
            'source_id' => $model->source_id,
            'destination_id' => $data['destination_id'],
            'type_id' => $data['type_id'],
            'weight' => $data['weight'],
            'cost' => $data['cost'],
            'parcel_info' => $data['parcel_info'],
            'received_by_id' => $model->received_by_id,
        ]);

        // return $this->redirect(['view', 'id' => $model->parcel_id]);
    } else {
        return $this->render('create', [
            'model' => $model, 'customerModel' => $customerModel,
        ]);
    }
}
</code>```

Customers::create function in the Customers Model

```<code>public static function create($data)
{

    $model = new self;

    $mobile_number = $data['mobile_number'];

    $exists = $model->find()->where( [ 'mobile_number' => $mobile_number ] )->exists();

    if($exists) {
        $existing_customer = Customers::find()
            ->where('mobile_number = :mobile_number', [':mobile_number' => $mobile_number])
            ->one();
        return $existing_customer['customer_id'];
    }
    else {
        $model->name = $data['name'];
        $model->registered_by_id = $data['registered_by_id'];
        $model->mobile_number = $data['mobile_number'];
        $model->sex = $data['sex'];
        $model->address = $data['address'];
        $model->status = 10;
        $model->save();
        return $model->getPrimaryKey();
    }

}
</code>```

Parcels::create function in the Parcels Model

```<code>public static function create($data)
{
    $model = new self;

    $consignment_number = $data['consignment_number'];
    $receiver_id = $data['receiver_id'];
    $sender_id = $data['sender_id'];
    $source_id = $data['source_id'];
    $destination_id = $data['destination_id'];
    $type_id = $data['type_id'];
    $weight = $data['weight'];
    $cost = $data['cost'];
    $parcel_info = $data['parcel_info'];
    $received_by_id = $data['received_by_id'];

    $model->save(false);
    return $model->getPrimaryKey();

    // echo var_dump($data);
    // echo "Consignment Number: ".$consignment_number." - Sender: ".$sender_id." - Receiver: ".$receiver_id." - From: ".$source_id." - To: ".$destination_id." - Type: ".$type_id." - Weight: ".$weight." - Cost: ".$cost." - Parcel Info: ".$parcel_info." - Received By: ".$received_by_id;
}
</code>```

And here is the function generateUniqueRandomString() in the Parcels Model

```<code>public function generateUniqueRandomString($attribute, $length = 10) {

    $randomString = Yii::$app->getSecurity()->generateRandomString($length);

    $randomString = strtoupper($randomString);

    if(!$this->findOne([$attribute => $randomString]))
        return $randomString;
    else
        return $this->generateUniqueRandomString($attribute, $length);

}
</code>```

答:
Sorry for bothering you guys. I was able to get the problem of where I was going wrong. In the create() function of the Parcels Model, I only created new variables and failed to bind them to the model, i.e.

```<code>$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];
</code>```

Should have been:

```<code>$model->consignment_number = $data['consignment_number'];
$model->weight = $data['weight'];
$model->cost = $data['cost'];
$model->parcel_info = $data['parcel_info'];
$model->received_by_id = $data['received_by_id'];
$model->status = $data['status'];
$model->receiver_id = $data['receiver_id'];
$model->sender_id = $data['sender_id'];
$model->source_id = $data['source_id'];
$model->destination_id = $data['destination_id'];
$model->type_id = $data['type_id'];
</code>```

Sorry for taking your time because of my carelessness.

Body:
I have a rather weired error on trying to add data to my database. It keeps telling me that there is an Integrity violation, i.e.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ticketing_system`.`parcels`, CONSTRAINT `FK_parcels_customers_customer_id` FOREIGN KEY (`sender_id`) REFERENCES `customers` (`customer_id`))
The SQL being executed was: INSERT INTO `parcels` (`parcel_id`) VALUES (DEFAULT)

I have checked the values being inserted and all of them are picked from the referenced table. Funny bit is that when I echo the values and use them to update the database directly via SQL query on the PHPMyAdmin, the database is populated well without any problem. Again, when I try to change the order of the foreign keys as they appear on the SQL query being performed, the first one fails, meaning all the foreign keys of the model are failing.

EDITED

Here is my actionCreate in the ParcelsController

public function actionCreate()
{
    $model = new Parcels();
    $customerModel = new Customers();

    //checking whether we are getting the logged in user id value
    Yii::info("User id=".Yii::$app->user->id);

    $model->received_by_id = Yii::$app->user->id;

    if (Yii::$app->request->post()) {

        $data = Yii::$app->request->post('Customers');

        $sender_id = Customers::create([
            'name' => $data['name'],
            'mobile_number' => $data['mobile_number'],
            'sex' => $data['sex'],
            'address' => $data['address'],
            'registered_by_id' => $model->received_by_id,
        ]);

        $data = Yii::$app->request->post('Parcels');

        $receiver_id = Customers::create([
            'name' => $data['name'],
            'mobile_number' => $data['mobile_number'],
            'sex' => $data['sex'],
            'address' => $data['address'],
            'registered_by_id' => $model->received_by_id,
        ]);

        $model->consignment_number = $model->generateUniqueRandomString("consignment_number");
        $model->source_id = $model->receivedBy->station_id;

        $model->parcel_id = Parcels::create([
            'consignment_number' => $model->consignment_number,
            'sender_id' => $sender_id,
            'receiver_id' => $receiver_id,
            'source_id' => $model->source_id,
            'destination_id' => $data['destination_id'],
            'type_id' => $data['type_id'],
            'weight' => $data['weight'],
            'cost' => $data['cost'],
            'parcel_info' => $data['parcel_info'],
            'received_by_id' => $model->received_by_id,
        ]);

        // return $this->redirect(['view', 'id' => $model->parcel_id]);
    } else {
        return $this->render('create', [
            'model' => $model, 'customerModel' => $customerModel,
        ]);
    }
}

Customers::create function in the Customers Model

public static function create($data)
{

    $model = new self;

    $mobile_number = $data['mobile_number'];

    $exists = $model->find()->where( [ 'mobile_number' => $mobile_number ] )->exists();

    if($exists) {
        $existing_customer = Customers::find()
            ->where('mobile_number = :mobile_number', [':mobile_number' => $mobile_number])
            ->one();
        return $existing_customer['customer_id'];
    }
    else {
        $model->name = $data['name'];
        $model->registered_by_id = $data['registered_by_id'];
        $model->mobile_number = $data['mobile_number'];
        $model->sex = $data['sex'];
        $model->address = $data['address'];
        $model->status = 10;
        $model->save();
        return $model->getPrimaryKey();
    }

}

Parcels::create function in the Parcels Model

public static function create($data)
{
    $model = new self;

    $consignment_number = $data['consignment_number'];
    $receiver_id = $data['receiver_id'];
    $sender_id = $data['sender_id'];
    $source_id = $data['source_id'];
    $destination_id = $data['destination_id'];
    $type_id = $data['type_id'];
    $weight = $data['weight'];
    $cost = $data['cost'];
    $parcel_info = $data['parcel_info'];
    $received_by_id = $data['received_by_id'];

    $model->save(false);
    return $model->getPrimaryKey();

    // echo var_dump($data);
    // echo "Consignment Number: ".$consignment_number." - Sender: ".$sender_id." - Receiver: ".$receiver_id." - From: ".$source_id." - To: ".$destination_id." - Type: ".$type_id." - Weight: ".$weight." - Cost: ".$cost." - Parcel Info: ".$parcel_info." - Received By: ".$received_by_id;
}

And here is the function generateUniqueRandomString() in the Parcels Model

public function generateUniqueRandomString($attribute, $length = 10) {

    $randomString = Yii::$app->getSecurity()->generateRandomString($length);

    $randomString = strtoupper($randomString);

    if(!$this->findOne([$attribute => $randomString]))
        return $randomString;
    else
        return $this->generateUniqueRandomString($attribute, $length);

}

Body:
Sorry for bothering you guys. I was able to get the problem of where I was going wrong. In the create() function of the Parcels Model, I only created new variables and failed to bind them to the model, i.e.

$consignment_number = $data['consignment_number'];
$receiver_id = $data['receiver_id'];
$sender_id = $data['sender_id'];
$source_id = $data['source_id'];
$destination_id = $data['destination_id'];
$type_id = $data['type_id'];
$weight = $data['weight'];
$cost = $data['cost'];
$parcel_info = $data['parcel_info'];
$received_by_id = $data['received_by_id'];

Should have been:

$model->consignment_number = $data['consignment_number'];
$model->weight = $data['weight'];
$model->cost = $data['cost'];
$model->parcel_info = $data['parcel_info'];
$model->received_by_id = $data['received_by_id'];
$model->status = $data['status'];
$model->receiver_id = $data['receiver_id'];
$model->sender_id = $data['sender_id'];
$model->source_id = $data['source_id'];
$model->destination_id = $data['destination_id'];
$model->type_id = $data['type_id'];

Sorry for taking your time because of my carelessness.


问:
Odd Newline Behaviour in c# WPF
I am migrating from Windows Forms in VB to WPF C# and I wrote the following code....

```<code>namespace TestWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            OutputBox.Document.Blocks.Clear();
        }

        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            OutputBox.AppendText(String.Format("You clicked the button.{0}",Environment.NewLine));
        }
    }
}
</code>```

Where OutputBox is a RichTextBox.

Upon running the program and clicking the button a few times I get output like the following....

```<code>You clicked the button.You clicked the button.

You clicked the button.

You clicked the button.
</code>```

Why does the 1st newline not appear, and then it inserts blank lines rather than just moving on to the next line.

If I change the code to

```<code>.AppendText(String.format("You clicked the button.{0}OK{0}",environment.NewLine
</code>```

I get output

```<code>You clicked the button.

OKYou clicked the button.

OK

You clicked the button.

OK
</code>```

What should my code be like to get output....

```<code>You clicked the button.
You clicked the button.
You clicked the button.
</code>```

答: Instead of Environment.NewLine use "\r". Although I can't find any link now, I think there's a bug in how RichTextBox handles Environment.NewLine

Title: Odd Newline Behaviour in c# WPF

Body:
I am migrating from Windows Forms in VB to WPF C# and I wrote the following code....

namespace TestWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            OutputBox.Document.Blocks.Clear();
        }

        private void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            OutputBox.AppendText(String.Format("You clicked the button.{0}",Environment.NewLine));
        }
    }
}

Where OutputBox is a RichTextBox.

Upon running the program and clicking the button a few times I get output like the following....

You clicked the button.You clicked the button.

You clicked the button.

You clicked the button.

Why does the 1st newline not appear, and then it inserts blank lines rather than just moving on to the next line.

If I change the code to

.AppendText(String.format("You clicked the button.{0}OK{0}",environment.NewLine

I get output

You clicked the button.

OKYou clicked the button.

OK

You clicked the button.

OK

What should my code be like to get output....

You clicked the button.
You clicked the button.
You clicked the button.


问:
How to create Custom WPA Hotspot with ssid and password in android?
I am using the following code for creating the Wifi-hotspot configuration.
I am able to create the Hotspot configuration and able to  enable it. but i have give configuration for WPA-PSK, But it always taken as OPEN network.

```<code>public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();

    for(Method mMethod: mMethods){

        if(mMethod.getName().equals("setWifiApEnabled")) {
            WifiConfiguration netConfig = new WifiConfiguration();
             netConfig.SSID = SSID ;
                netConfig.preSharedKey = passWord;
                netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            try {
                mMethod.invoke(mWifiManager, netConfig,true);
                mWifiManager.saveConfiguration();
                return true;

            } catch (Exception e) {
                e.printStackTrace();
                CommonUtil.log(TAG,"Exception : "+e.getLocalizedMessage());
            }
        }
    }
return false;
</code>```

}

After run this app the Hotspot got enabled. Please check the image below.

How to set the WPA_PSK wifi configuration in android app?

As per below answer i have modified the code below.

```<code>public boolean setHotSpot(String SSID, String passWord) {
    boolean apstatus;
    WifiConfiguration netConfig = new WifiConfiguration();
    if (passWord == "") {
        netConfig.SSID = SSID;
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    } else {
        netConfig.SSID = SSID;
        netConfig.preSharedKey = passWord;
                /*netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);*/
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    }

    try {
        Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
        //Thread.sleep(2000);
        apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, netConfig, true);
    } catch (Exception e) {
        CommonUtil.log(TAG, e.getMessage());
        return false;
    }
    return apstatus;
}
</code>```

答:
sollution </p>

```<code>/**
 * Uppsala University
 *
 * Project CS course, Fall 2012
 *
 * Projekt DV/Project CS, is a course in which the students develop software for
 * distributed systems. The aim of the course is to give insights into how a big
 * project is run (from planning to realization), how to construct a complex
 * distributed system and to give hands-on experience on modern construction
 * principles and programming methods.
 *
 * All rights reserved.
 *
 * Copyright (C) 2012 LISA team
 */
package project.cs.lisa.networksettings;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiHandler {
    //constants
    public static final int WEP = 1;
    public static final int WAP = 2;
    public static final int OPEN_NETWORK = 3;

    public static final String TAG = "LISA_Network";

    /** dfsdfsdfsdf. */
    WifiConfiguration wifiConf;             /* WifiConfiguration object */

    /** dfsdfsdfsdf. */
    WifiManager wifiMgr;                            /* WifiManager object */

    /** dfsdfsdfsdf. */
    WifiInfo wifiInfo;                              /* WifiInfo object */

    /** dfsdfsdfsdf. */
    List<ScanResult> wifiScan;              /* List of ScanResult objects */

    /**
     * Constructor initializes WifiManager and WifiInfo.
     * @param context
     */
    public WifiHandler(Context context) {
        wifiMgr  = getWifiManager(context);     // gets wifiMgr in the current context
        wifiInfo = getWifiInfo(context);            // gets wifiInfo in the current context
        wifiConf = getWifiConf(context);            // gets wifiConf in the current context
        wifiScan = getWifiInRange();                    // gets wifiScan in the current context
    }

    /**
     * Function checkWifiEnabled checks if the WiFi connection
     * is enabled on the device.
     * @param wifiMgr
     * @return true  if the WiFi connection is enabled,
     *               false if the WiFi connection is disabled
     */
    public boolean checkWifiEnabled() {
        // checks if WiFi is enabled
        return (wifiMgr != null && wifiMgr.isWifiEnabled());
    }

    /**
     * Function enableWifi enables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if the attempt to enable WiFi succeeded,
     *               false if the attempt to enable WiFi failed.
     */
    public boolean enableWifi() {
        // enables WiFi connection
        return wifiMgr.setWifiEnabled(true);
    }

    /**
     * Function disableWifi disables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if WiFi connection was disabled,
     *               false if attempt to disable WiFi failed.
     */
    public boolean disableWifi() {
        // disables WiFi connection
        return wifiMgr.setWifiEnabled(false);
    }

    /**
     * Function getWifiManager gets the WiFiManager object from the device.
     * @param context
     * @return WifiManager object. Also sets the class variable
     *               wifiMgr as the WifiManager object returned.
     */
    public WifiManager getWifiManager(Context context) {
        WifiManager wifiMgr = null;

        // gets WifiManager obj from the system
        wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiMgr == null) {
            Log.d("TAG", "WIFI_SERVICE is the wrong service name.");
        }

        return wifiMgr;
    }

    /**
     * Function getWifiInfo gets the current WiFi connection information in a
     * WifiInfo object from the device.
     * @param context
     * @return wifiInfo created object or
     *               null       if wifi is not enabled.
     */
    public WifiInfo getWifiInfo(Context context) {
        WifiInfo wifiInfo = null;

        // gets WiFi network info of the current connection
        if (checkWifiEnabled()) {
            wifiInfo = (WifiInfo) wifiMgr.getConnectionInfo();
        }

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty.");
        }

        return wifiInfo;
    }

    /**
     * Function that returns a WifiConfiguration object from the WifiInfo
     * object from the class. If wifiInfo exists, then we are able to retrieve
     * information from the current connection
     * @param context
     * @return WifiConfiguration object created.
     */
    public WifiConfiguration getWifiConf(Context context) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty");
            return null;
        }

        wifiConfiguration.SSID = wifiInfo.getSSID();
        wifiConfiguration.networkId = wifiInfo.getNetworkId();

        return wifiConfiguration;
    }

    /**
     * Creates a new WifiConfiguration object for wifiConf.
     */
    public void clearWifiConfig() {
        wifiConf = new WifiConfiguration();
    }

    /**
     * Function getWifiInRange returns all the WiFi networks that are
     * accessible through the access point (device AP) found during the
     * last scan.
     * @param wifi
     * @return List of ScanResult containing information on all WiFi networks
     *               discovered in the range.
     */
    public List<ScanResult> getWifiInRange() {
        // gets ~last~ list of WiFi networks accessible through the access point.
        return (wifiScan = (List<ScanResult>) wifiMgr.getScanResults());
    }

    /**
     * Function that scans for wifi networks available in the devices range.
     * @return true  if scan started
     *               false if scan could not be started
     */
    public boolean scanWifiInRange() {
        if (!checkWifiEnabled()) {
            return false;
        }

        if (!wifiMgr.startScan()) {
            Log.d("TAG", "Failed to scan wifi's in range.");
            return false;
        }

        return true;
    }

    /**
     * Function to disconnect from the currently connected WiFi AP.
     * @return true  if disconnection succeeded
     *               false if disconnection failed
     */
    public boolean disconnectFromWifi() {
        return (wifiMgr.disconnect());
    }

    /**
     * Function to connect to a selected network
     * @param networkSSID         network SSID name
     * @param   networkPassword     network password
     * @param networkId           network ID from WifiManager
     * @param SecurityProtocol    network security protocol
     * @return true  if connection to selected network succeeded
     *               false if connection to selected network failed
     */
    public boolean connectToSelectedNetwork(String networkSSID, String networkPassword) {
        int networkId;
        int SecurityProtocol = WEP;

        // Clear wifi configuration variable
        clearWifiConfig();

        // Sets network SSID name on wifiConf
        wifiConf.SSID = "\"" + networkSSID + "\"";
        Log.d(TAG, "SSID Received: " + wifiConf.SSID);
        switch(SecurityProtocol) {
            // WEP "security".
            case WEP:
                wifiConf.wepKeys[0] = "\"" + networkPassword + "\"";
                wifiConf.wepTxKeyIndex = 0;
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;

                // WAP security. We have to set preSharedKey.
            case WAP:
                wifiConf.preSharedKey = "\""+ networkPassword +"\"";
                break;

                // Network without security.
            case OPEN_NETWORK:
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }

        // Add WiFi configuration to list of recognizable networks
        if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
            Log.d("TAG", "Failed to add network configuration!");
            return false;
        }

        // Disconnect from current WiFi connection
        if (!disconnectFromWifi()) {
            Log.d("TAG", "Failed to disconnect from network!");
            return false;
        }

        // Enable network to be connected
        if (!wifiMgr.enableNetwork(networkId, true)) {
            Log.d("TAG", "Failed to enable network!");
            return false;
        }

        // Connect to network
        if (!wifiMgr.reconnect()) {
            Log.d("TAG", "Failed to connect!");
            return false;
        }

        return true;
    }
}
</code>```

Body:
I am using the following code for creating the Wifi-hotspot configuration.
I am able to create the Hotspot configuration and able to  enable it. but i have give configuration for WPA-PSK, But it always taken as OPEN network.

public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();

    for(Method mMethod: mMethods){

        if(mMethod.getName().equals("setWifiApEnabled")) {
            WifiConfiguration netConfig = new WifiConfiguration();
             netConfig.SSID = SSID ;
                netConfig.preSharedKey = passWord;
                netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

            try {
                mMethod.invoke(mWifiManager, netConfig,true);
                mWifiManager.saveConfiguration();
                return true;

            } catch (Exception e) {
                e.printStackTrace();
                CommonUtil.log(TAG,"Exception : "+e.getLocalizedMessage());
            }
        }
    }
return false;

}

After run this app the Hotspot got enabled. Please check the image below.

How to set the WPA_PSK wifi configuration in android app?

As per below answer i have modified the code below.

public boolean setHotSpot(String SSID, String passWord) {
    boolean apstatus;
    WifiConfiguration netConfig = new WifiConfiguration();
    if (passWord == "") {
        netConfig.SSID = SSID;
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    } else {
        netConfig.SSID = SSID;
        netConfig.preSharedKey = passWord;
                /*netConfig.hiddenSSID = true;
                netConfig.status = WifiConfiguration.Status.ENABLED;
                netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                netConfig.allowedKeyManagement.set(4);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
                netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);*/
        netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
        netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    }

    try {
        Method setWifiApMethod = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        //setWifiApMethod.invoke(mWifiManager, previousConfigurations, false);
        //Thread.sleep(2000);
        apstatus = (Boolean) setWifiApMethod.invoke(mWifiManager, netConfig, true);
    } catch (Exception e) {
        CommonUtil.log(TAG, e.getMessage());
        return false;
    }
    return apstatus;
}

Body:
sollution

/**
 * Uppsala University
 *
 * Project CS course, Fall 2012
 *
 * Projekt DV/Project CS, is a course in which the students develop software for
 * distributed systems. The aim of the course is to give insights into how a big
 * project is run (from planning to realization), how to construct a complex
 * distributed system and to give hands-on experience on modern construction
 * principles and programming methods.
 *
 * All rights reserved.
 *
 * Copyright (C) 2012 LISA team
 */
package project.cs.lisa.networksettings;

import java.util.List;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiHandler {
    //constants
    public static final int WEP = 1;
    public static final int WAP = 2;
    public static final int OPEN_NETWORK = 3;

    public static final String TAG = "LISA_Network";

    /** dfsdfsdfsdf. */
    WifiConfiguration wifiConf;             /* WifiConfiguration object */

    /** dfsdfsdfsdf. */
    WifiManager wifiMgr;                            /* WifiManager object */

    /** dfsdfsdfsdf. */
    WifiInfo wifiInfo;                              /* WifiInfo object */

    /** dfsdfsdfsdf. */
    List<ScanResult> wifiScan;              /* List of ScanResult objects */

    /**
     * Constructor initializes WifiManager and WifiInfo.
     * @param context
     */
    public WifiHandler(Context context) {
        wifiMgr  = getWifiManager(context);     // gets wifiMgr in the current context
        wifiInfo = getWifiInfo(context);            // gets wifiInfo in the current context
        wifiConf = getWifiConf(context);            // gets wifiConf in the current context
        wifiScan = getWifiInRange();                    // gets wifiScan in the current context
    }

    /**
     * Function checkWifiEnabled checks if the WiFi connection
     * is enabled on the device.
     * @param wifiMgr
     * @return true  if the WiFi connection is enabled,
     *               false if the WiFi connection is disabled
     */
    public boolean checkWifiEnabled() {
        // checks if WiFi is enabled
        return (wifiMgr != null && wifiMgr.isWifiEnabled());
    }

    /**
     * Function enableWifi enables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if the attempt to enable WiFi succeeded,
     *               false if the attempt to enable WiFi failed.
     */
    public boolean enableWifi() {
        // enables WiFi connection
        return wifiMgr.setWifiEnabled(true);
    }

    /**
     * Function disableWifi disables WiFi connection on the device.
     * @param wifiMgr
     * @return true  if WiFi connection was disabled,
     *               false if attempt to disable WiFi failed.
     */
    public boolean disableWifi() {
        // disables WiFi connection
        return wifiMgr.setWifiEnabled(false);
    }

    /**
     * Function getWifiManager gets the WiFiManager object from the device.
     * @param context
     * @return WifiManager object. Also sets the class variable
     *               wifiMgr as the WifiManager object returned.
     */
    public WifiManager getWifiManager(Context context) {
        WifiManager wifiMgr = null;

        // gets WifiManager obj from the system
        wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiMgr == null) {
            Log.d("TAG", "WIFI_SERVICE is the wrong service name.");
        }

        return wifiMgr;
    }

    /**
     * Function getWifiInfo gets the current WiFi connection information in a
     * WifiInfo object from the device.
     * @param context
     * @return wifiInfo created object or
     *               null       if wifi is not enabled.
     */
    public WifiInfo getWifiInfo(Context context) {
        WifiInfo wifiInfo = null;

        // gets WiFi network info of the current connection
        if (checkWifiEnabled()) {
            wifiInfo = (WifiInfo) wifiMgr.getConnectionInfo();
        }

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty.");
        }

        return wifiInfo;
    }

    /**
     * Function that returns a WifiConfiguration object from the WifiInfo
     * object from the class. If wifiInfo exists, then we are able to retrieve
     * information from the current connection
     * @param context
     * @return WifiConfiguration object created.
     */
    public WifiConfiguration getWifiConf(Context context) {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();

        if (wifiInfo == null) {
            Log.d("TAG", "WifiInfo object is empty");
            return null;
        }

        wifiConfiguration.SSID = wifiInfo.getSSID();
        wifiConfiguration.networkId = wifiInfo.getNetworkId();

        return wifiConfiguration;
    }

    /**
     * Creates a new WifiConfiguration object for wifiConf.
     */
    public void clearWifiConfig() {
        wifiConf = new WifiConfiguration();
    }

    /**
     * Function getWifiInRange returns all the WiFi networks that are
     * accessible through the access point (device AP) found during the
     * last scan.
     * @param wifi
     * @return List of ScanResult containing information on all WiFi networks
     *               discovered in the range.
     */
    public List<ScanResult> getWifiInRange() {
        // gets ~last~ list of WiFi networks accessible through the access point.
        return (wifiScan = (List<ScanResult>) wifiMgr.getScanResults());
    }

    /**
     * Function that scans for wifi networks available in the devices range.
     * @return true  if scan started
     *               false if scan could not be started
     */
    public boolean scanWifiInRange() {
        if (!checkWifiEnabled()) {
            return false;
        }

        if (!wifiMgr.startScan()) {
            Log.d("TAG", "Failed to scan wifi's in range.");
            return false;
        }

        return true;
    }

    /**
     * Function to disconnect from the currently connected WiFi AP.
     * @return true  if disconnection succeeded
     *               false if disconnection failed
     */
    public boolean disconnectFromWifi() {
        return (wifiMgr.disconnect());
    }

    /**
     * Function to connect to a selected network
     * @param networkSSID         network SSID name
     * @param   networkPassword     network password
     * @param networkId           network ID from WifiManager
     * @param SecurityProtocol    network security protocol
     * @return true  if connection to selected network succeeded
     *               false if connection to selected network failed
     */
    public boolean connectToSelectedNetwork(String networkSSID, String networkPassword) {
        int networkId;
        int SecurityProtocol = WEP;

        // Clear wifi configuration variable
        clearWifiConfig();

        // Sets network SSID name on wifiConf
        wifiConf.SSID = "\"" + networkSSID + "\"";
        Log.d(TAG, "SSID Received: " + wifiConf.SSID);
        switch(SecurityProtocol) {
            // WEP "security".
            case WEP:
                wifiConf.wepKeys[0] = "\"" + networkPassword + "\"";
                wifiConf.wepTxKeyIndex = 0;
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                wifiConf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                break;

                // WAP security. We have to set preSharedKey.
            case WAP:
                wifiConf.preSharedKey = "\""+ networkPassword +"\"";
                break;

                // Network without security.
            case OPEN_NETWORK:
                wifiConf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                break;
        }

        // Add WiFi configuration to list of recognizable networks
        if ((networkId = wifiMgr.addNetwork(wifiConf)) == -1) {
            Log.d("TAG", "Failed to add network configuration!");
            return false;
        }

        // Disconnect from current WiFi connection
        if (!disconnectFromWifi()) {
            Log.d("TAG", "Failed to disconnect from network!");
            return false;
        }

        // Enable network to be connected
        if (!wifiMgr.enableNetwork(networkId, true)) {
            Log.d("TAG", "Failed to enable network!");
            return false;
        }

        // Connect to network
        if (!wifiMgr.reconnect()) {
            Log.d("TAG", "Failed to connect!");
            return false;
        }

        return true;
    }
}


问:
RDB and RDF mapping - how to?
I have 3 Relational DBs, I would like to map a graph database so we can manage ontologies and query across them, the databases must remain as RDBs and the RDF mapping should allow querying via SPARQL. While I understand the theory I'm struggling to find a walk through guide, and help appreciated. </p>

答: I think what you are looking for is R2RML.</p>

Title: RDB and RDF mapping - how to?


问:
p-dialog onHide not working in angular 2 component - primeng
I'm using primeng in an angular 2 application and facing this issue (stackoverflow question)

Although the plunkr provided in the accepted answer works but it doesn't in my scenario. I have a separate component that loads the  based on an input from the parent component. I want to toggle the visibility flag when the child component is closed/hidden.

Here's the code snippet

```<code> <p-dialog header="Assets Management" [(visible)]="showDialog" modal="modal" [closable]="true" (onHide)="close()" appendTo="body">
          .. some content ..
  </p-dialog>
</code>```

In component, I have:

```<code>@Component({
    selector: 'view-car-colors',
    templateUrl: '/view-car-colors.html',
    inputs: ['showDialog'],
    outputs: ["onCloseDialog"],
})
export class ViewCarColorsComponent {
    private showDialog: boolean = false;    //default close
    private onCloseDialog: EventEmitter<any> = new EventEmitter();

    public close(): void {
        this.showDialog = false;
        //emit this to its parent
        this.onCloseDialog.emit({ hasChanges: true });
    }
}
</code>```

And finally in my parent component, I am calling it like:

```<code><view-car-colors [showDialog]="showCarColorsDialog" (onCloseDialog)="onCarColorsCloseDialog($event)"></view-car-colors>
</code>```

Where showCarColorsDialog is changed based on a button click.

```<code>private onCarColorsCloseDialog($event: any): void {
    this.showCarColorsDialog = false;
    if ($event.hasChanges) {
        //fetch the changes again
        this.getCarColors();
    }
}
</code>```

I have used the primeng controls on multiple places and they all work fine but just has this issue so I'm sure it can't be because of the version.

答:
try (onAfterHide)="close()".

https://github.com/primefaces/primeng/issues/956

Body:
I'm using primeng in an angular 2 application and facing this issue (stackoverflow question)

Although the plunkr provided in the accepted answer works but it doesn't in my scenario. I have a separate component that loads the  based on an input from the parent component. I want to toggle the visibility flag when the child component is closed/hidden.

Here's the code snippet

          .. some content ..

In component, I have:

@Component({
    selector: 'view-car-colors',
    templateUrl: '/view-car-colors.html',
    inputs: ['showDialog'],
    outputs: ["onCloseDialog"],
})
export class ViewCarColorsComponent {
    private showDialog: boolean = false;    //default close
    private onCloseDialog: EventEmitter<any> = new EventEmitter();

    public close(): void {
        this.showDialog = false;
        //emit this to its parent
        this.onCloseDialog.emit({ hasChanges: true });
    }
}

And finally in my parent component, I am calling it like:

<view-car-colors [showDialog]="showCarColorsDialog" (onCloseDialog)="onCarColorsCloseDialog($event)"></view-car-colors>

Where showCarColorsDialog is changed based on a button click.

private onCarColorsCloseDialog($event: any): void {
    this.showCarColorsDialog = false;
    if ($event.hasChanges) {
        //fetch the changes again
        this.getCarColors();
    }
}

I have used the primeng controls on multiple places and they all work fine but just has this issue so I'm sure it can't be because of the version.


答:
Just provide correct pattern in SimpleDateForamt</p>

```<code>    String startDateString = "09/23/2009";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

Body:
Just provide correct pattern in SimpleDateForamt

    String startDateString = "09/23/2009";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
    startDate = df.parse(startDateString);
    String newDateString = df.format(startDate);
    System.out.println(newDateString);
} catch (ParseException e) {
    e.printStackTrace();
}


问:
Ruby execute a multiline cmd string
I had build a curl command

```<code>cmd = %Q(curl --tlsv1.2 -b #{config['cookies']} -c #{config['cookies']} --
connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '#{xml_content}'
            --location #{uri})
puts cmd
</code>```

The output is as follow when the string is printed

```<code>curl --tlsv1.2 -b /tmp/cookie.txt -c /tmp/cookie.txt --connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '<?xml version="1.0" encoding="UTF-8" ?>
            <ns:login xmlns:ns="http://www.actility.com/smp/ws/admin">
            <login>hello</login><password>wPa4GwYbRTCw0Uy!</password></ns:login>'
            --location https://myapi.application.com
</code>```

How do I execute it in ruby w/o modifying the cmd string to a single cmd ?

答:
You already built a string containing the command, so you need to pass it to one of Ruby's shell execution methods.
I'd suggest

```<code>result = %x(#{cmd})
</code>```

Here is a more detailed answer you might find useful: https://stackoverflow.com/a/2400/2029766

Title: Ruby execute a multiline cmd string

Body:
I had build a curl command

cmd = %Q(curl --tlsv1.2 -b #{config['cookies']} -c #{config['cookies']} --
connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '#{xml_content}'
            --location #{uri})
puts cmd

The output is as follow when the string is printed

curl --tlsv1.2 -b /tmp/cookie.txt -c /tmp/cookie.txt --connect-timeout 60 -X POST
            -H 'Content-Type: application/xml'
            -H 'Accept: application/xml'
            -d '<?xml version="1.0" encoding="UTF-8" ?>
            <ns:login xmlns:ns="http://www.actility.com/smp/ws/admin">
            <login>hello</login><password>wPa4GwYbRTCw0Uy!</password></ns:login>'
            --location https://myapi.application.com

How do I execute it in ruby w/o modifying the cmd string to a single cmd ?

Body:
You already built a string containing the command, so you need to pass it to one of Ruby's shell execution methods.
I'd suggest

result = %x(#{cmd})

Here is a more detailed answer you might find useful: https://stackoverflow.com/a/2400/2029766


问:
Why is goto poor practise?

This question is a duplicate of  Goto Still Considered Harmful. If you wish to discuss this further please use the original question.

Why exactly is GOTO poor programming practise? It makes sense on some occasions to use it.

答:
It means you haven't designed the code procedurally.

If you build your whiles and ifs properly, you should rarely ever need goto.

Rarely is the key word.  There are times where it's useful.  In that sense, many people nowadays just explicitly throw and catch exceptions, just to avoid the dreaded goto.

Title: Why is goto poor practise?

LastEditorDisplayName: Rich B


问:
Database: when to split into separate tables?
Say if I have two different types of sensors: one monitors analog voltage (such as on a temperature sensor) and one measures whether something is on or off (switch sensor).

I can't decide whether to have one table:

```<code>[Sensor]
Id : PK
UpperLimit : FLOAT
UpperLimitAlertDelay : INT
LowerLimit : FLOAT
LowerLimitAlertDelay : INT
IsAnalog : BOOL

[SensorReading]
Id : PK
SensorId : FK
AnalogValue : FLOAT
IsOn : BOOL
</code>```

OR separate it all out into separate tables:

```<code>[AnalogSensor]
Id : PK
UpperLimit : FLOAT
UpperLimitAlertDelay : INT
LowerLimit : FLOAT
LowerLimitAlertDelay : INT

[AnalogSensorReadings]
Id : PK
AnalogSensorId : FK
Value : FLOAT

[SwitchSensor]
Id : PK
OnTooLongAlertDelay : INT

[SwitchSensorReadings]
Id : PK
SwitchSensorId : FK
IsOn : BOOL
</code>```

At the moment I have it as one table and I use the "UpperLimitAlertDelay" as the "OnTooLongAlertDelay" when not using it as the analog sensor.

In the code I differentiate by the boolean flag on the Sensor table and create the appropriate object (i.e. AnalogSensor or SwitchSensor) but I'm wondering if it'd be neater / more proper at the database level to separate it out.

What rule of thumb would you use for this kind of decision?  They are different entities on one level, but on another level you could say they are both just sensors.

This is often where I can never decide what direction to take when creating a database.  Maybe whenever I use a bool to differentiate what fields mean / should be used, it should really be a separate table?

General thoughts on this topic or this sepcific problem appreciated.

Thanks!

EDIT: Some further information.

The switch sensors monitor things like whether a door is open, a fridge compressor is running, whether an appliance is turned on, etc.

Graphs and reports can be generated on any sensor so they are used in the same way; it's just the data will either be on/off or an analog value depending on the type.

So basically they are generally treated the same.

In the readings table, it is always one row for ONE reading off of ONE sensor.

So far the opinions seem to be quiet subjective - I guess there are just pros and cons to both ways.

Does the information above change anybody's opinion?

Thanks!
Mark.

答:
Is this the same application/database as your other question ?

In which case, the answer has been supplied in that Data Model.

If it isn't the same app/db, or if this question has not been adequately answered, pls post or comment.  Eg. Based on previous info, I modelled it so that the SensorType table differentiates Sensor (analogue or boolean) ... but we could:

differentiate it at the Sensor level,

or make Reading into subtypes: ReadingAnalog and ReadingSwitch.  That could make it a little easier for the programs that produce graphs, etc.

Body:
Say if I have two different types of sensors: one monitors analog voltage (such as on a temperature sensor) and one measures whether something is on or off (switch sensor).

I can't decide whether to have one table:

[Sensor]
Id : PK
UpperLimit : FLOAT
UpperLimitAlertDelay : INT
LowerLimit : FLOAT
LowerLimitAlertDelay : INT
IsAnalog : BOOL

[SensorReading]
Id : PK
SensorId : FK
AnalogValue : FLOAT
IsOn : BOOL

OR separate it all out into separate tables:

[AnalogSensor]
Id : PK
UpperLimit : FLOAT
UpperLimitAlertDelay : INT
LowerLimit : FLOAT
LowerLimitAlertDelay : INT

[AnalogSensorReadings]
Id : PK
AnalogSensorId : FK
Value : FLOAT

[SwitchSensor]
Id : PK
OnTooLongAlertDelay : INT

[SwitchSensorReadings]
Id : PK
SwitchSensorId : FK
IsOn : BOOL

At the moment I have it as one table and I use the "UpperLimitAlertDelay" as the "OnTooLongAlertDelay" when not using it as the analog sensor.

In the code I differentiate by the boolean flag on the Sensor table and create the appropriate object (i.e. AnalogSensor or SwitchSensor) but I'm wondering if it'd be neater / more proper at the database level to separate it out.

What rule of thumb would you use for this kind of decision?  They are different entities on one level, but on another level you could say they are both just sensors.

This is often where I can never decide what direction to take when creating a database.  Maybe whenever I use a bool to differentiate what fields mean / should be used, it should really be a separate table?

General thoughts on this topic or this sepcific problem appreciated.

Thanks!

EDIT: Some further information.

The switch sensors monitor things like whether a door is open, a fridge compressor is running, whether an appliance is turned on, etc.

Graphs and reports can be generated on any sensor so they are used in the same way; it's just the data will either be on/off or an analog value depending on the type.

So basically they are generally treated the same.

In the readings table, it is always one row for ONE reading off of ONE sensor.

So far the opinions seem to be quiet subjective - I guess there are just pros and cons to both ways.

Does the information above change anybody's opinion?

Thanks!
Mark.