问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答:
Most developers will choose the technology to use for their own reasons. So if you provide an API that is easier than what they use to scrape your screens, then some unkown percent will move to it. Bandwidth reduction will probably be very low on their lists of considerations.

Since you haven't specified what's being scraped for, we can't help you guess what kind of API to provide, or what proportion will use it.

One very common tool for scraping that's hard to deflect is using Excel or some other product that makes the scrape painless.

If your intent is just to minimize the pain (which one might infer from your question), then by far the most useful thing to do is to query they scrapers - more useful than querying SO, anyway.

You might check woot.com and see what they provide on an RSS feed to unburden the web http server.

OwnerDisplayName: Tom Anderson

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


来源: stackexchange

问:
How can I stop a character in pygame from leaving the edge of the screen?
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?</p>

```<code>import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)
</code>```

答:
This should work

```<code>if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5
</code>```

Where 600 and 800 is the screen size and 60 the size of your rectangle

ContentLicense: CC BY-SA 3.0

Body:
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

Body:
This should work

if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

Where 600 and 800 is the screen size and 60 the size of your rectangle


问:
AES-256-CBC Decrypt Error Stating Padding is invalid and cannot be removed
I have a PHP application using openSSL to send a AES-256-CBC encrypted string with Base64 encoding to a .NET application. I start the decrypt method, but I always error when I try to actually decrypt the data. The error states "Padding is invalid and cannot be removed". What am I doing wrong here?

The encrypted Base64 value generated by the PHP function is:
p07cNwcvcYLxvYHCUsmZqKYr40IXXYjEHr7r+JdgXiJT5/wpDSDmr48JLOXyNEL7

The key is:
M2AZULUALPHA

The salt is:
TripBuilder2017x

The PHP function is:

```<code>function encrypt($text) {
$key = "M2AZULUALPHA";
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$padding = $block - (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);

$crypttext = openssl_encrypt($text,'aes-256-cbc', $key,  OPENSSL_RAW_DATA, 'TripBuilder2017x');
return base64_encode($crypttext);
</code>```

}

The .NET Decrypt function:

```<code> private string Decrypt(string cipherText)
        {
            string EncryptionKey = "M2AZULUALPHA";
            byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");

            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
                encryptor.Mode = CipherMode.CBC;
                encryptor.BlockSize = 128;
                encryptor.KeySize = 256;
                encryptor.Padding = PaddingMode.PKCS7;
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }

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

UPDATE I went to an online openSSL decrypt tool, entered my IV,Key and base64 text. It generated the correct string but had some weird blocks in the string.

UPDATE 2
Here is the updated PHP code. I increased the key size to 16 bytes as well. I am still receiving the same error.

```<code>$key = "M2AZULUALPHAECHO";
$salt = "TripBuilder2017x";
$mode = "aes-256-cbc";
$text = "BrassMonkey";

function encrypt($text,$key,$salt,$mode) {

    return base64_encode(encryptplain($text,$key,$salt,$mode));
}

function encryptplain($text,$key,$salt,$mode) {

    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);

    $crypttext = openssl_encrypt($text, $mode, $key, 1, $salt);
    return ($crypttext);
}
</code>```

UPDATE 3: My .NET Code

```<code>private string Decrypt(string cipherText)
        {
            string EncryptionKey = "M2AZULUALPHAECHO";
            byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");

            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {

                encryptor.Mode = CipherMode.CBC;
                encryptor.BlockSize = 128;
                encryptor.KeySize = 256;
                encryptor.Padding = PaddingMode.PKCS7;
                encryptor.Key = Encoding.ASCII.GetBytes(EncryptionKey);
                encryptor.IV = saltArray;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }

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

答:
I can see several immediate problems:

Your C# decryption code is using PBKDF2 to derive the AES key and IV from a password and salt, while your PHP encryption code is using the password and salt directly as the AES key and IV. You need to use the same logic in both places if you want it to work properly.

You're specifying the wrong encryption algorithm in your PHP code when calculating the block length and padding your input - the various versions of Rijndael are named according to their block length, while all versions of AES have a 128-bit block length (i.e. Rijndael-128) and use varying key lengths. Thus, you want to specify MCRYPT_RIJNDAEL_128 if you want the proper padding.

You shouldn't perform padding yourself during encryption unless you also specify the OPENSSL_ZERO_PADDING flag - if you fail to specify this flag, OpenSSL will add its own PKCS#7 padding to the input text, extending it by another block, and your decryption logic will only strip off that part, ignoring your manually-added padding (and resulting in the "weird blocks in the string" you observed with your online OpenSSL decrypt tool).

You need to make sure that your specified AES key size actually matches the algorithm you specified - PHP's openssl_encrypt() function extends your key size (with null bytes) to match the algorithm you specified, while C# will automatically adjust the algorithm to match your provided key size. In this case, your C# code is actually performing AES-128 decryption, which is incompatible with the AES-256 encryption being done in your PHP code.

Other remarks:

If you want a Base64-encoded result from openssl_encrypt(), you can omit the OPENSSL_RAW_DATA flag and it'll return Base64-encoded ciphertext.

The proper solution to problem #1 should be to perform key derivation in both places, or to use binary keys and IV values - a plaintext key has far less entropy and is significantly less secure.

You shouldn't be hardcoding the key and IV in your code - the key should be provided as a parameter, and the IV should be randomly generated and subsequently associated with the ciphertext.

Body:
I have a PHP application using openSSL to send a AES-256-CBC encrypted string with Base64 encoding to a .NET application. I start the decrypt method, but I always error when I try to actually decrypt the data. The error states "Padding is invalid and cannot be removed". What am I doing wrong here?

The encrypted Base64 value generated by the PHP function is:
p07cNwcvcYLxvYHCUsmZqKYr40IXXYjEHr7r+JdgXiJT5/wpDSDmr48JLOXyNEL7

The key is:
M2AZULUALPHA

The salt is:
TripBuilder2017x

The PHP function is:

function encrypt($text) {
$key = "M2AZULUALPHA";
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$padding = $block - (strlen($text) % $block);
$text .= str_repeat(chr($padding), $padding);

$crypttext = openssl_encrypt($text,'aes-256-cbc', $key,  OPENSSL_RAW_DATA, 'TripBuilder2017x');
return base64_encode($crypttext);

}

The .NET Decrypt function:

 private string Decrypt(string cipherText)
        {
            string EncryptionKey = "M2AZULUALPHA";
            byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");

            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, saltArray);
                encryptor.Mode = CipherMode.CBC;
                encryptor.BlockSize = 128;
                encryptor.KeySize = 256;
                encryptor.Padding = PaddingMode.PKCS7;
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }

            }
            return cipherText;
        }

UPDATE I went to an online openSSL decrypt tool, entered my IV,Key and base64 text. It generated the correct string but had some weird blocks in the string.

UPDATE 2
Here is the updated PHP code. I increased the key size to 16 bytes as well. I am still receiving the same error.

$key = "M2AZULUALPHAECHO";
$salt = "TripBuilder2017x";
$mode = "aes-256-cbc";
$text = "BrassMonkey";

function encrypt($text,$key,$salt,$mode) {

    return base64_encode(encryptplain($text,$key,$salt,$mode));
}

function encryptplain($text,$key,$salt,$mode) {

    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $padding = $block - (strlen($text) % $block);
    $text .= str_repeat(chr($padding), $padding);

    $crypttext = openssl_encrypt($text, $mode, $key, 1, $salt);
    return ($crypttext);
}

UPDATE 3: My .NET Code

private string Decrypt(string cipherText)
        {
            string EncryptionKey = "M2AZULUALPHAECHO";
            byte[] saltArray = Encoding.ASCII.GetBytes("TripBuilder2017x");

            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {

                encryptor.Mode = CipherMode.CBC;
                encryptor.BlockSize = 128;
                encryptor.KeySize = 256;
                encryptor.Padding = PaddingMode.PKCS7;
                encryptor.Key = Encoding.ASCII.GetBytes(EncryptionKey);
                encryptor.IV = saltArray;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }

            }
            return cipherText;
        }


问:
12 month rolling from a entered month?
Hi can someone please help me, I want to create a script with a month parameter, the results I require is the next 12 month's names as column headings.

For example if the parameter is February the results should be:

```<code>March | April | May | June | July | August | September | October | November | December | January | February |
</code>```

As the column names which I want to use to fill in values at a later stage.
Can someone please advise me on this and how I can achieve this

My script I have so far don't know how to approach this

```<code>declare @MonthParam varchar(20) = 'March'
declare @MonthNumber int = (
Select CASE WHEN @MonthParam = 'January' THEN 1
            WHEN @MonthParam = 'February' THEN 2
            WHEN @MonthParam = 'March' THEN 3
            WHEN @MonthParam = 'April' THEN 4
            WHEN @MonthParam = 'May' THEN 5
            WHEN @MonthParam = 'June' THEN 6
            WHEN @MonthParam = 'July' THEN 7
            WHEN @MonthParam = 'August' THEN 8
            WHEN @MonthParam = 'September' THEN 9
            WHEN @MonthParam = 'October' THEN 10
            WHEN @MonthParam = 'November' THEN 11
            WHEN @MonthParam = 'December' THEN 12
END)
WHILE(@MonthNumber < 13)

    BEGIN

    declare @month varchar(20) = DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
    declare @sql varchar(max)
    set @sql = 'select val as ' + @month + ' from t'
    exec (@sql)

    SET @MonthNumber = @MonthNumber + 1;

    END
</code>```

答:
I've used a temp table with some dummy data to show the final output as a table</p>

```<code>DECLARE @PivotColumnHeaders VARCHAR(MAX);
DECLARE @date_entered varchar(50) = 'February';
SET @date_entered = @date_entered + ' 01 ' + CONVERT(CHAR(4),YEAR(GETDATE()));
DECLARE @s INT= 1, @e INT = 12;
CREATE TABLE PivotTemp (Dummy INT, [MonthName] VARCHAR(15));

WHILE ( @s <= @e)
BEGIN
    SELECT @PivotColumnHeaders =
    COALESCE(
        @PivotColumnHeaders + ',[' + DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered)) + ']',
        '[' + DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered))+ ']'
    );
    INSERT INTO PivotTemp ( Dummy, [MonthName] )  VALUES ( @s, DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered)) );
    SET @s = @s + 1;
END;
--SELECT @PivotColumnHeaders ;
--SELECT * FROM PivotTemp ;

DECLARE @PivotTableSQL NVARCHAR(MAX);
SET @PivotTableSQL = N'
  SELECT *
  FROM (
    SELECT
      H.Dummy [DummyValue],
      H.[MonthName] [MonthName]
    FROM dbo.PivotTemp H
  ) AS PivotData
  PIVOT (
    MAX(DummyValue)
    FOR [MonthName] IN (
      ' + @PivotColumnHeaders + '
    )
  ) AS PivotTable
';

EXECUTE(@PivotTableSQL);
DROP TABLE PivotTemp;
</code>```

Title: 12 month rolling from a entered month?

Body:
Hi can someone please help me, I want to create a script with a month parameter, the results I require is the next 12 month's names as column headings.

For example if the parameter is February the results should be:

March | April | May | June | July | August | September | October | November | December | January | February |

As the column names which I want to use to fill in values at a later stage.
Can someone please advise me on this and how I can achieve this

My script I have so far don't know how to approach this

declare @MonthParam varchar(20) = 'March'
declare @MonthNumber int = (
Select CASE WHEN @MonthParam = 'January' THEN 1
            WHEN @MonthParam = 'February' THEN 2
            WHEN @MonthParam = 'March' THEN 3
            WHEN @MonthParam = 'April' THEN 4
            WHEN @MonthParam = 'May' THEN 5
            WHEN @MonthParam = 'June' THEN 6
            WHEN @MonthParam = 'July' THEN 7
            WHEN @MonthParam = 'August' THEN 8
            WHEN @MonthParam = 'September' THEN 9
            WHEN @MonthParam = 'October' THEN 10
            WHEN @MonthParam = 'November' THEN 11
            WHEN @MonthParam = 'December' THEN 12
END)
WHILE(@MonthNumber < 13)

    BEGIN

    declare @month varchar(20) = DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 )
    declare @sql varchar(max)
    set @sql = 'select val as ' + @month + ' from t'
    exec (@sql)

    SET @MonthNumber = @MonthNumber + 1;

    END

Body:
I've used a temp table with some dummy data to show the final output as a table

DECLARE @PivotColumnHeaders VARCHAR(MAX);
DECLARE @date_entered varchar(50) = 'February';
SET @date_entered = @date_entered + ' 01 ' + CONVERT(CHAR(4),YEAR(GETDATE()));
DECLARE @s INT= 1, @e INT = 12;
CREATE TABLE PivotTemp (Dummy INT, [MonthName] VARCHAR(15));

WHILE ( @s <= @e)
BEGIN
    SELECT @PivotColumnHeaders =
    COALESCE(
        @PivotColumnHeaders + ',[' + DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered)) + ']',
        '[' + DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered))+ ']'
    );
    INSERT INTO PivotTemp ( Dummy, [MonthName] )  VALUES ( @s, DATENAME(MONTH,DATEADD(MONTH, @s, @date_entered)) );
    SET @s = @s + 1;
END;
--SELECT @PivotColumnHeaders ;
--SELECT * FROM PivotTemp ;

DECLARE @PivotTableSQL NVARCHAR(MAX);
SET @PivotTableSQL = N'
  SELECT *
  FROM (
    SELECT
      H.Dummy [DummyValue],
      H.[MonthName] [MonthName]
    FROM dbo.PivotTemp H
  ) AS PivotData
  PIVOT (
    MAX(DummyValue)
    FOR [MonthName] IN (
      ' + @PivotColumnHeaders + '
    )
  ) AS PivotTable
';

EXECUTE(@PivotTableSQL);
DROP TABLE PivotTemp;


问:
Send push notification to Android repackage bar file in Blackberry OS using FCM
Can I send the push notification to Android application in Blackberry OS 10.3 using FCM push notification.

If not, Is there any way to send the push notification to blackberry OS devices.

答:
Confirming @CommonsWare's comment, there is currently no FCM support for BlackBerry OS.

For the available Push Notification services for BlackBerry, you should check out the Official BlackBerry documentations like this one.


问:
Do add-in and its popup browser window share a same localStorage?
I am building an Excel add-in with JavaScript API.

The add-in can popup a browser window by

```<code>popup = window.open("https://localhost:3000/#/new", "popup", "status=1, location=1, width=1000, height=1200");
</code>```

I have tested that the add-in and the popup browser window could communicate by postMessage.

However, it seems that they do NOT share the same localStorage. For exemple, if i set localStorage.setItem("item", "content") in the webpage, localStorage.getItem("item") in the add-in returns null.

Does anyone know if the add-in and the popup browser window share the same localStorage?

PS: I have tested that an add-in itself can set an item in localStorage and get the value. Also, webpages can set and get items in localStorage even though they may be in the same browser window.

答:
They do not (on Office for Windows).  They run in different trust modes, do cookies, localStorage, etc. are not shared.

If you need a popup-like scenario, that is what the DialogAPI is for.

Body:
I am building an Excel add-in with JavaScript API.

The add-in can popup a browser window by

popup = window.open("https://localhost:3000/#/new", "popup", "status=1, location=1, width=1000, height=1200");

I have tested that the add-in and the popup browser window could communicate by postMessage.

However, it seems that they do NOT share the same localStorage. For exemple, if i set localStorage.setItem("item", "content") in the webpage, localStorage.getItem("item") in the add-in returns null.

Does anyone know if the add-in and the popup browser window share the same localStorage?

PS: I have tested that an add-in itself can set an item in localStorage and get the value. Also, webpages can set and get items in localStorage even though they may be in the same browser window.


问:
How can I name a navigation property a different name from it's entity name in my EF POCO?
I have a POCO Entity named Employee.
And then I have a second POCO Entity named Case.

I want a navigation property that looks like instead this:

```<code>public class Case : BaseEntity
{
    public long EmployeeId { get; set; }
    public virtual Employee Employee{ get; set; }
</code>```

like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```

I want to name my property InitialContact.  Not Employee.

But I get this error when EF tries to create the Database:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 1:

I got it to work like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }
</code>```

}

The primary key is ID in my BaseEntity.  Not EmployeeId.

But I have second part to my question.

Here is my Complete Employee POCO:

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Hrsa.Core.Generic.Model.Framework.Concrete;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Hrsa.Core.Generic.Model.Lerd
{
    public class Employee : BaseEntity
    {
        [BindNever]
        public string Email { get; set; }
        [BindNever]
        public long OrganizationId { get; set; }
        [BindNever]
        public string Supervisor { get; set; }
        [BindNever]
        public string SupervisorEmail { get; set; }
        [BindNever]
        public string FirstName { get; set; }
        [BindNever]
        public string LastName { get; set; }
        public string Notes { get; set; }
        [BindNever]
        public  long BargainingUnitId { get; set; }
        [BindNever]
        public long PayPlanId { get; set; }
        [BindNever]
        public long GradeRankId { get; set; }
        [BindNever]
        public long PositionTitleId { get; set; }
        [BindNever]
        public long SeriesId { get; set; }
        public bool IsUnionEmployee { get; set; }
        public virtual Organization Organization { get; set; }
        public virtual BargainingUnit BargainingUnit { get; set; }
        public virtual PayPlan PayPlan { get; set; }
        public virtual GradeRank GradeRank { get; set; }
        public virtual PositionTitle PositionTitle { get; set; }
        public virtual  Series Series { get; set; }
        public virtual ICollection<UnionHours> UnionHours { get; set; }
        public virtual ICollection<Case> Cases { get; set; }
        [NotMapped]
        public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";
   }
}
</code>```

I want my Employee to have many Cases:

```<code>public virtual ICollection<Case> Cases { get; set; }
</code>```

Here is my complete Cases POCO:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}
</code>```

So now my DB looks like this:

So I have my InitialContactId in Cases ok.

But now I need my Case to have many Employees.

So I add this in to my Case POCO:

```<code>public virtual ICollection<Employee> Employees { get; set; }
</code>```

Now it looks like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
</code>```

}

Now when I run it, I get this error again:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 2:

I found this article for a Many-Many relationship in .Net Core 1:
http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

So now I have a bridge lookup entity:

```<code>public class EmployeeCase
{
    [ForeignKey("Id")]
    public long EmployeeId { get; set; }
    public Employee Employee { get; set; }
    [ForeignKey("Id")]
    public long CaseId { get; set; }
    public Case Case { get; set; }

}
</code>```

Employee POCO:

Changed:

```<code>public virtual ICollection<Case> Cases { get; set; }
</code>```

to:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```0

Case POCO:

Changed:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```1

to:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```2

In my AppDbContext

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

    }
</code>```

Now when I run I get this error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Introducing FOREIGN KEY constraint 'FK_EmployeeCase_Employees_EmployeeId' on table 'EmployeeCase' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Could not create constraint or index. See previous errors.

Update 3:

Finally got my tables the way I want with this piece of code from:
Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Get rid of Cascading Circular error on ModelBuilding
        foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationShip.DeleteBehavior = DeleteBehavior.Restrict;
        }

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

        base.OnModelCreating(modelBuilder);
    }
</code>```

Update 4:

This did not work after all.
Remvoving the delete behavior for everything messes up my other relationships and I get errors.

How can I fix this?
This is disgusting.
So wishing I did not go Core.

答:
Entity Framework uses conventions to guess how to map your C# model to database objects.

In your case you violate convention by custom name, so you should explain Entity Framework how to map this stuff.

There are two possible ways: attributes and fluent API. I'd suggest to use the latter one.

See section "Configuring a Foreign Key Name That Does Not Follow the Code First Convention" here: Entity Framework Fluent API - Relationships

Body:
I have a POCO Entity named Employee.
And then I have a second POCO Entity named Case.

I want a navigation property that looks like instead this:

public class Case : BaseEntity
{
    public long EmployeeId { get; set; }
    public virtual Employee Employee{ get; set; }

like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }

I want to name my property InitialContact.  Not Employee.

But I get this error when EF tries to create the Database:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 1:

I got it to work like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}

The primary key is ID in my BaseEntity.  Not EmployeeId.

But I have second part to my question.

Here is my Complete Employee POCO:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Hrsa.Core.Generic.Model.Framework.Concrete;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Hrsa.Core.Generic.Model.Lerd
{
    public class Employee : BaseEntity
    {
        [BindNever]
        public string Email { get; set; }
        [BindNever]
        public long OrganizationId { get; set; }
        [BindNever]
        public string Supervisor { get; set; }
        [BindNever]
        public string SupervisorEmail { get; set; }
        [BindNever]
        public string FirstName { get; set; }
        [BindNever]
        public string LastName { get; set; }
        public string Notes { get; set; }
        [BindNever]
        public  long BargainingUnitId { get; set; }
        [BindNever]
        public long PayPlanId { get; set; }
        [BindNever]
        public long GradeRankId { get; set; }
        [BindNever]
        public long PositionTitleId { get; set; }
        [BindNever]
        public long SeriesId { get; set; }
        public bool IsUnionEmployee { get; set; }
        public virtual Organization Organization { get; set; }
        public virtual BargainingUnit BargainingUnit { get; set; }
        public virtual PayPlan PayPlan { get; set; }
        public virtual GradeRank GradeRank { get; set; }
        public virtual PositionTitle PositionTitle { get; set; }
        public virtual  Series Series { get; set; }
        public virtual ICollection<UnionHours> UnionHours { get; set; }
        public virtual ICollection<Case> Cases { get; set; }
        [NotMapped]
        public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";
   }
}

I want my Employee to have many Cases:

public virtual ICollection<Case> Cases { get; set; }

Here is my complete Cases POCO:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}

So now my DB looks like this:

So I have my InitialContactId in Cases ok.

But now I need my Case to have many Employees.

So I add this in to my Case POCO:

public virtual ICollection<Employee> Employees { get; set; }

Now it looks like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

}

Now when I run it, I get this error again:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 2:

I found this article for a Many-Many relationship in .Net Core 1:
http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

So now I have a bridge lookup entity:

public class EmployeeCase
{
    [ForeignKey("Id")]
    public long EmployeeId { get; set; }
    public Employee Employee { get; set; }
    [ForeignKey("Id")]
    public long CaseId { get; set; }
    public Case Case { get; set; }

}

Employee POCO:

Changed:

public virtual ICollection<Case> Cases { get; set; }

to:

// Mapping - Collection of Cases
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }

Case POCO:

Changed:

public virtual ICollection<Employee> Employees { get; set; }

to:

 // Mapping - Collection of Employees
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }

In my AppDbContext

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

    }

Now when I run I get this error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Introducing FOREIGN KEY constraint 'FK_EmployeeCase_Employees_EmployeeId' on table 'EmployeeCase' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Could not create constraint or index. See previous errors.

Update 3:

Finally got my tables the way I want with this piece of code from:
Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Get rid of Cascading Circular error on ModelBuilding
        foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationShip.DeleteBehavior = DeleteBehavior.Restrict;
        }

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

        base.OnModelCreating(modelBuilder);
    }

Update 4:

This did not work after all.
Remvoving the delete behavior for everything messes up my other relationships and I get errors.

How can I fix this?
This is disgusting.
So wishing I did not go Core.


问:
How to call curl request to fetch data through design document?
My design document is something like this..

```<code>{
  "_id": "_design/dataFilter",
  "_rev": "1-29032a3479f5bfb016ea4e2f5e8afae3",
  "filters": {
    "getUser": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc._id) }",
    "getCustomer": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc.user) }",
    "getOrders": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc.user) }",
    "getCloths": "function (doc, req) { return (req.query.id == doc._id) }",
    "getDevices": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc._id) }"
  }
}
</code>```

This is how I am trying to fetch the records from couchdb.

```<code>curl -X GET http://example.com/database?filter=dataFilter/getCustomer -d '{"query_params":{"id":"jayesh","type":"user"}}'
</code>```

How can we fetch records from the couchdb with the help of design document?

答:
Regarding the documentation of couchdb, filters can only be used for the _changes feed:
http://docs.couchdb.org/en/2.0.0/couchapp/ddocs.html#filter-functions

What you can do, is using views with map/reduce functions:
http://docs.couchdb.org/en/2.0.0/couchapp/ddocs.html#view-functions

You just have to emit all documents that match the filter. The key and the value of the emit-function can be used as you want.

In your example, the design-doc would look like this:

This would look like this:

```<code>{
  "_id": "_design/dataFilter",
  "_rev": "1-29032a3479f5bfb016ea4e2f5e8afae3",
  "views": {
    "getUser": {
      "map": "function(doc) { if (req.query.type == doc.type && req.query.id == doc._id) { emit(doc._id, "something") } }"
    },

...

  }
}
</code>```

After the view has been computed (what could take some time on big databases) you can fetch the results with:

GET DB/_design/dataFilter/_view/getUser

Body:
My design document is something like this..

{
  "_id": "_design/dataFilter",
  "_rev": "1-29032a3479f5bfb016ea4e2f5e8afae3",
  "filters": {
    "getUser": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc._id) }",
    "getCustomer": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc.user) }",
    "getOrders": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc.user) }",
    "getCloths": "function (doc, req) { return (req.query.id == doc._id) }",
    "getDevices": "function (doc, req) { return (req.query.type == doc.type && req.query.id == doc._id) }"
  }
}

This is how I am trying to fetch the records from couchdb.

curl -X GET http://example.com/database?filter=dataFilter/getCustomer -d '{"query_params":{"id":"jayesh","type":"user"}}'

How can we fetch records from the couchdb with the help of design document?

Body:
Regarding the documentation of couchdb, filters can only be used for the _changes feed:
http://docs.couchdb.org/en/2.0.0/couchapp/ddocs.html#filter-functions

What you can do, is using views with map/reduce functions:
http://docs.couchdb.org/en/2.0.0/couchapp/ddocs.html#view-functions

You just have to emit all documents that match the filter. The key and the value of the emit-function can be used as you want.

In your example, the design-doc would look like this:

This would look like this:

{
  "_id": "_design/dataFilter",
  "_rev": "1-29032a3479f5bfb016ea4e2f5e8afae3",
  "views": {
    "getUser": {
      "map": "function(doc) { if (req.query.type == doc.type && req.query.id == doc._id) { emit(doc._id, "something") } }"
    },

...

  }
}

After the view has been computed (what could take some time on big databases) you can fetch the results with:

GET DB/_design/dataFilter/_view/getUser


问:
Secure communication basics
Till now I haven't really studied secure communication and I have some basic questions. Assume there is a browser(the client) and a server. From what I have understood, the server has both a public and a private key. The public key is known by everyone and the private key only by the server. So when the client sends a message to the server, it is encrypted with the public key of the server and only the server can decrypt it(cause only the server has the private key).

Now to my question: What happens when the server wants to send a message to the client? The server encrypts the message with its private key and the client decrypts it with the public key(it is known by everyone). So far so good. But if someone sniff the traffic, he can also decrypt the message, cause everyone knows the public key. How is it secure? I am sure I don't understand something really basic here:(

Thanks in advance!

Best regards,
Petar

答:
Secure communications involve not only encryption (which is actually the easy part) but also, and more importantly, authentication.

It is possible to establish encrypted communications between two parties without needing any keys exchanged beforehand (e.g. see Diffie–Hellman key exchange).

The hard part is making sure that whoever you are talking to is trustworthy. This is where public and private keys come in.

So the workflow goes somewhat like this:

A connection is made between client and server.

The client already knows the server's public key (assymetric cryptography), so it can prove that the other endpoint is who they say they are: the public key is used to decrypt a token that, when validated, shows that it was indeed encrypted with the server's private key.

Now that authentication is complete, the two parties use some method like Diffie-Hellman above to establish a shared secret.

This shared secret is used as the encryption/decryption key (symmetric cryptography) for all data exchanges for the remainder of the client/server session.

When the connection is closed, the above encryption key is discarded. If a new connection is established, the algorithm above will generate a new encryption key for that new session.

ContentLicense: CC BY-SA 2.5

Title: Secure communication basics


答:
What you are trying to do is called edge detection, as in detect if you are at an edge, in this case you want the edges to be the screen's edges. what you should do, is check if your x or y are at an edge, if so don't go any further.

```<code>if pressed[pygame.K_UP]:
    if 0 < y-5 < 600:  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
        y -= 5
</code>```

Note this will only detect if the top left's square is going out of bounds, since x and y is the top and left coords for the rectangle, meaning the bottom right of the square will be able to still go out of bounds,

If you want to check the whole square, you will have to make adjustment calculations in the if statement, or base your x and y on the center (which you will still have to modify the if statement to something like below. (note I'm altering based on your current code for x and y being top left.

```<code>if pressed[pygame.K_UP]:
    if (0 < y-5 < 600) or (0< y+60-5 <600)  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
        y -= 5
</code>```

This checks the other side of the square. Note for x you will check for the horizontal limits which in this case is 800. Also we are checking including the -5 because we want to see where we are going, not where we are at.

Title: How can I stop a character in pygame from leaving the edge of the screen?

Body:
What you are trying to do is called edge detection, as in detect if you are at an edge, in this case you want the edges to be the screen's edges. what you should do, is check if your x or y are at an edge, if so don't go any further.

if pressed[pygame.K_UP]:
    if 0 < y-5 < 600:  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
        y -= 5

Note this will only detect if the top left's square is going out of bounds, since x and y is the top and left coords for the rectangle, meaning the bottom right of the square will be able to still go out of bounds,

If you want to check the whole square, you will have to make adjustment calculations in the if statement, or base your x and y on the center (which you will still have to modify the if statement to something like below. (note I'm altering based on your current code for x and y being top left.

if pressed[pygame.K_UP]:
    if (0 < y-5 < 600) or (0< y+60-5 <600)  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one
        y -= 5

This checks the other side of the square. Note for x you will check for the horizontal limits which in this case is 800. Also we are checking including the -5 because we want to see where we are going, not where we are at.


问:
Android LinkedHashMap deserializing as HashMap, causes CCE error
I'm attempting to pass a serialized LinkedHashMap between activities, and getting a confusing result/error when I deserialize the object.

I serialize the object as follows:

```<code>    Bundle exDetails = new Bundle();
    LinkedHashMap<String, Exercise> exMap = new LinkedHashMap<String,
    Exercise (workout.getExercises());

    exDetails.putString(WORKOUTNAME, workout.getWorkoutName());
    exDetails.putSerializable(workout.getWorkoutName(), exMap);

    iComplete.putExtra("wName", exDetails);
    startActivity(iComplete);
</code>```

That seems to work fine, the problem shows up in the next activity:

```<code>    Bundle exDetails =  getIntent().getBundleExtra("wName");
    workoutName = exDetails.getString(WORKOUTNAME);
    Serializable eData = exDetails.getSerializable(workoutName);

    ex = new LinkedHashMap<String, Exercise>();
    ex = (LinkedHashMap<String, Exercise>) eData;
</code>```

At this point, the deserialized object (eData) contains a HashMap object (not LinkedHashMap), and it gives me

```<code>java.lang.ClassCastException:java.util.HashMap cannot be
cast to java.util.LinkedHashMap
</code>```

on that last line. I've verified with the debugger that the bundle (in the second activity) contains a HashMap, instead of a LinkedHashMap (as I'm assuming it should). I should also mention that I need to maintain the order in which entries are added to the Map, hence the usage of LinkedHashMap. The entries eventually get printed, and order is very important for the output.

Questions:
Am I doing anything wrong in particular, or is this problem due to bugs with LinkedHashMap's serialization? I've noticed a few similar threads, that seem to speak of this being an ongoing problem with several of the Map implementations. They didn't answer my problem directly though.

If the latter, is there a workaround that isn't too advanced (I'm not far beyond beginner level, but I'm willing to try most things), or do I need to just bite the bullet and work something other than LinkedHashMap?

P.s. I tried to include everything relevant, but I can add more code if I left out anything important.

答:
I went for a different approach: serialize any (type of) Map into 2 ArrayLists: one containing the keys and the other one containing the values. This way, the order of the map entries (important in a LinkedHashMap) is kept.

Each key/value implements Serializable. If you know for sure you need just Strings or just one particular type of Map, then it should be really easy to convert the following generic code into the scenario needed which also simplifies the complexity.

Map -> 2 ArrayLists:

```<code>public static <K extends Serializable, V extends Serializable> Pair<ArrayList<K>, ArrayList<V>> convertMapToArrays(@NonNull Map<K, V> map) {
        final Set<Map.Entry<K, V>> entries = map.entrySet();
        final int size = entries.size();
        final ArrayList<K> keys = new ArrayList<>(size);
        final ArrayList<V> values = new ArrayList<>(size);
        for (Map.Entry<K, V> entry : entries) {
            keys.add(entry.getKey());
            values.add(entry.getValue());
        }
        return new Pair<>(keys, values);
}
</code>```

2 ArrayLists -> Map of a specific type

```<code> public static <K extends Serializable, V extends Serializable> Map<K, V> convertArraysToMap(@NonNull ArrayList<K> keys, @NonNull ArrayList<V> values, @NonNull Class<? extends Map<K, V>> mapClass) {
        if (keys.size() != values.size()) {
            throw new RuntimeException("keys and values must have the same number of elements");
        }
        final int size = keys.size();
        Map<K, V> map;
        try {
            final Constructor<? extends Map<K, V>> constructor = mapClass.getConstructor(Integer.TYPE);
            map = constructor.newInstance(size);
        } catch (Exception nse) {
            throw new RuntimeException("Map constructor that accepts the initial capacity not found.");
        }

        for (int i = 0; i < size; i++) {
            final K key = keys.get(i);
            final V value = values.get(i);
            map.put(key, value);
        }
        return map;
    }
</code>```

Helpers for Android's Bundle:

```<code> public static <K extends Serializable, V extends Serializable> void saveMapToBundleAsArrays(@NonNull Map<K, V> map, @NonNull String key, @NonNull Bundle bundle) {
        final Pair<ArrayList<K>, ArrayList<V>> mapToArrays = convertMapToArrays(map);
        final String keyForKeys = key + "_keys";
        final String keyForValues = key + "_values";
        bundle.putSerializable(keyForKeys, mapToArrays.first);
        bundle.putSerializable(keyForValues, mapToArrays.second);
    }

public static Map<Serializable, Serializable> loadMapFromBundle(@NonNull Bundle bundle, @NonNull String key, @NonNull Class<? extends Map<Serializable, Serializable>> mapClass) {
        final String keyForKeys = key + "_keys";
        final String keyForValues = key + "_values";
        final ArrayList<Serializable> keys = (ArrayList<Serializable>) bundle.getSerializable(keyForKeys);
        final ArrayList<Serializable> values = (ArrayList<Serializable>) bundle.getSerializable(keyForValues);
        return convertArraysToMap(keys, values, mapClass);
    }
</code>```

Usage:

```<code>saveMapToBundleAsArrays(mModelEvolution, KEY_MODEL_DATA, bundle);

Class<LinkedHashMap<Serializable, Serializable>> linkedHashMapClazz =
                (Class<LinkedHashMap<Serializable, Serializable>>) new LinkedHashMap<String, String>().getClass();
mModelEvolution = (LinkedHashMap) ObjectUtils.loadMapFromBundle(bundle, KEY_MODEL_DATA, linkedHashMapClazz);
</code>```

Body:
I'm attempting to pass a serialized LinkedHashMap between activities, and getting a confusing result/error when I deserialize the object.

I serialize the object as follows:

    Bundle exDetails = new Bundle();
    LinkedHashMap<String, Exercise> exMap = new LinkedHashMap<String,
    Exercise (workout.getExercises());

    exDetails.putString(WORKOUTNAME, workout.getWorkoutName());
    exDetails.putSerializable(workout.getWorkoutName(), exMap);

    iComplete.putExtra("wName", exDetails);
    startActivity(iComplete);

That seems to work fine, the problem shows up in the next activity:

    Bundle exDetails =  getIntent().getBundleExtra("wName");
    workoutName = exDetails.getString(WORKOUTNAME);
    Serializable eData = exDetails.getSerializable(workoutName);

    ex = new LinkedHashMap<String, Exercise>();
    ex = (LinkedHashMap<String, Exercise>) eData;

At this point, the deserialized object (eData) contains a HashMap object (not LinkedHashMap), and it gives me

java.lang.ClassCastException:java.util.HashMap cannot be
cast to java.util.LinkedHashMap

on that last line. I've verified with the debugger that the bundle (in the second activity) contains a HashMap, instead of a LinkedHashMap (as I'm assuming it should). I should also mention that I need to maintain the order in which entries are added to the Map, hence the usage of LinkedHashMap. The entries eventually get printed, and order is very important for the output.

Questions:
Am I doing anything wrong in particular, or is this problem due to bugs with LinkedHashMap's serialization? I've noticed a few similar threads, that seem to speak of this being an ongoing problem with several of the Map implementations. They didn't answer my problem directly though.

If the latter, is there a workaround that isn't too advanced (I'm not far beyond beginner level, but I'm willing to try most things), or do I need to just bite the bullet and work something other than LinkedHashMap?

P.s. I tried to include everything relevant, but I can add more code if I left out anything important.

Body:
I went for a different approach: serialize any (type of) Map into 2 ArrayLists: one containing the keys and the other one containing the values. This way, the order of the map entries (important in a LinkedHashMap) is kept.

Each key/value implements Serializable. If you know for sure you need just Strings or just one particular type of Map, then it should be really easy to convert the following generic code into the scenario needed which also simplifies the complexity.

Map -> 2 ArrayLists:

public static <K extends Serializable, V extends Serializable> Pair<ArrayList<K>, ArrayList<V>> convertMapToArrays(@NonNull Map<K, V> map) {
        final Set<Map.Entry<K, V>> entries = map.entrySet();
        final int size = entries.size();
        final ArrayList<K> keys = new ArrayList<>(size);
        final ArrayList<V> values = new ArrayList<>(size);
        for (Map.Entry<K, V> entry : entries) {
            keys.add(entry.getKey());
            values.add(entry.getValue());
        }
        return new Pair<>(keys, values);
}

2 ArrayLists -> Map of a specific type

 public static <K extends Serializable, V extends Serializable> Map<K, V> convertArraysToMap(@NonNull ArrayList<K> keys, @NonNull ArrayList<V> values, @NonNull Class<? extends Map<K, V>> mapClass) {
        if (keys.size() != values.size()) {
            throw new RuntimeException("keys and values must have the same number of elements");
        }
        final int size = keys.size();
        Map<K, V> map;
        try {
            final Constructor<? extends Map<K, V>> constructor = mapClass.getConstructor(Integer.TYPE);
            map = constructor.newInstance(size);
        } catch (Exception nse) {
            throw new RuntimeException("Map constructor that accepts the initial capacity not found.");
        }

        for (int i = 0; i < size; i++) {
            final K key = keys.get(i);
            final V value = values.get(i);
            map.put(key, value);
        }
        return map;
    }

Helpers for Android's Bundle:

 public static <K extends Serializable, V extends Serializable> void saveMapToBundleAsArrays(@NonNull Map<K, V> map, @NonNull String key, @NonNull Bundle bundle) {
        final Pair<ArrayList<K>, ArrayList<V>> mapToArrays = convertMapToArrays(map);
        final String keyForKeys = key + "_keys";
        final String keyForValues = key + "_values";
        bundle.putSerializable(keyForKeys, mapToArrays.first);
        bundle.putSerializable(keyForValues, mapToArrays.second);
    }

public static Map<Serializable, Serializable> loadMapFromBundle(@NonNull Bundle bundle, @NonNull String key, @NonNull Class<? extends Map<Serializable, Serializable>> mapClass) {
        final String keyForKeys = key + "_keys";
        final String keyForValues = key + "_values";
        final ArrayList<Serializable> keys = (ArrayList<Serializable>) bundle.getSerializable(keyForKeys);
        final ArrayList<Serializable> values = (ArrayList<Serializable>) bundle.getSerializable(keyForValues);
        return convertArraysToMap(keys, values, mapClass);
    }

Usage:

saveMapToBundleAsArrays(mModelEvolution, KEY_MODEL_DATA, bundle);

Class<LinkedHashMap<Serializable, Serializable>> linkedHashMapClazz =
                (Class<LinkedHashMap<Serializable, Serializable>>) new LinkedHashMap<String, String>().getClass();
mModelEvolution = (LinkedHashMap) ObjectUtils.loadMapFromBundle(bundle, KEY_MODEL_DATA, linkedHashMapClazz);


问:
cannot resolve method 'getFont(?)'
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

```<code>cannot resolve method 'getFont(?)'
</code>```

Previously I used to do the following:

```<code>Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
</code>```

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.

答: The fonts folder should be under assets folder, so try to create folder there.</p>

Title: cannot resolve method 'getFont(?)'

Body:
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

cannot resolve method 'getFont(?)'

Previously I used to do the following:

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.


问:
npm refuses to install mongoose
```<code>  ~ npm install mongoose
npm ERR! Darwin 15.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "mongoose"
npm ERR! node v5.9.1
npm ERR! npm  v3.7.3
npm ERR! code ENOSELF

npm ERR! Refusing to install mongoose as a dependency of itself
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com
</code>```

this has been asked before, however the answer does not work when using npm to uninstall mongoose  the following occurs:

```<code> ~ npm uninstall mongoose
npm WARN karma-chai@0.1.0 requires a peer of chai@* but none was installed.
</code>```

so uninstall is failing to happen

答:
You can make a try in this way,adding "mongoose":"*" in 'package.json' file then code in cmd

```<code>~npm insatll
</code>```

Title: npm refuses to install mongoose

Body:
  ~ npm install mongoose
npm ERR! Darwin 15.4.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "mongoose"
npm ERR! node v5.9.1
npm ERR! npm  v3.7.3
npm ERR! code ENOSELF

npm ERR! Refusing to install mongoose as a dependency of itself
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com

this has been asked before, however the answer does not work when using npm to uninstall mongoose  the following occurs:

 ~ npm uninstall mongoose
npm WARN karma-chai@0.1.0 requires a peer of chai@* but none was installed.

so uninstall is failing to happen

Body:
You can make a try in this way,adding "mongoose":"*" in 'package.json' file then code in cmd

~npm insatll


问:
Time Series forecast on Spark
So I´m trying to do power consumption forecast with time series data with Apache Spark. Sample of the data is :

```<code>03.01.15;22:30;236,25
03.01.15;22:15;240
04.01.15;16:00;243,775
</code>```

and so on for two year. I have Observations every 15 minutes

What is the best way to predict the power consumption  ?

I try LinearRegression, Decision trees etc. I always get huge MSEs (788).
I try pass months, days, hours, minutes as OneHotEncoder. I try to do a forecast only for weeks etc.

Means of the data year, month, day:

```<code>[2014.3996710526321,5.726973684210525,15.713815789473673]
</code>```

Variance of the data year, month, day:

```<code>[0.2403293809070049,10.218579294199253,77.46326844706495]
</code>```

Test Mean Squared Error

```<code>788.2397552290726
</code>```

If I pass the values direct like LabeledPoint(236.25, 2015.0,1.0,3.0,22.0,30.0)) the MSE goes up to 1280.8. If I pass to the model only one observation per day being this the max value it does not help to.

But If I use KNIME and try the example for time series but with my data they do not take the dates and time in consideration, instead they lagged the power consumptions for each observation.

I see that Cloudera has a library for Time Series but I do not understand why do I need it.

Can someone describe the process of doing a good forecast on time series data ?  At the end I want to input a date and time and get a prediction.

答:
I have multiple questions about your issue, but let me try to work with what you've given me.

First, let's generalise the problem.

You have data in the form <timestamp>, <value>. Given the data was collected every 15 minutes for 2 years, you have a sample size of (4 x 24 x 365 x 2) 70080 observations (rows)

And let's say you want to develop a regression model to predict its behaviour.

First things first, you need to partition your dataset into training and test sets. You develop a model using the training set and you test the model on the test set. I would suggest a 9:1 split.

Q1. Is this the kind of approach you have taken?

MSE is calculated using the predicted values against the actual values in the test set.

Q2. You mention an MSE - I have no idea how this was calculated (only 3 data points provided) or the range of values you are working with. Can you please affirm how your error is calculated and what the minimization criteria is?

If linear regression fails (cannot predict the movements succesfully), it may be the case that your model is too simple - try using an MLP or combine the regression model with a Bayesian model (as power consumption is a continuous function).

Title: Time Series forecast on Spark

Body:
So I´m trying to do power consumption forecast with time series data with Apache Spark. Sample of the data is :

03.01.15;22:30;236,25
03.01.15;22:15;240
04.01.15;16:00;243,775

and so on for two year. I have Observations every 15 minutes

What is the best way to predict the power consumption  ?

I try LinearRegression, Decision trees etc. I always get huge MSEs (788).
I try pass months, days, hours, minutes as OneHotEncoder. I try to do a forecast only for weeks etc.

Means of the data year, month, day:

[2014.3996710526321,5.726973684210525,15.713815789473673]

Variance of the data year, month, day:

[0.2403293809070049,10.218579294199253,77.46326844706495]

Test Mean Squared Error

788.2397552290726

If I pass the values direct like LabeledPoint(236.25, 2015.0,1.0,3.0,22.0,30.0)) the MSE goes up to 1280.8. If I pass to the model only one observation per day being this the max value it does not help to.

But If I use KNIME and try the example for time series but with my data they do not take the dates and time in consideration, instead they lagged the power consumptions for each observation.

I see that Cloudera has a library for Time Series but I do not understand why do I need it.

Can someone describe the process of doing a good forecast on time series data ?  At the end I want to input a date and time and get a prediction.


问:
Having trouble populating <asp:DropDownList> with jquery and json
I'm trying to populate a dropdownlist with a json and jquery. I've got a .json file in a project folder named "scripts" where I've also got all my .js files.
Here it is:

```<code>{
    Cities: [{
        "City": "Sofia",
        "cityID": "1"
    }, {
        "City": "Plovdiv",
        "cityID": "2"
    }, {
        "City": "Varna",
        "cityID": "3"
    }, {
        "City": "Burgas",
        "cityID": "4"
    },
    {
        "City": "Rousse",
        "cityID": "5"
    },
    {
        "City": "Stara Zagora",
        "cityID": "6"
    },
    {
        "City": "Pleven",
        "cityID": "7"
    },
    {
        "City": "Sliven",
        "cityID": "8"
    },
    {
        "City": "Dobrich",
        "cityID": "9"
    },
    {
        "City": "Shumen",
        "cityID": "10"
    }]
}
</code>```

And here is my js that is on the page.

```<code>$(document).ready(function () {
    $.getJSON("Scripts/cities.json", function (obj) {
        $.each(obj.cities, function (key, value) {
            $("#db_City").append("<option>" + value.City + "</option>");
                });
        });
</code>```

I can't figure out why its not populating, I can't tell what I'm missing since I'm a complete novice at this. Thank you for any tips/advice that I get in advance.

答:
You have two issues:

in Scripts/cities.json you have Cities: change to "Cities"

in the each loop you have obj.cities: change to obj.Cities

In any case you can declare your json as a library and include it like a normal js. It's enough to associate  the object to a variable.

The snippet:

var obj = {
    Cities: [{
        "City": "Sofia",
        "cityID": "1"
    }, {
        "City": "Plovdiv",
        "cityID": "2"
    }, {
        "City": "Varna",
        "cityID": "3"
    }, {
        "City": "Burgas",
        "cityID": "4"
    },
        {
            "City": "Rousse",
            "cityID": "5"
        },
        {
            "City": "Stara Zagora",
            "cityID": "6"
        },
        {
            "City": "Pleven",
            "cityID": "7"
        },
        {
            "City": "Sliven",
            "cityID": "8"
        },
        {
            "City": "Dobrich",
            "cityID": "9"
        },
        {
            "City": "Shumen",
            "cityID": "10"
        }]
};

//$.getJSON("..../data.json", function (obj) {
    $.each(obj.Cities, function (key, value) {
        $("#db_City").append("<option>" + value.City + "</option>");
    });
//});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="db_City"></select></code>```

Body:
I'm trying to populate a dropdownlist with a json and jquery. I've got a .json file in a project folder named "scripts" where I've also got all my .js files.
Here it is:

{
    Cities: [{
        "City": "Sofia",
        "cityID": "1"
    }, {
        "City": "Plovdiv",
        "cityID": "2"
    }, {
        "City": "Varna",
        "cityID": "3"
    }, {
        "City": "Burgas",
        "cityID": "4"
    },
    {
        "City": "Rousse",
        "cityID": "5"
    },
    {
        "City": "Stara Zagora",
        "cityID": "6"
    },
    {
        "City": "Pleven",
        "cityID": "7"
    },
    {
        "City": "Sliven",
        "cityID": "8"
    },
    {
        "City": "Dobrich",
        "cityID": "9"
    },
    {
        "City": "Shumen",
        "cityID": "10"
    }]
}

And here is my js that is on the page.

$(document).ready(function () {
    $.getJSON("Scripts/cities.json", function (obj) {
        $.each(obj.cities, function (key, value) {
            $("#db_City").append("<option>" + value.City + "</option>");
                });
        });

I can't figure out why its not populating, I can't tell what I'm missing since I'm a complete novice at this. Thank you for any tips/advice that I get in advance.

Body:
You have two issues:

in Scripts/cities.json you have Cities: change to "Cities"

in the each loop you have obj.cities: change to obj.Cities

In any case you can declare your json as a library and include it like a normal js. It's enough to associate  the object to a variable.

The snippet:

var obj = {
    Cities: [{
        "City": "Sofia",
        "cityID": "1"
    }, {
        "City": "Plovdiv",
        "cityID": "2"
    }, {
        "City": "Varna",
        "cityID": "3"
    }, {
        "City": "Burgas",
        "cityID": "4"
    },
        {
            "City": "Rousse",
            "cityID": "5"
        },
        {
            "City": "Stara Zagora",
            "cityID": "6"
        },
        {
            "City": "Pleven",
            "cityID": "7"
        },
        {
            "City": "Sliven",
            "cityID": "8"
        },
        {
            "City": "Dobrich",
            "cityID": "9"
        },
        {
            "City": "Shumen",
            "cityID": "10"
        }]
};

//$.getJSON("..../data.json", function (obj) {
    $.each(obj.Cities, function (key, value) {
        $("#db_City").append("<option>" + value.City + "</option>");
    });
//});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="db_City"></select>


问:
Can't create an object from an Ajax view
Edit: The problem was solved, now I've another problem. The data variable returns nothing when it should return "OK" or "EXISTS".

I have a template with an overlay effect. The income.html template has a form and a button "Add a new category", when you click on it a new window is displayed(overlay effect) with a tiny form. I don't know why, but the category doesn't get created. It seems I've got some errors in the html script but I can't identify them.

income.html:

```<code>(document).ready(function(){
$("#new_cat").live("click", ( function() {
    var cat_name = $("#nc").val();
    if (cat_name) {
        $.get("/cashflow/new_cat/0/", { name: cat_name, account: {{ account }} },
          function(data){
            if (data == "OK") {
                $("#id_category").val(cat_name);
            }
            if (data == "EXISTS") {
                var error = "The category already exists";
                alert(error);
            }
          });
    }
    else {
         var error = "Please enter a name";
         alert(error);
    }
}))
});
</script>
...

<form>{% csrf_token %}
       <label for="name">Name:</label><input type="text" id="nc" />
       <input type="submit" value="Submit" id="new_cat" />
</form>
</code>```

views.py:

```<code>@login_required
def income(request, account_name):
    account = account_name
    if request.method == 'POST':
        form = TransForm(user=request.user, data=request.POST)
        if form.is_valid():
            income = form.save(commit=False)
            income.type = 0
            income.account = Account.objects.get(
                            name = account_name,
                            user = request.user)
            income.name = form.cleaned_data['name']
            income.category = form.cleaned_data['category']
            income.save()
            uri = ("/cashflow/account/%s") % str(account_name)
            return HttpResponseRedirect(uri)

    else:
        form = TransForm(user=request.user)

    context = {
          'TransForm': form,
          'type': '0',
          'account': account,
    }
    return render_to_response(
        'cashflow/income.html',
        context,
        context_instance = RequestContext(request),
    )

def new_cat(request, tipo):
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'name'):
            name = request.GET[u'name']
            account = request.GET[u'account']
            c = Category.objects.filter(namee=name, account=account)
            if c:
                s = "EXISTS"
            else:
                c = Category(name = name, user = request.user,
                        type = type, account = account)
                c.save()
                s = "OK"

    return HttpResponse(s)
</code>```

答:
This looks a bit dodgy:

```<code>{ name: cat_name, account: {{ account }} }
</code>```

Remember that this is being rendered inside a Javascript block. cat_name is a JS variable, so will be evaluated correctly. But {{ account }} renders to a string, so as far as the JS is concerned it is a literal. So it needs to be in quotes:

```<code>{ name: cat_name, account: "{{ account }}" }
</code>```

Body:
Edit: The problem was solved, now I've another problem. The data variable returns nothing when it should return "OK" or "EXISTS".

I have a template with an overlay effect. The income.html template has a form and a button "Add a new category", when you click on it a new window is displayed(overlay effect) with a tiny form. I don't know why, but the category doesn't get created. It seems I've got some errors in the html script but I can't identify them.

income.html:

(document).ready(function(){
$("#new_cat").live("click", ( function() {
    var cat_name = $("#nc").val();
    if (cat_name) {
        $.get("/cashflow/new_cat/0/", { name: cat_name, account: {{ account }} },
          function(data){
            if (data == "OK") {
                $("#id_category").val(cat_name);
            }
            if (data == "EXISTS") {
                var error = "The category already exists";
                alert(error);
            }
          });
    }
    else {
         var error = "Please enter a name";
         alert(error);
    }
}))
});
</script>
...

<form>{% csrf_token %}
       Name:<input type="text" id="nc" />
       <input type="submit" value="Submit" id="new_cat" />
</form>

views.py:

@login_required
def income(request, account_name):
    account = account_name
    if request.method == 'POST':
        form = TransForm(user=request.user, data=request.POST)
        if form.is_valid():
            income = form.save(commit=False)
            income.type = 0
            income.account = Account.objects.get(
                            name = account_name,
                            user = request.user)
            income.name = form.cleaned_data['name']
            income.category = form.cleaned_data['category']
            income.save()
            uri = ("/cashflow/account/%s") % str(account_name)
            return HttpResponseRedirect(uri)

    else:
        form = TransForm(user=request.user)

    context = {
          'TransForm': form,
          'type': '0',
          'account': account,
    }
    return render_to_response(
        'cashflow/income.html',
        context,
        context_instance = RequestContext(request),
    )

def new_cat(request, tipo):
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'name'):
            name = request.GET[u'name']
            account = request.GET[u'account']
            c = Category.objects.filter(namee=name, account=account)
            if c:
                s = "EXISTS"
            else:
                c = Category(name = name, user = request.user,
                        type = type, account = account)
                c.save()
                s = "OK"

    return HttpResponse(s)

Body:
This looks a bit dodgy:

{ name: cat_name, account: {{ account }} }

Remember that this is being rendered inside a Javascript block. cat_name is a JS variable, so will be evaluated correctly. But {{ account }} renders to a string, so as far as the JS is concerned it is a literal. So it needs to be in quotes:

{ name: cat_name, account: "{{ account }}" }


问:
How to keep header the same size as the window
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:</p>

```<code><header>
        <div id="adresa">
            <ul>
              <li><img name="telefon" src="Prvisajt/Rounded-16-128.png" width="20"; height="18"; align="bottom";> 011/2762-124 </li>
              <li>  <img name="adresa" src="Prvisajt/location-square-social-media-128.png" width="20"; height="18"; align="bottom";> Ruzveltova 45, 11000 Beograd, Frizerski salon Marko</li>
              <li id="mail"><a href="mailto:kontakt@frizerskisalonmarko.com"> <img src="Prvisajt/mail-square-social-media-128.png" width="20"; height="18"; align="bottom"> </a></li>
              <li id="face"><a href="https://www.facebook.com/FSM.Beograd/"> <img src="Prvisajt/Facebook_social_media_logo-128.png" width="20"; height="18"; align="bottom"> </a></li>
            </ul>
        </div>

       <div id="navbar">
        <ul>
            <li><img id="logo" src="Prvisajt/logo-alternate.png" alt="Logo"></li>
            <li><a href="galerija.html">GALERIJA</a></li>
            <li><a href="cenovnik.html">CENOVNIK</a></li>
            <li><a href="kontakt.html">KONTAKT</a></li>
        </ul>
      </div>
    </header>

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}
</code>```

答:
remove left property and add float: right;
then add this
#adresa ul li img {
width: 100%;
height: 100%;
}

Body:
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:

 011/2762-124

   Ruzveltova 45, 11000 Beograd, Frizerski salon Marko

GALERIJA

CENOVNIK

KONTAKT

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}


问:
Elasticsearch Mapping - Rename existing field
Is there anyway I can rename an element in an existing elasticsearch mapping without having to add a new element ?
If so whats the best way to do it in order to avoid breaking the existing mapping?

e.g. from fieldCamelcase to fieldCamelCase

```<code>{
    "myType": {
        "properties": {
            "timestamp": {
                "type": "date",
                "format": "date_optional_time"
            },
            "fieldCamelcase": {
                "type": "string",
                "index": "not_analyzed"
            },
            "field_test": {
                "type": "double"
            }
        }
    }
}
</code>```

答:
You could do this by creating an Ingest pipeline, that contains a Rename Processor in combination with the Reindex API. </p>

```<code>PUT _ingest/pipeline/my_rename_pipeline
{
  "description" : "describe pipeline",
  "processors" : [
    {
      "rename": {
        "field": "fieldCamelcase",
        "target_field": "fieldCamelCase"
      }
    }
  ]
}

POST _reindex
{
  "source": {
    "index": "source"
  },
  "dest": {
    "index": "dest",
    "pipeline": "my_rename_pipeline"
  }
}
</code>```

<p>Note that you need to be running Elasticsearch 5.x in order to use ingest. If you're running < 5.x then you'll have to go with what @Val mentioned in his comment :) </p>

ContentLicense: CC BY-SA 4.0

Body:
Is there anyway I can rename an element in an existing elasticsearch mapping without having to add a new element ?
If so whats the best way to do it in order to avoid breaking the existing mapping?

e.g. from fieldCamelcase to fieldCamelCase

{
    "myType": {
        "properties": {
            "timestamp": {
                "type": "date",
                "format": "date_optional_time"
            },
            "fieldCamelcase": {
                "type": "string",
                "index": "not_analyzed"
            },
            "field_test": {
                "type": "double"
            }
        }
    }
}

Body:
You could do this by creating an Ingest pipeline, that contains a Rename Processor in combination with the Reindex API.

PUT _ingest/pipeline/my_rename_pipeline
{
  "description" : "describe pipeline",
  "processors" : [
    {
      "rename": {
        "field": "fieldCamelcase",
        "target_field": "fieldCamelCase"
      }
    }
  ]
}

POST _reindex
{
  "source": {
    "index": "source"
  },
  "dest": {
    "index": "dest",
    "pipeline": "my_rename_pipeline"
  }
}

Note that you need to be running Elasticsearch 5.x in order to use ingest. If you're running < 5.x then you'll have to go with what @Val mentioned in his comment :)


问:
C strtok is not tokenizing empty token value
I have a small program that uses strtok as below:

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

int main ()
{
  char str[] ="1,2,,3,4,5";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,",");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, ",");
  }
  return 0;
}
</code>```

My output is coming as:

```<code>Splitting string "1,2,,3,4,5" into tokens:
1
2
3
4
5
</code>```

But I need to get an empty value as an empty string when I encounter consecutive delimiters as ,, for example in this case.
I.e. I need the output to be as:
Splitting string "1,2,,3,4,5" into tokens:

```<code>1
2

3
4
5
</code>```

Any remedy?

答:
That's how strtok() behave. Quoting the man page

A sequence of two or more contiguous delimiter bytes in the parsed string is considered to be a single delimiter. [...]

You can make use of strchr() or strpbrk() to find out each occurrences of the delimiter and count separately.

Body:
I have a small program that uses strtok as below:

#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="1,2,,3,4,5";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,",");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, ",");
  }
  return 0;
}

My output is coming as:

Splitting string "1,2,,3,4,5" into tokens:
1
2
3
4
5

But I need to get an empty value as an empty string when I encounter consecutive delimiters as ,, for example in this case.
I.e. I need the output to be as:
Splitting string "1,2,,3,4,5" into tokens:

1
2

3
4
5

Any remedy?


问:
How to implement a dual list box control in rails 4
I want to implement a dual list box in a form using rails 4 that gets the column names from another table

I have googled for some examples and so far i have tried the example below but with no success. I just need a simple way to implement a dual list box that gets the column name it doesn't have to be this although this is looks pretty
http://geodan.github.io/duallistbox/sample-100.html.

Here is application.js

```<code>//= require bootstrap-sprockets
//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require bootstrap
//= require turbolinks
//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.bootstrap3
//= require_tree .
</code>```

i have downloaded dual-list-box.js to my assets/javacrtipt from https://github.com/Geodan/DualListBox/

Here is my data_set.coffe

```<code>ready = ->
  $('dualListBox').DualListBox();
  return

$(document).ready ready
</code>```

Here is my _form.html.erb

<%= form_for(@data_set) do |f| %>
  <% if @data_set.errors.any? %>

<%= pluralize(@data_set.errors.count, "error") %> prohibited this data_set from being saved:

      <% @data_set.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name ,class:'form-control' %>

        Select Features

       <select id="dualListBox">

    <%= f.submit :class =>"btn btn-default"  %>

<% end %>```
</div>
</div>
</p>

<p>My gem file</p>

```source 'https://rubygems.org'
gem 'rails', '4.2.5.1'
gem 'pg'
gem 'rails_12factor', group: :production

gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'

gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'tzinfo-data', platforms: [:mingw, :mswin]
gem 'rails_refactor'

gem 'bcrypt', platforms: :ruby
gem 'bootstrap-sass'
gem 'sprockets-rails', '2.3.3'
gem 'devise'
gem 'jquery-datatables-rails', '~> 1.12.2'
```

EDIT:

my final result was this:

I am having problems with compatibility between bootstrap sprockets and jquery, so fonts are not loading,i have decided for now to stop working on this component.

答:
```<code>$(document).ready ->
  ready()

ready = ->
  $('#dualListBox').DualListBox()
</code>```

You have an element with id "dualListBox" so you need to use '#' in the jQuery selector.

Body:
I want to implement a dual list box in a form using rails 4 that gets the column names from another table

I have googled for some examples and so far i have tried the example below but with no success. I just need a simple way to implement a dual list box that gets the column name it doesn't have to be this although this is looks pretty
http://geodan.github.io/duallistbox/sample-100.html.

Here is application.js

//= require bootstrap-sprockets
//= require jquery
//= require jquery_ujs
//= require bootstrap.min
//= require bootstrap
//= require turbolinks
//= require dataTables/jquery.dataTables
//= require dataTables/jquery.dataTables.bootstrap3
//= require_tree .

i have downloaded dual-list-box.js to my assets/javacrtipt from https://github.com/Geodan/DualListBox/

Here is my data_set.coffe

ready = ->
  $('dualListBox').DualListBox();
  return

$(document).ready ready

Here is my _form.html.erb

<%= form_for(@data_set) do |f| %>
  <% if @data_set.errors.any? %>

<%= pluralize(@data_set.errors.count, "error") %> prohibited this data_set from being saved:

      <% @data_set.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name ,class:'form-control' %>

        Select Features

       <select id="dualListBox">

    <%= f.submit :class =>"btn btn-default"  %>

<% end %>

My gem file

source 'https://rubygems.org'
gem 'rails', '4.2.5.1'
gem 'pg'
gem 'rails_12factor', group: :production

gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'

gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'tzinfo-data', platforms: [:mingw, :mswin]
gem 'rails_refactor'

gem 'bcrypt', platforms: :ruby
gem 'bootstrap-sass'
gem 'sprockets-rails', '2.3.3'
gem 'devise'
gem 'jquery-datatables-rails', '~> 1.12.2'

EDIT:

my final result was this:

I am having problems with compatibility between bootstrap sprockets and jquery, so fonts are not loading,i have decided for now to stop working on this component.

Body:
$(document).ready ->
  ready()

ready = ->
  $('#dualListBox').DualListBox()

You have an element with id "dualListBox" so you need to use '#' in the jQuery selector.