问:
How to use connection from one class into another
```<code>class Database {

    public $isConn;
    private static $_instance = null;
    private $datab;

    // connect to db
    public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
        $this->isConn = TRUE;
        try {
            $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
            $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new Database();
        }
        return self::$_instance;
    }
</code>```

Now in every class that needs database connection

```<code>class test {

    private $_db = null;

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
        }
</code>```

Now it gives me an error saying cannot use $this, then how i can use it using self:: ??
    }

Now how can i use it in static function and non static function together

答:
I like the straightforward answer from @WOLFF, but I'd like to help explain the error you got, so you understand in similar cases in the future.

http://php.net/manual/en/language.oop5.basic.php says:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object.

But you're trying to use $this in a static function, so there's no reference to a calling object. The pseudo-variable $this is therefore undefined.

Because you can't use $this in a static method, you can't use any object properties like your private $this->_db. You can only use static class properties in a static method.

PHP doesn't have any way of auto-initializing static properties of a class. The only way to do it is to call a static initialization method of the class before you try to use any other static methods.

```<code>class test {

    private static $_staticDb = null;
    private $_db = null;

    public static function init() {
        self::$_staticDb = Database::getInstance();
    }

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return self::$_staticDb->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

}

test::init();
print_r(test::testStatic());

$test = new test();
print_r($test->test());
</code>```

There's nothing magic about the init() static method I show in the example above. You can name the method anything you want. You just have to remember to call it yourself before using other static methods that depend on the stuff it initializes.

So why doesn't PHP have any magic method to initialize a class? There's a draft proposal to add a static class "constructor" to PHP, but it's still just a draft. It has not been implemented in any released version of PHP. There's no way to know when or if it will ever be implemented.

https://wiki.php.net/rfc/static_class_constructor

PS: FWIW, Python and Java are examples of languages that have the feature of static class initialization.

See example in Python in this question: Pythonic Way to Initialize (Complex) Static Data Members

See example in Java in this question: static variable initialization java

I know you're using PHP not those other languages, I'm just pointing out that such a thing is possible.

Body:
class Database {

    public $isConn;
    private static $_instance = null;
    private $datab;

    // connect to db
    public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
        $this->isConn = TRUE;
        try {
            $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
            $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new Database();
        }
        return self::$_instance;
    }

Now in every class that needs database connection

class test {

    private $_db = null;

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
        }

Now it gives me an error saying cannot use $this, then how i can use it using self:: ??
    }

Now how can i use it in static function and non static function together

Body:
I like the straightforward answer from @WOLFF, but I'd like to help explain the error you got, so you understand in similar cases in the future.

http://php.net/manual/en/language.oop5.basic.php says:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object.

But you're trying to use $this in a static function, so there's no reference to a calling object. The pseudo-variable $this is therefore undefined.

Because you can't use $this in a static method, you can't use any object properties like your private $this->_db. You can only use static class properties in a static method.

PHP doesn't have any way of auto-initializing static properties of a class. The only way to do it is to call a static initialization method of the class before you try to use any other static methods.

class test {

    private static $_staticDb = null;
    private $_db = null;

    public static function init() {
        self::$_staticDb = Database::getInstance();
    }

    public function __construct() {
        $this->_db = Database::getInstance();
    }

    public function test(){
       return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

   public static function testStatic(){
        return self::$_staticDb->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
    }

}

test::init();
print_r(test::testStatic());

$test = new test();
print_r($test->test());

There's nothing magic about the init() static method I show in the example above. You can name the method anything you want. You just have to remember to call it yourself before using other static methods that depend on the stuff it initializes.

So why doesn't PHP have any magic method to initialize a class? There's a draft proposal to add a static class "constructor" to PHP, but it's still just a draft. It has not been implemented in any released version of PHP. There's no way to know when or if it will ever be implemented.

https://wiki.php.net/rfc/static_class_constructor

PS: FWIW, Python and Java are examples of languages that have the feature of static class initialization.

See example in Python in this question: Pythonic Way to Initialize (Complex) Static Data Members

See example in Java in this question: static variable initialization java

I know you're using PHP not those other languages, I'm just pointing out that such a thing is possible.


来源: stackexchange

问:
How to request IdentityServer3 client access token from JavaScript?
I have an authentication service built on IdentityServer3 and a WebAPI Shopper service that is secured with IdentityServer Bearer Token Authentication. I've built a simple MVC client app that can access the Shopper service either as a client app with an access token or on behalf of an authenticated user with an identity token. The Shopper service will return more data to the authenticated user.
Now I'm trying to build a JavaScript client that does the same two-tier level of access to the Shopper service. So far, following some IdentityServer3 JavaScript client examples, I've got the JS client successfully calling the Shopper service on behalf of an authenticated user. (I will probably need to reorganize the code a bit to accommodate the non-authenticated scenario, but that shouldn't be too difficult.) What I don't know how to do from the JavaScript code is request the client access token from the Authentication service, i.e. the JavaScript equivalent of the server-side TokenClient.RequestClientCredentialsAsync("shopper-service") in the MVC client. Does anyone know how to request that token from JavaScript or know of a sample that shows how to do it? Here's the JavaScript code that I have so far for the authenticated case and below that is the working MVC client code:

```<code>function display(selector, data) {
    if (data && typeof data === 'string') {
        data = JSON.parse(data);
    }
    if (data) {
        data = JSON.stringify(data, null, 2);
    }

    $(selector).text(data);
}

var settings = {
    authority: 'https://localhost:44332',
    client_id: 'js-sample',
    popup_redirect_uri: 'http://localhost:15264/popup.html',
    response_type: 'id_token token',
    scope: 'openid orvis-shopper-service',
    filterProtocolClaims: false
};

var manager = new Oidc.UserManager(settings);
var user;

manager.events.addUserLoaded(function (loadedUser) {
    user = loadedUser;
    display('.js-user', user);
});

$('.js-login').on('click', function () {
    manager
        .signinPopup()
        .catch(function (error) {
            console.error('error while logging in through the popup', error);
        });
});

$('.js-call-api').on('click', function () {
    var headers = {};
    if (user && user.access_token) {
        headers['Authorization'] = 'Bearer ' + user.access_token;
    }

    $.ajax({
        url: 'https://localhost:44368/api/Shopper/{5FA13934-AD20-4AB2-A386-11653D71AE55}',
        method: 'GET',
        dataType: 'json',
        headers: headers
    }).then(function (data) {
        display('.js-api-result', data);
    }).catch(function (error) {
        display('.js-api-result', {
            status: error.status,
            statusText: error.statusText,
            response: error.responseJSON
        });
    });
});
</code>```

The client app code works as I intend and looks like this:

```<code>public async Task<ActionResult> Index()
{
    string tokenValue;
    var user = User as ClaimsPrincipal;
    if (user.Identity.IsAuthenticated)
    {
        tokenValue = user.FindFirst("access_token").Value;
    }
    else
    {
        var tokenResponse = await GetTokenAsync();
        tokenValue = tokenResponse.AccessToken;
    }
    var result = await CallShopperService(tokenValue);
    ViewBag.Json = result;
    return View();
}

private async Task<TokenResponse> GetTokenAsync()
{
    var client = new TokenClient(
        "https://localhost:44332/connect/token",
        "mvc-sample-svc",
        "mvcsamplesecret");

    return await client.RequestClientCredentialsAsync("shopper-service");
}

private async Task<string> CallShopperService(string token)
{
    var client = new HttpClient();
    client.SetBearerToken(token);
    var json = await client.GetStringAsync("https://localhost:44368/api/Shopper/{5FA13934-AD20-4AB2-A386-11653D71AE55}");
    return json;
}
</code>```

答:
JS implicit client is also able to get back you access token, as long as you set token in response_type which you did according to your pasted script.

The Oidc-client.js builds up an authorize challenge URL and redirect browser to it, which is where login flow begins. After user signs in, then they get bounced back to your client page following same redirect path. When your client page loaded (depends on which flow your client is configured, it should be hash fragment by default), oidc-client grabs token from URL (everything after #) and transforms it into JSON object then save in local storage (which means you can check it there too).

I would suggest following method to help you debug:

Turn on traffic monitoring tool (e.g. fiddler) to ensure response that returned back from your identity server after login does contains access token (you can decode token string using https://jwt.io/), if not, check if authorize request url formed correctly

If response returned from identity server does contains access token , then you can debug oidc-client.js javascript by setting a breakpoint at _signinEnd method

Hope it helps

Updated, from comment section

For "anonymous token" senario? See this example if that is what you are looking for github.com/IdentityServer/IdentityServer3/issues/1953

ContentLicense: CC BY-SA 3.0

Body:
I have an authentication service built on IdentityServer3 and a WebAPI Shopper service that is secured with IdentityServer Bearer Token Authentication. I've built a simple MVC client app that can access the Shopper service either as a client app with an access token or on behalf of an authenticated user with an identity token. The Shopper service will return more data to the authenticated user.
Now I'm trying to build a JavaScript client that does the same two-tier level of access to the Shopper service. So far, following some IdentityServer3 JavaScript client examples, I've got the JS client successfully calling the Shopper service on behalf of an authenticated user. (I will probably need to reorganize the code a bit to accommodate the non-authenticated scenario, but that shouldn't be too difficult.) What I don't know how to do from the JavaScript code is request the client access token from the Authentication service, i.e. the JavaScript equivalent of the server-side TokenClient.RequestClientCredentialsAsync("shopper-service") in the MVC client. Does anyone know how to request that token from JavaScript or know of a sample that shows how to do it? Here's the JavaScript code that I have so far for the authenticated case and below that is the working MVC client code:

function display(selector, data) {
    if (data && typeof data === 'string') {
        data = JSON.parse(data);
    }
    if (data) {
        data = JSON.stringify(data, null, 2);
    }

    $(selector).text(data);
}

var settings = {
    authority: 'https://localhost:44332',
    client_id: 'js-sample',
    popup_redirect_uri: 'http://localhost:15264/popup.html',
    response_type: 'id_token token',
    scope: 'openid orvis-shopper-service',
    filterProtocolClaims: false
};

var manager = new Oidc.UserManager(settings);
var user;

manager.events.addUserLoaded(function (loadedUser) {
    user = loadedUser;
    display('.js-user', user);
});

$('.js-login').on('click', function () {
    manager
        .signinPopup()
        .catch(function (error) {
            console.error('error while logging in through the popup', error);
        });
});

$('.js-call-api').on('click', function () {
    var headers = {};
    if (user && user.access_token) {
        headers['Authorization'] = 'Bearer ' + user.access_token;
    }

    $.ajax({
        url: 'https://localhost:44368/api/Shopper/{5FA13934-AD20-4AB2-A386-11653D71AE55}',
        method: 'GET',
        dataType: 'json',
        headers: headers
    }).then(function (data) {
        display('.js-api-result', data);
    }).catch(function (error) {
        display('.js-api-result', {
            status: error.status,
            statusText: error.statusText,
            response: error.responseJSON
        });
    });
});

The client app code works as I intend and looks like this:

public async Task<ActionResult> Index()
{
    string tokenValue;
    var user = User as ClaimsPrincipal;
    if (user.Identity.IsAuthenticated)
    {
        tokenValue = user.FindFirst("access_token").Value;
    }
    else
    {
        var tokenResponse = await GetTokenAsync();
        tokenValue = tokenResponse.AccessToken;
    }
    var result = await CallShopperService(tokenValue);
    ViewBag.Json = result;
    return View();
}

private async Task<TokenResponse> GetTokenAsync()
{
    var client = new TokenClient(
        "https://localhost:44332/connect/token",
        "mvc-sample-svc",
        "mvcsamplesecret");

    return await client.RequestClientCredentialsAsync("shopper-service");
}

private async Task<string> CallShopperService(string token)
{
    var client = new HttpClient();
    client.SetBearerToken(token);
    var json = await client.GetStringAsync("https://localhost:44368/api/Shopper/{5FA13934-AD20-4AB2-A386-11653D71AE55}");
    return json;
}


问:
WPF Data binding: How to data bind an enum to combo box using XAML?
I have a class:

```<code>public class AccountDetail
{
    public DetailScope Scope
    {
        get { return scope; }
        set { scope = value; }
    }

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailScope scope;
    private string value;

    public AccountDetail(DetailScope scope, string value)
    {
        this.scope = scope;
        this.value = value;
    }
}
</code>```

and an enum:

```<code>public enum DetailScope
{
    Private,
    Business,
    OtherDetail
}
</code>```

Lastly, I have a .xaml file:

```<code><Window x:Class="Gui.Wpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test"
    SizeToContent="WidthAndHeight">

    <Grid>
        <ComboBox
            Name="ScopeComboBox"
            Width="120"
            Height="23"
            Margin="12" />
    </Grid>
</Window>
</code>```

I would like to do two things:

I wish to data bind DetailsScope enum values to the combo box values. I don't wish to
bind enum values directly because the last enum value would be OtherDetail instead of
Other detail (added a space character and small letter 'd').

I wish to data bind the selected value in the combo box to the one specified in the
instance of the AccountDetail object.

Could you help me out? Thanks.

Update: I found this post http://blogs.msdn.com/b/wpfsdk/archive/2007/02/22/displaying-enum-values-using-data-binding.aspx. I need something similar.

答:
A pretty easy way to do this is to use an ObjectDataProvider

```<code><ObjectDataProvider MethodName="GetValues"
                    ObjectType="{x:Type sys:Enum}"
                    x:Key="DetailScopeDataProvider">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:DetailScope" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</code>```

Use the ObjectDataProvider as the ItemsSource for the ComboBox, bind SelectedItem to the Scope property and apply a converter for the display of each ComboBoxItem

```<code><ComboBox Name="ScopeComboBox"
          ItemsSource="{Binding Source={StaticResource DetailScopeDataProvider}}"
          SelectedItem="{Binding Scope}"
          Width="120"
          Height="23"
          Margin="12">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource CamelCaseConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

And in the converter you can use Regex for CamelCase string splitter found in this question. I used the most advanced version but you can probably use a simplier one. OtherDetail + the regex = Other Detail. Making return value lower and then return a string with first Character UpperCase should give you expected result

```<code>public class CamelCaseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string enumString = value.ToString();
        string camelCaseString = Regex.Replace(enumString, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ").ToLower();
        return char.ToUpper(camelCaseString[0]) + camelCaseString.Substring(1);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a class:

public class AccountDetail
{
    public DetailScope Scope
    {
        get { return scope; }
        set { scope = value; }
    }

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    private DetailScope scope;
    private string value;

    public AccountDetail(DetailScope scope, string value)
    {
        this.scope = scope;
        this.value = value;
    }
}

and an enum:

public enum DetailScope
{
    Private,
    Business,
    OtherDetail
}

Lastly, I have a .xaml file:

<Window x:Class="Gui.Wpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Test"
    SizeToContent="WidthAndHeight">

    <Grid>
        <ComboBox
            Name="ScopeComboBox"
            Width="120"
            Height="23"
            Margin="12" />
    </Grid>
</Window>

I would like to do two things:

I wish to data bind DetailsScope enum values to the combo box values. I don't wish to
bind enum values directly because the last enum value would be OtherDetail instead of
Other detail (added a space character and small letter 'd').

I wish to data bind the selected value in the combo box to the one specified in the
instance of the AccountDetail object.

Could you help me out? Thanks.

Update: I found this post http://blogs.msdn.com/b/wpfsdk/archive/2007/02/22/displaying-enum-values-using-data-binding.aspx. I need something similar.

Body:
A pretty easy way to do this is to use an ObjectDataProvider

<ObjectDataProvider MethodName="GetValues"
                    ObjectType="{x:Type sys:Enum}"
                    x:Key="DetailScopeDataProvider">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="local:DetailScope" />
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

Use the ObjectDataProvider as the ItemsSource for the ComboBox, bind SelectedItem to the Scope property and apply a converter for the display of each ComboBoxItem

<ComboBox Name="ScopeComboBox"
          ItemsSource="{Binding Source={StaticResource DetailScopeDataProvider}}"
          SelectedItem="{Binding Scope}"
          Width="120"
          Height="23"
          Margin="12">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource CamelCaseConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And in the converter you can use Regex for CamelCase string splitter found in this question. I used the most advanced version but you can probably use a simplier one. OtherDetail + the regex = Other Detail. Making return value lower and then return a string with first Character UpperCase should give you expected result

public class CamelCaseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string enumString = value.ToString();
        string camelCaseString = Regex.Replace(enumString, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ").ToLower();
        return char.ToUpper(camelCaseString[0]) + camelCaseString.Substring(1);
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }
}


问:
"Valid CSRF Token Required" in Osticket After login?
My osTicket Version 1.10 is installed in PLESK Windows Server. I have tried to install XAMPP on the PLESK Windows Server but not able to start XAMPP .

Soon I get error after login  to osTicket "Valid CSRF Token Required in Osticket After login" which was earlier working fine

After login I get this error:

答: I had the same problem with PHP 7.1.1, then I changed to 7.0.15 and it worked</p>


问:
LocalDate in form
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

```<code>@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields
</code>```

Thymeleaf view / form:

```<code><form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>
</code>```

What's the reason for this problem? Maybe there is the other, better way to storage date?

答:
I'm unable to reproduce the exact error, but I believe that adding a custom editor for the LocalDate class should fix this.  Add this method to your controller:

```<code>@InitBinder
protected void initBinder(WebDataBinder binder) {
  binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
    @Override
    public void setAsText(String text) throws IllegalArgumentException{
      setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

    @Override
    public String getAsText() throws IllegalArgumentException {
      return DateTimeFormatter.ofPattern("yyyy-MM-dd").format((LocalDate) getValue());
    }
  });
}
</code>```

It's also possible to add this globally, you'll have to create a ControllerAdvice class and add the method there instead.

Title: LocalDate in form

Body:
I have a question about Spring + Thymeleaf date format.
I have a simple entity with LocalDate date field. I want to get this date from a user in form and save it to MySQL database.
I'm getting such an error:

Failed to convert property value of type java.lang.String to required type java.time.LocalDate for property date; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.time.LocalDate for value 2019-04-30; nested exception is java.time.format.DateTimeParseException: Text 2019-04-30 could not be parsed at index 2

My entity:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields

Thymeleaf view / form:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">

Date: <input type="date" th:field="*{date}" />

</form>

What's the reason for this problem? Maybe there is the other, better way to storage date?

Body:
I'm unable to reproduce the exact error, but I believe that adding a custom editor for the LocalDate class should fix this.  Add this method to your controller:

@InitBinder
protected void initBinder(WebDataBinder binder) {
  binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
    @Override
    public void setAsText(String text) throws IllegalArgumentException{
      setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    }

    @Override
    public String getAsText() throws IllegalArgumentException {
      return DateTimeFormatter.ofPattern("yyyy-MM-dd").format((LocalDate) getValue());
    }
  });
}

It's also possible to add this globally, you'll have to create a ControllerAdvice class and add the method there instead.


问:
Numpy reduce multiple operations for hashing
I'm trying to implement some hashing functions for numpy arrays to easily find these inside a big list of arrays, but almost every hashing function I find needs to make a reduce with more than one operation, for example:

```<code>def fnv_hash (arr):
    result = FNV_offset_basis
    for v in arr.view(dtype = np.uint8):
        result *= FNV_prime
        result ^= v
    return result
</code>```

It would take two operations to the result variable in each loop, which (I think) is not possible using only reduce calls in numpy functions (i.e. numpy.ufunc.reduce).

I want to avoid basic loops as they do not treat numpy arrays as memory regions (which is slow) and I don't want to use hashlib functions. Also, converting a function using numpy.vectorize and similar (which is just a for loop as said in the documentation) does not helps performance.

Unfortunately I cannot use numba.jit because, as I'm working with large arrays, I need to run my code in a cluster which doesn't have numba installed. The same happens for xxhash.

My solution so far is to use a simple hashing function as

```<code>def my_hash (arr):
    indices = np.arange(arr.shape[0])
    return int((arr * ((1 << (indices * 5)) - indices)).sum())
</code>```

Which is kinda fast (this isn't the actual function code, I made some optimizations in my script but I can assure you the output is the same), but it makes some unwanted collisions.

In short: I want to implement a good hashing function using only numpy operations, as my arrays and my search space are enormous.

Thanks in advance.

答:
Since your arrays are enormous, but you don't have many of them, did you try hashing just a part of each array? For example, even if arr is huge, hash(tuple(arr[:10e5])) is ~60ms on my machine and is probably unique enough to distinguish 10k different arrays, depending on how they were generated.

If this won't solve your problem, any additional context you can give on your problem would be helpful. How and when are these arrays generated? Why are you trying to hash them?

Body:
I'm trying to implement some hashing functions for numpy arrays to easily find these inside a big list of arrays, but almost every hashing function I find needs to make a reduce with more than one operation, for example:

def fnv_hash (arr):
    result = FNV_offset_basis
    for v in arr.view(dtype = np.uint8):
        result *= FNV_prime
        result ^= v
    return result

It would take two operations to the result variable in each loop, which (I think) is not possible using only reduce calls in numpy functions (i.e. numpy.ufunc.reduce).

I want to avoid basic loops as they do not treat numpy arrays as memory regions (which is slow) and I don't want to use hashlib functions. Also, converting a function using numpy.vectorize and similar (which is just a for loop as said in the documentation) does not helps performance.

Unfortunately I cannot use numba.jit because, as I'm working with large arrays, I need to run my code in a cluster which doesn't have numba installed. The same happens for xxhash.

My solution so far is to use a simple hashing function as

def my_hash (arr):
    indices = np.arange(arr.shape[0])
    return int((arr * ((1 << (indices * 5)) - indices)).sum())

Which is kinda fast (this isn't the actual function code, I made some optimizations in my script but I can assure you the output is the same), but it makes some unwanted collisions.

In short: I want to implement a good hashing function using only numpy operations, as my arrays and my search space are enormous.

Thanks in advance.


问:
Architecture for Authentication/Authorization of Mobile and Web Users
This seems to be a reoccurring problem for me as I seem to gravitate around mobile applications the last few years. I want to authenticate and authorize mobile users in addition to web users. I need to make this seamless enough so that users can ease into having a web account without causing interruption to their data. I want the solution to be architectural in topic, not specific to any language/framework.

Requirements/Assumptions

Mobile users must be able to use the native application without a login, including for contributing content (marking favorites, uploading photos, etc).

Mobile user should be securely and uniquely authenticating to the web service even without specifying account credentials.

Mobile user may have multiple devices, which will be unaware of each other.

Mobile user should be able to Register/Login, which should roll in any content into the account's ownership. This "synchronization" should occur with each account that is subsequently logged in.

It should not matter whether an account was created on mobile or web.

Architectures Considered

NO SHIRT, NO SHOES, NO LOGIN = NO CONTRIBUTION. Require login to contribute content of any kind. This prevents the need to "synchronize" device accounts with a master account. Simply require a single username/password + tokens in order for devices to login. Server objects: User, Role

Multi-device self-authentication. Server negotiates with device and hands it credentials which the device stores. Each device self-authenticates and is associated with an anonymous account until Register/Login occurs. If Register occurs, anonymous account is converted into known account. If Login occurs, content from anonymous account is moved over to known account and then thrown away. Devices that lose the self-authentication details will get new authentication details, and the previous anonymous account is abandoned (and then hopefully later thrown away) and not restorable since it was never converted into a known account. Server objects: User, Role, Device

What do you think is a good solution? One of these, or something else?

答:
Number 2 is good enough as base decision. Users hate registration ;) So ability to use service without registration is good idea.

You can use GUID/UUID to identify devise. And use it as anonymous login before user login.

But what to do if 2 (or more) people use 1 device? Or device will be losed, stolen?
I think no one of the points cover these cases.

I have no idea what kind of web service you architect so can't advise more.


问:
Calling a phone number in swift
I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!</p>

```<code>    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }
</code>```

答:
Swift 3.0 & iOS 10+

UIApplication.shared.openURL(url)
was changed to
UIApplication.shared.open(_ url: URL, options:[:], completionHandler completion: nil)

options and completion handler are optional, rendering:

UIApplication.shared.open(url)

https://developer.apple.com/reference/uikit/uiapplication/1648685-open

Title: Calling a phone number in swift

Body:
I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!

    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }


问:
Prevent click events in a FrameLayout
I have a FrameLayout, inside the FrameLayout I have two views, one a is a ViewPager and the other is a LinearLayout, the LinearLayout acts like a window, so it has some buttons. I show and hide the LinearLayout using the visibility property. The problem is when I show the LinearLayout, it covers the ViewPager but the user can still scroll the ListView inside the ViewPager. I want to prevent all the click events to the view behind.

The XML looks something like this:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/colorBeige"
          android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_diner_food"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:titleTextColor="@android:color/white"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"/>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout_diner_food"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/white"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager_diner_food"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linea_layout_filter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlackAlpha">

        <com.wonderkiln.blurkit.BlurLayout
            android:id="@+id/blurLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipChildren="true"
                android:orientation="vertical">

                <SeekBar
                    android:id="@+id/seek_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="61dp"/>
            </LinearLayout>
        </com.wonderkiln.blurkit.BlurLayout>
    </LinearLayout>
</FrameLayout>
</code>```

答:
Add an onTouchEvent method to the view with top position then return true. True will tell the event bubbling that the event was consumed therefore prevent event from bubbling to other views.

```<code>protected boolean onTouchEvent (MotionEvent me) {
    return true;
}
</code>```

that to prevent scrolling underneath ListView
And to disable any clicking you can use

```<code>view.setClickable(false);
</code>```

Title: Prevent click events in a FrameLayout

Body:
I have a FrameLayout, inside the FrameLayout I have two views, one a is a ViewPager and the other is a LinearLayout, the LinearLayout acts like a window, so it has some buttons. I show and hide the LinearLayout using the visibility property. The problem is when I show the LinearLayout, it covers the ViewPager but the user can still scroll the ListView inside the ViewPager. I want to prevent all the click events to the view behind.

The XML looks something like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/colorBeige"
          android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_diner_food"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:titleTextColor="@android:color/white"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"/>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout_diner_food"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/white"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager_diner_food"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linea_layout_filter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlackAlpha">

        <com.wonderkiln.blurkit.BlurLayout
            android:id="@+id/blurLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipChildren="true"
                android:orientation="vertical">

                <SeekBar
                    android:id="@+id/seek_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="61dp"/>
            </LinearLayout>
        </com.wonderkiln.blurkit.BlurLayout>
    </LinearLayout>
</FrameLayout>

Body:
Add an onTouchEvent method to the view with top position then return true. True will tell the event bubbling that the event was consumed therefore prevent event from bubbling to other views.

protected boolean onTouchEvent (MotionEvent me) {
    return true;
}

that to prevent scrolling underneath ListView
And to disable any clicking you can use

view.setClickable(false);


问:
Does omniauth-saml support only SHA1?
We would like to update the certificate that we use with our SAML integrations to SHA256.  We're using the omniauth-saml and ruby-saml gems to implement SSO.

Based on this code, it looks like omniauth-saml assumes that the IdP's certificate uses SHA1.
https://github.com/omniauth/omniauth-saml/blob/master/lib/omniauth/strategies/saml.rb#L96

So, two questions:
1) Is there any way to allow the IdP to use a different hashing algorithm with omniauth-saml?
2) Would it work for us to upgrade our cert to SHA256, while still leaving the IdP's cert on SHA1?

答:
Looks tadman is right, and the answer to my question is that code does not mean that omniauth-saml does not support other hashing algorithms.

What that code says is: use the SHA1 algorithm to generate a fingerprint.  It does not care what algorithm was used to generate the original certificate.

Title: Does omniauth-saml support only SHA1?


问:
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
Using the function I wrote in Python 2, I was trying to concatenate csv files:

```<code>def concat_csv():
    """
    A function to concatenate the previously wrangled csv files in current working dir
    """
    with open('2017_oldnew.csv', 'a') as f_out:
        # First file
        with open('old.csv') as f_read:
            for line in f_read:
                f_out.write(line)
        # Second file
        with open('new.csv') as f_read:
            f_read.next()
            for line in f_read:
                f_out.write(line)
</code>```

However, running this Python 3 gives me an error message:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-110-a5a430e1b905> in <module>()
      1 # Concatenate the files
----> 2 concat_csv()

<ipython-input-109-9a5ae77e9dd8> in concat_csv()
     10         # Second file
     11         with open('new.csv') as f_read:
---> 12             f_read.next()
     13             for line in f_read:
     14                 f_out.write(line)

AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
</code>```

答:
It turns out that in Python 3, the syntax has changed. Instead of using next as a method, we need to use it as a function as below:

```<code>next(f_read)
</code>```

which fixes the problem immediately.

Body:
Using the function I wrote in Python 2, I was trying to concatenate csv files:

def concat_csv():
    """
    A function to concatenate the previously wrangled csv files in current working dir
    """
    with open('2017_oldnew.csv', 'a') as f_out:
        # First file
        with open('old.csv') as f_read:
            for line in f_read:
                f_out.write(line)
        # Second file
        with open('new.csv') as f_read:
            f_read.next()
            for line in f_read:
                f_out.write(line)

However, running this Python 3 gives me an error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-110-a5a430e1b905> in <module>()
      1 # Concatenate the files
----> 2 concat_csv()

<ipython-input-109-9a5ae77e9dd8> in concat_csv()
     10         # Second file
     11         with open('new.csv') as f_read:
---> 12             f_read.next()
     13             for line in f_read:
     14                 f_out.write(line)

AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

Body:
It turns out that in Python 3, the syntax has changed. Instead of using next as a method, we need to use it as a function as below:

next(f_read)

which fixes the problem immediately.


问:
Spring Data and stored procedures
I have a stored procedure with the following declaration:

```<code>CREATE PROCEDURE GetAttributesForCategory(IN catId BIGINT(20))
</code>```

In my Spring Boot-backed app there is an entity:

```<code>@Entity
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(
                name = "ProductAttribute.getAttributesForCategory",
                procedureName = "GetAttributesForCategory",
                parameters = {
                        @StoredProcedureParameter(name = "catId",
                                                    type = Long.class,
                                                    mode = ParameterMode.IN)
                }
        )
})
public class ProductAttribute {
    ...
}
</code>```

And the correspondent repository looks like:

```<code>public interface ProductAttributeReposirory extends JpaRepository<ProductAttribute, Long> {

    @Procedure(name = "getAttributesForCategory")
    List<ProductAttribute> getAttributesForCategory(@Param("catId") Long catId);
}
</code>```

All is made according to this example, but an exception is occurred during Spring context loading:

```<code>org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productAttributeRepository': Invocation of init method failed;
nested exception is org.springframework.data.mapping.PropertyReferenceException:
No property getAttributesForCategory found for type ProductAttribute!
</code>```

I can't imagine what goes wrong. Anybody can?

答:
I was having the same issue with this, and resolved it by adding an OUT @StoredProcedureParameter:

@StoredProcedureParameter(mode = ParameterMode.IN, name = "inVar", type = String.class),
@StoredProcedureParameter(mode = ParameterMode.OUT, name = "outVar", type = ArrayList.class)

though at this point I'm getting a different error "Parameter index of 2 is out of range"

Title: Spring Data and stored procedures

Body:
I have a stored procedure with the following declaration:

CREATE PROCEDURE GetAttributesForCategory(IN catId BIGINT(20))

In my Spring Boot-backed app there is an entity:

@Entity
@NamedStoredProcedureQueries({
        @NamedStoredProcedureQuery(
                name = "ProductAttribute.getAttributesForCategory",
                procedureName = "GetAttributesForCategory",
                parameters = {
                        @StoredProcedureParameter(name = "catId",
                                                    type = Long.class,
                                                    mode = ParameterMode.IN)
                }
        )
})
public class ProductAttribute {
    ...
}

And the correspondent repository looks like:

public interface ProductAttributeReposirory extends JpaRepository<ProductAttribute, Long> {

    @Procedure(name = "getAttributesForCategory")
    List<ProductAttribute> getAttributesForCategory(@Param("catId") Long catId);
}

All is made according to this example, but an exception is occurred during Spring context loading:

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'productAttributeRepository': Invocation of init method failed;
nested exception is org.springframework.data.mapping.PropertyReferenceException:
No property getAttributesForCategory found for type ProductAttribute!

I can't imagine what goes wrong. Anybody can?


问:
How to disable shordcode in a category description backend, in admin area?
I have enabled shortcodes in pretty much everywhere by adding this line:

```<code>add_filter( 'term_description', 'do_shortcode' );
</code>```

Unfortunately it now shows in admin area, in the category tab, in the description of a category where the shortcode is present. I only want it to be executed on an actual page, I don't need to preview it in the admin area.

Is there a way of disabling it being executed in the admin area?

答:
https://codex.wordpress.org/Function_Reference/is_admin

Is this what you're seeking?

```<code>if( is_admin() == false )
{
  add_filter( 'term_description', 'do_shortcode' );
}
</code>```

Body:
I have enabled shortcodes in pretty much everywhere by adding this line:

add_filter( 'term_description', 'do_shortcode' );

Unfortunately it now shows in admin area, in the category tab, in the description of a category where the shortcode is present. I only want it to be executed on an actual page, I don't need to preview it in the admin area.

Is there a way of disabling it being executed in the admin area?

Body:
https://codex.wordpress.org/Function_Reference/is_admin

Is this what you're seeking?

if( is_admin() == false )
{
  add_filter( 'term_description', 'do_shortcode' );
}


问:
How do I calculate an array of very large numbers without getting NaN in my output?
I made a calculator that works for small numbers but when the results get too large it returns NaN

```<code>List<string> memory = new List<string> { };

string display = "";
while (display.Contains("%") == false)
{
    string line = ReadLine();
    display = line;
    memory.Add(line);
}

float result = float.Parse(memory[0]);

for (int i = 1; i < memory.Count; i++)
{
    string temp = memory[i];
    char[] _temp = temp.ToCharArray();
    _temp = _temp.Where(x => x > _temp[0]).ToArray();
    float num = float.Parse(string.Join("", _temp));

    if (temp.Contains("+") == true) result += num;
    else if (temp.Contains("-") == true) result -= num;
    else if (temp.Contains("*") == true) result *= num;
    else if (temp.Contains("/") == true) result /= num;
    else if (temp.Contains("%") == true) result %= num;
}
</code>```

Take these numbers for example:

```<code>797 * 2 + 38 * 212 * 275 * 806 * 67 * 9939 + 7 + 74 + 515 + 610 * 516 * 6921
+ 4 * 2 * 494 * 3153 * 8 + 2501 * 769 + 4 * 2472 + 1 * 21 * 6535 + 30 + 26
+ 44 + 240 + 88 * 1111 * 817 * 1576 + 551 * 535 + 9150 + 36 * 85 * 4598
* 9276 * 766 + 584 + 5 * 1 + 7 + 45 * 8152 % 7984
</code>```

I enter each number in a new readline with the math symbol infront of it.
If you test it with these numbers just be aware.

I've looked everywhere and cant figure out a solution to this problem so that it can return a real number.

Anyone know what I can do to fix this?

答:
The following limits apply:

Float: 7 digits (32 bit)

Double: 15-16 digits (64 bit)

Decimal: 28-29 significant digits (128 bit)

Body:
I made a calculator that works for small numbers but when the results get too large it returns NaN

List<string> memory = new List<string> { };

string display = "";
while (display.Contains("%") == false)
{
    string line = ReadLine();
    display = line;
    memory.Add(line);
}

float result = float.Parse(memory[0]);

for (int i = 1; i < memory.Count; i++)
{
    string temp = memory[i];
    char[] _temp = temp.ToCharArray();
    _temp = _temp.Where(x => x > _temp[0]).ToArray();
    float num = float.Parse(string.Join("", _temp));

    if (temp.Contains("+") == true) result += num;
    else if (temp.Contains("-") == true) result -= num;
    else if (temp.Contains("*") == true) result *= num;
    else if (temp.Contains("/") == true) result /= num;
    else if (temp.Contains("%") == true) result %= num;
}

Take these numbers for example:

797 * 2 + 38 * 212 * 275 * 806 * 67 * 9939 + 7 + 74 + 515 + 610 * 516 * 6921
+ 4 * 2 * 494 * 3153 * 8 + 2501 * 769 + 4 * 2472 + 1 * 21 * 6535 + 30 + 26
+ 44 + 240 + 88 * 1111 * 817 * 1576 + 551 * 535 + 9150 + 36 * 85 * 4598
* 9276 * 766 + 584 + 5 * 1 + 7 + 45 * 8152 % 7984

I enter each number in a new readline with the math symbol infront of it.
If you test it with these numbers just be aware.

I've looked everywhere and cant figure out a solution to this problem so that it can return a real number.

Anyone know what I can do to fix this?


问:
Trouble downloading images into array from Firebase
Here is the code I'm having trouble with.

Shared:

```<code>// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()
</code>```

Upload:

```<code>let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)
</code>```

}

Download:

```<code>let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
 })
})
</code>```

I've been trying to use the above code posted originally by @Mike-McDonald a few months ago, to pull and append an array of images from my Firebase DB.  I am successfully able to upload images using the above, but for the life of me, I cannot get the images to download, nor append to an images array.

I'm not getting any errors - it's just that simply the "download" code does not appear to be running (I've tried to verify this in the console as well).  A couple of lines are different for Swift 3, but the only one that I'm unsure about is:

```<code>let storageRef = storage.referenceFromURL(downloadURL)
</code>```

is now

```<code>let storageRef = self.storage.reference(forURL: downloadURL)
</code>```

Any suggestions on this, or on how to create/append an array of images using the childadded observer with Firebase would be appreciated. Thanks!

答:
Looks fine to me except that you have to update to data(withMaxSize:completion), observe(_:with:) and use reference(forURL:) like you already mentioned. So you need the code to update to this:

```<code>let dbRef = database.reference().child("myFiles")
dbRef.observe(.childAdded, with: { (snaphot) in
  // Get download URL from snapshot
  let downloadURL = snapshot.value() as! String
  // Create a storage reference from the URL
  let storageRef = storage.reference(forURL: downloadURL)
  // Download the data, assuming a max size of 1MB (you can change this as necessary)
  storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
    let pic = UIImage(data: data!)
    picArray.append(pic)
  }
})
</code>```

Body:
Here is the code I'm having trouble with.

Shared:

// Firebase services
var database: FIRDatabase!
var storage: FIRStorage!
...
// Initialize Database, Auth, Storage
database = FIRDatabase.database()
storage = FIRStorage.storage()
...
// Initialize an array for your pictures
var picArray: [UIImage]()

Upload:

let fileData = NSData() // get data...
let storageRef = storage.reference().child("myFiles/myFile")
storageRef.putData(fileData).observeStatus(.Success) { (snapshot) in
// When the image has successfully uploaded, we get it's download URL
let downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
// Write the download URL to the Realtime Database
let dbRef = database.reference().child("myFiles/myFile")
dbRef.setValue(downloadURL)

}

Download:

let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
 })
})

I've been trying to use the above code posted originally by @Mike-McDonald a few months ago, to pull and append an array of images from my Firebase DB.  I am successfully able to upload images using the above, but for the life of me, I cannot get the images to download, nor append to an images array.

I'm not getting any errors - it's just that simply the "download" code does not appear to be running (I've tried to verify this in the console as well).  A couple of lines are different for Swift 3, but the only one that I'm unsure about is:

let storageRef = storage.referenceFromURL(downloadURL)

is now

let storageRef = self.storage.reference(forURL: downloadURL)

Any suggestions on this, or on how to create/append an array of images using the childadded observer with Firebase would be appreciated. Thanks!

Body:
Looks fine to me except that you have to update to data(withMaxSize:completion), observe(_:with:) and use reference(forURL:) like you already mentioned. So you need the code to update to this:

let dbRef = database.reference().child("myFiles")
dbRef.observe(.childAdded, with: { (snaphot) in
  // Get download URL from snapshot
  let downloadURL = snapshot.value() as! String
  // Create a storage reference from the URL
  let storageRef = storage.reference(forURL: downloadURL)
  // Download the data, assuming a max size of 1MB (you can change this as necessary)
  storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
    let pic = UIImage(data: data!)
    picArray.append(pic)
  }
})


问:
Single row (or column) heat map in python
I can create and n by n heatmap using the following code, for example let n be 10:

```<code>random_matrix = np.random.rand(10,10)
number = 10
incrmnt = 1.0
x = list(range(1,number +1))
plt.pcolormesh(x, x, random_matrix)
plt.colorbar()
plt.xlim(1, number)
plt.xlabel('Number 1')
plt.ylim(1, number)
plt.ylabel('Number 2')
plt.tick_params(
    axis = 'both',
    which = 'both',
    bottom = 'off',
    top = 'off',
    labelbottom = 'off',
    right = 'off',
    left = 'off',
    labelleft = 'off')
</code>```

I would like to add a 2 row heatmap one near each of the x and y axis, from say row1 = np.random.rand(1,10)and col1 = np.random.rand(1,10).
Here is an example image of what I would like to produce:

Thanks in advance.

答:
You would create a subplot grid where the width- and height ratios between the subplots correspond to the number of pixels in the respective dimension. You can then add respective plots to those subplots. In the code below I used an imshow plot, because I find it more intuitive to have one pixel per item in the array (instead of one less).

In order to have the colorbar represent the colors accross the different subplots, one can use a matplotlib.colors.Normalize instance, which is provided to each of the subplots, as well as the manually created ScalarMappable for the colorbar.

```<code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np

m = np.random.rand(10,10)
x = np.random.rand(1,m.shape[1])
y = np.random.rand(m.shape[0],1)

norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
grid = dict(height_ratios=[1, m.shape[0]], width_ratios=[1,m.shape[0], 0.5 ])
fig, axes = plt.subplots(ncols=3, nrows=2, gridspec_kw = grid)

axes[1,1].imshow(m, aspect="auto", cmap="viridis", norm=norm)
axes[0,1].imshow(x, aspect="auto", cmap="viridis", norm=norm)
axes[1,0].imshow(y, aspect="auto", cmap="viridis", norm=norm)

axes[0,0].axis("off")
axes[0,2].axis("off")

axes[1,1].set_xlabel('Number 1')
axes[1,1].set_ylabel('Number 2')
for ax in [axes[1,1], axes[0,1], axes[1,0]]:
    ax.set_xticks([]); ax.set_yticks([])

sm = matplotlib.cm.ScalarMappable(cmap="viridis", norm=norm)
sm.set_array([])

fig.colorbar(sm, cax=axes[1,2])

plt.show()
</code>```

Body:
I can create and n by n heatmap using the following code, for example let n be 10:

random_matrix = np.random.rand(10,10)
number = 10
incrmnt = 1.0
x = list(range(1,number +1))
plt.pcolormesh(x, x, random_matrix)
plt.colorbar()
plt.xlim(1, number)
plt.xlabel('Number 1')
plt.ylim(1, number)
plt.ylabel('Number 2')
plt.tick_params(
    axis = 'both',
    which = 'both',
    bottom = 'off',
    top = 'off',
    labelbottom = 'off',
    right = 'off',
    left = 'off',
    labelleft = 'off')

I would like to add a 2 row heatmap one near each of the x and y axis, from say row1 = np.random.rand(1,10)and col1 = np.random.rand(1,10).
Here is an example image of what I would like to produce:

Thanks in advance.

Body:
You would create a subplot grid where the width- and height ratios between the subplots correspond to the number of pixels in the respective dimension. You can then add respective plots to those subplots. In the code below I used an imshow plot, because I find it more intuitive to have one pixel per item in the array (instead of one less).

In order to have the colorbar represent the colors accross the different subplots, one can use a matplotlib.colors.Normalize instance, which is provided to each of the subplots, as well as the manually created ScalarMappable for the colorbar.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

m = np.random.rand(10,10)
x = np.random.rand(1,m.shape[1])
y = np.random.rand(m.shape[0],1)

norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
grid = dict(height_ratios=[1, m.shape[0]], width_ratios=[1,m.shape[0], 0.5 ])
fig, axes = plt.subplots(ncols=3, nrows=2, gridspec_kw = grid)

axes[1,1].imshow(m, aspect="auto", cmap="viridis", norm=norm)
axes[0,1].imshow(x, aspect="auto", cmap="viridis", norm=norm)
axes[1,0].imshow(y, aspect="auto", cmap="viridis", norm=norm)

axes[0,0].axis("off")
axes[0,2].axis("off")

axes[1,1].set_xlabel('Number 1')
axes[1,1].set_ylabel('Number 2')
for ax in [axes[1,1], axes[0,1], axes[1,0]]:
    ax.set_xticks([]); ax.set_yticks([])

sm = matplotlib.cm.ScalarMappable(cmap="viridis", norm=norm)
sm.set_array([])

fig.colorbar(sm, cax=axes[1,2])

plt.show()


问:
amazon S3 upload API is sensitive to http post parameter ordering
I've created a bucket where policy makes it mandatory to specify the content-type of the object being uploaded. If I specify the content-type after file element, (example below)

```<code><form action="..">
...
<input type='file' name='file' />
<input name='content-type' value='image/jpeg' />
<input type='submit' />
</form>
</code>```

it returns following error

```<code><Error>
    <Code>AccessDenied</Code>
    <Message>Invalid according to Policy: Policy Condition failed: ["starts-with", "$Content-Type", ""]</Message>
    <RequestId>15063EB427B4A469</RequestId>
    <HostId>yEzAPF4Z2inaafhcqyQ4ooLVKdwnsrwqQhnYg6jm5hPQWSOLtPTuk0t9hn+zkBEbk+rP4S5Nfvs=</HostId>
</Error>
</code>```

If I specify content-type before file element, upload works as expected. I encountered this behaviour for the first time. I have a few questions regarding it.

Is it part of some specification where clients and all intermediate proxies are supposed to maintain order of http post params? Please point me to it.

Why would you make your API be aware of such ordering? In this particular case I can guess that the file can be huge and unless you are seeing all expected params before, you should immediately return failure. Please correct me if my understanding is not correct.

答:
It is part of the spec that the parts are sent as ordered in the form.  There is no reason to believe that reordering by an intermediate proxy would be allowed.

The form data and boundaries (excluding the contents of the file) cannot exceed 20K.

...

The file or content must be the last field in the form.

http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTForms.html#sigv4-HTTPPOSTFormFields

The logical assumption is that this design allows S3 to reject invalid uploads early.

Body:
I've created a bucket where policy makes it mandatory to specify the content-type of the object being uploaded. If I specify the content-type after file element, (example below)

<form action="..">
...
<input type='file' name='file' />
<input name='content-type' value='image/jpeg' />
<input type='submit' />
</form>

it returns following error

<Error>
    AccessDenied
    <Message>Invalid according to Policy: Policy Condition failed: ["starts-with", "$Content-Type", ""]</Message>
    <RequestId>15063EB427B4A469</RequestId>
    <HostId>yEzAPF4Z2inaafhcqyQ4ooLVKdwnsrwqQhnYg6jm5hPQWSOLtPTuk0t9hn+zkBEbk+rP4S5Nfvs=</HostId>
</Error>

If I specify content-type before file element, upload works as expected. I encountered this behaviour for the first time. I have a few questions regarding it.

Is it part of some specification where clients and all intermediate proxies are supposed to maintain order of http post params? Please point me to it.

Why would you make your API be aware of such ordering? In this particular case I can guess that the file can be huge and unless you are seeing all expected params before, you should immediately return failure. Please correct me if my understanding is not correct.


问:
Number guessing game play again
Im having problems making my game play again. I have a boolean variable but when i enter yes or no the program just ends. Im having trouble making it restart the //Game loop. My boolean doesn't execute anything at the moment

```<code>    //Game

    System.out.println("Pick a number between 1-100");

    Scanner keyboard = new Scanner(System.in);
    Random rand = new Random();
    int number = rand.nextInt(100)+1;
    int round = 0;
    int count = 0;
    int guess = 0;
    int win = 0;

    while(win == 0)
    {
        round++;
        System.out.println("Round " + round);

        System.out.print("What is your first guess? ");
        guess = keyboard.nextInt();
        count++;

        if (guess == number)
        {
            if (count == 1)
            {
                System.out.println("You win in " + count + " guess.");
                ++win;
                break;
            }
        }
        else if (guess > number)
        {
            System.out.println("That's too high. Try again: ");
        }
        else if (guess < number)
        {
            System.out.println("That's too low. Try again: ");
        }

    }

    //Ask to play again
    boolean isValidAnswer;
    do
    {
        System.out.print("Would you like to play again (yes/no)? ");
        String playAgain = keyboard.next().toUpperCase();
        isValidAnswer= playAgain.equals("YES") || playAgain.equals("NO");
        if(! isValidAnswer)
        {
            System.out.println("Error: Please enter yes or no");
            System.out.println();
        }
    }while(!isValidAnswer);
}
</code>```

}

答:
You are incrementing the round before the user wins the guess which is incorrect, so place it inside the if block which means that it will be incremented only when the guess is right as shown below, also initialize the round to 1 during the start of the game.

```<code>    int round = 1;
    int count = 0;
    int guess = 0;
    int win = 0;
    boolean showRound=true;
    while(win == 0) {
        if(showRound) {
            System.out.println("Round " + round);
        }
        System.out.print("What is your first guess? ");
        guess = Integer.parseInt(keyboard.nextLine());//Use scanner.nextLine()
        count++;

        if (guess == number) {
            showRound = true;
            round++;//Increment the round only after win
            System.out.println("You win in " + count + " guess.");
            ++win;
            break;
        } else if (guess > number) {
            System.out.println("That's too high. Try again: ");
            showRound=false;
        } else if (guess < number) {
            System.out.println("That's too low. Try again: ");
            showRound=false;
        }
    }
</code>```

Title: Number guessing game play again

Body:
Im having problems making my game play again. I have a boolean variable but when i enter yes or no the program just ends. Im having trouble making it restart the //Game loop. My boolean doesn't execute anything at the moment

    //Game

    System.out.println("Pick a number between 1-100");

    Scanner keyboard = new Scanner(System.in);
    Random rand = new Random();
    int number = rand.nextInt(100)+1;
    int round = 0;
    int count = 0;
    int guess = 0;
    int win = 0;

    while(win == 0)
    {
        round++;
        System.out.println("Round " + round);

        System.out.print("What is your first guess? ");
        guess = keyboard.nextInt();
        count++;

        if (guess == number)
        {
            if (count == 1)
            {
                System.out.println("You win in " + count + " guess.");
                ++win;
                break;
            }
        }
        else if (guess > number)
        {
            System.out.println("That's too high. Try again: ");
        }
        else if (guess < number)
        {
            System.out.println("That's too low. Try again: ");
        }

    }

    //Ask to play again
    boolean isValidAnswer;
    do
    {
        System.out.print("Would you like to play again (yes/no)? ");
        String playAgain = keyboard.next().toUpperCase();
        isValidAnswer= playAgain.equals("YES") || playAgain.equals("NO");
        if(! isValidAnswer)
        {
            System.out.println("Error: Please enter yes or no");
            System.out.println();
        }
    }while(!isValidAnswer);
}

}

Body:
You are incrementing the round before the user wins the guess which is incorrect, so place it inside the if block which means that it will be incremented only when the guess is right as shown below, also initialize the round to 1 during the start of the game.

    int round = 1;
    int count = 0;
    int guess = 0;
    int win = 0;
    boolean showRound=true;
    while(win == 0) {
        if(showRound) {
            System.out.println("Round " + round);
        }
        System.out.print("What is your first guess? ");
        guess = Integer.parseInt(keyboard.nextLine());//Use scanner.nextLine()
        count++;

        if (guess == number) {
            showRound = true;
            round++;//Increment the round only after win
            System.out.println("You win in " + count + " guess.");
            ++win;
            break;
        } else if (guess > number) {
            System.out.println("That's too high. Try again: ");
            showRound=false;
        } else if (guess < number) {
            System.out.println("That's too low. Try again: ");
            showRound=false;
        }
    }


问:
How do I install the mysql gem without a mysql server?
I'm trying to install the mysql2 gem for a rails app on a machine with an external mysql server. The machine I'm installing onto doesn't have or need a mysql server on it. However, whenever I try to install it always checks for a mysql install and fails.
Is there an install configuration or work-around for this?

Cheers

答:
You need just the MySQL header files to be there where the native compiling takes place.

Depending on your OS / Distribution you should find the way to install the header files without installing the actual server (Debian / Ubuntu alikes should allow you to do so with the standard apt-get, but I might be wrong).

If you are on Windows, please check this post about mysql2 gem issues on Windows.


问:
Racket servlet serve static files
I want to try and code some blog or personal website or local web service in Racket. I've done the tutorial here and then I found this mailing list entry. In addition to that, I used the information from the documenation. URL based dispatch seems way easier than the tutorial, so I went for that and got the following code:

```<code>#lang racket

(provide/contract
  (start (-> request? response?)))

(require
  web-server/templates
  web-server/servlet-env
  web-server/servlet
  web-server/dispatch)

;; =====
;; STATE
;; =====
(define (get-vocabulary-for-topic topic)
  ;; for now always returns the same
  (list
    (list "sich fuer eine Person entscheiden" "xuǎnzé" "32" "选择")
    (list "teilnehmen" "cānyù" "14" "参与")
    (list "die Wahl" "dàxuǎn" "43" "大选")))

;; ======================
;; APPS HANDLING REQUESTS
;; ======================

(define (vocabulary-app request topic)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-vocabulary-page topic)))))

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

(define (overview-app request)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-overview-page)))))

;; ===============
;; RENDERING STUFF
;; ===============

(define (render-vocabulary-page topic)
  (let
    ([vocabulary (get-vocabulary-for-topic topic)])
    (let
      ([content (render-vocabulary-table vocabulary)]
        [page-title "Vocabulary"]
        [special-css-imports
          (render-css-include "css/vocabulary-table.css")]
        [special-js-imports ""]
        [header ""]
        [footer ""]
        [navigation ""])
      (include-template
        "templates/base.html"))))

(define (render-vocabulary-table vocabulary)
  (let
    ([table-headers (list "German" "Pinyin" "Tones" "Chinese")]
      [word-list vocabulary])
    (include-template "templates/vocabulary-table.html")))

(define (render-overview-page)
  (let
    ([content
       (let
         ([subpage-titles (list "vocabulary")])
         (include-template "templates/overview.html"))]
      [page-title "Overview"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (include-template
      "templates/base.html")))

(define (render-css-include path)
  (let
    ([path path])
    (include-template "templates/css-link.html")))

;; ====================
;; ROUTES MANAGING CODE
;; ====================
(define (start request)
  ;; for now only calling the dispatch
  ;; we could put some action here, which shall happen before dispatch
  (blog-dispatch request))

(define-values (blog-dispatch blug-url)
  (dispatch-rules
    [("index") overview-app]
    [("vocabulary") vocabulary-overview-app]
    [("vocabulary" (string-arg)) vocabulary-app]))

(define (respond-unknown-file req)
  (let
    ([content (include-template "templates/unknown-file.html")]
      [page-title "unknown file"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (response/full
      404 #"ERROR"
      (current-seconds) TEXT/HTML-MIME-TYPE
      empty
      (list
        (string->bytes/utf-8
          (include-template "templates/base.html"))))))

;; ===========================
;; ADDED FOR RUNNING A SERVLET
;; ===========================
(serve/servlet
  start
  #:servlet-path "/index"  ; default URL
  #:extra-files-paths (list (build-path (current-directory) "static"))  ; directory for static files
  #:port 8000 ; the port on which the servlet is running
  #:servlet-regexp #rx""
  #:launch-browser? true  ; should racket show the servlet running in a browser upon startup?
  ;; #:quit? false  ; ???
  #:listen-ip false  ; the server will listen on ALL available IP addresses, not only on one specified
  #:server-root-path (current-directory)
  #:file-not-found-responder respond-unknown-file)
</code>```

This works fine so far, except that any file in my static directory, actually in subdirectories of the static directory, namely css cannot be found, when I navigate to any "subpages".

What I mean by that is, that a "main page" would be something like localhost:8000/index or localhost:8000/vocabulary and a subpage would be a page like localhost:8000/vocabulary/something.

It seems that the template rendering gets it wrong, does not always access the static directory from the root of the application directory, but instead only looks at localhost:8000/vocabulary/css/general.css, while it should look at localhost:8000/css/general.css, which it does, when I go to any "main page".

Here is a screenshot of this on a main page:

And here it is on a subpage:

So the static directory seems to change depending on what URL is visited. At first I thought I had finally understood how to serve static files, but it seems I have not and I don't know how to fix the problem in the best way.

Here is my directory structure:

```<code>/home/xiaolong/development/Racket/blog2
  - static/
    - css/
      general.css
      vocabulary-table.css
    + img/
    + js/
  - templates/
    base.html
    css-link.html
    js-link.html
    overview.html
    unknown-file.html
    vocabulary-table.html
  blog-demo.rkt
  blog.rkt
</code>```

How can I fix the paths for static files?

I want to be able to simply type css/something.css in the code and no matter which app or route, it should serve the files and I don't want to change the include path depending on what route I am treating in the code.

The command I use for running the server is simply:

```<code>racket blog.rkt
</code>```

from the root directory of the project.

答:
It sure looks to me like this is an HTML problem, not a racket problem. Specifically, it looks like you need to specify these as absolute paths, not as relative ones. So, in your code, you might want to change

```<code>(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))
</code>```

to

```<code>(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "/css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))
</code>```

(note the leading slash in the path to the css file)

Does this answer your question?

Title: Racket servlet serve static files

Body:
I want to try and code some blog or personal website or local web service in Racket. I've done the tutorial here and then I found this mailing list entry. In addition to that, I used the information from the documenation. URL based dispatch seems way easier than the tutorial, so I went for that and got the following code:

#lang racket

(provide/contract
  (start (-> request? response?)))

(require
  web-server/templates
  web-server/servlet-env
  web-server/servlet
  web-server/dispatch)

;; =====
;; STATE
;; =====
(define (get-vocabulary-for-topic topic)
  ;; for now always returns the same
  (list
    (list "sich fuer eine Person entscheiden" "xuǎnzé" "32" "选择")
    (list "teilnehmen" "cānyù" "14" "参与")
    (list "die Wahl" "dàxuǎn" "43" "大选")))

;; ======================
;; APPS HANDLING REQUESTS
;; ======================

(define (vocabulary-app request topic)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-vocabulary-page topic)))))

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

(define (overview-app request)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-overview-page)))))

;; ===============
;; RENDERING STUFF
;; ===============

(define (render-vocabulary-page topic)
  (let
    ([vocabulary (get-vocabulary-for-topic topic)])
    (let
      ([content (render-vocabulary-table vocabulary)]
        [page-title "Vocabulary"]
        [special-css-imports
          (render-css-include "css/vocabulary-table.css")]
        [special-js-imports ""]
        [header ""]
        [footer ""]
        [navigation ""])
      (include-template
        "templates/base.html"))))

(define (render-vocabulary-table vocabulary)
  (let
    ([table-headers (list "German" "Pinyin" "Tones" "Chinese")]
      [word-list vocabulary])
    (include-template "templates/vocabulary-table.html")))

(define (render-overview-page)
  (let
    ([content
       (let
         ([subpage-titles (list "vocabulary")])
         (include-template "templates/overview.html"))]
      [page-title "Overview"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (include-template
      "templates/base.html")))

(define (render-css-include path)
  (let
    ([path path])
    (include-template "templates/css-link.html")))

;; ====================
;; ROUTES MANAGING CODE
;; ====================
(define (start request)
  ;; for now only calling the dispatch
  ;; we could put some action here, which shall happen before dispatch
  (blog-dispatch request))

(define-values (blog-dispatch blug-url)
  (dispatch-rules
    [("index") overview-app]
    [("vocabulary") vocabulary-overview-app]
    [("vocabulary" (string-arg)) vocabulary-app]))

(define (respond-unknown-file req)
  (let
    ([content (include-template "templates/unknown-file.html")]
      [page-title "unknown file"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (response/full
      404 #"ERROR"
      (current-seconds) TEXT/HTML-MIME-TYPE
      empty
      (list
        (string->bytes/utf-8
          (include-template "templates/base.html"))))))

;; ===========================
;; ADDED FOR RUNNING A SERVLET
;; ===========================
(serve/servlet
  start
  #:servlet-path "/index"  ; default URL
  #:extra-files-paths (list (build-path (current-directory) "static"))  ; directory for static files
  #:port 8000 ; the port on which the servlet is running
  #:servlet-regexp #rx""
  #:launch-browser? true  ; should racket show the servlet running in a browser upon startup?
  ;; #:quit? false  ; ???
  #:listen-ip false  ; the server will listen on ALL available IP addresses, not only on one specified
  #:server-root-path (current-directory)
  #:file-not-found-responder respond-unknown-file)

This works fine so far, except that any file in my static directory, actually in subdirectories of the static directory, namely css cannot be found, when I navigate to any "subpages".

What I mean by that is, that a "main page" would be something like localhost:8000/index or localhost:8000/vocabulary and a subpage would be a page like localhost:8000/vocabulary/something.

It seems that the template rendering gets it wrong, does not always access the static directory from the root of the application directory, but instead only looks at localhost:8000/vocabulary/css/general.css, while it should look at localhost:8000/css/general.css, which it does, when I go to any "main page".

Here is a screenshot of this on a main page:

And here it is on a subpage:

So the static directory seems to change depending on what URL is visited. At first I thought I had finally understood how to serve static files, but it seems I have not and I don't know how to fix the problem in the best way.

Here is my directory structure:

/home/xiaolong/development/Racket/blog2
  - static/
    - css/
      general.css
      vocabulary-table.css
    + img/
    + js/
  - templates/
    base.html
    css-link.html
    js-link.html
    overview.html
    unknown-file.html
    vocabulary-table.html
  blog-demo.rkt
  blog.rkt

How can I fix the paths for static files?

I want to be able to simply type css/something.css in the code and no matter which app or route, it should serve the files and I don't want to change the include path depending on what route I am treating in the code.

The command I use for running the server is simply:

racket blog.rkt

from the root directory of the project.

Body:
It sure looks to me like this is an HTML problem, not a racket problem. Specifically, it looks like you need to specify these as absolute paths, not as relative ones. So, in your code, you might want to change

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

to

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "/css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

(note the leading slash in the path to the css file)

Does this answer your question?


问:
Big-O Notation and coding
I'm struggling to wrap my head around working out big-o notation from code.

I understand the basic steps i.e.

for (int i = 0; i < n; i++) would be O(n)

And that

```<code>for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
</code>```

would be O(n2)

I am struggling to understand where or how to calculate the logarithmic values.

i.e.

Would :

for (int i = 0; i < n * 2; i++) be O(log n) or O(n log n) or O(log 2n) etc

Can someone please demonstrate in code form as to an example and how the notation was formed.

I have researched and keep getting examples where sorting is concerned and the lists are chopped etc, which makes sense in a form but I don't seem to get how to apply that to code as above.

I am new to the whole coding and big-o notation.

I have am familiar with objects, classes, loops, functions, structs, etc.
I am busy learning c++ as it is part of my course.
My text book does not explain logarithmic big-o calculations very well or pretty much at all.

答:
One could represent the code as a recurrence relation:

T(n) = T(n-1)  + 2 * c, where c = the inner part of the code,

which we will do 2 * n times.

Giving us solution like:
T(n) = 2 c n + c_1, where c_1 a constant

And since 2 * c is a constant, and the second term, also a constant drops off, we can write:

O(n)

Title: Big-O Notation and coding

Body:
I'm struggling to wrap my head around working out big-o notation from code.

I understand the basic steps i.e.

for (int i = 0; i < n; i++) would be O(n)

And that

for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)

would be O(n2)

I am struggling to understand where or how to calculate the logarithmic values.

i.e.

Would :

for (int i = 0; i < n * 2; i++) be O(log n) or O(n log n) or O(log 2n) etc

Can someone please demonstrate in code form as to an example and how the notation was formed.

I have researched and keep getting examples where sorting is concerned and the lists are chopped etc, which makes sense in a form but I don't seem to get how to apply that to code as above.

I am new to the whole coding and big-o notation.

I have am familiar with objects, classes, loops, functions, structs, etc.
I am busy learning c++ as it is part of my course.
My text book does not explain logarithmic big-o calculations very well or pretty much at all.


问:
AWS Kinesis and Lambda data versioning
I have created an AWS Firehose endpoint (might change to simple Kinesis) that receives logs from producers and saves them to a S3 bucket and a lambda function that consumes data, processes it and saves output to db.

Everything works fine. Now i am planning about creating a staging and development flow for this entire structure. When i release a new version i am not capable of replacing entire producers instantly, therefore i need to keep older production versions until no producer left - because i might make breaking protocol changes on new versions.

I am not sure what would be the best approach to create a versionable system using kinesis and lambda. Should i copy entire structure for new versions (including dev and staging) and make producers write to specific versioned stream?

or should i create a mid lambda function that inspects packets (which contain their version info) and outputs events to specific s3 which has versioned folders? So that lambda functions would consume only data that they know about. This will let me use versioning support for lambda functions.

Here is an structure image for first idea

Here is second structure

I wonder which will be a better solution or are there better ways to accomplish this

答:
First, Lambdas can be triggered directly using Kinesis- no need for Kinesis Firehose or S3.

Second, your question really boils down to: do you need separate Kinesis+Lambda pipeline per version or not. I'd go with the following solution:

One Kinesis stream for all versions of data.

One Lambda function on this stream. It internally handles different versions separately. Crudely speaking, think of various if-else checks on version number.

The advantages of above approach vs one Kinesis+Lambda pipeline per version:

The former is operationally simpler. In the latter, you'll need to setup a new pipeline every time a new version is introduced.

At any point of time, you'd have a small number of active versions. So, a few if-else checks in code should work just fine.

Of course, keep Dev and Prod pipelines separate, so as to minimize blast radius of bad code code in former.

Title: AWS Kinesis and Lambda data versioning


问:
Using SQLite-net PCL how can I assign a custom PrimaryKey?
How can I assign a string as a PrimaryKey for a SQLite row?
Normally, I use this for auto incrementation:   </p>

```<code>public class BaseItem {
    [PrimaryKey, AutoIncrement]
    public int Name { get; set; }
}
</code>```

答:
You should be able to simply leave out the "AutoIncrement". This is how we do it in an application by setting in the ctor:</p>

```<code>public class MySuperAwesomeClass
{
  [PrimaryKey]
  public Guid Key { get; set; }

  public MySuperAwesomeClass()
  {
    Key = Guid.NewGuid();
  }
}
</code>```

Body:
How can I assign a string as a PrimaryKey for a SQLite row?
Normally, I use this for auto incrementation:

public class BaseItem {
    [PrimaryKey, AutoIncrement]
    public int Name { get; set; }
}

Body:
You should be able to simply leave out the "AutoIncrement". This is how we do it in an application by setting in the ctor:

public class MySuperAwesomeClass
{
  [PrimaryKey]
  public Guid Key { get; set; }

  public MySuperAwesomeClass()
  {
    Key = Guid.NewGuid();
  }
}