问:
rails mongoid dynamc model fails
I am using rails/mongodb as my backend server for my web application.

My database needs to be very flexible - I need to be able to define new tables and modify them during runtime. So I created a model Entity and a model Column (belongs to Entity) so I can dynamically create new models with dynamic columns.

To create/read/update the records I wrote a function which I can call with the entity record and it returns the class of the requested model:

I call the function getObject with the Entity record:

```<code>entity = Entity.find_by(name: obj)
datarecord = getObject(entity)
</code>```

Using this function:

```<code>def getObject(entity)

  obj= Class.new() do
      include Mongoid::Document
      include Mongoid::Attributes::Dynamic
      store_in collection: entity.name.pluralize.downcase

      entity.columns.each do |column|
          field column[:fieldNameOrPath]
      end

      entity.relationships.each do |relationship|
        if relationship.typ =='Belongs To'
          e = Entity.find(relationship.relationship_id)
          belongs_to e.name.downcase
          default_scope { includes(e.name.downcase)}
        end
        if relationship.typ =='Has Many'
          e = Entity.find(relationship.relationship_id)
          has_many e.name.pluralize.downcase
        end
        if relationship.typ =='Has And Belongs To Many'
          e = Entity.find(relationship.relationship_id)
          has_and_belongs_to_many e.name.pluralize.downcase
        end
      end

#     def as_json(options={})
#        attrs = super(:include => [:user])
#        attrs["user"]["id"] = attrs["user"]["_id"].to_s
#        attrs
#     end
     end
   end
   obj
end
</code>```

This works when I use the returned object obj to retrieve data:

```<code>render json: { result: datarecord.all()}
</code>```

It also works for creating and updating new records. But as soon as my entity has 'Belongs To' relationship I get runtime errors:

```<code>NoMethodError (undefined method `demodulize' for nil:NilClass):
</code>```

Or

```<code>NoMethodError (undefined method `constantize' for nil:NilClass):
</code>```

I guess the issues is that I have no class defined for the related models?

My second problem is that I want to have other records which this record belongs_to automatically loaded. In a static implementation I can achieve this definde a as_json method which includes the associated records (see the commented rows in my code). But I dont know how I can do this in my dynamic model.

Any idea whats going wrong here and how to fix it? Not sure my way to implement this is the right weay anyway - perhaps there is a better way?

Thanks,
Michael

答:
Mongoid's relations code does a lot of guessing, based on the name (as do many other parts of rails or gems, like active_model_serializer or what-have-you). So if you have class User, it will assume, without any additional configuration, that it should be stored in collection users, by doing something along these lines:

```<code>user.class.name.tableize
</code>```

I don't see the full stack trace of your errors, so I can't tell where exactly it's coming from, but the root cause of this is that your dynamic classes have no name.

```<code>datarecord.name # => nil
</code>```

A class acquires a name by being assigned to a constant. (and maybe some other way, but I can't remember now.)

```<code>datarecord.name # => nil
FooBar = datarecord
datarecord.name # => 'FooBar'
</code>```

Title: rails mongoid dynamc model fails

Body:
I am using rails/mongodb as my backend server for my web application.

My database needs to be very flexible - I need to be able to define new tables and modify them during runtime. So I created a model Entity and a model Column (belongs to Entity) so I can dynamically create new models with dynamic columns.

To create/read/update the records I wrote a function which I can call with the entity record and it returns the class of the requested model:

I call the function getObject with the Entity record:

entity = Entity.find_by(name: obj)
datarecord = getObject(entity)

Using this function:

def getObject(entity)

  obj= Class.new() do
      include Mongoid::Document
      include Mongoid::Attributes::Dynamic
      store_in collection: entity.name.pluralize.downcase

      entity.columns.each do |column|
          field column[:fieldNameOrPath]
      end

      entity.relationships.each do |relationship|
        if relationship.typ =='Belongs To'
          e = Entity.find(relationship.relationship_id)
          belongs_to e.name.downcase
          default_scope { includes(e.name.downcase)}
        end
        if relationship.typ =='Has Many'
          e = Entity.find(relationship.relationship_id)
          has_many e.name.pluralize.downcase
        end
        if relationship.typ =='Has And Belongs To Many'
          e = Entity.find(relationship.relationship_id)
          has_and_belongs_to_many e.name.pluralize.downcase
        end
      end

#     def as_json(options={})
#        attrs = super(:include => [:user])
#        attrs["user"]["id"] = attrs["user"]["_id"].to_s
#        attrs
#     end
     end
   end
   obj
end

This works when I use the returned object obj to retrieve data:

render json: { result: datarecord.all()}

It also works for creating and updating new records. But as soon as my entity has 'Belongs To' relationship I get runtime errors:

NoMethodError (undefined method `demodulize' for nil:NilClass):

Or

NoMethodError (undefined method `constantize' for nil:NilClass):

I guess the issues is that I have no class defined for the related models?

My second problem is that I want to have other records which this record belongs_to automatically loaded. In a static implementation I can achieve this definde a as_json method which includes the associated records (see the commented rows in my code). But I dont know how I can do this in my dynamic model.

Any idea whats going wrong here and how to fix it? Not sure my way to implement this is the right weay anyway - perhaps there is a better way?

Thanks,
Michael

Body:
Mongoid's relations code does a lot of guessing, based on the name (as do many other parts of rails or gems, like active_model_serializer or what-have-you). So if you have class User, it will assume, without any additional configuration, that it should be stored in collection users, by doing something along these lines:

user.class.name.tableize

I don't see the full stack trace of your errors, so I can't tell where exactly it's coming from, but the root cause of this is that your dynamic classes have no name.

datarecord.name # => nil

A class acquires a name by being assigned to a constant. (and maybe some other way, but I can't remember now.)

datarecord.name # => nil
FooBar = datarecord
datarecord.name # => 'FooBar'


来源: stackexchange

问:
Positionning button from bottom screen
I am doing some XML for an android app.

I have images, text, and button in my view.

I used a Linear layout, but I think it's not what I need.

I would like to set my last button to 80 dp from the bottom screen. Regardless the smartphone and the size of the screen.
I want my button to be at 80 dp from the bottom of all device.

I have no idea how to do it if someone can help me it could be cool!

I tried with a LinearLayout but i think i can't do it.

Now I'm trying with a constraintLayout but I'm not sure it will work.

Thanks

答:
You can do it with a RelativeLayout and layout_alignParentBottom take a look at this:

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<TextView
    android:id="@+id/textview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="textview1"/>

<ImageView
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_below="@+id/textview1"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="Button"
    android:layout_marginBottom="80dp"
    android:layout_alignParentBottom="true"/>

 </RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Positionning button from bottom screen

Body:
You can do it with a RelativeLayout and layout_alignParentBottom take a look at this:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<TextView
    android:id="@+id/textview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="textview1"/>

<ImageView
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:layout_below="@+id/textview1"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:text="Button"
    android:layout_marginBottom="80dp"
    android:layout_alignParentBottom="true"/>

 </RelativeLayout>


问:
How do I install all packages that are included in Anaconda?
I'm attending a course which advises us to use anaconda. Because of this, there is no requirements.txt, but rather only packages included in anaconda are required.

Since I already have a python environment set up, I dont want to install another python. Is there a requirements.txt that installs all packages from anaconda?

答:
Check https://docs.anaconda.com/anaconda/packages/pkg-docs when you select the desired python version and target OS and architecture you will see all available packages and there is a column with the packages that are included by default in the anaconda installer.

For example python 2.7 win 64bits

You could make a python script to check for  and make a txt of the default packages.

EDIT:
Adding another way I suggested in comments below.

Alternative method:
Using online regex web services

Step 1: copy the html table removing for simpler regex the unnecesary tags and keeping the tr td tags like so

    _nb_ext_conf
    0.4.0
    A configuration metapackage for enabling Anaconda-bundled jupyter extensions / BSD

Step 2: Paste it into a regex web like regexr and craft your regex, I managed to come up real quick with this one: (.+)<\/a><\/td>\s+.+<\/td>\s+.+<\/td>\s+<i.+check.+<\/td> im pretty sure it can be improved but works.

Step 3: get your list by specifying how you want to output your capture group: $1 \n $1 is your capture group and \n is newline, so you would get a list of packages like so:

alabaster
anaconda-client
anaconda-navigator
anaconda-project
asn1crypto
astroid
astropy
babel

Body:
Check https://docs.anaconda.com/anaconda/packages/pkg-docs when you select the desired python version and target OS and architecture you will see all available packages and there is a column with the packages that are included by default in the anaconda installer.

For example python 2.7 win 64bits

You could make a python script to check for <i class="fa fa-check"></i> and make a txt of the default packages.

EDIT:
Adding another way I suggested in comments below.

Alternative method:
Using online regex web services

Step 1: copy the html table removing for simpler regex the unnecesary tags and keeping the tr td tags like so

<tr>
    <td><a href="https://github.com/ContinuumIO/anaconda-nb-extensions-meta-config">_nb_ext_conf</a></td>
    <td>0.4.0</td>
    <td>A configuration metapackage for enabling Anaconda-bundled jupyter extensions / BSD</td>
    <td></td>
  </tr>

Step 2: Paste it into a regex web like regexr and craft your regex, I managed to come up real quick with this one: <td><a.+">(.+)<\/a><\/td>\s+<td>.+<\/td>\s+<td>.+<\/td>\s+<td><i.+check.+<\/td> im pretty sure it can be improved but works.

Step 3: get your list by specifying how you want to output your capture group: $1 \n $1 is your capture group and \n is newline, so you would get a list of packages like so:

alabaster
anaconda-client
anaconda-navigator
anaconda-project
asn1crypto
astroid
astropy
babel


问:
Python Telegram bot keyboard
i'm trying to do buttons,inline buttons,

```<code>json.dumps({"keyboard":[[{'text':'yayaya','request_contact':True},{'text':'google','url':'https://tts.ua'}]],})
</code>```

First button wokrs, but other send only text, please help me

答:
You want to use keyboard, which only supported requests.

But url is parameter of inline_keyboard, you can't use both at the same time.

Title: Python Telegram bot keyboard

Body:
i'm trying to do buttons,inline buttons,

json.dumps({"keyboard":[[{'text':'yayaya','request_contact':True},{'text':'google','url':'https://tts.ua'}]],})

First button wokrs, but other send only text, please help me


问:
Swing Table - rows
I have to build a table with one column,exactly 24 rows and with function to add more columns.
Each row must have a specific height, which I do with cell renderer.
The problem is that the 21 row shrink and when I add a column it look fine.
What is the problem?</p>

答:
Setting the height of the rows:

myTable.setRowHeight (24);

works with both Default and AbstractTableModels
Now if I only could find a way to make the height of the header same as the rows!
Anybody went there? Thanks, - M.S.

Title: Swing Table - rows

ContentLicense: CC BY-SA 2.5


问:
why is it not possible to check a type as instance of `Null`
Why I cannot check whether a type is Null?

```<code>scala> val s:String = null
s: String = null

scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]

                 ^
</code>```

答:
The general contract of x.isInstanceOf[C] is to return true if and only if x is an instance of C. Being "an instance of" anything implies that x is not null.

According to that specification, x.isInstanceOf[Null] must always return false, since x would not be an instance of Null even if it happens to be null. The compiler protects you from that confusion by refusing to compile that test instead.

The idiomatic way to test whether x is null is to simply use

```<code>x == null
</code>```

Body:
Why I cannot check whether a type is Null?

scala> val s:String = null
s: String = null

scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]

                 ^

Body:
The general contract of x.isInstanceOf[C] is to return true if and only if x is an instance of C. Being "an instance of" anything implies that x is not null.

According to that specification, x.isInstanceOf[Null] must always return false, since x would not be an instance of Null even if it happens to be null. The compiler protects you from that confusion by refusing to compile that test instead.

The idiomatic way to test whether x is null is to simply use

x == null


问:
STUR X9,[X2,X12]
Assume a number in stored in the register X12 and X2 is the address and X9 has another number, Does this work? STUR X9,[X2,X12]</p>

答:
If you want to use a register offset addressing mode to store a register you can use the STR instruction. So the following:

```<code>str x9, [x2, x12]
</code>```

assembles just fine for aarch64 and disassembles as

```<code>f82c6849    str x9, [x2, x12]
</code>```

Title: STUR X9,[X2,X12]

Body:
If you want to use a register offset addressing mode to store a register you can use the STR instruction. So the following:

str x9, [x2, x12]

assembles just fine for aarch64 and disassembles as

f82c6849    str x9, [x2, x12]


问:
How to hide or disable the input field which appears when clicking the axis in plotly.js?
How to hide or disable the input field which appears when clicking the axis in plotly.js?

答:
Fixed the issue. Add this to your CSS:</p>

```<code>.drag.wdrag.cursor-w-resize {
  display: none;
}
</code>```

Body:
Fixed the issue. Add this to your CSS:

.drag.wdrag.cursor-w-resize {
  display: none;
}


问:
Owl Carousel 2 - how to get a current item?
I am working on a web site with Owl Carousel 2.
I just want to detect which item is displayed on the front.

It used to be like this.
http://owlgraphic.com/owlcarousel/demos/owlStatus.html

```<code>$(document).ready(function() {

  var owl = $("#owl-demo"),
      status = $("#owlStatus");

  owl.owlCarousel({
    navigation : true,
    afterAction : afterAction
  });

  function updateResult(pos,value){
    status.find(pos).find(".result").text(value);
  }

  function afterAction(){
    updateResult(".currentItem", this.owl.currentItem);
  }
});
</code>```

But it is an example of version 1.
In version 2, the above doesn't work, and it seems that we should use "info" according to the official document.
http://owlcarousel.owlgraphic.com/docs/api-options.html#info

I tried to figure out it, but there are no extra example or documents. I also went through the .js file, but couldn't get it. I wonder if the "info" is not implemented yet.

I don't really want to know about info, but just want to get data of current item.

I also tried this way below, but it doesn't work correctly.
Do you have any possible solutions?

```<code>var active = $("#owl-demo").find(".owl-item.active");
console.log(active.text());
</code>```

答:
```<code>owl.on('changed.owl.carousel', function (e) {
    //console.log("current: ",e.item.index) //same
    if (("current: ",e.item.index == 0)){
        console.log("page01");
    }
    if (("current: ",e.item.index == 1)){
        console.log("page02");
    }
})
</code>```

Body:
I am working on a web site with Owl Carousel 2.
I just want to detect which item is displayed on the front.

It used to be like this.
http://owlgraphic.com/owlcarousel/demos/owlStatus.html

$(document).ready(function() {

  var owl = $("#owl-demo"),
      status = $("#owlStatus");

  owl.owlCarousel({
    navigation : true,
    afterAction : afterAction
  });

  function updateResult(pos,value){
    status.find(pos).find(".result").text(value);
  }

  function afterAction(){
    updateResult(".currentItem", this.owl.currentItem);
  }
});

But it is an example of version 1.
In version 2, the above doesn't work, and it seems that we should use "info" according to the official document.
http://owlcarousel.owlgraphic.com/docs/api-options.html#info

I tried to figure out it, but there are no extra example or documents. I also went through the .js file, but couldn't get it. I wonder if the "info" is not implemented yet.

I don't really want to know about info, but just want to get data of current item.

I also tried this way below, but it doesn't work correctly.
Do you have any possible solutions?

var active = $("#owl-demo").find(".owl-item.active");
console.log(active.text());


问:
"Arithmetic overflow error converting expression to data type datetime" SQL SERVER
I am currently getting this error and i am completely lost as to what the issue is. I tracked the error down to a view and completed a select * statement from it and i get that message. Now, the weird thing is is that this error has never appeared on this view before. It has always ran without any issues and nothings been changed so i am unsure as to what the issue is.

I cant show the data for security reasons but it holds 2 date fields that are

```<code> datetime, not null
</code>```

but i am not trying to change this data in anyway, i am simply just trying to select it.

The only other fields i thought it might concern are

```<code>decimal (38,20)
</code>```

could this be the issue?

Sorry for the lack of information regarding the tables but i have literally tried everything from casting the fields to larger decimals, floats etc and still nothing.

It would be great if there was any small advice anyone could give that would possibly point me in the right direction?

UPDATE

If i do a

```<code>select top (1000)
</code>```

query it works but any larger and i get that error

答:
i think there are some wrong date has been inserted in database, you need to use

ISDATE() sql function for same eg. like below in your select query

```<code> (CASE WHEN ISDATE (your_date) = 1
             THEN convert(datetime, cast([your_date] as char(8)))
             END) AS your_Date
</code>```

Body:
I am currently getting this error and i am completely lost as to what the issue is. I tracked the error down to a view and completed a select * statement from it and i get that message. Now, the weird thing is is that this error has never appeared on this view before. It has always ran without any issues and nothings been changed so i am unsure as to what the issue is.

I cant show the data for security reasons but it holds 2 date fields that are

 datetime, not null

but i am not trying to change this data in anyway, i am simply just trying to select it.

The only other fields i thought it might concern are

decimal (38,20)

could this be the issue?

Sorry for the lack of information regarding the tables but i have literally tried everything from casting the fields to larger decimals, floats etc and still nothing.

It would be great if there was any small advice anyone could give that would possibly point me in the right direction?

UPDATE

If i do a

select top (1000)

query it works but any larger and i get that error

Body:
i think there are some wrong date has been inserted in database, you need to use

ISDATE() sql function for same eg. like below in your select query

 (CASE WHEN ISDATE (your_date) = 1
             THEN convert(datetime, cast([your_date] as char(8)))
             END) AS your_Date


问:
Problem with UITableView clear color
I have a tableview in grouped style. When I set the tableview background color to clear color then I see dark black corners around the tableview. Is there a way to solve this problem and remove those dark corners?

Any help would be appreciated.

答:
You can set a UIView and set clear color to it. This works for me.</p>

```<code>UIView *backView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;
</code>```

Title: Problem with UITableView clear color

Body:
You can set a UIView and set clear color to it. This works for me.

UIView *backView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
backView.backgroundColor = [UIColor clearColor];
cell.backgroundView = backView;


问:
how to handle empty JSON responses?
```<code>[]
</code>```

this is the JSON response i'm getting when calling a webservice. i need to print nothing to show if the response is empty.

```<code>$http({
        method:'POST',
        url: 'http://xxxxxx',
        headers: {
           Content-Type: 'application/json',
           Accept: 'application/json'
        },
        data: JSON.stringify(x)
}).then(function (response) {
        $scope.details=response.data;
        if($scope.invoiceDetails == null){
           console.log("nothing to show");
        }
    });
</code>```

This is the code i'm using now. But it is not working. Someone please give me some suggestions.

答:
```<code>if (response!=undefined)
{
    //your code here
}
else{
console.log("nothing to show");
}
</code>```

something like this

Title: how to handle empty JSON responses?

Body:
[]

this is the JSON response i'm getting when calling a webservice. i need to print nothing to show if the response is empty.

$http({
        method:'POST',
        url: 'http://xxxxxx',
        headers: {
           Content-Type: 'application/json',
           Accept: 'application/json'
        },
        data: JSON.stringify(x)
}).then(function (response) {
        $scope.details=response.data;
        if($scope.invoiceDetails == null){
           console.log("nothing to show");
        }
    });

This is the code i'm using now. But it is not working. Someone please give me some suggestions.

Body:
if (response!=undefined)
{
    //your code here
}
else{
console.log("nothing to show");
}

something like this


问:
Google Analytics reports 10 times lesser sessions than hits in server logs
Let's say I've a page mysite.com/mypage

Landing Page Report in GA for this URL for a specified duration, gives me a number of sessions - say 50.

For the same duration, I checked Apache's access.log, and did a grep "GET /mypage, and I've got around 10x more hits -- say 500.

How can we have a 10x anomaly between GA & Server Logs? Where did the hits go?

This anomaly is present for other durations too. I've compared various durations.

Before someone tells the standard reasons for this, let me point out that:

A difference of 2x or 3x is understandable, but not 10x.

No, this is not Bot Traffic. I extracted all unique IPs from the logs, and the IPs are 99% unique. So the traffic is all coming from different IPs.

I also analyzed user agents, and they all look real (with various models of phones like iPhone, Samsung etc.)

GA also says that this report is based on 100% data (sampling ruled out).

As I pointed out, I'm only counting the GET requests to the /mypage. That is, I'm not counting asset downloads, favicon hits etc. etc.

I performed another test. I took all IPs, then made them unique, then for each IP I analyzed how many hits came from that IP. I found from 84% of the IPs, there's no second request. They made only 1 request.

I've read Anamoly between google analytics and server hits and have taken care of everything given in the accepted answer.

What could it be? Any clues on how to debug this? The traffic is coming from Paid Facebook Ads.

答:
Facebook has some sort of pre-load mechanism on mobile, that fetches data for a lot of external objects just in case the user might want to actually view them.

Apparently that thing is called “Facebook Liger”, check if what is described here matches the requests you’re seeing: http://inchoo.net/dev-talk/magento-website-hammering-facebook-liger/

You should be able to detect this via the User-Agent header, and maybe exclude those requests from your analytics.


问:
addEventListener for "offline" firing multiple times in ionic
For some reason, When the application goes into offline mode the event listener is firing multiple times and how to make it fire only once.</p>

```<code>  $rootScope.$on('$ionicView.afterEnter', function (event, view) {

    $rootScope.online = navigator.onLine;
    var popup;

    $window.addEventListener("offline", function () {
      $rootScope.$apply(function () {
        $rootScope.online = false;
        popup = $ionicPopup.confirm({
          title: 'Network Problem',
          content: 'Sorry, Please Check Your Network Connection.'
        })
      });
    }, false);
    $window.addEventListener("online", function () {
      $rootScope.$apply(function () {
        $ionicLoading.show({
          template: '<p>Loading...</p><ion-spinner></ion-spinner>',
        });
        $rootScope.online = true;
        $state.reload();
  }, false);
});
</code>```

答:
By clearing cache, event firing only once.</p>

```<code> $rootScope.$on('$ionicView.afterLeave', function (event, view) {
   $ionicHistory.clearCache();
 });
</code>```

Body:
For some reason, When the application goes into offline mode the event listener is firing multiple times and how to make it fire only once.

  $rootScope.$on('$ionicView.afterEnter', function (event, view) {

    $rootScope.online = navigator.onLine;
    var popup;

    $window.addEventListener("offline", function () {
      $rootScope.$apply(function () {
        $rootScope.online = false;
        popup = $ionicPopup.confirm({
          title: 'Network Problem',
          content: 'Sorry, Please Check Your Network Connection.'
        })
      });
    }, false);
    $window.addEventListener("online", function () {
      $rootScope.$apply(function () {
        $ionicLoading.show({
          template: '
Loading...
<ion-spinner></ion-spinner>',
        });
        $rootScope.online = true;
        $state.reload();
  }, false);
});

Body:
By clearing cache, event firing only once.

 $rootScope.$on('$ionicView.afterLeave', function (event, view) {
   $ionicHistory.clearCache();
 });


问:
Getting the field of an object
I have objects like below

```<code>{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}
</code>```

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

答:
Don't forget to check errors after json_decode, like this:

```<code>$payload = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON.');
}
// also you cah check this
if (property_exists($payload, 'user')) {
    var_export($payload->user);
}
</code>```

Title: Getting the field of an object

Body:
I have objects like below

{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}

I need to get 'user' field, ..->type returns "template_created" and ..->count gives its value but ..->user returns null. These objects come from mongodb aggregation framework by the way.

Body:
Don't forget to check errors after json_decode, like this:

$payload = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON.');
}
// also you cah check this
if (property_exists($payload, 'user')) {
    var_export($payload->user);
}


问:
Position sticky broken in Firefox 57
I'm trying to use position sticky to make a sticky table header.

The following jsfiddle works in Chrome v64, but isn't working in Firefox v57.

https://jsfiddle.net/b5fv94m0/

Is there some additional CSS I'm missing to make it work in Firefox?

CSS

```<code>.container {
  height: 200px;
  overflow: scroll;
}

th {
  position: sticky;
  top: 0;
}
</code>```

HTML

```<code><div class="container">
<table>
<thead>
  <tr>
    <th>Header</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
  <tr>
    <td>Cell</td>
  </tr>
</tbody>
</table>
</div>
</code>```

答:
Most of the browsers are not supporting this position: sticky attribute as mentioned it's an experimental API. Instead of that use position: fixed; for making it sticky.

Check here for browser compatibility.

Title: Position sticky broken in Firefox 57

Body:
I'm trying to use position sticky to make a sticky table header.

The following jsfiddle works in Chrome v64, but isn't working in Firefox v57.

https://jsfiddle.net/b5fv94m0/

Is there some additional CSS I'm missing to make it work in Firefox?

CSS

.container {
  height: 200px;
  overflow: scroll;
}

th {
  position: sticky;
  top: 0;
}

HTML

    Header

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell

    Cell


问:
Open Source (Free) ASP.NET Site Seacrch
Does anybody know of an easy to implement site search engine for asp.net? The less complicated the better.

Probably just needs a crawler and backend to store results. Some sort of API to get the search results back would be handy but I can get it straight from the DB as well.

答: Take a look at Lucene.Net. It is a .Net port of a very mature Java search engine. I've heard very good things about the .Net version. </p>

OwnerDisplayName: William

Title: Open Source (Free) ASP.NET Site Seacrch

OwnerDisplayName: Jim Blizard


问:
Selecting arrays with specific element values
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

```<code>// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}
</code>```

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

```<code>var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];
</code>```

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

答:
May set up a gallery map:

```<code>const galleries = new Map();
</code>```

Then fill in your media:

```<code>media.forEach( ([path, gallery]) => {
  if( galleries.has(gallery) ){
    galleries.get(gallery).push(path);
  } else {
    galleries.set(gallery, [path]);
  }
});
</code>```

So now you can get the paths in a gallery like this:

```<code>console.log(galleries.get("somegallery"));
</code>```

Body:
This is driving me nuts, I've been trying to figure out how to do this one thing for hours now.

What I want to do is select all array items that have a specific value. This is easiest to explain by example:

I have an array, called media[]. It holds ALL of the media in my media gallery. It has two properties of note: path and gallery, or media[x][0] and media[x][1].

I want to select all media objects that belong in a certain gallery, and then add them to that gallery. That's where I'm struggling and it's driving me mad.

Here are my fumbled attempts at trying to do this... this is some seriously messy code (and mostly pointless), I'm just providing it so you can get a sense of how clueless I am about this. Please note that NONE of the code I have right now actually tries to do anything; everything I've done so far ends up as a broken for or while loop that either does nothing or crashes Chrome.

// this function is meant to return an array of all media items
// that belong in a certain gallery... didn't get that far because
// the loops tripped me up
function getTheMedia (galNum) {
    var output = [];
    for (var i = 0; i < media.length; ++i) {
        // I tried using an if statement here to check if the
        // media[i][1] == galNum, and if so, add it to the output
        // but that didn't work
        output.push(media[i]);
    }
    return output;
}

// this function was actually my first attempt but I kept running into
// the same issue as above
function fillGal () {
    /*
    var output = [];
    for (var i = 0; i < Gallery.length; ++i) {
        output.push(Gallery[i]);
    }
    */
    var output = [];
    var i = 0;
    while (i < media.length) {
        output.push(i);
        i++;
    }
    console.log(output);
}

Seeing as I'm kind of burnt out and frustrating with running in circles (...loops? aha...), all I'm really looking for is a way to select only those specific array items as specified above. Everything else (adding them to the Gallery, etc) I can figure out myself.

Otherwise I'm just going to have to go back to the old way: define separate media[]arrays for each "gallery" (mediaThisGallery, mediaThatGallery, etc), and then combine them all at the end to get "allMedia". Only reason I don't want to do that is because I want to be able to change which gallery a media item belongs to... this HAS to be possible, right?

Thanks in advance! Sorry for the scatter-brainedness. I also apologize if the title is a bit off.

EDIT:

var media = [];

media[0] = ['0.png', 0, 'index'];
media[1] = ['0.png', 0];

media[2] = ['new/316.png', 1, "316"];
media[3] = ['new/kitties.jpg', 1, "D'aww kitties!!"];
media[4] = ['new/home.jpg', 1, "\"I'm Going Home\""];
media[5] = ['new/3.mp4', 1, "Crucible Carnage"];
media[6] = ['new/942.jpg', 1, "this is straight for testing purposes like omg long ass title lol"];
media[7] = ['new/boom.mp4', 1, "Maximum Efficiency"];
media[8] = ['new/42.jpg', 1, "Moo"];

// this is only included as a quick fix so my working code doesn't break
// as my "production" code is using multiple arrays; Media is used
// to store only the selected array (current Gallery)
// in other words, ignore this
var Media = [];
Media = media;

var Gallery = [];
Gallery[0] = [mediaRoot, "index", media ];
Gallery[1] = [mediaRoot, "new", Media ];

It's pretty arbitrary atm.

Note that the main reason I'm converting from multiple arrays to a single array is that eventually, I plan to expand this app and I thought it made more sense to store ALL media in a single "database".

Body:
May set up a gallery map:

const galleries = new Map();

Then fill in your media:

media.forEach( ([path, gallery]) => {
  if( galleries.has(gallery) ){
    galleries.get(gallery).push(path);
  } else {
    galleries.set(gallery, [path]);
  }
});

So now you can get the paths in a gallery like this:

console.log(galleries.get("somegallery"));


问:
Is it possible to disable type checks when transpiling typescript via tsc to speed up transpiling?
TypeScript checks the entire codebase on transpiling, even if only one file has actually changed. For small projects, that is fine, yet since our codebase grew, it takes quite a long time.

During development, I want quick response time of my unit tests. The unit test should run as soon as possible.

Unfortunately, I have to wait on each run about 10-15 seconds for the unit test to even start as the the tsc takes a long time to transpile, and of that time 60%-80% is spent on checking.

These example runs are just from removing and adding a newline in one file:

```<code>yarn tsc v0.27.5
$ "/home/philipp/fancyProject/node_modules/.bin/tsc" "--watch" "--diagnostics"
Files:           511
Lines:        260611
Nodes:        898141
Identifiers:  323004
Symbols:      863060
Types:        302553
Memory used: 704680K
I/O read:      0.17s
I/O write:     0.09s
Parse time:    2.61s
Bind time:     0.95s
Check time:    7.65s
Emit time:     1.45s
Total time:   12.65s
00:35:34 - Compilation complete. Watching for file changes.

00:41:58 - File change detected. Starting incremental compilation...

Files:            511
Lines:         260612
Nodes:         898141
Identifiers:   323004
Symbols:       863060
Types:         302553
Memory used: 1085950K
I/O read:       0.00s
I/O write:      0.04s
Parse time:     0.68s
Bind time:      0.00s
Check time:    12.65s
Emit time:      1.36s
Total time:    14.69s
00:42:13 - Compilation complete. Watching for file changes.

00:42:17 - File change detected. Starting incremental compilation...

Files:            511
Lines:         260611
Nodes:         898141
Identifiers:   323004
Symbols:       863060
Types:         302553
Memory used: 1106446K
I/O read:       0.00s
I/O write:      0.12s
Parse time:     0.32s
Bind time:      0.01s
Check time:     9.28s
Emit time:      0.89s
Total time:    10.50s
00:42:27 - Compilation complete. Watching for file changes.
</code>```

I wonder if there is a way to tell typescript:

Just treat everything as OK and just dump the JavaScript as quickly as possible to the disk.

I want to ensure first that my unit test pass in order to have a quick feedback loop.

And since my IDE takes care of the type checks already within the file I am currently working on, I rarely have mistake in the check of the transpiling anyway. And if there was a big issue, my unit tests should catch them.

When building the project, I would just use the classic tsc with the checks. As I have said, this is only for development and having a quick feedback loop.

答:
Start using WebPack

Add awesome-typescript-loader

Set transpileOnly in setting to true

Also you can change other paramers, which can boost speed: ignoreDiagnostics, forceIsolatedModules, etc.

Body:
TypeScript checks the entire codebase on transpiling, even if only one file has actually changed. For small projects, that is fine, yet since our codebase grew, it takes quite a long time.

During development, I want quick response time of my unit tests. The unit test should run as soon as possible.

Unfortunately, I have to wait on each run about 10-15 seconds for the unit test to even start as the the tsc takes a long time to transpile, and of that time 60%-80% is spent on checking.

These example runs are just from removing and adding a newline in one file:

yarn tsc v0.27.5
$ "/home/philipp/fancyProject/node_modules/.bin/tsc" "--watch" "--diagnostics"
Files:           511
Lines:        260611
Nodes:        898141
Identifiers:  323004
Symbols:      863060
Types:        302553
Memory used: 704680K
I/O read:      0.17s
I/O write:     0.09s
Parse time:    2.61s
Bind time:     0.95s
Check time:    7.65s
Emit time:     1.45s
Total time:   12.65s
00:35:34 - Compilation complete. Watching for file changes.

00:41:58 - File change detected. Starting incremental compilation...

Files:            511
Lines:         260612
Nodes:         898141
Identifiers:   323004
Symbols:       863060
Types:         302553
Memory used: 1085950K
I/O read:       0.00s
I/O write:      0.04s
Parse time:     0.68s
Bind time:      0.00s
Check time:    12.65s
Emit time:      1.36s
Total time:    14.69s
00:42:13 - Compilation complete. Watching for file changes.

00:42:17 - File change detected. Starting incremental compilation...

Files:            511
Lines:         260611
Nodes:         898141
Identifiers:   323004
Symbols:       863060
Types:         302553
Memory used: 1106446K
I/O read:       0.00s
I/O write:      0.12s
Parse time:     0.32s
Bind time:      0.01s
Check time:     9.28s
Emit time:      0.89s
Total time:    10.50s
00:42:27 - Compilation complete. Watching for file changes.

I wonder if there is a way to tell typescript:

Just treat everything as OK and just dump the JavaScript as quickly as possible to the disk.

I want to ensure first that my unit test pass in order to have a quick feedback loop.

And since my IDE takes care of the type checks already within the file I am currently working on, I rarely have mistake in the check of the transpiling anyway. And if there was a big issue, my unit tests should catch them.

When building the project, I would just use the classic tsc with the checks. As I have said, this is only for development and having a quick feedback loop.


问:
How to submit data in using easyui form
In my project, I use easyui form which id is ff.

And I want to check the data before submit form. So I use onSubmit in form method.

But I cannot accept data from oat.php, the method alert(data) in success can not display "Your name".

Perhaps jquery.form.js is the reason, but i am not sure.

Here is the head code:

```<code><link rel="stylesheet" type="text/css" href="jsui/easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jsui/easyui-1.5.3/themes/icon.css">
<script type="text/javascript" src="jsui/easyui-1.5.3/jquery.min.js"></script>
<script type="text/javascript" src="jsui/easyui-1.5.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</code>```

Here js code:

```<code> <script>
 function submitForm(){
  $('#ff').form('submit',{
        url:oat.php,
        onSubmit:function(){
            return $(this).form('enableValidation').form('validate');
            },
        success:function(data){
            alert(data)
            }
        });
}
function clearForm(){
    $('#ff').form('clear');
}
</script>
</code>```

Here is html code:

```<code><form id="ff" class="easyui-form" method="post" data-options="novalidate:true"  enctype='multipart/form-data'>
        <table cellpadding="5">
            <tr>
                <td>announceTitle:</td>
                <td><input class="easyui-textbox" type="text" name="annTitle" data-options="required:true,multiline:true" style="height:60px"></input></td>
            </tr>
        </table>
        <div class="attFile" id="attFileId">
        <div class="upBtDiv"><label style="color:green">attfile:</label><input type="file" id="fulId" name="mypic"></div>
        <div class="ulfDiv" id="ulfId1"></div>
    </div>
     <div style="text-align:center;padding:5px">
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">submit</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()">clear</a>
    </div>
    </form>
</code>```

Here is oat.php code:

```<code><?php
echo "Your Name";
?>
</code>```

I don't know how? who can help me?

答:
In your code oat.php treated as a variable, you should add quotes so JS would treat it as a string value.

```<code> $('#ff').form('submit',{
        url: 'oat.php', //added quotes.
        onSubmit:function(){
            return $(this).form('enableValidation').form('validate');
            },...
</code>```

Title: How to submit data in using easyui form

Body:
In my project, I use easyui form which id is ff.

And I want to check the data before submit form. So I use onSubmit in form method.

But I cannot accept data from oat.php, the method alert(data) in success can not display "Your name".

Perhaps jquery.form.js is the reason, but i am not sure.

Here is the head code:

<link rel="stylesheet" type="text/css" href="jsui/easyui-1.5.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jsui/easyui-1.5.3/themes/icon.css">

Here js code:

Here is html code:

<form id="ff" class="easyui-form" method="post" data-options="novalidate:true"  enctype='multipart/form-data'>

                announceTitle:
                <input class="easyui-textbox" type="text" name="annTitle" data-options="required:true,multiline:true" style="height:60px"></input>

attfile:<input type="file" id="fulId" name="mypic">

        submit
        clear

    </form>

Here is oat.php code:

<?php
echo "Your Name";
?>

I don't know how? who can help me?

Body:
In your code oat.php treated as a variable, you should add quotes so JS would treat it as a string value.

 $('#ff').form('submit',{
        url: 'oat.php', //added quotes.
        onSubmit:function(){
            return $(this).form('enableValidation').form('validate');
            },...


问:
Setting device permission from driver code fails
I want to access I2C device driver nodes from user space in a linux kernel 3.10.14.
I added i2c-dev in the kernel configuration and got the /dev/i2c-* device nodes. However they have permission

```<code>$ ls -l /dev/i2c-*
crw------- root     root      89,   1 2014-08-21 20:00 i2c-1
</code>```

In drivers/i2c/i2c-dev.c I added the callback

```<code>static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
{
    if (!mode)
            return NULL;
    if (MAJOR(dev->devt) == I2C_MAJOR)
            *mode = 0666;
    return NULL;
}
</code>```

and in the same file I added the callback to the device class struct:

```<code>static int __init i2c_dev_init(void)
{
   ...
   i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
   ...

    /* set access rights */
    i2c_dev_class->devnode = i2c_dev_devnode;
   ...
}
</code>```

However the access rights of the device node remain

```<code>crw------- root     root      89,   1 2014-08-21 20:00 i2c-1
</code>```

There is no /lib/udev/rules.d or /etc/udev/rules.d

I would appreciate any suggestions what might go wrong here.

I am also interested in ideas how to test this issue.

答:
I understand the return value of devnode callback function shall not be "NULL" but device node name.
So,
Change your functions return value from "NULL" to devname. Refer the code:

----------------------patch--------------------

```<code>diff --git a/drivers/i2c/i2c-dev.c b/drivers/i2c/i2c-dev.c
index 6f638bb..35a42c6 100644
--- a/drivers/i2c/i2c-dev.c
+++ b/drivers/i2c/i2c-dev.c
@@ -614,6 +614,14 @@ static int i2cdev_notifier_call(struct notifier_block *nb, unsigned long action,
    .notifier_call = i2cdev_notifier_call,
 };

+static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
+{
+   printk("\n\n****%s: %d\n\n",__func__,__LINE__);
+    if (mode != NULL)
+            *mode = 0666;
+    return kasprintf(GFP_KERNEL, "i2cr/%s", dev_name(dev));;
+}
+
 /* ------------------------------------------------------------------------- */

 /*
@@ -636,7 +644,12 @@ static int __init i2c_dev_init(void)
        goto out_unreg_chrdev;
    }
    i2c_dev_class->dev_groups = i2c_groups;
+   /* set access rights */
+   printk(KERN_INFO "i2c setting devnode\n");
+   i2c_dev_class->devnode = i2c_dev_devnode;
+

+
    /* Keep track of adapters which will be added or removed later */
    res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
    if (res)
</code>```

Results:
Without applying this patch:

```<code>root@x86-generic-64:~# ls -l /dev/i2c-*
crw------- 1 root root 89,  0 Nov  1 13:47 /dev/i2c-0
crw------- 1 root root 89,  1 Nov  1 13:47 /dev/i2c-1
</code>```

With patch:

```<code>root@x86-generic-64:~# ls -l /dev/i2cr/*
crw-rw-rw- 1 root root 89,  0 Nov  1 13:38 /dev/i2cr/i2c-0
crw-rw-rw- 1 root root 89,  1 Nov  1 13:38 /dev/i2cr/i2c-1
</code>```

Body:
I want to access I2C device driver nodes from user space in a linux kernel 3.10.14.
I added i2c-dev in the kernel configuration and got the /dev/i2c-* device nodes. However they have permission

$ ls -l /dev/i2c-*
crw------- root     root      89,   1 2014-08-21 20:00 i2c-1

In drivers/i2c/i2c-dev.c I added the callback

static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
{
    if (!mode)
            return NULL;
    if (MAJOR(dev->devt) == I2C_MAJOR)
            *mode = 0666;
    return NULL;
}

and in the same file I added the callback to the device class struct:

static int __init i2c_dev_init(void)
{
   ...
   i2c_dev_class = class_create(THIS_MODULE, "i2c-dev");
   ...

    /* set access rights */
    i2c_dev_class->devnode = i2c_dev_devnode;
   ...
}

However the access rights of the device node remain

crw------- root     root      89,   1 2014-08-21 20:00 i2c-1

There is no /lib/udev/rules.d or /etc/udev/rules.d

I would appreciate any suggestions what might go wrong here.

I am also interested in ideas how to test this issue.

Body:
I understand the return value of devnode callback function shall not be "NULL" but device node name.
So,
Change your functions return value from "NULL" to devname. Refer the code:

----------------------patch--------------------

diff --git a/drivers/i2c/i2c-dev.c b/drivers/i2c/i2c-dev.c
index 6f638bb..35a42c6 100644
--- a/drivers/i2c/i2c-dev.c
+++ b/drivers/i2c/i2c-dev.c
@@ -614,6 +614,14 @@ static int i2cdev_notifier_call(struct notifier_block *nb, unsigned long action,
    .notifier_call = i2cdev_notifier_call,
 };

+static char *i2c_dev_devnode(struct device *dev, umode_t *mode)
+{
+   printk("\n\n****%s: %d\n\n",__func__,__LINE__);
+    if (mode != NULL)
+            *mode = 0666;
+    return kasprintf(GFP_KERNEL, "i2cr/%s", dev_name(dev));;
+}
+
 /* ------------------------------------------------------------------------- */

 /*
@@ -636,7 +644,12 @@ static int __init i2c_dev_init(void)
        goto out_unreg_chrdev;
    }
    i2c_dev_class->dev_groups = i2c_groups;
+   /* set access rights */
+   printk(KERN_INFO "i2c setting devnode\n");
+   i2c_dev_class->devnode = i2c_dev_devnode;
+

+
    /* Keep track of adapters which will be added or removed later */
    res = bus_register_notifier(&i2c_bus_type, &i2cdev_notifier);
    if (res)

Results:
Without applying this patch:

root@x86-generic-64:~# ls -l /dev/i2c-*
crw------- 1 root root 89,  0 Nov  1 13:47 /dev/i2c-0
crw------- 1 root root 89,  1 Nov  1 13:47 /dev/i2c-1

With patch:

root@x86-generic-64:~# ls -l /dev/i2cr/*
crw-rw-rw- 1 root root 89,  0 Nov  1 13:38 /dev/i2cr/i2c-0
crw-rw-rw- 1 root root 89,  1 Nov  1 13:38 /dev/i2cr/i2c-1


问:
Looping through an array to get index of item - swift
I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.

I have the following code however this causes the app to crash due:

```<code>let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
        scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)
</code>```

When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.

Any ideas on why this may be happening?

Using the suggested answer throws the following error:

```<code>unrecognized selector sent to instance 0x101134af0'
</code>```

There is definitely a match in assetArray[0] with the name that is being passed through.

Doing a bit more investigation trying to run the following line of code alone gives the same error:

```<code>scroll_owners.selectRow(0, inComponent: 0, animated: true)
</code>```

Does this mean I'm missing a delegate method?

Asset Array and Name Array:

```<code>var assetArray : [Asset] = []

var nameArray = [String]()
</code>```

EDIT:

```<code>    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
}

    self.scroll_owners.delegate = self
    self.scroll_owners.dataSource = self
</code>```

I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:

```<code>            var i : Int = 0
        while (nameArray[i] != name)
        {
            print(nameArray[i])
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: 0, animated: true)
</code>```

This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?

答:
I have managed to solve this error myself in a slightly different way.

In my function which populates the nameArray and the UIPicker I have placed the following code:

```<code>                var i : Int = 0
            while (self.nameArray[i] != name)
            {
                print(self.nameArray[i])
                i=i+1
            }
            self.scroll_owners.selectRow(i, inComponent: 0, animated: true)
</code>```

The reason the code was crashing was due to the fact that the nameArray was not finishing being populated before I was trying to do the comparisons. I know this may not be the accepted swift way of doing this but it works.

The issues were caused due to the function being run on a seperate thread I believe.

Body:
I am trying to loop through an array of names to get the index of a certain string. I then want to set the index of my UIPicker to the said string.

I have the following code however this causes the app to crash due:

let index = self.nameArray.index(where: {$0 == assetArray[0].Owner })
        scroll_owners.selectRow(index ?? 0, inComponent: 0, animated: true)

When debugging the index is getting a value of index 6176573120 which of course isn't in the range of my UIPicker so causes the crash.

Any ideas on why this may be happening?

Using the suggested answer throws the following error:

unrecognized selector sent to instance 0x101134af0'

There is definitely a match in assetArray[0] with the name that is being passed through.

Doing a bit more investigation trying to run the following line of code alone gives the same error:

scroll_owners.selectRow(0, inComponent: 0, animated: true)

Does this mean I'm missing a delegate method?

Asset Array and Name Array:

var assetArray : [Asset] = []

var nameArray = [String]()

EDIT:

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
}

    self.scroll_owners.delegate = self
    self.scroll_owners.dataSource = self

I've tried to get this working another way - I know this is an ugly way of doing it I'm just trying to see why the accepted swift way isn't working:

            var i : Int = 0
        while (nameArray[i] != name)
        {
            print(nameArray[i])
            i=i+1
        }
        scroll_owners.selectRow(i, inComponent: 0, animated: true)

This section of code crashes and the while loops is never entered due to the index being out of bounds - does this mean the issue could be with nameArray?

Body:
I have managed to solve this error myself in a slightly different way.

In my function which populates the nameArray and the UIPicker I have placed the following code:

                var i : Int = 0
            while (self.nameArray[i] != name)
            {
                print(self.nameArray[i])
                i=i+1
            }
            self.scroll_owners.selectRow(i, inComponent: 0, animated: true)

The reason the code was crashing was due to the fact that the nameArray was not finishing being populated before I was trying to do the comparisons. I know this may not be the accepted swift way of doing this but it works.

The issues were caused due to the function being run on a seperate thread I believe.


问:
Resizing inkcanvas to the left and top
I want to resize width and height of inkcanvas to fit the screen. When I resized it, the width expands to the right and height expands to the bottom. But inkcanvas is not fit to screen.

I also want to fix the position of inkcanvas child element. If I can resize inkcanvas to fit the screen, the position of inkcanvas child element will not change.

How do I resize inkcanvas to the left and top to fit the screen?

```<code><Canvas x:Name="Screen" >

                <InkCanvas Name="inkcanvas" ResizeEnabled="True"
                          Width="{Binding ElementName=LayoutRoot, Path=ActualWidth}"
                        Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"
                           EditingMode="Select" ClipToBounds="False"
                    Background="Bisque"
                    SelectionChanging="OnSelectionChanging"
                    Visibility="Collapsed" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

                    <!-- InkCanvas' Child Elements -->
                </InkCanvas>
                <Canvas.RenderTransform>
                    <MatrixTransform/>
                </Canvas.RenderTransform>
            </Canvas>
</code>```

Thanks

Update:
I put inkcanvas in a grid. It fit to the screen but the position of child element is changed.

I want to fix the red rectangle position.

The position of red rectangle should not be changed.

```<code><Grid>
        <InkCanvas x:Name="inkcanvas"  Background="Transparent">
            <Rectangle Height="41" HorizontalAlignment="Left"  Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="69" Fill="#FFDB1111" />
        </InkCanvas>
        </Grid>
</code>```

My big picure:

My WPF Application contain many pictures. I can zoom in/out the canvas. I can select the pictures by using selection tool.

I have canvas and inkcanvas.

canvas: contain picture and zoom in/out

inkcanvas: has selection tool

If I zoom out, the canvas and inkcanvas become smaller.

If I use selection tool, I copy all pictures from canvas to inkcanvas.

But the inkcanvas is zoom out, I cannot use selection tool if outside the inkcanvas boundary.

It is the reason why I want to resize inkcanvas and fix the children position.

答:
Remove all the margins from the inkcanvas and put it in a Grid.

Could you explain why this would not work for you?

```<code><Grid>
    <InkCanvas>
    ...
    </InkCanvas>
</Grid>
</code>```

Edit There are two way to keep the child element where it is:

As soon as the position or the size of the InkCanvas changes adjust the child positions accordingly. this means that you have to pick a fixed position (window topleft, screen topleft, ...) that determines the actual position of the child.

Remove the child from the InkCanvas and put it in the correct container (the one that determines the child's position.

I would prefer #2 as is is more logical and requires less calculations/event-handling

Title: Resizing inkcanvas to the left and top

Body:
I want to resize width and height of inkcanvas to fit the screen. When I resized it, the width expands to the right and height expands to the bottom. But inkcanvas is not fit to screen.

I also want to fix the position of inkcanvas child element. If I can resize inkcanvas to fit the screen, the position of inkcanvas child element will not change.

How do I resize inkcanvas to the left and top to fit the screen?

<Canvas x:Name="Screen" >

                <InkCanvas Name="inkcanvas" ResizeEnabled="True"
                          Width="{Binding ElementName=LayoutRoot, Path=ActualWidth}"
                        Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"
                           EditingMode="Select" ClipToBounds="False"
                    Background="Bisque"
                    SelectionChanging="OnSelectionChanging"
                    Visibility="Collapsed" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">

                </InkCanvas>
                <Canvas.RenderTransform>
                    <MatrixTransform/>
                </Canvas.RenderTransform>
            </Canvas>

Thanks

Update:
I put inkcanvas in a grid. It fit to the screen but the position of child element is changed.

I want to fix the red rectangle position.

The position of red rectangle should not be changed.

<Grid>
        <InkCanvas x:Name="inkcanvas"  Background="Transparent">
            <Rectangle Height="41" HorizontalAlignment="Left"  Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="69" Fill="#FFDB1111" />
        </InkCanvas>
        </Grid>

My big picure:

My WPF Application contain many pictures. I can zoom in/out the canvas. I can select the pictures by using selection tool.

I have canvas and inkcanvas.

canvas: contain picture and zoom in/out

inkcanvas: has selection tool

If I zoom out, the canvas and inkcanvas become smaller.

If I use selection tool, I copy all pictures from canvas to inkcanvas.

But the inkcanvas is zoom out, I cannot use selection tool if outside the inkcanvas boundary.

It is the reason why I want to resize inkcanvas and fix the children position.

Body:
Remove all the margins from the inkcanvas and put it in a Grid.

Could you explain why this would not work for you?

<Grid>
    <InkCanvas>
    ...
    </InkCanvas>
</Grid>

Edit There are two way to keep the child element where it is:

As soon as the position or the size of the InkCanvas changes adjust the child positions accordingly. this means that you have to pick a fixed position (window topleft, screen topleft, ...) that determines the actual position of the child.

Remove the child from the InkCanvas and put it in the correct container (the one that determines the child's position.

I would prefer #2 as is is more logical and requires less calculations/event-handling


问:
Xamarin.Forms Disable slide menu in pushed page
I use Xamarin.Forms (ver 1.4)

Page hierarchy:

->NavigationPage

-->MasterDetailPage

How can disable sliding menu (open master page by gesture) in pushed screen?

Push method:

await ((NavigationPage)((MasterDetailPage)Application.Current.MainPage).Detail).PushAsync(page))

Sliding menu should work only on root page.

答:
MasterMenuPage holds a bool property called "IsGestureEnabled" which determines if the swipe in menu is available.

```<code>IsGestureEnabled = false //no swipe gesture
</code>```

Here I can give you an easy implementation for a custom MasterDetailPage

```<code>public class MainMDPage : MasterDetailPage
    {
        public MainMDPage(Page masterPage, Page detailPage)
        {
            MasterBehavior = MasterBehavior.Popover;
            Master = masterPage;
            Detail = detailPage;
        }

        /// <summary>
        /// Pushes a page and disables the master menu.
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task PushAsync(Page page)
        {
            if(Detail is NavigationPage navPage)
            {
                await navPage.PushAsync(page);
                IsGestureEnabled = false;
            }
        }

        /// <summary>
        /// Pops a page and enables the master menu if we get to the root page.
        /// </summary>
        /// <returns></returns>
        public async Task PopAsync()
        {
            if (Detail is NavigationPage navPage)
            {
                await navPage.PopAsync();

                if (navPage.Navigation.NavigationStack.Count == 1)  //if count == 1 -> is root page
                    IsGestureEnabled = true;
            }
        }
    }
</code>```

Body:
MasterMenuPage holds a bool property called "IsGestureEnabled" which determines if the swipe in menu is available.

IsGestureEnabled = false //no swipe gesture

Here I can give you an easy implementation for a custom MasterDetailPage

public class MainMDPage : MasterDetailPage
    {
        public MainMDPage(Page masterPage, Page detailPage)
        {
            MasterBehavior = MasterBehavior.Popover;
            Master = masterPage;
            Detail = detailPage;
        }

        /// <summary>
        /// Pushes a page and disables the master menu.
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public async Task PushAsync(Page page)
        {
            if(Detail is NavigationPage navPage)
            {
                await navPage.PushAsync(page);
                IsGestureEnabled = false;
            }
        }

        /// <summary>
        /// Pops a page and enables the master menu if we get to the root page.
        /// </summary>
        /// <returns></returns>
        public async Task PopAsync()
        {
            if (Detail is NavigationPage navPage)
            {
                await navPage.PopAsync();

                if (navPage.Navigation.NavigationStack.Count == 1)  //if count == 1 -> is root page
                    IsGestureEnabled = true;
            }
        }
    }


问:
How to protect a Firebase Node depending on sibling Node?
I need to implement some rules in Firebase to protect my data.

Let's say I have node a and node b. The structure is as follows:

```<code>{
    a:
    [
        a1: {uid: 123},
        a2: {uid: 321},
        a3: {uid: 567}
    ],
    b:
    [
        a1: {data: 'foo.bar'},
        a2: {data: 'foo.bar'},
        a3: {data: 'foo.bar'}
    ]
}
</code>```

As in the example above, the child nodes of a are the keys of node b. How can I restrict the access to data of node b depending on the uid of node a?

For example. The user with uid 123 in the node a, his key is a1, so, in node b only can retrieve data from child node a1 (b -> a1).

答:
I think a rule system like this would match your requirement:

{
  "rules": {
    "b": {
      "$key": {
        ".read": "auth.uid == root.child('a').child($key).child('uid').val()",
        ".write": "auth !== null"
      }
    }
  }
}
```

In this example, $key is a $location variable that matches any key under the list of node b.

We can then use this $key variable to match the current user's auth.uid to the uid of the corresponding node under a, using root.child().

The result is that this will only grant read access to a child under b if the uid of the corresponding child with the same key under a matches the current user's uid.

Body:
I need to implement some rules in Firebase to protect my data.

Let's say I have node a and node b. The structure is as follows:

{
    a:
    [
        a1: {uid: 123},
        a2: {uid: 321},
        a3: {uid: 567}
    ],
    b:
    [
        a1: {data: 'foo.bar'},
        a2: {data: 'foo.bar'},
        a3: {data: 'foo.bar'}
    ]
}

As in the example above, the child nodes of a are the keys of node b. How can I restrict the access to data of node b depending on the uid of node a?

For example. The user with uid 123 in the node a, his key is a1, so, in node b only can retrieve data from child node a1 (b -> a1).

Body:
I think a rule system like this would match your requirement:

{
  "rules": {
    "b": {
      "$key": {
        ".read": "auth.uid == root.child('a').child($key).child('uid').val()",
        ".write": "auth !== null"
      }
    }
  }
}

In this example, $key is a $location variable that matches any key under the list of node b.

We can then use this $key variable to match the current user's auth.uid to the uid of the corresponding node under a, using root.child().

The result is that this will only grant read access to a child under b if the uid of the corresponding child with the same key under a matches the current user's uid.


问:
Reordering two columns using a third one
I have a df like:

```<code>chr11   1757418 1754950 ERR164550   4   +
chr1    116399450   116400907   ERR164550   3   -
...
</code>```

Looking at the last column (+ or -, in this case) I would like to reorder the second and the third variable. If the last column is a - then the values should stay that way. If the last column is a + then I would like to invert the values of the given row.

I could re-ask the question in another way: I would like to reoder to column 2 and 3 in every row and keeping the lowest value in column 2 and the highest in 3.

Any thoughs?

Thanks!

答:
I wouldn't use the +/- column:</p>

```<code>df[,2:3]=t(apply(df[,2:3],1,sort))
</code>```

Body:
I have a df like:

chr11   1757418 1754950 ERR164550   4   +
chr1    116399450   116400907   ERR164550   3   -
...

Looking at the last column (+ or -, in this case) I would like to reorder the second and the third variable. If the last column is a - then the values should stay that way. If the last column is a + then I would like to invert the values of the given row.

I could re-ask the question in another way: I would like to reoder to column 2 and 3 in every row and keeping the lowest value in column 2 and the highest in 3.

Any thoughs?

Thanks!

Body:
I wouldn't use the +/- column:

df[,2:3]=t(apply(df[,2:3],1,sort))


问:
what is object instance?Does it mean creating a copy of class?
When an object instance is created from a class, the class's constructor function is run to create it. This process of creating an object instance from a class is called instantiation — the object instance is instantiated from the class.I am confused with term instance.Does it mean creating a copy of a class?</p>

答:
Creating an instance of a class is creating an object of that class type.

Example

```<code>class A{}

A a = new A();
</code>```

Type of variable a is A.

Body:
Creating an instance of a class is creating an object of that class type.

Example

class A{}

A a = new A();

Type of variable a is A.


问:
How to get additional claims on client side in identity server 4?
In my identity server's Startup.cs file, I have server configured as below. I am using asp.net identity for user management.

```<code>services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

services.AddTransient<IProfileService, ProfileService>();
</code>```

My IdentiyResources are as follow. Here I want to return extra claim as IS_Token which I want to use for some further business logic of my application.

```<code>public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    new IdentityResource("IS_token", new []{ "IS_token" } ),
                };
        }
</code>```

I'm also adding this claim in IssuedClaims inside my IProfileService as below.

```<code>public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        public ProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
        {
            _userManager = userManager;
            _claimsFactory = claimsFactory;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            var principal = await _claimsFactory.CreateAsync(user);

            var claims = principal.Claims.ToList();
            claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
            claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));
            claims.Add(new Claim(IdentityServerConstants.StandardScopes.Email, user.Email));

            //Get user claims from AspNetUserClaims table
            var userClaims = await _userManager.GetClaimsAsync(user);
            claims.AddRange(userClaims);

            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }
</code>```

My MVC client is configured as below

```<code>               new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "api"
                        },

                        AllowOfflineAccess = true
                    },
</code>```

In my MVC application, I have the following code in Startup.cs file

```<code>services.AddMvc();

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "mvc";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;

        options.Scope.Add("api");
        options.Scope.Add("offline_access");
    });
</code>```

When I authenticate user in identity server and get back to my secured link i got following claims but IS_token is missing from my users claims.

My secured page's cshtml

```<code><dl>

    @foreach (var claim in User.Claims)

    {

        <dt>@claim.Type</dt>

        <dd>@claim.Value</dd>

    }

    <dt>access token</dt>
    <dd>@await ViewContext.HttpContext.GetTokenAsync("access_token")</dd>

    <dt>refresh token</dt>
    <dd>@await ViewContext.HttpContext.GetTokenAsync("refresh_token")</dd>

</dl>
</code>```

This is my secured page's screenshot

My secure page's output

As you can see in image IS_token is missing. How can i get IS_token claim???

答:
I need to set  AlwaysIncludeUserClaimsInIdToken = true in my client config in identity server. So I should define my client as below.

```<code>                new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "poslink"
                        },

                        AlwaysIncludeUserClaimsInIdToken = true,

                        AllowOfflineAccess = true
                    },
</code>```

Body:
In my identity server's Startup.cs file, I have server configured as below. I am using asp.net identity for user management.

services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddInMemoryPersistedGrants()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();

services.AddTransient<IProfileService, ProfileService>();

My IdentiyResources are as follow. Here I want to return extra claim as IS_Token which I want to use for some further business logic of my application.

public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    new IdentityResource("IS_token", new []{ "IS_token" } ),
                };
        }

I'm also adding this claim in IssuedClaims inside my IProfileService as below.

public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        public ProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory)
        {
            _userManager = userManager;
            _claimsFactory = claimsFactory;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            var principal = await _claimsFactory.CreateAsync(user);

            var claims = principal.Claims.ToList();
            claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList();
            claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName));
            claims.Add(new Claim(IdentityServerConstants.StandardScopes.Email, user.Email));

            //Get user claims from AspNetUserClaims table
            var userClaims = await _userManager.GetClaimsAsync(user);
            claims.AddRange(userClaims);

            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }

My MVC client is configured as below

               new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "api"
                        },

                        AllowOfflineAccess = true
                    },

In my MVC application, I have the following code in Startup.cs file

services.AddMvc();

    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "http://localhost:5000";
        options.RequireHttpsMetadata = false;

        options.ClientId = "mvc";
        options.ClientSecret = "secret";
        options.ResponseType = "code id_token";

        options.SaveTokens = true;
        options.GetClaimsFromUserInfoEndpoint = true;

        options.Scope.Add("api");
        options.Scope.Add("offline_access");
    });

When I authenticate user in identity server and get back to my secured link i got following claims but IS_token is missing from my users claims.

My secured page's cshtml

    @foreach (var claim in User.Claims)

    {

@claim.Type

@claim.Value

    }

access token

@await ViewContext.HttpContext.GetTokenAsync("access_token")

refresh token

@await ViewContext.HttpContext.GetTokenAsync("refresh_token")

This is my secured page's screenshot

My secure page's output

As you can see in image IS_token is missing. How can i get IS_token claim???

Body:
I need to set  AlwaysIncludeUserClaimsInIdToken = true in my client config in identity server. So I should define my client as below.

                new Client
                    {
                        ClientId = "mvc",
                        ClientName = "MVC Client",
                        AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                        RequireConsent = false,

                        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },

                        // where to redirect to after login
                        RedirectUris = { "http://localhost:5002/signin-oidc" },

                        // where to redirect to after logout
                        PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },

                        AllowedScopes = new List<string>
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile,
                            "IS_token",
                            "poslink"
                        },

                        AlwaysIncludeUserClaimsInIdToken = true,

                        AllowOfflineAccess = true
                    },


问:
C - Passing single struct from array to function by reference
having not worked with C for a while I'm stuck with passing a single struct from an array of structs to a function by reference.

The code I have looks like this:

```<code>struct Sensor {
    //ROM data
    char romCRC[1];
    char romSerial[6];
    char romFamily[1];
};

const int maxSens = 10;

void Read_ROM(struct Sensor *sens){
        char ROM[10];
        for (k = 0; k<8; k++){
             ROM[k] = read_byte();
             sens->romFamily = ROM[0];
        }
}

int main(){
    struct Sensor Sensors[maxSens];
    Read_ROM(&Sensors[0]);
}
</code>```

What I expect it to do is:

Create an array of 10 structs of type Sensor

Pass the address of the first struct to the function Read_ROM

Set the member romFamily of the struct Sensor[0] to ROM[0]

read_byte is tested and working. It does return 1 char.

When I try to compile I get this error:

```<code>#138 expression must be a modifiable lvalue
</code>```

With 138 being the line number of:

```<code>sens->romFamily = ROM[0];
</code>```

What is wrong here?

答:
Arrays are not assignable in C, although you can set individual elements.

In your case you need sens->romFamily[0] = ROM[0];

But do question why you need a single element array in the first place.

Body:
having not worked with C for a while I'm stuck with passing a single struct from an array of structs to a function by reference.

The code I have looks like this:

struct Sensor {
    //ROM data
    char romCRC[1];
    char romSerial[6];
    char romFamily[1];
};

const int maxSens = 10;

void Read_ROM(struct Sensor *sens){
        char ROM[10];
        for (k = 0; k<8; k++){
             ROM[k] = read_byte();
             sens->romFamily = ROM[0];
        }
}

int main(){
    struct Sensor Sensors[maxSens];
    Read_ROM(&Sensors[0]);
}

What I expect it to do is:

Create an array of 10 structs of type Sensor

Pass the address of the first struct to the function Read_ROM

Set the member romFamily of the struct Sensor[0] to ROM[0]

read_byte is tested and working. It does return 1 char.

When I try to compile I get this error:

#138 expression must be a modifiable lvalue

With 138 being the line number of:

sens->romFamily = ROM[0];

What is wrong here?


问:
Get elements by id array and order by this array
I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

```<code>ids = [6, 3, 8]
Product.where(id: ids)
</code>```

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

答:
If you want to do this in one ActiveRecord query, it depends on the RDBMS you are using and will include a raw sql string in the order method, but you can also do this in plain ruby:

```<code>Product.where(id: ids).sort_by { |item| ids.index(item.id) }
</code>```

P.S. After sorting class of the collection is going to change from ActiveRecord_Relation to Array.

Body:
I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

ids = [6, 3, 8]
Product.where(id: ids)

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

Body:
If you want to do this in one ActiveRecord query, it depends on the RDBMS you are using and will include a raw sql string in the order method, but you can also do this in plain ruby:

Product.where(id: ids).sort_by { |item| ids.index(item.id) }

P.S. After sorting class of the collection is going to change from ActiveRecord_Relation to Array.


问:
VBA - sumifs in for loop - is there a more efficient way?
I am trying to build a macro that calculates several sumifs, looking for conditions on a different worksheet. This is the code I have so far:

```<code>Sub SumPerYear()

Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

Sheets("Temp").Activate

For i = 2 To NoClients + 1

    'Fill 2015 € in column E
    Cells(i, 5).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2015 # in column F
    Cells(i, 6).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 € in column G
    Cells(i, 7).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 # in column H
    Cells(i, 8).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 € in column I
    Cells(i, 9).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 # in column J
    Cells(i, 10).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill Tot € in column K
    Cells(i, 11).Value2 = Cells(i, 5) + Cells(i, 7) + Cells(i, 9)

    'Fill Tot # in column L
    Cells(i, 12).Value2 = Cells(i, 6) + Cells(i, 8) + Cells(i, 10)

Next i

End Sub
</code>```

This code works, but because there are thousands of records, it takes a long time to complete. Is there a way to make this more efficient/faster?

Thanks for your input!

答:
Unfortunately, Application methods work too slow on big count of cells, so you should write some code, that's not so nice and simple as yours.
Main idea is catched here:</p>

```<code>Dim arrA as Variant 'change Variant to your type
Dim arrCD as Variant
Dim arr as Variant
Dim i as long
Dim k as integer
Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

'assign Ranges to arrays
'we can't assign non-contiguous range, so we create two arrays
arrA = Range("A:A")
arrCD = Range("C:D")
ReDim arr(UBound(arrA), 3)
ReDim outArr(NoClients, 5 to 10)
'loop and fill third merged array
For i = 1 To UBound(arrA)
    arr(i, 0) = arrA(i, 1)
    arr(i, 1) = arrCD(i, 1)
    arr(i, 2) = arrCD(i, 2)
Next i

'the rest of code You just loop through
For k = 2 To NoClients + 1 'get client
    For i = 1 To UBound(arr) 'count summuries for him
        if (arr(i,0) = 2016) and (arr(i,1) = true) and (arr(i,2) = _
            Worksheets("Temp").Range("A" & k).Value2) then
            'sumifs replacement
            outArr(k, 5) = outArr(k, 5)  + Worksheets("Q ALL").Cells(1+i, "I").Value2
            'countifs replacement
            outArr(k, 6) = outArr(k, 6) + 1
        end if
    Next i
Next k

Worksheets("Temp").Range("A2").Value2 = outArr 'prints array on sheet with top left corner at A2
</code>```

Body:
I am trying to build a macro that calculates several sumifs, looking for conditions on a different worksheet. This is the code I have so far:

Sub SumPerYear()

Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

Sheets("Temp").Activate

For i = 2 To NoClients + 1

    'Fill 2015 € in column E
    Cells(i, 5).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2015 # in column F
    Cells(i, 6).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2015, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 € in column G
    Cells(i, 7).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2016 # in column H
    Cells(i, 8).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2016, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 € in column I
    Cells(i, 9).Value2 = Application.SumIfs(Worksheets("Q ALL").Range("I:I"), _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill 2017 # in column J
    Cells(i, 10).Value2 = Application.CountIfs( _
        Worksheets("Q ALL").Range("A:A"), 2017, _
        Worksheets("Q ALL").Range("D:D"), Worksheets("Temp").Range("A" & i).Value2, _
        Worksheets("Q ALL").Range("C:C"), True)

    'Fill Tot € in column K
    Cells(i, 11).Value2 = Cells(i, 5) + Cells(i, 7) + Cells(i, 9)

    'Fill Tot # in column L
    Cells(i, 12).Value2 = Cells(i, 6) + Cells(i, 8) + Cells(i, 10)

Next i

End Sub

This code works, but because there are thousands of records, it takes a long time to complete. Is there a way to make this more efficient/faster?

Thanks for your input!

Body:
Unfortunately, Application methods work too slow on big count of cells, so you should write some code, that's not so nice and simple as yours.
Main idea is catched here:

Dim arrA as Variant 'change Variant to your type
Dim arrCD as Variant
Dim arr as Variant
Dim i as long
Dim k as integer
Dim NoClients As Long
NoClients = Worksheets("Temp").Range("A2").End(xlDown).Row - 1

'assign Ranges to arrays
'we can't assign non-contiguous range, so we create two arrays
arrA = Range("A:A")
arrCD = Range("C:D")
ReDim arr(UBound(arrA), 3)
ReDim outArr(NoClients, 5 to 10)
'loop and fill third merged array
For i = 1 To UBound(arrA)
    arr(i, 0) = arrA(i, 1)
    arr(i, 1) = arrCD(i, 1)
    arr(i, 2) = arrCD(i, 2)
Next i

'the rest of code You just loop through
For k = 2 To NoClients + 1 'get client
    For i = 1 To UBound(arr) 'count summuries for him
        if (arr(i,0) = 2016) and (arr(i,1) = true) and (arr(i,2) = _
            Worksheets("Temp").Range("A" & k).Value2) then
            'sumifs replacement
            outArr(k, 5) = outArr(k, 5)  + Worksheets("Q ALL").Cells(1+i, "I").Value2
            'countifs replacement
            outArr(k, 6) = outArr(k, 6) + 1
        end if
    Next i
Next k

Worksheets("Temp").Range("A2").Value2 = outArr 'prints array on sheet with top left corner at A2