问:
What is the best practice to save a quiz answers with different data types in MYSQL?
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

```<code>    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text
</code>```

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

```<code>Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext
</code>```

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

```<code>question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

</code>```

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?

答:
Non-EAV

What is the datatype for?  The user typed the Answer as a string; he did not specify the datatype, did he?  That avoids EAV -- Just store strings.  At that point, the question can simply be a TEXT column in one table.  And the answer a column in another table, such as the profile_answers you proffered.

As for queries like "getting customers average age, getting married customers, customers with salary > 30.52", you are stuck with table scans, whether it is EAV or not.  The non-EAV approach will be more efficient since there are fewer hoops to go through to get to the value.

You have a Customers table; one row per customer, with birthdate as a column.  Average age involves reading that column and doing some simple arithmetic.  Ditto for marital status and salary.

In other words, the UI has a <form> that asks about "customer info".  (And other forms that ask about other stuff.)  Then answers for one customer goes directly into a table designed specifically for customer info.

You could have that form and the table be "table-driven".  But that is unnecessarily complex.  If, as I first understood you Question, you are building a classroom app that involves test-taking with hundreds of questions, that might lead to something table-driven.

EAV

If you do stick with 5 datatypes, then you have these tough questions:  How much precision in your DECIMAL?  If the Question is "What is the value of pi", then how do you handle this variety:  3.14, 3.1416, 3.14159, 3.14159265358979, 22/7, "about 3.14", etc?  Only VARCHAR(...) or TEXT handles those.

What did you mean by "(for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc)" ?  If you mean that the user typed in "30.52", then it works fine to put that into a TEXT column and generate the query

```<code>with salary > "30.52"
</code>```

That is, numeric value can be fed into queries as strings; the datatype does not need to match.  (However "22/7" would be treated as 22, and "about 3.14" would be compared as 0.)

Millions of rows -- Will you be looking through all of them at once?  Very often?  If you have 50 students answering 40 questions, that is a paultry 2000 Q&A to go through at a single time; not millions.

Body:
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?

Body:
Non-EAV

What is the datatype for?  The user typed the Answer as a string; he did not specify the datatype, did he?  That avoids EAV -- Just store strings.  At that point, the question can simply be a TEXT column in one table.  And the answer a column in another table, such as the profile_answers you proffered.

As for queries like "getting customers average age, getting married customers, customers with salary > 30.52", you are stuck with table scans, whether it is EAV or not.  The non-EAV approach will be more efficient since there are fewer hoops to go through to get to the value.

You have a Customers table; one row per customer, with birthdate as a column.  Average age involves reading that column and doing some simple arithmetic.  Ditto for marital status and salary.

In other words, the UI has a <form> that asks about "customer info".  (And other forms that ask about other stuff.)  Then answers for one customer goes directly into a table designed specifically for customer info.

You could have that form and the table be "table-driven".  But that is unnecessarily complex.  If, as I first understood you Question, you are building a classroom app that involves test-taking with hundreds of questions, that might lead to something table-driven.

EAV

If you do stick with 5 datatypes, then you have these tough questions:  How much precision in your DECIMAL?  If the Question is "What is the value of pi", then how do you handle this variety:  3.14, 3.1416, 3.14159, 3.14159265358979, 22/7, "about 3.14", etc?  Only VARCHAR(...) or TEXT handles those.

What did you mean by "(for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc)" ?  If you mean that the user typed in "30.52", then it works fine to put that into a TEXT column and generate the query

with salary > "30.52"

That is, numeric value can be fed into queries as strings; the datatype does not need to match.  (However "22/7" would be treated as 22, and "about 3.14" would be compared as 0.)

Millions of rows -- Will you be looking through all of them at once?  Very often?  If you have 50 students answering 40 questions, that is a paultry 2000 Q&A to go through at a single time; not millions.


来源: stackexchange

问:
Use the css class or variable in Typescript file in angular
Is there a way to use the scss class or variable in the typescript file?

scss

```<code>.thisIsGreen {
   color: green;
}
.thisIsBlue {
   color: blue;
}
</code>```

or

```<code>$thisIsGreen {
  color: green;
}
$thisIsBlue {
  color: blue;
}
</code>```

Now in the typescript I would like to use this class or variable.

component.ts

```<code>const colors = ['thisIsGreen', 'thisIsBlue'];
</code>```

I would like to use the colors in my charts, so don't know how can I use the css variable or class, instead of hardcoding the color in component.ts.

Any help is appreciated.

Thanks

答:
I had used in my project the following: (Use of stylesheet(css) in TypeScript(.ts) file in Angular)

```<code>let greet1:HTMLElement = document.getElementById("greet1");
greet1.innerHTML = '<i class="pi pi-caret-down" style="vertical-align:bottom;float:inherit;display: inline-block;">  </i>' +' ' + event.item.label + ' ';
</code>```

In InnerHTML you can have different HTML attributes like style, float, display etc: Css at .ts in Angular.

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to use the scss class or variable in the typescript file?

scss

.thisIsGreen {
   color: green;
}
.thisIsBlue {
   color: blue;
}

or

$thisIsGreen {
  color: green;
}
$thisIsBlue {
  color: blue;
}

Now in the typescript I would like to use this class or variable.

component.ts

const colors = ['thisIsGreen', 'thisIsBlue'];

I would like to use the colors in my charts, so don't know how can I use the css variable or class, instead of hardcoding the color in component.ts.

Any help is appreciated.

Thanks

Body:
I had used in my project the following: (Use of stylesheet(css) in TypeScript(.ts) file in Angular)

let greet1:HTMLElement = document.getElementById("greet1");
greet1.innerHTML = '<i class="pi pi-caret-down" style="vertical-align:bottom;float:inherit;display: inline-block;">  </i>' +' ' + event.item.label + ' ';

In InnerHTML you can have different HTML attributes like style, float, display etc: Css at .ts in Angular.


问:
Change class property value in method A and access updated value in method B
I'm using a custom PHP framework which is largely based on CodeIgniter.

In one of my controller files, I've set a class property called $orderId. After the user has filled in the form and submitted, I'll do a DB insert, get the order no. and override the $orderId class property value with that order no.

Then I'll redirect to the submit page where I want to access that updated $orderId class property value. This final part is not working, the submit class gets a blank value for property $orderId.

Where am I going wrong pls? The basic example below. Maybe I can't do this because of the redirect and should use a session var instead?

Thanks!

[EDIT] Or I could pass the orderId as the 3rd URL param in the redirect. E.G. redirect('orders/submit/'.self::$orderId); in which case I'll turn all the self:: instances into $this-> for class level scope.

```<code>class Orders extends Controller {
    private static $orderId;

    public function __construct() {
        // assign db model
    }

    public function index() {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {

            $data = [
                // form data to pass to db model
            ];

            self::$orderId = 12345; // example order no. return from db model
            if(!empty(self::$orderId)) {
                redirect('orders/submit');
            }
        }
    }

    public function submit() {
        $data = [
            'orderId' => self::$orderId
        ];
        $this->view('orders/submit', $data);
    }
}
</code>```

答: The issue itself is a fundamental architecture problem. static only works when you're working with the same instance. But since you're redirecting, the framework is getting reinitialised. Losing the value of your static property. Best way to go about doing this is by storing the order id in a session variable and then read that variable. Sessions last for the as long as the browser window is open</p>

Body:
I'm using a custom PHP framework which is largely based on CodeIgniter.

In one of my controller files, I've set a class property called $orderId. After the user has filled in the form and submitted, I'll do a DB insert, get the order no. and override the $orderId class property value with that order no.

Then I'll redirect to the submit page where I want to access that updated $orderId class property value. This final part is not working, the submit class gets a blank value for property $orderId.

Where am I going wrong pls? The basic example below. Maybe I can't do this because of the redirect and should use a session var instead?

Thanks!

[EDIT] Or I could pass the orderId as the 3rd URL param in the redirect. E.G. redirect('orders/submit/'.self::$orderId); in which case I'll turn all the self:: instances into $this-> for class level scope.

class Orders extends Controller {
    private static $orderId;

    public function __construct() {
        // assign db model
    }

    public function index() {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {

            $data = [
                // form data to pass to db model
            ];

            self::$orderId = 12345; // example order no. return from db model
            if(!empty(self::$orderId)) {
                redirect('orders/submit');
            }
        }
    }

    public function submit() {
        $data = [
            'orderId' => self::$orderId
        ];
        $this->view('orders/submit', $data);
    }
}


问:
WPF update UI Control asynchronously with a delay?
```<code>public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                SendWithDelay(textBoxChildren[i]);
            }
        }

        async Task SendWithDelay(TextBox txt)
        {
            await Task.Delay(1000);
            txt.Background = Brushes.Red;
        }
</code>```

I want 81 grids to get a red background 1 by one, now it just waits a bit and updates everything at once.

Any suggestions?

Note: This code is runnable but it does complain about SendWithDelay(textBoxChildren[i]); not being awaited, if I change this and also change void to async Task it says Error   CS0407 'Task EventHandling.TextChangedEvent(object, EventArgs)' has the wrong return type.

EDIT

This is what I have now:

```<code>public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                x SendWithDelay(textBoxChildren[i]);
            }
        }

        async void SendWithDelay(TextBox txt)
        {
            txt.Background = Brushes.Red;
            x await Task.Delay(500);
        }
</code>```

The breakpoints(x) just alternate between each other. Then when they're done everything gets red.

答:
1 second Delay

```<code>async Task LongRunningProcess()
{

    await Task.Delay(1000);

}
</code>```

In your loop

```<code>public async void TextChangedEvent(object sender, EventArgs e)
{
  for (int i = 0; i < textBoxChildren.Count; i++)
  {
     txt.Background = Brushes.Red;
     await Task.Run(() => LongRunningProcess());
  }
}

</code>```

Body:
public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                SendWithDelay(textBoxChildren[i]);
            }
        }

        async Task SendWithDelay(TextBox txt)
        {
            await Task.Delay(1000);
            txt.Background = Brushes.Red;
        }

I want 81 grids to get a red background 1 by one, now it just waits a bit and updates everything at once.

Any suggestions?

Note: This code is runnable but it does complain about SendWithDelay(textBoxChildren[i]); not being awaited, if I change this and also change void to async Task it says Error   CS0407 'Task EventHandling.TextChangedEvent(object, EventArgs)' has the wrong return type.

EDIT

This is what I have now:

public void TextChangedEvent(object sender, EventArgs e)
        {
            TextBox changedTextBox = sender as TextBox;
            List<TextBox> textBoxes = new List<TextBox>();
            //gets Grid that contains all the textboxes
            var parentGrid = VisualHierarchyHelper.FindParent<Grid>(changedTextBox);
            var mainGrid = VisualHierarchyHelper.FindParent<Grid>(parentGrid);
            //ALL 81 textboxes
            var textBoxChildren = VisualHierarchyHelper.FindVisualChildren<TextBox>(mainGrid).ToList();
            for (int i = 0; i < textBoxChildren.Count; i++)
            {
                x SendWithDelay(textBoxChildren[i]);
            }
        }

        async void SendWithDelay(TextBox txt)
        {
            txt.Background = Brushes.Red;
            x await Task.Delay(500);
        }

The breakpoints(x) just alternate between each other. Then when they're done everything gets red.

Body:
1 second Delay

async Task LongRunningProcess()
{

    await Task.Delay(1000);

}

In your loop

public async void TextChangedEvent(object sender, EventArgs e)
{
  for (int i = 0; i < textBoxChildren.Count; i++)
  {
     txt.Background = Brushes.Red;
     await Task.Run(() => LongRunningProcess());
  }
}


问:
How to equal two strings case sensitively in Linq to SQL?
How to equal two strings case sensitively in Linq to SQL (in a where query)?

Thanks.

答:
How to equal two strings case sensitively in Linq to SQL (in a where query)?</p>

```<code>Select * from tblemp Where empname='nAveen' COLLATE SQL_Latin1_General_Cp1_CS_AS
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How to equal two strings case sensitively in Linq to SQL (in a where query)?

Select * from tblemp Where empname='nAveen' COLLATE SQL_Latin1_General_Cp1_CS_AS

ContentLicense: CC BY-SA 3.0


问:
Find the smallest positive integer that does not occur in a given sequence
I was trying to solve this problem:

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

```<code>Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.
</code>```

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

```

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

答:
Objective-C example:</p>

```<code> int solution(NSMutableArray *array) {
     NSArray* sortedArray = [array sortedArrayUsingSelector: @selector(compare:)];
     int x = 1;
     for (NSNumber *number in sortedArray) {

       if (number.intValue < 0) {
         continue;
       }
       if (x < number.intValue){
         return x;
       }
      x = number.intValue + 1;
     }

     return x;
}
</code>```

Body:
I was trying to solve this problem:

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

Body:
Objective-C example:

 int solution(NSMutableArray *array) {
     NSArray* sortedArray = [array sortedArrayUsingSelector: @selector(compare:)];
     int x = 1;
     for (NSNumber *number in sortedArray) {

       if (number.intValue < 0) {
         continue;
       }
       if (x < number.intValue){
         return x;
       }
      x = number.intValue + 1;
     }

     return x;
}


问:
Javascript object creation best practice
I have the following javascript :

```<code>            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });
</code>```

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

```<code>        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...
</code>```

...and when calling this in the helperFunc like this:

```<code>                       return this.getTotal();
</code>```

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

```<code>                       var myObject = (function() { ... } ();
</code>```

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

答:
I've done a series on basic javascript fundamentals - objects and prototypes are covered here:

Javascript Object Instantation and Prototypes

I delve into Closures here:Javascript Closures

Hope they help. Cheers.

Body:
I have the following javascript :

            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...

...and when calling this in the helperFunc like this:

                       return this.getTotal();

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

                       var myObject = (function() { ... } ();

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem


问:
"object 'i' not found" the for loop
I am trying to make a simple for loop, that would add a new column to the existing data frame, by assigning a time class to each observation. I am getting 'object 'i' not found' and not sure where is a mistake. I am not that experienced with R, so thank you for any help!

for (i in 1:nrow(my.data)) {
    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }ifelse (my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }esle {
        my.data$RTimeHour[i] <- 3
    }
}
```

答:
I think you can simply use a nested ifelse statement:

```<code>my.data$RTimeHour <- ifelse(my.data$RTime <= 3600, 1,
                            ifelse(my.data$RTime > 3600 & my.data$RTime <= 7200, 2, 3))
</code>```

Title: "object 'i' not found" the for loop

Body:
I think you can simply use a nested ifelse statement:

my.data$RTimeHour <- ifelse(my.data$RTime <= 3600, 1,
                            ifelse(my.data$RTime > 3600 & my.data$RTime <= 7200, 2, 3))


问:
Standard "About" dialog in Qt
What's the standard way to implement an "About" application dialog in Qt? You know, the kind that pops up when you go Help > About... from the application menu.  I'm using Qt Designer to layout my main window, but I don't need anything fancy. It would be nice to do it in 2 lines of code instead of creating a new class or a new form in Qt Designer...</p>

答:
Here's how I did it with Python/PySide2:

First set up the menus/actions (I did this inside the __init__ function of my QMainWindow subclass):

```<code>menu = self.menuBar().addMenu('&Help')

about_action = QAction('&About', self)
about_action.triggered.connect(self.about)
menu.addAction(about_action)
</code>```

Then create a new slot to call QMessageBox.about:

```<code>@Slot()
def about(self):
    QMessageBox.about(self, 'title', 'text')
</code>```

Title: Standard "About" dialog in Qt

Body:
Here's how I did it with Python/PySide2:

First set up the menus/actions (I did this inside the __init__ function of my QMainWindow subclass):

menu = self.menuBar().addMenu('&Help')

about_action = QAction('&About', self)
about_action.triggered.connect(self.about)
menu.addAction(about_action)

Then create a new slot to call QMessageBox.about:

@Slot()
def about(self):
    QMessageBox.about(self, 'title', 'text')


问:
Numbering rows based on unique combinations of multiple columns in R
I have a data set in this style of format:

```<code>Treatments         Replicates           Value      Id
1                  1                    ###        NA
1                  1                    ###        NA
1                  1                    ###        NA
1                  2                    ###        NA
1                  2                    ###        NA
1                  2                    ###        NA
2                  1                    ###        NA
2                  1                    ###        NA
2                  1                    ###        NA
2                  2                    ###        NA
2                  2                    ###        NA
2                  2                    ###        NA
</code>```

I am trying to code for R to fill in the 'id' column by numbering the rows for each unique combination of columns 'Treatments' and 'Replicates'.

The end result would be like:

```<code>Treatments         Replicates           Value      Id
1                  1                    ###        1
1                  1                    ###        2
1                  1                    ###        3
1                  2                    ###        1
1                  2                    ###        2
1                  2                    ###        3
2                  1                    ###        1
2                  1                    ###        2
2                  1                    ###        3
2                  2                    ###        1
2                  2                    ###        2
2                  2                    ###        3
</code>```

This is a simplified data set. There are unequal numbers of each unique combination so the code will have to work down the dataframe somehow.

Thank you

Additional:

Is there a way to have the Id be a count of unique combinations? with a resulting df like:

```<code>Treatments         Replicates           Value      Id
1                  1                    ###        1
1                  1                    ###        1
1                  1                    ###        1
1                  2                    ###        2
1                  2                    ###        2
1                  2                    ###        2
2                  1                    ###        3
2                  1                    ###        3
2                  1                    ###        3
2                  2                    ###        4
2                  2                    ###        4
2                  2                    ###        4
</code>```

答:
We can use rowid from data.table

```<code>library(data.table)
df1$Id <- with(df1, rowid(Treatments, Replicates))
</code>```

Or using data.table syntax

```<code>setDT(df1)[, Id := rowid(Treatments, Replicates))]
</code>```

If we need the group id, use .GRP

```<code>setDT(df1)[, Id := .GRP, .(Treatments, Replicates)]
</code>```

Or using dplyr

```<code>df1 %>%
    group_by(Treatments, Replicates) %>%
    mutate(Id = row_number())
</code>```

To get the group indices, in the devel version

```<code>df1 %>%
  group_by(Treatments, Replicates) %>%
  mutate(Id = cur_group_id())
</code>```

Or in the current dplyr version

```<code>df1 %>%
    mutate(Id = group_indices(., Treatments, Replicates))
</code>```

In base R, this can be done using ave

```<code>df1$Id <- with(df1, ave(seq_along(Treatments), Treatments,
             Replicates, FUN = seq_along))
</code>```

data

```<code>df1 <- structure(list(Treatments = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L), Replicates = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L), Value = c(4L, 5L, 7L, 9L, 25L, 39L, 43L, 24L,
12L, 9L, 4L, 2L), Id = c(NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_)), row.names = c(NA,
-12L), class = "data.frame")
</code>```

Body:
I have a data set in this style of format:

Treatments         Replicates           Value      Id
1                  1                    ###        NA
1                  1                    ###        NA
1                  1                    ###        NA
1                  2                    ###        NA
1                  2                    ###        NA
1                  2                    ###        NA
2                  1                    ###        NA
2                  1                    ###        NA
2                  1                    ###        NA
2                  2                    ###        NA
2                  2                    ###        NA
2                  2                    ###        NA

I am trying to code for R to fill in the 'id' column by numbering the rows for each unique combination of columns 'Treatments' and 'Replicates'.

The end result would be like:

Treatments         Replicates           Value      Id
1                  1                    ###        1
1                  1                    ###        2
1                  1                    ###        3
1                  2                    ###        1
1                  2                    ###        2
1                  2                    ###        3
2                  1                    ###        1
2                  1                    ###        2
2                  1                    ###        3
2                  2                    ###        1
2                  2                    ###        2
2                  2                    ###        3

This is a simplified data set. There are unequal numbers of each unique combination so the code will have to work down the dataframe somehow.

Thank you

Additional:

Is there a way to have the Id be a count of unique combinations? with a resulting df like:

Treatments         Replicates           Value      Id
1                  1                    ###        1
1                  1                    ###        1
1                  1                    ###        1
1                  2                    ###        2
1                  2                    ###        2
1                  2                    ###        2
2                  1                    ###        3
2                  1                    ###        3
2                  1                    ###        3
2                  2                    ###        4
2                  2                    ###        4
2                  2                    ###        4

Body:
We can use rowid from data.table

library(data.table)
df1$Id <- with(df1, rowid(Treatments, Replicates))

Or using data.table syntax

setDT(df1)[, Id := rowid(Treatments, Replicates))]

If we need the group id, use .GRP

setDT(df1)[, Id := .GRP, .(Treatments, Replicates)]

Or using dplyr

df1 %>%
    group_by(Treatments, Replicates) %>%
    mutate(Id = row_number())

To get the group indices, in the devel version

df1 %>%
  group_by(Treatments, Replicates) %>%
  mutate(Id = cur_group_id())

Or in the current dplyr version

df1 %>%
    mutate(Id = group_indices(., Treatments, Replicates))

In base R, this can be done using ave

df1$Id <- with(df1, ave(seq_along(Treatments), Treatments,
             Replicates, FUN = seq_along))

data

df1 <- structure(list(Treatments = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L), Replicates = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L,
1L, 2L, 2L, 2L), Value = c(4L, 5L, 7L, 9L, 25L, 39L, 43L, 24L,
12L, 9L, 4L, 2L), Id = c(NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_)), row.names = c(NA,
-12L), class = "data.frame")


问:
Find out if selected cell is in databodyrange
I have a macro set up to perform a chunk of code in an 'onclick' event, and I'm trying to determine if they've selected a numeric value in a table range. An example of my table is below, and I'm trying to figure out if they've selected a number > 0 in the second column. I know how to reference the second column of a specific table, something like:

```<code>ListObjects("Table1").ListColumns(2).DataBodyRange
</code>```

but I'm not sure how to figure out if the selected cell is in that range. Any suggestions? Thanks so much for your help!

答:
Use Intersect.

```<code>Dim rangeToCheck as Range
Set rangeToCheck = Intersect(ActiveCell, ListObjects("Table1").ListColumns(2).DataBodyRange)

If Not rangeToCheck Is Nothing Then
    If IsNumeric(ActiveCell.Value) Then
        If ActiveCell.Value > 0 Then
            ' do the suff
        End If
    End If
End If
</code>```

Body:
I have a macro set up to perform a chunk of code in an 'onclick' event, and I'm trying to determine if they've selected a numeric value in a table range. An example of my table is below, and I'm trying to figure out if they've selected a number > 0 in the second column. I know how to reference the second column of a specific table, something like:

ListObjects("Table1").ListColumns(2).DataBodyRange

but I'm not sure how to figure out if the selected cell is in that range. Any suggestions? Thanks so much for your help!

Body:
Use Intersect.

Dim rangeToCheck as Range
Set rangeToCheck = Intersect(ActiveCell, ListObjects("Table1").ListColumns(2).DataBodyRange)

If Not rangeToCheck Is Nothing Then
    If IsNumeric(ActiveCell.Value) Then
        If ActiveCell.Value > 0 Then
            ' do the suff
        End If
    End If
End If


问:
Pandas Dataframe Manipulation logic
Can use please help with below problem:

Given two dataframes df1 and df2, need to get something like result dataframe.
```<code>
import pandas as pd
import numpy as np
feature_list = [ str(i) for i in range(6)]</p>

<p>df1 = pd.DataFrame( {'value' :  [0,3,0,4,2,5]})</p>

<p>df2 = pd.DataFrame(0, index=np.arange(6), columns=feature_list)
```

Expected Dataframe :
Need to be driven by comparing values from df1 with column names (features) in df2. if they match, we put 1 in resultDf

Here's expected output (or resultsDf):

答:
I think you need:

```<code>(pd.get_dummies(df1['value'])
   .rename(columns = str)
   .reindex(columns = df2.columns,
            index = df2.index,
            fill_value = 0))
</code>```

```<code>   0  1  2  3  4  5
0  1  0  0  0  0  0
1  0  0  0  1  0  0
2  1  0  0  0  0  0
3  0  0  0  0  1  0
4  0  0  1  0  0  0
5  0  0  0  0  0  1
</code>```

Title: Pandas Dataframe Manipulation logic

Body:
Can use please help with below problem:

Given two dataframes df1 and df2, need to get something like result dataframe.

import pandas as pd
import numpy as np
feature_list = [ str(i) for i in range(6)]

df1 = pd.DataFrame( {'value' :  [0,3,0,4,2,5]})

df2 = pd.DataFrame(0, index=np.arange(6), columns=feature_list)

Expected Dataframe :
Need to be driven by comparing values from df1 with column names (features) in df2. if they match, we put 1 in resultDf

Here's expected output (or resultsDf):

Body:
I think you need:

(pd.get_dummies(df1['value'])
   .rename(columns = str)
   .reindex(columns = df2.columns,
            index = df2.index,
            fill_value = 0))

   0  1  2  3  4  5
0  1  0  0  0  0  0
1  0  0  0  1  0  0
2  1  0  0  0  0  0
3  0  0  0  0  1  0
4  0  0  1  0  0  0
5  0  0  0  0  0  1


问:
how do I convert json data into Html tag?
I am trying to display JSON data in the Html tag. But I got the error:

Uncaught (in promise) TypeError.

async function fetchData() {
        const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
        const data = await response.json();
        console.log(data);

        document.getElementById("display").insertAdjacentText = `
        ${data.articles.map(function (article) {
            return `

${article.title}

${article.description}

${article.author}

${article.url} target="_blank">

             `
        }).join('')}`

    }
    fetchData();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="display"></div></code>```

答:
Currently you are inserting HTML entities as text, which is not going to work.

Try

    async function fetchData() {
        const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
        const data = await response.json();
        console.log(data);

        document.getElementsByClassName("display")[0].innerHTML = data.articles.map(function (article) {
            return `

${article.title}

${article.description}

${article.author}

${article.url} target="_blank">

`;
        }).join('');

    }
    fetchData();```

Body:
Currently you are inserting HTML entities as text, which is not going to work.

Try

    async function fetchData() {
        const response = await fetch('http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76');
        const data = await response.json();
        console.log(data);

        document.getElementsByClassName("display")[0].innerHTML = data.articles.map(function (article) {
            return `
            <ul id="news-articles">
            <li class="article"><img class="article-img" src="${article.urlToImage}" alt="article-img"></li>
            <li class="article"><h2 class="article-title">${article.title}</h2></li>
            <li class="article"><p class="article-description">${article.description}</p></li>
           <li class="article"><span class="article-author">${article.author}</span></li>
            <li class="article"><a class="article-link" href="">${article.url} target="_blank"> </a></li>
            </ul>`;
        }).join('');

    }
    fetchData();


问:
Accessing Native Codecs in Android 3.x version and above
I would like to use the native decoder for a custom video player.  The VideoView and MediaPlayer does not provide functionality that will support my requirements.

I am using FFMPEG (software decoder) right now, but I would prefer to use native hardware decoding if possible. Is there a way to do this through the NDK?

答:
There isn't currently a public API available for accessing any native hardware and I believe the presence of such hardware isn't guaranteed. While you could go digging into the DSP capabilities of the ARM processors being used by some devices it wouldn't be portable to all Android devices.

I would recommend continuing your software approach for guaranteed support on all devices.


问:
error: invalid conversion from ‘int’ to enum c++
I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

```<code>#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}
</code>```

Please let me know if anyone knows how to resolve this.

答:
According to name of the variable and operation you are performing type of numFlag should be int or int * if you need a pointer instead. Otherwise you may have Undefined Behaviour if you try to keep multiple flags in that variable/memory (and according to values of that flags you suppose to do so):

```<code>int numFlag = NUM_ZERO;
numFlag |= NUM_TWO; // no casting is necessary
numFlag |= NUM_ONE; // and it will not lead to UB if you do this
</code>```

Body:
I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}

Please let me know if anyone knows how to resolve this.

Body:
According to name of the variable and operation you are performing type of numFlag should be int or int * if you need a pointer instead. Otherwise you may have Undefined Behaviour if you try to keep multiple flags in that variable/memory (and according to values of that flags you suppose to do so):

int numFlag = NUM_ZERO;
numFlag |= NUM_TWO; // no casting is necessary
numFlag |= NUM_ONE; // and it will not lead to UB if you do this


问:
How to log from a custom ai platform model
I recently deployed a custom model to google cloud's ai-platform, and I am trying to debug some parts of my preprocessing logic. However, My print statements are not being logged to the stackdriver output. I have also tried using the logging client imported from google.cloud, to no avail. Here is my custom prediction file:

```<code>import os
import pickle

import numpy as np
from sklearn.datasets import load_iris
import tensorflow as tf

from google.cloud import logging

class MyPredictor(object):
  def __init__(self, model, preprocessor):
    self.logging_client = logging.Client()
    self._model = model
    self._preprocessor = preprocessor
    self._class_names = ["Snare", "Kicks", "ClosedHH", "ClosedHH",  "Clap", "Crash", "Perc"]

  def predict(self, instances, **kwargs):
    log_name = "Here I am"
    logger = self.logging_client.logger(log_name)
    text = 'Hello, world!'
    logger.log_text(text)
    print('Logged: {}'.format(text), kwargs.get("sr"))

    inputs = np.asarray(instances)

    outputs = self._model.predict(inputs)

    if kwargs.get('probabilities'):
      return outputs.tolist()
      #return "[]"
    else:
      return [self._class_names[index] for index in np.argmax(outputs.tolist(), axis=1)]

  @classmethod
  def from_path(cls, model_dir):
    model_path = os.path.join(model_dir, 'model.h5')
    model = tf.keras.models.load_model(model_path, custom_objects={"adam": tf.keras.optimizers.Adam,
 "categorical_crossentropy":tf.keras.losses.categorical_crossentropy, "lr":0.01, "name": "Adam"})

    preprocessor_path = os.path.join(model_dir, 'preprocessor.pkl')
    with open(preprocessor_path, 'rb') as f:
      preprocessor = pickle.load(f)

    return cls(model, preprocessor)

</code>```

I can't find anything online for why my logs are not showing up in stackdriver (neither print statements nor the logging library calls). Has anyone faced this issue?

Thanks,
Nikita

NOTE: If you have enough rep to create tags please add the google-ai-platform tag to this post. I think it would really help people who are in my position. Thanks!

答:
From Documentation:

If you want to enable online prediction logging, you must configure it
  when you create a model resource or when you create a model version
  resource, depending on which type of logging you want to enable. There
  are three types of logging, which you can enable independently:

Access logging, which logs information like timestamp and latency for
  each request to Stackdriver Logging.

You can enable access logging when you create a model resource.

Stream logging, which logs the stderr and stdout streams from your
  prediction nodes to Stackdriver Logging, and can be useful for
  debugging. This type of logging is in beta, and it is not supported by
  Compute Engine (N1) machine types.

You can enable stream logging when you create a model resource.

Request-response logging, which logs a sample of online prediction
  requests and responses to a BigQuery table. This type of logging is in
  beta.

You can enable request-response logging by creating a model version
  resource, then updating that version.

For your use case, please use the following template to log custom information into StackDriver:

Model

```<code>gcloud beta ai-platform models create {MODEL_NAME} \
 --regions {REGION} \
 --enable-logging \
 --enable-console-logging
</code>```

Model version

```<code>gcloud beta ai-platform versions create {VERSION_NAME} \
    --model {MODEL_NAME} \
    --origin gs://{BUCKET}/{MODEL_DIR} \
    --python-version 3.7 \
    --runtime-version 1.15 \
    --package-uris gs://{BUCKET}/{PACKAGES_DIR}/custom-model-0.1.tar.gz \
    --prediction-class=custom_prediction.CustomModelPrediction \
    --service-account custom@project_id.iam.gserviceaccount.com
</code>```

I tried this and worked fine:

I did some modification to the constructor due to the @classmethod decorator.

Create a service account and grant it "Stackdriver Debugger User" role, use it during model version creation

Add google-cloud-logging library to your setup.py

Consider extra cost of enabling StackDriver logging

When using log_struct check the correct type is passed. (If using str, make sure you convert bytes to str in Python 3 using .decode('utf-8'))

Define the project_id parameter during Stackdriver client creation
logging.Client(), otherwise you will get:

```<code>ERROR:root:Prediction failed: 400 Name "projects//logs/my-custom-prediction-log" is missing the parent component. Expected the form projects/[PROJECT_ID]/logs/[ID]"
</code>```

Code below:

```<code>%%writefile cloud_logging.py

import os
import pickle
import numpy as np

from datetime import date
from google.cloud import logging

import tensorflow.keras as keras
LOG_NAME = 'my-custom-prediction-log'

class CustomModelPrediction(object):
    def __init__(self, model, processor, client):
        self._model = model
        self._processor = processor
        self._client = client

    def _postprocess(self, predictions):
        labels = ['negative', 'positive']
        return [
            {
                "label":labels[int(np.round(prediction))],
                "score":float(np.round(prediction, 4))
            } for prediction in predictions]

    def predict(self, instances, **kwargs):
        logger = self._client.logger(LOG_NAME)
        logger.log_struct({'instances':instances})
        preprocessed_data = self._processor.transform(instances)
        predictions =  self._model.predict(preprocessed_data)
        labels = self._postprocess(predictions)
        return labels

    @classmethod
    def from_path(cls, model_dir):
        client = logging.Client(project='project_id') # Change to your project
        model = keras.models.load_model(
          os.path.join(model_dir,'keras_saved_model.h5'))
        with open(os.path.join(model_dir, 'processor_state.pkl'), 'rb') as f:
            processor = pickle.load(f)
        return cls(model, processor, client)

# Verify model locally

from cloud_logging import CustomModelPrediction
classifier = CustomModelPrediction.from_path('.')

requests = ["God I hate the north", "god I love this"]
response = classifier.predict(requests)
response

</code>```

Then I check with the sample library:

```<code>python snippets.py my-custom-prediction-log list
Listing entries for logger my-custom-prediction-log:
* 2020-02-19T19:51:45.809767+00:00: {u'instances': [u'God I hate the north', u'god I love this']}
* 2020-02-19T19:57:18.615159+00:00: {u'instances': [u'God I hate the north', u'god I love this']}
</code>```

To visualize the logs, in StackDriver > Logging > Select Global and your Log name, if you want to see Model logs you should be able to select Cloud ML Model version.

You can use my files here: model and pre-processor

Body:
I recently deployed a custom model to google cloud's ai-platform, and I am trying to debug some parts of my preprocessing logic. However, My print statements are not being logged to the stackdriver output. I have also tried using the logging client imported from google.cloud, to no avail. Here is my custom prediction file:

import os
import pickle

import numpy as np
from sklearn.datasets import load_iris
import tensorflow as tf

from google.cloud import logging

class MyPredictor(object):
  def __init__(self, model, preprocessor):
    self.logging_client = logging.Client()
    self._model = model
    self._preprocessor = preprocessor
    self._class_names = ["Snare", "Kicks", "ClosedHH", "ClosedHH",  "Clap", "Crash", "Perc"]

  def predict(self, instances, **kwargs):
    log_name = "Here I am"
    logger = self.logging_client.logger(log_name)
    text = 'Hello, world!'
    logger.log_text(text)
    print('Logged: {}'.format(text), kwargs.get("sr"))

    inputs = np.asarray(instances)

    outputs = self._model.predict(inputs)

    if kwargs.get('probabilities'):
      return outputs.tolist()
      #return "[]"
    else:
      return [self._class_names[index] for index in np.argmax(outputs.tolist(), axis=1)]

  @classmethod
  def from_path(cls, model_dir):
    model_path = os.path.join(model_dir, 'model.h5')
    model = tf.keras.models.load_model(model_path, custom_objects={"adam": tf.keras.optimizers.Adam,
 "categorical_crossentropy":tf.keras.losses.categorical_crossentropy, "lr":0.01, "name": "Adam"})

    preprocessor_path = os.path.join(model_dir, 'preprocessor.pkl')
    with open(preprocessor_path, 'rb') as f:
      preprocessor = pickle.load(f)

    return cls(model, preprocessor)

I can't find anything online for why my logs are not showing up in stackdriver (neither print statements nor the logging library calls). Has anyone faced this issue?

Thanks,
Nikita

NOTE: If you have enough rep to create tags please add the google-ai-platform tag to this post. I think it would really help people who are in my position. Thanks!

Body:
From Documentation:

If you want to enable online prediction logging, you must configure it
  when you create a model resource or when you create a model version
  resource, depending on which type of logging you want to enable. There
  are three types of logging, which you can enable independently:

Access logging, which logs information like timestamp and latency for
  each request to Stackdriver Logging.

You can enable access logging when you create a model resource.

Stream logging, which logs the stderr and stdout streams from your
  prediction nodes to Stackdriver Logging, and can be useful for
  debugging. This type of logging is in beta, and it is not supported by
  Compute Engine (N1) machine types.

You can enable stream logging when you create a model resource.

Request-response logging, which logs a sample of online prediction
  requests and responses to a BigQuery table. This type of logging is in
  beta.

You can enable request-response logging by creating a model version
  resource, then updating that version.

For your use case, please use the following template to log custom information into StackDriver:

Model

gcloud beta ai-platform models create {MODEL_NAME} \
 --regions {REGION} \
 --enable-logging \
 --enable-console-logging

Model version

gcloud beta ai-platform versions create {VERSION_NAME} \
    --model {MODEL_NAME} \
    --origin gs://{BUCKET}/{MODEL_DIR} \
    --python-version 3.7 \
    --runtime-version 1.15 \
    --package-uris gs://{BUCKET}/{PACKAGES_DIR}/custom-model-0.1.tar.gz \
    --prediction-class=custom_prediction.CustomModelPrediction \
    --service-account custom@project_id.iam.gserviceaccount.com

I tried this and worked fine:

I did some modification to the constructor due to the @classmethod decorator.

Create a service account and grant it "Stackdriver Debugger User" role, use it during model version creation

Add google-cloud-logging library to your setup.py

Consider extra cost of enabling StackDriver logging

When using log_struct check the correct type is passed. (If using str, make sure you convert bytes to str in Python 3 using .decode('utf-8'))

Define the project_id parameter during Stackdriver client creation
logging.Client(), otherwise you will get:

ERROR:root:Prediction failed: 400 Name "projects//logs/my-custom-prediction-log" is missing the parent component. Expected the form projects/[PROJECT_ID]/logs/[ID]"

Code below:

%%writefile cloud_logging.py

import os
import pickle
import numpy as np

from datetime import date
from google.cloud import logging

import tensorflow.keras as keras
LOG_NAME = 'my-custom-prediction-log'

class CustomModelPrediction(object):
    def __init__(self, model, processor, client):
        self._model = model
        self._processor = processor
        self._client = client

    def _postprocess(self, predictions):
        labels = ['negative', 'positive']
        return [
            {
                "label":labels[int(np.round(prediction))],
                "score":float(np.round(prediction, 4))
            } for prediction in predictions]

    def predict(self, instances, **kwargs):
        logger = self._client.logger(LOG_NAME)
        logger.log_struct({'instances':instances})
        preprocessed_data = self._processor.transform(instances)
        predictions =  self._model.predict(preprocessed_data)
        labels = self._postprocess(predictions)
        return labels

    @classmethod
    def from_path(cls, model_dir):
        client = logging.Client(project='project_id') # Change to your project
        model = keras.models.load_model(
          os.path.join(model_dir,'keras_saved_model.h5'))
        with open(os.path.join(model_dir, 'processor_state.pkl'), 'rb') as f:
            processor = pickle.load(f)
        return cls(model, processor, client)

# Verify model locally

from cloud_logging import CustomModelPrediction
classifier = CustomModelPrediction.from_path('.')

requests = ["God I hate the north", "god I love this"]
response = classifier.predict(requests)
response

Then I check with the sample library:

python snippets.py my-custom-prediction-log list
Listing entries for logger my-custom-prediction-log:
* 2020-02-19T19:51:45.809767+00:00: {u'instances': [u'God I hate the north', u'god I love this']}
* 2020-02-19T19:57:18.615159+00:00: {u'instances': [u'God I hate the north', u'god I love this']}

To visualize the logs, in StackDriver > Logging > Select Global and your Log name, if you want to see Model logs you should be able to select Cloud ML Model version.

You can use my files here: model and pre-processor


问:
Python ceasar cipher
You will be implementing a shift-cypher.  This type of code shifts every letter by a set amount.

Instructions:
Complete the encode method so that it returns the encoded message.
Complete the decode method so that it returns the decoded message.
In the main method,
      - prompt the user for the message.
      - prompt the user for the shift amount.

      - Print the message.

      - Call encode with the message and the shift amount.

      - Store the encoded message returned from encode.

      - Print the encoded message.

      - Send the encoded message and the shift amount to the decode method.

      - Print the decoded message.

Tips:
chr(ord('A') + 5) will give you 'F', and chr(ord('F') - 5) will give you 'A'.  You will need to be check for, and adjust for, the times when the shift moves you off the end or beginning of the alphabet.  For example, how will you handle 'B' - 14?
The easiest way to check for upper case or lower case letters is using 'in'.  Refer to the demonstration in class.
Remember, you can compare letters with greater-than and less-than.  'A' > 'B' would be False.
You may assume there is no punctuation (most codes omit punctuation to avoid giving clues about the encoded message).
You do not have to modify the capitalization.
Make sure you preserve spaces. (though a real cypher would not)
You can check to see if your encoding is working using this website.  https://cryptii.com/pipes/caesar-cipher

Sample Input/Output:
    Enter the message: Hello World
    Enter the shift: 10
    Hello World
    Rovvy Gybvn
    Hello World

My Code

```<code>  def encode(s, shiftamount):
      for x in range(0, s-1):
        if s[x] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
          if chr(ord(x) + shiftamount) > Z :
            print(chr(ord(s[x])) + (shiftamount - 25),end="")

          if chr(ord(x) + shiftamount) <= Z :
            print(chr(ord(s[x])) + shiftamount,end="")

        if s[x] in "abcdefghijklmnopqrstuvwxyz":
          if chr(ord(x) + shiftamount) > Z :
            print(chr(ord(s[x])) + (shiftamount - 25) ,end="")

          if chr(ord(x) + shiftamount) <= Z :
            print(chr(ord(s[x])) + shiftamount,end="")

      print(chr(ord(s[x]) + shiftamount,end="")

    #def decode(s, shiftamount):

    def main():
      s = input("Enter the message:")
      shiftamount = input("Enter the shift")
      print(s)
      encode()
      decode()

    ########################################################################
    ###                Do not modify anything below here                 ###
    ########################################################################
    if __name__ == '__main__':
      main()
</code>```

答:
I think this code can help you</p>

```<code>def encode(s, shiftamount):
    for x in range(0, len(s)):
        if s[x] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            if chr(ord(x) + shiftamount) > Z :
                print(chr(ord(s[x])) + (shiftamount - 25),end="")
            if chr(ord(x) + shiftamount) <= Z :
                print(chr(ord(s[x])) + shiftamount,end="")
         if s[x] in "abcdefghijklmnopqrstuvwxyz":
            if chr(ord(x) + shiftamount) > Z :
                print(chr(ord(s[x])) + (shiftamount - 25) ,end="")
            if chr(ord(x) + shiftamount) <= Z :
                print(chr(ord(s[x])) + shiftamount,end="")
                print(chr(ord(s[x]) + shiftamount,end="")

def main():
    s = input("Enter the message:")
    shiftamount = int(input("Enter the shift"))
    print(s)
    encode(s, shiftamount)
</code>```

Title: Python ceasar cipher

Body:
You will be implementing a shift-cypher.  This type of code shifts every letter by a set amount.

Instructions:
Complete the encode method so that it returns the encoded message.
Complete the decode method so that it returns the decoded message.
In the main method,
      - prompt the user for the message.
      - prompt the user for the shift amount.

      - Print the message.

      - Call encode with the message and the shift amount.

      - Store the encoded message returned from encode.

      - Print the encoded message.

      - Send the encoded message and the shift amount to the decode method.

      - Print the decoded message.

Tips:
chr(ord('A') + 5) will give you 'F', and chr(ord('F') - 5) will give you 'A'.  You will need to be check for, and adjust for, the times when the shift moves you off the end or beginning of the alphabet.  For example, how will you handle 'B' - 14?
The easiest way to check for upper case or lower case letters is using 'in'.  Refer to the demonstration in class.
Remember, you can compare letters with greater-than and less-than.  'A' > 'B' would be False.
You may assume there is no punctuation (most codes omit punctuation to avoid giving clues about the encoded message).
You do not have to modify the capitalization.
Make sure you preserve spaces. (though a real cypher would not)
You can check to see if your encoding is working using this website.  https://cryptii.com/pipes/caesar-cipher

Sample Input/Output:
    Enter the message: Hello World
    Enter the shift: 10
    Hello World
    Rovvy Gybvn
    Hello World

My Code

  def encode(s, shiftamount):
      for x in range(0, s-1):
        if s[x] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
          if chr(ord(x) + shiftamount) > Z :
            print(chr(ord(s[x])) + (shiftamount - 25),end="")

          if chr(ord(x) + shiftamount) <= Z :
            print(chr(ord(s[x])) + shiftamount,end="")

        if s[x] in "abcdefghijklmnopqrstuvwxyz":
          if chr(ord(x) + shiftamount) > Z :
            print(chr(ord(s[x])) + (shiftamount - 25) ,end="")

          if chr(ord(x) + shiftamount) <= Z :
            print(chr(ord(s[x])) + shiftamount,end="")

      print(chr(ord(s[x]) + shiftamount,end="")

    #def decode(s, shiftamount):

    def main():
      s = input("Enter the message:")
      shiftamount = input("Enter the shift")
      print(s)
      encode()
      decode()

    ########################################################################
    ###                Do not modify anything below here                 ###
    ########################################################################
    if __name__ == '__main__':
      main()

Body:
I think this code can help you

def encode(s, shiftamount):
    for x in range(0, len(s)):
        if s[x] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            if chr(ord(x) + shiftamount) > Z :
                print(chr(ord(s[x])) + (shiftamount - 25),end="")
            if chr(ord(x) + shiftamount) <= Z :
                print(chr(ord(s[x])) + shiftamount,end="")
         if s[x] in "abcdefghijklmnopqrstuvwxyz":
            if chr(ord(x) + shiftamount) > Z :
                print(chr(ord(s[x])) + (shiftamount - 25) ,end="")
            if chr(ord(x) + shiftamount) <= Z :
                print(chr(ord(s[x])) + shiftamount,end="")
                print(chr(ord(s[x]) + shiftamount,end="")

def main():
    s = input("Enter the message:")
    shiftamount = int(input("Enter the shift"))
    print(s)
    encode(s, shiftamount)


问:
Late fees for customer profiles with or without recurring billing subscriptions in authorize.net
For a school that has many enrollments of children and their parents making payments, is there a way in the Authorize.net API to charge customer profiles late fees? They may be enrolled in recurring billing subscriptions or not. Does authorize.net allow late fees and balances to be paid? I'm wondering how to implement this with the APIs.

I find these APIs helpful, but not the complete solution:
* Create a Subscription from Customer Profile
* Get Customer Profile
* Get Customer Payment Profile

答: There is no API call for handling with late fees. If your amounts to charge are going to vary for any reason, adding late fees being an example, you would want to build your own engine for making payments. The best way to do this is to use the CIM API to create and manage payment accounts and then charge against them. That way you can charge a varying amount if a late fee needs to be added. Of course this means you are responsible for handling all payments and cannot count on a built in scheduling engine like the one provided by the ARB API.</p>


问:
How to add listener to ul li list?
How to add listener to ul li list, that is in component template?

```<code><ul #list>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

I have tried:

```<code>@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}
</code>```

But it does not work for me.

答:
This is what you need :

HTML :

```<code><ul #list tabindex="0">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

TS :

```<code>import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  @ViewChild("list", { static: false }) list: ElementRef;

  ngAfterViewInit() {
    this.list.nativeElement.focus();
    this.list.nativeElement.addEventListener('keydown', this.onKeyDown);
  }

  onKeyDown = (e) => { console.log(e); }

}
</code>```

Stackblitz : angular-add-listener-to-ul-li-list

Title: How to add listener to ul li list?

Body:
How to add listener to ul li list, that is in component template?

1

2

3

I have tried:

@ViewChild("list", { static: false }) list: ElementRef;

ngOnInit() {
   list.addEventListener('keydown', this.onKeyDown);
}

 onKeyDown = (e) => { console.log(e); // event keydown}

But it does not work for me.

Body:
This is what you need :

HTML :

<ul #list tabindex="0">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>

TS :

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  @ViewChild("list", { static: false }) list: ElementRef;

  ngAfterViewInit() {
    this.list.nativeElement.focus();
    this.list.nativeElement.addEventListener('keydown', this.onKeyDown);
  }

  onKeyDown = (e) => { console.log(e); }

}

Stackblitz : angular-add-listener-to-ul-li-list


问:
class name and then the tag name contains the distinguish text
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

```<code>  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));
</code>```

also i tried

```<code>  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))
</code>```

also tried this

```<code>  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;
</code>```

Every time i get no such element found
ANythoughts
this is the html code

```<code><li class="active">
 <div class="a">
  <div class="b">
   <div class="c">
    <h1></h1>
     <h3 class="d"> some text</h3>
      <div class="e">
       <span class="f">
         Active Text</span>
</div></div></div></div>
</li>
</code>```

答:
So what worked for me was this,

FindElement(By.CssSelector("li.active")).FindElement(By.XPath("//span[contains(.,'Active Text')]"));

Body:
I have class name active and then there is unique text called active text in span(which is nested). Class name active is the unique among other class names then nested text is unique. How would i click on that. I have used following methods.

  FindElement(By.XPath("//li[@class='active']//*[contains(.,'active text')]"));

also i tried

  findelement(BY.xpath(//li[@class='active']//div//div//div//span[contains(.,'active text')]"))

also tried this

  FindElement(By.XPath("//li[contains(@class,'active')] and //span[contains(.,'active text')]")).Text;

Every time i get no such element found
ANythoughts
this is the html code

 some text

         Active Text


问:
Slow "Select" Query with varchar(max)
I have a small table with 500 rows.
This table has 10 columns including one varchar(max) column.

When I perform this query:

```<code>SELECT TOP 36 *
FROM MyTable
WHERE (Column1 = Value1)
</code>```

It retrieves around 36 rows in 3 minutes.
The varchar(max) columns contains in each row 3000 characters.

If I try to retrieve only one row less:

```<code>SELECT TOP 35 *
FROM MyTable
WHERE (Column1 = Value1)
</code>```

Then the query retrieves 35 rows in 0 seconds.

In my clients statistics, Bytes received from server, I have:

95 292 for the query retrieving data in 0 sec

over 200 000 000 for the query retrieving data in 3 min

Do you know does it come from?

EDIT --- Here is my real code:

```<code>select top 36 *
from Snapshots
where ExamId = 212

select top 35 *
from Snapshots
where ExamId = 212
</code>```

EDIT --- More info on clients statistics

The two statistics having a huge variation are:

Bytes received from server : 66 038 Vs  More than 2 000 000

TDS packets received from server 30 Vs 11000

答:
Your execution time should be very low, while fetch is much longer.
Remove the varchar(max) from the SELECT TOP statement and only retrieve those values as you specifically need them.</p>

Title: Slow "Select" Query with varchar(max)

Body:
I have a small table with 500 rows.
This table has 10 columns including one varchar(max) column.

When I perform this query:

SELECT TOP 36 *
FROM MyTable
WHERE (Column1 = Value1)

It retrieves around 36 rows in 3 minutes.
The varchar(max) columns contains in each row 3000 characters.

If I try to retrieve only one row less:

SELECT TOP 35 *
FROM MyTable
WHERE (Column1 = Value1)

Then the query retrieves 35 rows in 0 seconds.

In my clients statistics, Bytes received from server, I have:

95 292 for the query retrieving data in 0 sec

over 200 000 000 for the query retrieving data in 3 min

Do you know does it come from?

EDIT --- Here is my real code:

select top 36 *
from Snapshots
where ExamId = 212

select top 35 *
from Snapshots
where ExamId = 212

EDIT --- More info on clients statistics

The two statistics having a huge variation are:

Bytes received from server : 66 038 Vs  More than 2 000 000

TDS packets received from server 30 Vs 11000


问:
How the count the number of whitespaces between the first and second word in Java
I have a string that looks like the following:

```<code>Here    is a test
</code>```

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

```<code>int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}
</code>```

答:
I take your code, just edit a bit:

```<code>public int countSpace(String line) {
    int spaceCount = 0;
    int word = 0;
    boolean isSpace = false;
    for (char c : line.toCharArray()) {
        if (c == ' ') {
            ++spaceCount;
            isSpace = true;
            continue;
        }

        if (isSpace) {
            ++word;
            isSpace = false;
        }

        if (1 == word) {
            break;
        }
    }

    return spaceCount;
}
</code>```

It's not the simplest solution and you should trim whitespace before use it.

Body:
I have a string that looks like the following:

Here    is a test

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

Body:
I take your code, just edit a bit:

public int countSpace(String line) {
    int spaceCount = 0;
    int word = 0;
    boolean isSpace = false;
    for (char c : line.toCharArray()) {
        if (c == ' ') {
            ++spaceCount;
            isSpace = true;
            continue;
        }

        if (isSpace) {
            ++word;
            isSpace = false;
        }

        if (1 == word) {
            break;
        }
    }

    return spaceCount;
}

It's not the simplest solution and you should trim whitespace before use it.


问:
Minimizing a 6 dimensional problem with 3 constraints in python
We are given a problem that required the minimization of the cost of food for a student.She has to have calories (2,000 kcal), protein (55 g), and calcium (800 mg). and there are six types of food in total. We have to do this problem with the Python CVXPY package.
Here are my code, but it is returning the ValueError: Cannot broadcast dimensions  (3,) (3, 1)error.
Here is the code of my matrix.

```<code>A=np.array([[110,205,160,160,420,260],[4,32,13,8,4,14],[2,12,54,285,22,80])
//Note:A is the matrix with the contents of all the foods//
b=np.array([[2000,55,800]])
//Note: b represents the desired value for calories, protein and calcium.//
c=np.array([[3,24,13,9,20,19]])
//Note c represents the price of the 6 types of food. //
</code>```

There was an additional criterion that was added where a max serving of each type of food was required. and my code for that looked like:

```<code>d= np.array([[4,3,2,8,2,2]])
x_vec = cp.Variable(6)
//where d represented the max serving constraints on each of the six types of foods.//
</code>```

Lastly, I have to code for the minimizing and problem-solving, which for some reason just doesn't seem to work

```<code>matrix_prob = cp.Problem(cp.Minimize(cp.sum(c.T @ x_vec)),
                        constraints=[A@x_vec <= b, x_vec <= d])
//Note:here I minize the sum of matrix c while considering the constraints of b and d.//
matrix_solution = matrix_prob.solve()
print('Optimal value (matrix form):    {:.4f}'.format(matrix_solution))
</code>```

答:
The error:

```<code>ValueError: Cannot broadcast dimensions  (3,) (3, 1)
</code>```

speaks for itself: you're trying to do an operation involving a one-dimensional and a two-dimensional object. Since the 2d object has length 1 in its second dimension, this suggests that dropping that dimension will solve your problem.

Therefore, try making b, c, and d one-dimensional arrays, e.g.:

```<code>d = np.array([4,3,2,8,2,2])
</code>```

Also: Python uses # for comments. I'm not sure why you've used //, but don't.

Body:
We are given a problem that required the minimization of the cost of food for a student.She has to have calories (2,000 kcal), protein (55 g), and calcium (800 mg). and there are six types of food in total. We have to do this problem with the Python CVXPY package.
Here are my code, but it is returning the ValueError: Cannot broadcast dimensions  (3,) (3, 1)error.
Here is the code of my matrix.

A=np.array([[110,205,160,160,420,260],[4,32,13,8,4,14],[2,12,54,285,22,80])
//Note:A is the matrix with the contents of all the foods//
b=np.array([[2000,55,800]])
//Note: b represents the desired value for calories, protein and calcium.//
c=np.array([[3,24,13,9,20,19]])
//Note c represents the price of the 6 types of food. //

There was an additional criterion that was added where a max serving of each type of food was required. and my code for that looked like:

d= np.array([[4,3,2,8,2,2]])
x_vec = cp.Variable(6)
//where d represented the max serving constraints on each of the six types of foods.//

Lastly, I have to code for the minimizing and problem-solving, which for some reason just doesn't seem to work

matrix_prob = cp.Problem(cp.Minimize(cp.sum(c.T @ x_vec)),
                        constraints=[A@x_vec <= b, x_vec <= d])
//Note:here I minize the sum of matrix c while considering the constraints of b and d.//
matrix_solution = matrix_prob.solve()
print('Optimal value (matrix form):    {:.4f}'.format(matrix_solution))

Body:
The error:

ValueError: Cannot broadcast dimensions  (3,) (3, 1)

speaks for itself: you're trying to do an operation involving a one-dimensional and a two-dimensional object. Since the 2d object has length 1 in its second dimension, this suggests that dropping that dimension will solve your problem.

Therefore, try making b, c, and d one-dimensional arrays, e.g.:

d = np.array([4,3,2,8,2,2])

Also: Python uses # for comments. I'm not sure why you've used //, but don't.


问:
Image uploaded with Active storage not showing in the view
I am trying to upgrade and a Rails app to RoR6 with ActiveStorage.
In the view, I use an image_tag on the attached image called "whiteboard_background" on @project.

And it shows a broken link in the browser:
Link

Environment: development and files stored locally

Model:

```<code>class Project < ApplicationRecord

  has_one_attached :whiteboard_background
</code>```

View code:

```<code>attachment: <%= @project.whiteboard_background.attached? %>
<p>image:
<%= image_tag @project.whiteboard_background if @project.whiteboard_background.attached? %>
</p>
</code>```

Server:

```<code>Started GET "/projects/6" for 127.0.0.1 at 2020-02-19 20:29:27 +0100
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"6"}
...
ActiveStorage::Attachment Load (2.8ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4  [["record_id", 6], ["record_type", "Project"], ["name", "whiteboard_background"], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:94
  ActiveStorage::Blob Load (0.6ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:96
  Location Load (0.5ms)  SELECT "locations".* FROM "locations" ....
</code>```

I have checked that @project.whiteboard_background.attached? is true and in the console Project.last.whiteboard_background.metadata gives correct image data which indicates that the upload works fine.

The Firefox inspector does show the element with a source path, but says "could not load image". Same behaviour in chrome

If I repeat the process in a blank test app from scratch, it works fine and i can display the image.

Any idea?

答:
For images on local storage use this

```<code><%= url_for(@project.whiteboard_background) %>
</code>```

It if is in production and on something like S3 then you probably want something like this

```<code><%= @project.whiteboard_background.service_url %>
</code>```

Body:
I am trying to upgrade and a Rails app to RoR6 with ActiveStorage.
In the view, I use an image_tag on the attached image called "whiteboard_background" on @project.

And it shows a broken link in the browser:
Link

Environment: development and files stored locally

Model:

class Project < ApplicationRecord

  has_one_attached :whiteboard_background

View code:

attachment: <%= @project.whiteboard_background.attached? %>

image:
<%= image_tag @project.whiteboard_background if @project.whiteboard_background.attached? %>

Server:

Started GET "/projects/6" for 127.0.0.1 at 2020-02-19 20:29:27 +0100
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"6"}
...
ActiveStorage::Attachment Load (2.8ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4  [["record_id", 6], ["record_type", "Project"], ["name", "whiteboard_background"], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:94
  ActiveStorage::Blob Load (0.6ms)  SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2  [["id", 13], ["LIMIT", 1]]
  ↳ app/views/projects/show.html.erb:96
  Location Load (0.5ms)  SELECT "locations".* FROM "locations" ....

I have checked that @project.whiteboard_background.attached? is true and in the console Project.last.whiteboard_background.metadata gives correct image data which indicates that the upload works fine.

The Firefox inspector does show the element with a source path, but says "could not load image". Same behaviour in chrome

If I repeat the process in a blank test app from scratch, it works fine and i can display the image.

Any idea?

Body:
For images on local storage use this

<%= url_for(@project.whiteboard_background) %>

It if is in production and on something like S3 then you probably want something like this

<%= @project.whiteboard_background.service_url %>


问:
Need help understanding jQuery .val() function
```<code>alert("data going into $hidden: " + selected.data[1]);

hidden.val(selected.data[1]);

alert("data now in $hidden: " + $hidden.val());
</code>```

What would be a reason that $hidden.val() in the last line above would return undefined?  I have verified that selected.data[1] contains an integer value.

Edit #1: Some additional context per comments:  ($hidden is a hidden input field)

```<code>$.fn.extend({
    autocomplete: function(urlOrData, hidden, options) {
        var isUrl = typeof urlOrData == "string";
        var $hidden = $(hidden);
        options = $.extend({}, $.Autocompleter.defaults, {
            url: isUrl ? urlOrData : null,
            data: isUrl ? null : urlOrData,
            delay: isUrl ? $.Autocompleter.defaults.delay : 10,
            max: options && !options.scroll ? 10 : 150
        }, options);

        // if highlight is set to false, replace it with a do-nothing function
        options.highlight = options.highlight || function(value) { return value; };

        // if the formatMatch option is not specified, then use formatItem for backwards compatibility
        options.formatMatch = options.formatMatch || options.formatItem;

        return this.each(function() {
            new $.Autocompleter(this, options, $hidden);
        });
</code>```

and...

```<code>$.Autocompleter = function(input, options, $hidden) {
        //...

        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            alert("data going into $hidden: " + selected.data[1]);

            $hidden.val(selected.data[1]);

            alert("data now in $hidden: " + $hidden.val());
</code>```

Edit #2:  More details.... I'm trying to use the jQuery autocomplete extension on a form with multiple textbox controls (each implement the autocomplete).  There's a seperate button on the form beside each textbox that submits the form to a handler function that needs to find the value of the item selected and save it to the db.  The way I thought to go about this was to include a hidden field on the form to hold the selected value.

答: Could $hidden be a checkbox that is not checked?</p>

OwnerDisplayName: Aaron Palmer

Body:
alert("data going into $hidden: " + selected.data[1]);

hidden.val(selected.data[1]);

alert("data now in $hidden: " + $hidden.val());

What would be a reason that $hidden.val() in the last line above would return undefined?  I have verified that selected.data[1] contains an integer value.

Edit #1: Some additional context per comments:  ($hidden is a hidden input field)

$.fn.extend({
    autocomplete: function(urlOrData, hidden, options) {
        var isUrl = typeof urlOrData == "string";
        var $hidden = $(hidden);
        options = $.extend({}, $.Autocompleter.defaults, {
            url: isUrl ? urlOrData : null,
            data: isUrl ? null : urlOrData,
            delay: isUrl ? $.Autocompleter.defaults.delay : 10,
            max: options && !options.scroll ? 10 : 150
        }, options);

        // if highlight is set to false, replace it with a do-nothing function
        options.highlight = options.highlight || function(value) { return value; };

        // if the formatMatch option is not specified, then use formatItem for backwards compatibility
        options.formatMatch = options.formatMatch || options.formatItem;

        return this.each(function() {
            new $.Autocompleter(this, options, $hidden);
        });

and...

$.Autocompleter = function(input, options, $hidden) {
        //...

        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            alert("data going into $hidden: " + selected.data[1]);

            $hidden.val(selected.data[1]);

            alert("data now in $hidden: " + $hidden.val());

Edit #2:  More details.... I'm trying to use the jQuery autocomplete extension on a form with multiple textbox controls (each implement the autocomplete).  There's a seperate button on the form beside each textbox that submits the form to a handler function that needs to find the value of the item selected and save it to the db.  The way I thought to go about this was to include a hidden field on the form to hold the selected value.

LastEditorDisplayName: Aaron Palmer

OwnerDisplayName: Daniel Von Fange


答:
If you insist on doing this, at least wrap the ugliness up in an operator, so the rest of the code can be written at least reasonably cleanly:

```<code>#include <iostream>
using namespace std;
enum num
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
};

num &operator|=(num &a, num const &b) {
    a = static_cast<num>(a | b);
    return a;
}

int main()
{
    num numFlag;
    numFlag |= NUM_TWO;
}
</code>```

But keep in mind that this will let you generate values that aren't in your enumeration. For example, a sequence like:

```<code>num a{NUM_ZERO};
a |= NUM_TWO;
a |= NUM_THREE;
</code>```

...gives a a value that's not in the enumeration.

Title: error: invalid conversion from ‘int’ to enum c++

Body:
I am getting "error: invalid conversion from ‘int’ to ‘num'" when i compile the below sample code in c++. Typecasting it with enum name doesn't help.

#include <iostream>
using namespace std;
typedef enum
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
} num;

int main()
{
    num* numFlag;
    *numFlag |= static_cast<num>(NUM_TWO);
    return 0;
}

Please let me know if anyone knows how to resolve this.

Body:
If you insist on doing this, at least wrap the ugliness up in an operator, so the rest of the code can be written at least reasonably cleanly:

#include <iostream>
using namespace std;
enum num
{
    NUM_ZERO = 0,
    NUM_ONE = 1,
    NUM_TWO = 2,
    NUM_THREE = 4
};

num &operator|=(num &a, num const &b) {
    a = static_cast<num>(a | b);
    return a;
}

int main()
{
    num numFlag;
    numFlag |= NUM_TWO;
}

But keep in mind that this will let you generate values that aren't in your enumeration. For example, a sequence like:

num a{NUM_ZERO};
a |= NUM_TWO;
a |= NUM_THREE;

...gives a a value that's not in the enumeration.


问:
Schedule task to load BigQuery table into Apache Ignite
I have a use case where we need to periodically load BigQuery table in to a cache and support SQL query from there. I'm doing researching on Apache Ignite and think it could be a good fit to our use case. Only that it's not clear to me yet how I can get auto-load from BigQuery. By "auto-load" I mean to keep Apache Ignite updated with BigQuery table data and let this updating transparent to applications. In most cases, our BigQuery tables are updated by other scheduled jobs/queries with intervals from 5 minutes to 1 month.

I'm new to Ignite, and I guess my questions are as the following:

Is this a feature supported in Ignite already? (I couldn't find any)

Or is there any exiting pluggins already? (I couldn't find any)

how to implement the auto-load cache for BigQuery using Ignite?

答: You can do this once with Cache Store / loadCache(), but doing this every few minutes is infeasible. You may wish to design a BigQuery streamer to Apache Ignite, if it supports pushing of deltas.</p>


问:
bootstrap-select - dropdown disappeares when i add selectpicker class to the select tag
When i add the selectpicker class to my select tag and run my page in the browser, it doesn't show any <select> box...

Detail, when i remove the selectpicker class, it run normally. Anyway, it's possible to see the select box in code source.

```<code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.min.js"></script>

<!-- (Optional) Latest compiled and minified JavaScript translation files -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/i18n/defaults-*.min.js"></script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>
<body>

<select class="selectpicker" data-live-search="true" name="cidade">

<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>

</body>
</code>```

答:
I faced a similar issue. Through an AJAX request to my controller a string with the HTML was returned but I was not able to append it to the DOM. Nevertheless it appeared in the DOM upon inspection. It turned out that the problem was the selectpicker class. When removed, the HTML was appended successfully, and the element was not acting as expected, naturally.
After some search I came across the following solution:

$('.selectpicker').selectpicker('refresh')

Found it here with explanation why this might happen.
Hope this helps.

Cheers!

Body:
When i add the selectpicker class to my select tag and run my page in the browser, it doesn't show any <select> box...

Detail, when i remove the selectpicker class, it run normally. Anyway, it's possible to see the select box in code source.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<select class="selectpicker" data-live-search="true" name="cidade">

<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test3">Test 3</option>
</select>