问:
Responsive height of react-native-modal according to number of elements in it
i am trying to create a modal  in react native application, and there is a button or touchable opacity on a screen which toggles the modal, i am trying to populate a list of items on modal by the use of mapping. But it is not working as expected because elements i create are hidden behind other elements.

I have tried using Modal from react native but i was unable to set custom size of the modal as i needed some portion of it to be transparent. That is why i moved to react-native-modal library but i am facing above mentioned error in that.

```<code><Modal isVisible={this.state.modalVisible} >
                    <View style={{backgroundColor:'white', alignItems:'center', borderRadius:5}}>
                        <Image source={require('../../assets/Group3Copy.png')} style={{marginTop:responsiveFontSize, marginBottom:responsiveFontSize-2}}/>
                        <Text style={{color:'#92c848', alignSelf:'center', fontWeight:'bold', fontSize:responsiveFontSize+10}}>Well Done!</Text>
                        <Text style={{color:blueColor, fontWeight:'bold'}}>{this.state.plantCount} plants have been planted</Text>
                        <Text style={{color:blueColor, fontWeight:'bold'}}> {this.state.plantCount} پودے لگاۓ گۓ ہيں </Text>

                        {/* Mapping=========================================== */}

                        <View style={AppStyles.mainNoRow}>
                        <View style={AppStyles.colNoIco}>
                            <Image source={require('../../assets/plant.png')}/>
                        </View>
                        <View style={AppStyles.colOrderNoDetail}>
                            <Text style={{color:"#006f91", alignSelf:'flex-start', fontWeight:'bold',marginTop:10}}>Plant</Text>
                            <Text style={{color:"#747474", alignSelf:'flex-start', fontWeight:'bold',}}>Id</Text>
                        </View>

                        <View style={AppStyles.colOrderPickupYesDetail}>
                            <Text style={{color:greenColor ,fontWeight:'bold',}}>1 Jan 19</Text>
                            <Image source={require('../../assets/address.png')}/>
                        </View>
                    </View>

                       <TouchableOpacity onPress={this._toggleModal}
                        style={{
                        width: "90%",
                        height: 60,
                        justifyContent: "center",
                        alignSelf: "center",
                        borderWidth: 1,
                        borderRadius: 8,
                        borderColor: blueColor,
                        shadowColor: blueColor,
                        shadowOffset: { width: 0, height: 1 },
                        shadowOpacity: 0.9,
                        shadowRadius: 1,
                        backgroundColor: blueColor,
                        marginBottom:responsiveFontSize}} >
                        <Text style={AppStyles.textStylePlant}>OK</Text>

                        </TouchableOpacity>
                    </View>

                </Modal>
</code>```

I expect it's height to be set according to the number of elements mapped on it. and adjust it automatically if that is possible.
But right now elements are overlapping like shown here in this picture. https://i.imgur.com/jH9sBxV.png
Elements are hidden behind 'OK' button.

答: Adding marginBottom to the styling of main row seems to resolve the issue. And it also resize the height of modal accordingly.</p>

Body:
i am trying to create a modal  in react native application, and there is a button or touchable opacity on a screen which toggles the modal, i am trying to populate a list of items on modal by the use of mapping. But it is not working as expected because elements i create are hidden behind other elements.

I have tried using Modal from react native but i was unable to set custom size of the modal as i needed some portion of it to be transparent. That is why i moved to react-native-modal library but i am facing above mentioned error in that.

<Modal isVisible={this.state.modalVisible} >
                    <View style={{backgroundColor:'white', alignItems:'center', borderRadius:5}}>
                        <Image source={require('../../assets/Group3Copy.png')} style={{marginTop:responsiveFontSize, marginBottom:responsiveFontSize-2}}/>
                        <Text style={{color:'#92c848', alignSelf:'center', fontWeight:'bold', fontSize:responsiveFontSize+10}}>Well Done!</Text>
                        <Text style={{color:blueColor, fontWeight:'bold'}}>{this.state.plantCount} plants have been planted</Text>
                        <Text style={{color:blueColor, fontWeight:'bold'}}> {this.state.plantCount} پودے لگاۓ گۓ ہيں </Text>

                        {/* Mapping=========================================== */}

                        <View style={AppStyles.mainNoRow}>
                        <View style={AppStyles.colNoIco}>
                            <Image source={require('../../assets/plant.png')}/>
                        </View>
                        <View style={AppStyles.colOrderNoDetail}>
                            <Text style={{color:"#006f91", alignSelf:'flex-start', fontWeight:'bold',marginTop:10}}>Plant</Text>
                            <Text style={{color:"#747474", alignSelf:'flex-start', fontWeight:'bold',}}>Id</Text>
                        </View>

                        <View style={AppStyles.colOrderPickupYesDetail}>
                            <Text style={{color:greenColor ,fontWeight:'bold',}}>1 Jan 19</Text>
                            <Image source={require('../../assets/address.png')}/>
                        </View>
                    </View>

                       <TouchableOpacity onPress={this._toggleModal}
                        style={{
                        width: "90%",
                        height: 60,
                        justifyContent: "center",
                        alignSelf: "center",
                        borderWidth: 1,
                        borderRadius: 8,
                        borderColor: blueColor,
                        shadowColor: blueColor,
                        shadowOffset: { width: 0, height: 1 },
                        shadowOpacity: 0.9,
                        shadowRadius: 1,
                        backgroundColor: blueColor,
                        marginBottom:responsiveFontSize}} >
                        <Text style={AppStyles.textStylePlant}>OK</Text>

                        </TouchableOpacity>
                    </View>

                </Modal>

I expect it's height to be set according to the number of elements mapped on it. and adjust it automatically if that is possible.
But right now elements are overlapping like shown here in this picture. https://i.imgur.com/jH9sBxV.png
Elements are hidden behind 'OK' button.


来源: stackexchange

问:
Updated database - Now can't login to wordpress admin - invalid username
I run a LEMP stack on an Ubuntu VPS. I recently added a new wordpress installation and then installed a new theme. The new theme required that I install demo data in order to get the theme to the right look. In order to do this I had to use a plug-in called 'all-in-one WP migration'.

I installed the plugin, and installed the demo data in .wpress file format. Afterwards the successful data install, I was prompted with something about updating permalinks, I wasn't sure what this meant and since I didn't see why I would need to change this, I hit 'ok'.

Next wordpress suddenly said I needed a 'database update'. I have never seen wordpress do this however I hit 'ok'. The database updated and I was logged out of the admin screen.

Now whenever I try to log back into wordpress it says that my username is invalid. So I am unable to log back in as an admin or as any other user. The site and login page are up and work fine. I have restarted php-fpm, nginx and mysql. Still it says that my username is invalid.

I have no idea what exactly is causing this (besides something to do with the wordpress database) or where to start in finding the solution.

Any ideas of how to fix this?

答:
It seems the when I updated the database, for whatever reason, it wiped the normal admin account that I had created to log into WP. </p>

<p>I went into MySQL, looked into the wp_users table under the WP database. There was one user_login which was named admin. I reset the password and logged back into WP. </p>

ContentLicense: CC BY-SA 4.0

Body:
It seems the when I updated the database, for whatever reason, it wiped the normal admin account that I had created to log into WP.

I went into MySQL, looked into the wp_users table under the WP database. There was one user_login which was named admin. I reset the password and logged back into WP.


问:
Take a subscribed result and immediate apply it to another subscription
Using RxJS, I have a situation where I need to retrieve a single value from an Observable and then immediately apply it to a separate subscription using pluck().

I have a workable solution, but it is inelegant. Is there a way to simplify or improve the process?

```<code>this.fooService.singleValue$.subscribe(value => {
   this.barService.allResults$.pipe(pluck(value)).subscribe(pluckedResult => {
       // do something with the plucked result
   });
});
</code>```

答:
Nested subscriptions aren't recommended way of doing things (i.e. using explicit subscription).
Its better to use switchMap/concatMap/mergeMap operators in these types of situations, so you would not need to subscribe twice, but do it just once.

```<code>this.fooService.singleValue$.pipe(switchMap((value => {
                    return this.barService.allResults$.pipe(pluck(value));
                }))).subscribe(() => {
                    //do something
                });
</code>```

Body:
Using RxJS, I have a situation where I need to retrieve a single value from an Observable and then immediately apply it to a separate subscription using pluck().

I have a workable solution, but it is inelegant. Is there a way to simplify or improve the process?

this.fooService.singleValue$.subscribe(value => {
   this.barService.allResults$.pipe(pluck(value)).subscribe(pluckedResult => {
       // do something with the plucked result
   });
});

Body:
Nested subscriptions aren't recommended way of doing things (i.e. using explicit subscription).
Its better to use switchMap/concatMap/mergeMap operators in these types of situations, so you would not need to subscribe twice, but do it just once.

this.fooService.singleValue$.pipe(switchMap((value => {
                    return this.barService.allResults$.pipe(pluck(value));
                }))).subscribe(() => {
                    //do something
                });


问:
Javascript - invalid quantifier error, can someone help me see my mistake?
I'm not a JS guru, but could someone help me find the invalid quantifier error in the following snippet?

THANKS IN ADVANCE!
-mprototype

```<code>function $_GET(q,s) {
        s = s ? s : window.location.search;
        var re = new RegExp( '&' + q + '(?:=([^&]*))?(?=&|$)' , 'i' );
        return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
    }
</code>```

答:
? has a special meaning in Regular Expressions, specifically it makes the preceding item optional. If you are trying to find the question mark character itself you need to escape it with a backslash.

```<code>function $_GET(q,s) {
        s = s ? s : window.location.search;
        var re = new RegExp( '&' + q + '(?:=([^&]*))?(?=&|$)' , 'i' );
        return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm not a JS guru, but could someone help me find the invalid quantifier error in the following snippet?

THANKS IN ADVANCE!
-mprototype

function $_GET(q,s) {
        s = s ? s : window.location.search;
        var re = new RegExp( '&' + q + '(?:=([^&]*))?(?=&|$)' , 'i' );
        return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
    }

Body:
? has a special meaning in Regular Expressions, specifically it makes the preceding item optional. If you are trying to find the question mark character itself you need to escape it with a backslash.

function $_GET(q,s) {
        s = s ? s : window.location.search;
        var re = new RegExp( '&' + q + '(?:=([^&]*))?(?=&|$)' , 'i' );
        return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
    }


问:
How to connect to share point on premise server using azure logic apps or Azure data factory?
we have a share point installed on our organisation server. so I wanted to connect  to my organisations share point server using from azure logic app.
I have tried by installing on premise gateway in share point server buti'm unable to get the file path url from premise server.can any one help me with any link or process how to connect it?</p>

答:
Before you can connect to on-premises data sources from Azure Logic Apps, download and install the on-premises data gateway on a local computer. The gateway works as a bridge that provides quick data transfer and encryption between data sources on premises (not in the cloud) and your logic apps.

Here are the prerequisites

Steps to install data gateway

Download, save, and run the gateway installer on a local computer.

Accept the default installation path, or specify the location on your computer where you want to install the gateway.

Review and accept the terms of use and privacy statement, and then choose Install.

After the gateway successfully installs, provide the email address for your work or school account, and choose Sign in.

Choose Register a new gateway on this computer > Next, which registers your gateway installation with the gateway cloud service.

Provide this information for your gateway installation:

The name you want for your installation

The recovery key you want to create, which must have at least eight characters

Confirmation for your recovery key

Check the region selected for the gateway cloud service and Azure Service Bus that's used by your gateway installation.

To accept the default region, choose Configure. Or, to change the default region, follow these steps:

Next to the current region, select Change Region.

On the next page, open the Select Region list, select the region you want, and choose Done.

After the confirmation page appears, choose Close.
The installer confirms that your gateway is now online and ready for use.

Now register your gateway in Azure by creating an Azure resource for your gateway installation.


问:
Linux shared library depends on symbols in another shared library opened by dlopen with RTLD_LOCAL
I have a shared library libmain.so, loaded by the host program with dlopen("libmain.so", RTLD_LOCAL), and under some conditions, libmain.so will load another shared library, libpatch.so, also with dlopen. The problem is, libpatch.so depends on symbols inside libmain.so, so how can I solve this?

Change RTLD_LOCAL to RTLD_GLOBAL is not an option due to permission reasons.

There is a question quite similar to this one, the solution to that problem is to make libpatch.so a dependency of libmain.so, so it will be loaded when libmain.so is loaded, but my libpatch.so should be loaded conditionally, libpatch.so might not be there when libmain.so is linked.

EDIT: the original problem I want to solve is:

When the process is running, we may find that there is a bug in function SomeFunction inside libmain.so, but the process cannot be restarted and libmain.so cannot be reloaded, so we have to provide a libpatch.so with bug-fixed function SomeFunction, and send a signal to the process, make it to load libpatch.so, and use SomeFunction in libpatch.so instead the buggy one in libmain.so. However, SomeFunction depends on a global variable GlobalVar, and it might have changed in libmain.so, so we want to link SomeFunction to it inside libmain.so, but libmain.so is loaded with RTLD_LOCAL, GlobalVar cannot be referenced when libpatch.so is loading.

答: Compile a list of symbols from libmain.so needed by libpatch.so. Build a data structure that contains addresses of these symbols. Build libpatch.so not against libmain.so but against this data structure. Pass an instance of it to libpatch.so initialisation function. </p>


问:
How can i insert row into table sqlalchemy object?
i have table object that its name is tags and i don't know how to insert new row into it

this is my table object :

```<code>tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
    db.Column('Post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True)
)
</code>```

i tried to use this query for test :

```<code>db.session.add(tags(
        post_id = 1,
        tag_id = 2
))
</code>```

But I encountered this error :

```<code>TypeError: 'Table' object is not callable
</code>```

答:
A many-to-many relationship adds an association table between the two models.

```<code>tags = db.Table('tags',
        db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
        db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
    )

class Page(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tags = db.relationship('Tag', secondary=tags, lazy='subquery',
        backref=db.backref('pages', lazy=True))

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
</code>```

Now you can insert data into the table:

```<code>>>> page = Page()
>>> tag = Tag()
>>> page.tags.append(tag)
>>> db.session.add(page)
>>> db.session.commit()
</code>```

Read this for more information.

Body:
i have table object that its name is tags and i don't know how to insert new row into it

this is my table object :

tags = db.Table('tags',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
    db.Column('Post_id', db.Integer, db.ForeignKey('post.id'), primary_key=True)
)

i tried to use this query for test :

db.session.add(tags(
        post_id = 1,
        tag_id = 2
))

But I encountered this error :

TypeError: 'Table' object is not callable

Body:
A many-to-many relationship adds an association table between the two models.

tags = db.Table('tags',
        db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
        db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
    )

class Page(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tags = db.relationship('Tag', secondary=tags, lazy='subquery',
        backref=db.backref('pages', lazy=True))

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)

Now you can insert data into the table:

>>> page = Page()
>>> tag = Tag()
>>> page.tags.append(tag)
>>> db.session.add(page)
>>> db.session.commit()

Read this for more information.


问:
How store variable after data has been passed from server to client?
After passing my server side 'data' to the client I am unable to store the 'data' into a variable and receive an undefined.

Why is this happening and how can I resolve this?

The request is made on the client side:

```<code>(function () {

    var M;
    var url = '/app/get/metafield';

    fetch(url)
        .then((response) => response.json())
        .then(function (data) {
            filter(data)
        });

    function filter(data) {
        console.log('data :', data) // 25
        M = JSON.stringify(data);

    }

        console.log('M :', M) // undefined
});
</code>```

This is ther server side code:

```<code>  app.get('/app/get/metafield', function (req, res, next) {

               function (error, response, body) {
                    var data = JSON.parse(body)
                    var M = data.metafields[0].value;
                    return res.json(M);
                })

    });
</code>```

答:
You should try to run the console.log within the .then() block instead. This is because http requests are asynchronous operations, hence on your above block of code, the line with console.log('M :', M) will be executed before the request is completed and returned.

Therefore, you should add the console.log() statement within that filter function you have defined, such that the console.log() will be executed after the promise has been fulfilled.

```<code>fetch(url)
  .then((response) => response.json())
  .then(function (data) {
    filter(data);
    console.log(data);
  });

function filter(data) {
  console.log('data :', data) // 25
  M = JSON.stringify(data);
  console.log('M :', M)
}
</code>```

Body:
After passing my server side 'data' to the client I am unable to store the 'data' into a variable and receive an undefined.

Why is this happening and how can I resolve this?

The request is made on the client side:

(function () {

    var M;
    var url = '/app/get/metafield';

    fetch(url)
        .then((response) => response.json())
        .then(function (data) {
            filter(data)
        });

    function filter(data) {
        console.log('data :', data) // 25
        M = JSON.stringify(data);

    }

        console.log('M :', M) // undefined
});

This is ther server side code:

  app.get('/app/get/metafield', function (req, res, next) {

               function (error, response, body) {
                    var data = JSON.parse(body)
                    var M = data.metafields[0].value;
                    return res.json(M);
                })

    });

Body:
You should try to run the console.log within the .then() block instead. This is because http requests are asynchronous operations, hence on your above block of code, the line with console.log('M :', M) will be executed before the request is completed and returned.

Therefore, you should add the console.log() statement within that filter function you have defined, such that the console.log() will be executed after the promise has been fulfilled.

fetch(url)
  .then((response) => response.json())
  .then(function (data) {
    filter(data);
    console.log(data);
  });

function filter(data) {
  console.log('data :', data) // 25
  M = JSON.stringify(data);
  console.log('M :', M)
}


问:
External scripts do not load after routing to another component in Angular application
I have a navbar on my Angular 7 application.  I also have a custom javascript file that loads when the app initially load. After clicking on a link in my application to route to another component, the external javascript file stops working/does not load.  How can I get this javascript file to load or remain loaded when I click on a link to route to a different component?

I have added the javascript file to my angular.json file correctly, the problem still persists.  I have tried loading the script inside of my index.html file inside a script tag, that also does not solve my problem.

I've read through some older stackoverflow threads regarding the same problem but there doesn't seem to be a definitive answer or solution.

I expect my custom js file to load with all of its functionality after clicking on a link in my navbar to that routes me to another component but it does not load with any functionality.

答: When you change routes you are not loading a new page, you are replacing parts of the DOM of the same page. It is not going to reinvoke a JS file loaded on initial page load. If you want to run some JS on route change you can call it in a component's life cycle handler like ngAfterInit or you can create a universal route handler that invokes it each route change.</p>


问:
CRUD methods with PHP, JS/jQuery, and a little AJAX
I've been working on a system where you can create-read-update-delete to/from a table in a SQLite database.  So far I've only written the create and view methods (easy).

Now, I have ran into a roadblock on deciding how to go about deleting and updating items.  On the view page, there is query to the database through php and a generation of the table (echoed through php into html).  There is also a button added next to each row that looks like a little trash can to delete the row.

How can I use AJAX to simultaneously delete the row from the html table and sqlite table?  A more definitive question would be, how can I link each button to each row and query the database when the button is clicked?

Here is the generated table:

```<code>foreach($result as $entry){
 echo  '<tr>' . '<td>'. $entry['department']. ' ' . $entry['CRN']. '</td>' .
    '<td>'. $entry['title'] . '</td>' .
    '<td>'. $entry['addDate'] . '</td>'.
    '<td><button class="fg-button fg-button-icon-left ui-state-default ui-corner-all"><span class="ui-icon ui-icon-trash"></span></button></td>'.'</tr>';
}
</code>```

答:
You could have the Ajax call return the new list of values and just replace the entire table with the new content.

In the JS, make delete call with a callback.

In the callback:

empty the div that contains the
table

create a new table based on the
results of the call (by making a call to PHP if that's what's generating the table)

append that table
to the div

That's something we do often, although, we need to since it's a multi-user system.

Body:
I've been working on a system where you can create-read-update-delete to/from a table in a SQLite database.  So far I've only written the create and view methods (easy).

Now, I have ran into a roadblock on deciding how to go about deleting and updating items.  On the view page, there is query to the database through php and a generation of the table (echoed through php into html).  There is also a button added next to each row that looks like a little trash can to delete the row.

How can I use AJAX to simultaneously delete the row from the html table and sqlite table?  A more definitive question would be, how can I link each button to each row and query the database when the button is clicked?

Here is the generated table:

foreach($result as $entry){
 echo  '
' . ''. $entry['department']. ' ' . $entry['CRN']. '	' .
    ''. $entry['title'] . '	' .
    ''. $entry['addDate'] . '	'.
    '<button class="fg-button fg-button-icon-left ui-state-default ui-corner-all"></button>	'.'
';
}


问:
How to capture xpath of an amazon product selenium
After going to amazon.com I have typed yellow puma shoes. I am trying to capture xpath but not able to do so.

URL: https://www.amazon.com/s?k=yellow+puma+shoes&ref=nb_sb_noss_1

Any product will work.

These are the 3 I have tried but none of them work.

```<code>//a[@href='/PUMA-Fracture-Sneaker-Black-Safety-Yellow/dp/B072JPQ3JJ/ref=sr_1_1?keywords=yellow+puma+shoes&qid=1559275052&s=gateway&sr=8-1']

//span[contains(text(),'PUMA Men's Tazon 6 Fracture FM Cross-Trainer Shoe')]

//a//span[contains(text(),'PUMA Men's Tazon 6 Fracture FM Cross-Trainer Shoe')]
</code>```

Thanks in advance for your help.

答:
Here is the xpath to get the product name element.

```<code>(//div[@class='a-section a-spacing-none a-spacing-top-small']/h2)[10]//span
</code>```

Replace 10 with the desired product number.

Body:
After going to amazon.com I have typed yellow puma shoes. I am trying to capture xpath but not able to do so.

URL: https://www.amazon.com/s?k=yellow+puma+shoes&ref=nb_sb_noss_1

Any product will work.

These are the 3 I have tried but none of them work.

//a[@href='/PUMA-Fracture-Sneaker-Black-Safety-Yellow/dp/B072JPQ3JJ/ref=sr_1_1?keywords=yellow+puma+shoes&qid=1559275052&s=gateway&sr=8-1']

//span[contains(text(),'PUMA Men's Tazon 6 Fracture FM Cross-Trainer Shoe')]

//a//span[contains(text(),'PUMA Men's Tazon 6 Fracture FM Cross-Trainer Shoe')]

Thanks in advance for your help.

Body:
Here is the xpath to get the product name element.

(//div[@class='a-section a-spacing-none a-spacing-top-small']/h2)[10]//span

Replace 10 with the desired product number.


问:
How to add top layers to a pre-trained functional model
I'm trying to create a ResNet50 model using Keras to predict cats vs. dogs. I decided to just work with a 1000-point subset of the data, with a 700-150-150 train-validation-test split. (I know it's small, but it's what my computer can handle.) I've imported the model using

```<code>resnet_model = keras.applications.ResNet50(include_top=False, input_tensor=None, input_shape=None, pooling=None, classes=2)
resnet_model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])
</code>```

But when I try to fit it with

```<code>aug = ImageDataGenerator(rotation_range=20, zoom_range=0.15,
  width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15,
  horizontal_flip=True, fill_mode="nearest")

resnet_model.fit_generator(aug.flow(X_train, y_train, batch_size = batches), steps_per_epoch = len(X_train) // batches,
                          validation_data = (X_valid, y_valid), validation_steps = 4, epochs = 10, verbose = 1)
</code>```

I get the following value error:

ValueError: Error when checking target: expected activation_352 to have 4 dimensions, but got array with shape (150, 2)

The (150,2) array is clearly coming from valid_y, but I don't know why that particular output should have 4 dimensions--that's supposed to be a label vector, not a 4-d image size and color vector. Can someone help me work out how to get the model to recognize this input?

Note: I know that Daniel Möller mentions here that I need to add a Flatten() layer, but the nature of the functional model and its call hardly seems to allow for that, unless I want to rewrite the entire ResNet from scratch (which seems to defeat the purpose of having a reusable pre-trained model). Any insight would be appreciated.

答:
After reviewing Möller's comments and the code from Yu-Yang here, I was able to re-formulate the top of the model using the following code:

```<code>pre_resnet_model = keras.applications.ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224,224,3), pooling=None, classes=2)
for layer in pre_resnet_model.layers:
    layer.trainable = False
flatten = Flatten()(pre_resnet_model.output)
output = Dense(2, activation='softmax')(flatten)
resnet_model = Model(pre_resnet_model.input, output)
</code>```

The flatten layer flattens, and then the output layer draws on that. I'm not yet sure why the Model() only requires a ResNet50().input and an output, so if someone can explain to me why I skipped the Flatten() in there I would appreciate it--Model() clearly doesn't require a listing of all the layers, so is it just an input and an output? I'll take a look at the documentation, but in the meantime, if someone wanders by and has a clear explanation, I'll take it.

Body:
I'm trying to create a ResNet50 model using Keras to predict cats vs. dogs. I decided to just work with a 1000-point subset of the data, with a 700-150-150 train-validation-test split. (I know it's small, but it's what my computer can handle.) I've imported the model using

resnet_model = keras.applications.ResNet50(include_top=False, input_tensor=None, input_shape=None, pooling=None, classes=2)
resnet_model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])

But when I try to fit it with

aug = ImageDataGenerator(rotation_range=20, zoom_range=0.15,
  width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15,
  horizontal_flip=True, fill_mode="nearest")

resnet_model.fit_generator(aug.flow(X_train, y_train, batch_size = batches), steps_per_epoch = len(X_train) // batches,
                          validation_data = (X_valid, y_valid), validation_steps = 4, epochs = 10, verbose = 1)

I get the following value error:

ValueError: Error when checking target: expected activation_352 to have 4 dimensions, but got array with shape (150, 2)

The (150,2) array is clearly coming from valid_y, but I don't know why that particular output should have 4 dimensions--that's supposed to be a label vector, not a 4-d image size and color vector. Can someone help me work out how to get the model to recognize this input?

Note: I know that Daniel Möller mentions here that I need to add a Flatten() layer, but the nature of the functional model and its call hardly seems to allow for that, unless I want to rewrite the entire ResNet from scratch (which seems to defeat the purpose of having a reusable pre-trained model). Any insight would be appreciated.

Body:
After reviewing Möller's comments and the code from Yu-Yang here, I was able to re-formulate the top of the model using the following code:

pre_resnet_model = keras.applications.ResNet50(include_top=False, weights='imagenet', input_tensor=None, input_shape=(224,224,3), pooling=None, classes=2)
for layer in pre_resnet_model.layers:
    layer.trainable = False
flatten = Flatten()(pre_resnet_model.output)
output = Dense(2, activation='softmax')(flatten)
resnet_model = Model(pre_resnet_model.input, output)

The flatten layer flattens, and then the output layer draws on that. I'm not yet sure why the Model() only requires a ResNet50().input and an output, so if someone can explain to me why I skipped the Flatten() in there I would appreciate it--Model() clearly doesn't require a listing of all the layers, so is it just an input and an output? I'll take a look at the documentation, but in the meantime, if someone wanders by and has a clear explanation, I'll take it.


问:
How to get last sunday's date from today's date using shell script?
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

```<code>a=`date -dlast-sunday +%Y%m%d`
</code>```

but this gives a date of Sunday before the last one.

答:
Instead of asking for last Sunday, ask for one week before next Sunday.

```<code>$ date +%Y%m%d
20190531
$ date -d'next sunday - 1 week' +%Y%m%d
20190526
</code>```

Just as "last Sunday" is always earlier than the current day, so is "next Sunday" always after the current day.

As it is Friday as I write this answer, let's ask for last Friday using this technique:

```<code>$ date +"%A %F"
Friday 2019-05-31
$ date -d 'next Friday - 1 week' +"%A %F"
Friday 2019-05-31
</code>```

Body:
I want to print the date of last Sunday by taking today's date as input for all days of the week except Sunday, but if it is Sunday then it should print today's date.  I tried this,

a=`date -dlast-sunday +%Y%m%d`

but this gives a date of Sunday before the last one.

Body:
Instead of asking for last Sunday, ask for one week before next Sunday.

$ date +%Y%m%d
20190531
$ date -d'next sunday - 1 week' +%Y%m%d
20190526

Just as "last Sunday" is always earlier than the current day, so is "next Sunday" always after the current day.

As it is Friday as I write this answer, let's ask for last Friday using this technique:

$ date +"%A %F"
Friday 2019-05-31
$ date -d 'next Friday - 1 week' +"%A %F"
Friday 2019-05-31


问:
"Bidirectional" type projection / variance in Kotlin?
Let's say we have a class hierarchy like Pug : Dog : Mammal : Animal.

I want a function that accepts a Bag<T> (where Bag is invariant in T) argument of things that are sub OR superclasses of Dog: fun work(things: Bag<in/out Dog) Such that Bag<Animal>, Bag<Dog>, Bag<Pug> is OK, but Bag<Cat> is NOT accepted.

Honestly, I'm not even sure what that type of projection is called. Any pointers?

答:
If you think about what in and out modifiers truly mean, you will soon realize having in OR out does not really make sense.

Let's take a look at out first. Having <out T> does not mean that "This function accepts T and its subclass as a parameter". It actually means "This function will not do anything a parameter of class  T or any of its subclasses cannot do". This modifier imposes limitations on what you can do to that parameter.

Check this code:

```<code>fun doThingsWithBag(bag: Bag<out Dog>) {
    bag.getAny().walk() // allowed

    bag.put(Dog()) // not allowed
}
</code>```

You are not allowed to put any dog into this bag, because this bag could actually be a type Bag<Pug>, and Bag<Pug> won't accept a random Dog.

The same goes for in. <in T> does not mean that "This function accepts T and its super". It is more like "This function will not do anything T or any of its super classes cannot do".

```<code>fun doThingsWithBag(bag: Bag<in Dog>) {
    bag.put(Dog()) // allowed

    bag.getAny().walk() // not allowed
}
</code>```

Now you can put a dog inside the bag, but you can't really do anything with the dogs inside the bag because the bag could actually be a Bag<Animal> and there is no guarantee that the "thing" you take out from the bag is a Dog.

So as you can see, there is a clear distinction between what in and out can do, and therefore they cannot coexist.

Even the interface suggested in the other answer won't help you much because your Animal class would also need to implement that same interface which means Cat will also have access to that interface. The only way to work around is to have your work method to accept Bag<Any> and manually check its generic class.

Update:

What you are trying to do is not possible in OOP. What you are looking for is basically something like this:

```<code>update(Animal()) // allowed
update(Dog())    // allowed
update(Pug())    // allowed
update(Cat())    // not allowed (compile time error)
</code>```

However there is no way a compiler can stop you from doing this:

```<code>val animal: Animal = Cat()
update(animal)  // ???
</code>```

You can do something similar to this only in runtime, by manually checking the input type.

Body:
If you think about what in and out modifiers truly mean, you will soon realize having in OR out does not really make sense.

Let's take a look at out first. Having <out T> does not mean that "This function accepts T and its subclass as a parameter". It actually means "This function will not do anything a parameter of class  T or any of its subclasses cannot do". This modifier imposes limitations on what you can do to that parameter.

Check this code:

fun doThingsWithBag(bag: Bag<out Dog>) {
    bag.getAny().walk() // allowed

    bag.put(Dog()) // not allowed
}

You are not allowed to put any dog into this bag, because this bag could actually be a type Bag<Pug>, and Bag<Pug> won't accept a random Dog.

The same goes for in. <in T> does not mean that "This function accepts T and its super". It is more like "This function will not do anything T or any of its super classes cannot do".

fun doThingsWithBag(bag: Bag<in Dog>) {
    bag.put(Dog()) // allowed

    bag.getAny().walk() // not allowed
}

Now you can put a dog inside the bag, but you can't really do anything with the dogs inside the bag because the bag could actually be a Bag<Animal> and there is no guarantee that the "thing" you take out from the bag is a Dog.

So as you can see, there is a clear distinction between what in and out can do, and therefore they cannot coexist.

Even the interface suggested in the other answer won't help you much because your Animal class would also need to implement that same interface which means Cat will also have access to that interface. The only way to work around is to have your work method to accept Bag<Any> and manually check its generic class.

Update:

What you are trying to do is not possible in OOP. What you are looking for is basically something like this:

update(Animal()) // allowed
update(Dog())    // allowed
update(Pug())    // allowed
update(Cat())    // not allowed (compile time error)

However there is no way a compiler can stop you from doing this:

val animal: Animal = Cat()
update(animal)  // ???

You can do something similar to this only in runtime, by manually checking the input type.


问:
Java Collections - Effienct search for DateTime ranges
I have a case where I have a table (t1) which contains items like

```<code> | id | timestamp | att1 | att2 |
</code>```

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!

答: You can make the object you want in your collection, which I think is att1, implement the Comparable interface and then have the compareTo method compare the timestamp field.  With this in place it will work in any sorted collection, such as a treeSet, making it easy to iterate and pull out everything in a certain range.</p>

Body:
I have a case where I have a table (t1) which contains items like

 | id | timestamp | att1 | att2 |

Now I have to iterate over a collection of elements of type att1 and get all records from t1 which are between two certain timestamps for this att1. I have to do this operation several times for a single att1.

So in order to go easy on the database queries, I intended to load every entry from t1 which has a certain att1 attribute once into a collection and perform the subsequent searches on this collection.

Is there a collection that could handle a search like between '2011-02-06 09:00:00' and '2011-02-06 09:00:30'? It's not guaranteed to contain entries for those two timestamps.

Before writing an implementation for that (most likely a very slow implementation ^^) I wanted to ask you guys if there might be some existing collections already or how I could tackle this problem.

Thanks!


问:
Laravel blank projects.. so many files! Can it be reduced somehow?
Last time I used Laravel was a long time ago and I decided to get back to it.

Now coming from CodeIgniter, which was a powerful framework in its own time, I was happy to upload projects to websites as the "system" folder containing the framework files contained only 121 files.

The problem with composer-based solutions however is that a tiny project can become huge, much bigger than a very large scale CodeIgniter project back in the days. All the dependencies have test folders, documentation, and tons of modules when sometimes only one method is used.

I gasped when creating an empty Laravel project using the instructions from the official documentation and seeing the "vendor" folder containing over 8,000 files!! (Not counting the folders) And it's doing nothing yet.. That is when using the --prefer-dist flag by the way. And I know about the --no-dev argument, which still has 5,000+ files. My point was that there is no way all these files are used, especially when using the distribution channel.

So my question is if there is a way to have a more selective empty Laravel project, as servers often have limited Inodes and 8,000 files + folders for every project makes you reach the limit really quickly (and upload takes forever if you can't install composer on your server).

答:
I had a Same Situation Before few Days so i have created the console command to delete the unused files in the vendor  Directory

Step :1

```<code>php artisan make:command CleanVendorFolderCommand
</code>```

Step: 2

Copy the current code and paste int in the Command Class

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use FilesystemIterator;

class CleanVendorFolderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clean:vendor {--o : Verbose Output} {--dry : Runs in dry mode without deleting files.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleans up useless files from  vendor folder.';

    protected $patterns =
            [
                'test',
                'tests',
                '.github',
                'README',
                'CHANGELOG',
                'FAQ',
                'CONTRIBUTING',
                'HISTORY',
                'UPGRADING',
                'UPGRADE',
                'demo',
                'example',
                'examples',
                '.doc',
                'readme',
                'changelog',
                'composer',
                '.git',
                '.gitignore',
                '*.md',
                '.*.yml',
                '*.yml',
                '*.txt',
                '*.dist',
                'LICENSE',
                'AUTHORS',
                '.eslintrc',
                'ChangeLog',
                '.gitignore',
                '.editorconfig',
                '*.xml',
                '.npmignore',
                '.jshintrc',
                'Makefile',
                '.keep',

            ];
    /**
     * List of File and Folders Patters Going To Be Excluded
     *
     * @return void
     */
    protected $excluded =
            [
                /**List of  Folders*/
                'src',
                /**List of  Files*/
                '*.php',
                '*.stub',
                '*.js',
                '*.json',
            ];
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $patterns = array_diff($this->patterns, $this->excluded);

        $directories = $this->expandTree(base_path('vendor'));

        $isDry = $this->option('dry');

        foreach ($directories as $directory)
        {
            foreach ($patterns as $pattern)
            {
                $casePattern = preg_replace_callback('/([a-z])/i', [$this, 'prepareWord'], $pattern);
                $files = glob($directory . '/' . $casePattern, GLOB_BRACE);
                if (!$files)
                {
                    continue;
                }

                $files = array_diff($files, $this->excluded);
                foreach ($this->excluded as $excluded)
                {
                    $key = $this->arrayFind($excluded, $files);

                    if ($key !== false)
                    {
                        $this->warn('SKIPPED: ' . $files[$key]);
                        unset($files[$key]);
                    }
                }
                foreach ($files as $file)
                {
                    if (is_dir($file))
                    {
                        $this->warn('DELETING DIR: ' . $file);
                        if (!$isDry)
                        {
                            $this->delTree($file);
                        }
                    } else
                    {
                        $this->warn('DELETING FILE: ' . $file);
                        if (!$isDry)
                        {
                            @unlink($file);
                        }
                    }
                }
            }
        }
        $this->warn('Folder Cleanup Done!');
    }
    /**
     * Recursively traverses the directory tree
     *
     * @param  string $dir
     * @return array
     */
    protected function expandTree($dir)
    {
        $directories = [];
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file)
        {
            $directory = $dir . '/' . $file;
            if (is_dir($directory))
            {
                $directories[] = $directory;
                $directories = array_merge($directories, $this->expandTree($directory));
            }
        }
        return $directories;
    }
    /**
     * Recursively deletes the directory
     *
     * @param  string $dir
     * @return bool
     */
    protected function delTree($dir) {
        if (!file_exists($dir) || !is_dir($dir))
        {
            return false;
        }

        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($iterator as $filename => $fileInfo)
        {
            if ($fileInfo->isDir())
            {
                @rmdir($filename);
            } else {
                @unlink($filename);
            }
        }
        @rmdir($dir);
    }
    /**
     * Prepare word
     *
     * @param  string $matches
     * @return string
     */
    protected function prepareWord($matches)
    {
        return '[' . strtolower($matches[1]) . strtoupper($matches[1]) . ']';
    }
    protected function arrayFind($needle, array $haystack)
    {
        foreach ($haystack as $key => $value)
        {
            if (false !== stripos($value, $needle))
            {
                return $key;
            }
        }
        return false;
    }
    protected function out($message)
    {
        if ($this->option('o') || $this->option('dry'))
        {
            echo $message . PHP_EOL;
        }
    }
}
</code>```

TESTED ON

OS Name   Microsoft Windows 10 Pro

Version   10.0.16299 Build 16299

Processor Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz, 2400 Mhz, 2 Core(s), 4 Logical Processor(s)

NOW THE TESTING PART

Before Size of vendor Folder

Size 57.0 MB (5,98,29,604 bytes)

Size on disk  75.2 MB (7,88,80,768 bytes)

Contains  12,455 Files, 2,294 Folders

Now Run the Command

```<code>php artisan clean:vendor
</code>```

Size of vendor Folder after Running the command

Size 47.0 MB (4,93,51,781 bytes)

Size on disk  59.7 MB (6,26,76,992 bytes)

Contains  8,431 Files, 1,570 Folders

Hope it helps

Body:
I had a Same Situation Before few Days so i have created the console command to delete the unused files in the vendor  Directory

Step :1

php artisan make:command CleanVendorFolderCommand

Step: 2

Copy the current code and paste int in the Command Class

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;
use FilesystemIterator;

class CleanVendorFolderCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clean:vendor {--o : Verbose Output} {--dry : Runs in dry mode without deleting files.}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cleans up useless files from  vendor folder.';

    protected $patterns =
            [
                'test',
                'tests',
                '.github',
                'README',
                'CHANGELOG',
                'FAQ',
                'CONTRIBUTING',
                'HISTORY',
                'UPGRADING',
                'UPGRADE',
                'demo',
                'example',
                'examples',
                '.doc',
                'readme',
                'changelog',
                'composer',
                '.git',
                '.gitignore',
                '*.md',
                '.*.yml',
                '*.yml',
                '*.txt',
                '*.dist',
                'LICENSE',
                'AUTHORS',
                '.eslintrc',
                'ChangeLog',
                '.gitignore',
                '.editorconfig',
                '*.xml',
                '.npmignore',
                '.jshintrc',
                'Makefile',
                '.keep',

            ];
    /**
     * List of File and Folders Patters Going To Be Excluded
     *
     * @return void
     */
    protected $excluded =
            [
                /**List of  Folders*/
                'src',
                /**List of  Files*/
                '*.php',
                '*.stub',
                '*.js',
                '*.json',
            ];
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $patterns = array_diff($this->patterns, $this->excluded);

        $directories = $this->expandTree(base_path('vendor'));

        $isDry = $this->option('dry');

        foreach ($directories as $directory)
        {
            foreach ($patterns as $pattern)
            {
                $casePattern = preg_replace_callback('/([a-z])/i', [$this, 'prepareWord'], $pattern);
                $files = glob($directory . '/' . $casePattern, GLOB_BRACE);
                if (!$files)
                {
                    continue;
                }

                $files = array_diff($files, $this->excluded);
                foreach ($this->excluded as $excluded)
                {
                    $key = $this->arrayFind($excluded, $files);

                    if ($key !== false)
                    {
                        $this->warn('SKIPPED: ' . $files[$key]);
                        unset($files[$key]);
                    }
                }
                foreach ($files as $file)
                {
                    if (is_dir($file))
                    {
                        $this->warn('DELETING DIR: ' . $file);
                        if (!$isDry)
                        {
                            $this->delTree($file);
                        }
                    } else
                    {
                        $this->warn('DELETING FILE: ' . $file);
                        if (!$isDry)
                        {
                            @unlink($file);
                        }
                    }
                }
            }
        }
        $this->warn('Folder Cleanup Done!');
    }
    /**
     * Recursively traverses the directory tree
     *
     * @param  string $dir
     * @return array
     */
    protected function expandTree($dir)
    {
        $directories = [];
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file)
        {
            $directory = $dir . '/' . $file;
            if (is_dir($directory))
            {
                $directories[] = $directory;
                $directories = array_merge($directories, $this->expandTree($directory));
            }
        }
        return $directories;
    }
    /**
     * Recursively deletes the directory
     *
     * @param  string $dir
     * @return bool
     */
    protected function delTree($dir) {
        if (!file_exists($dir) || !is_dir($dir))
        {
            return false;
        }

        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($iterator as $filename => $fileInfo)
        {
            if ($fileInfo->isDir())
            {
                @rmdir($filename);
            } else {
                @unlink($filename);
            }
        }
        @rmdir($dir);
    }
    /**
     * Prepare word
     *
     * @param  string $matches
     * @return string
     */
    protected function prepareWord($matches)
    {
        return '[' . strtolower($matches[1]) . strtoupper($matches[1]) . ']';
    }
    protected function arrayFind($needle, array $haystack)
    {
        foreach ($haystack as $key => $value)
        {
            if (false !== stripos($value, $needle))
            {
                return $key;
            }
        }
        return false;
    }
    protected function out($message)
    {
        if ($this->option('o') || $this->option('dry'))
        {
            echo $message . PHP_EOL;
        }
    }
}

TESTED ON

OS Name   Microsoft Windows 10 Pro

Version   10.0.16299 Build 16299

Processor Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz, 2400 Mhz, 2 Core(s), 4 Logical Processor(s)

NOW THE TESTING PART

Before Size of vendor Folder

Size 57.0 MB (5,98,29,604 bytes)

Size on disk  75.2 MB (7,88,80,768 bytes)

Contains  12,455 Files, 2,294 Folders

Now Run the Command

php artisan clean:vendor

Size of vendor Folder after Running the command

Size 47.0 MB (4,93,51,781 bytes)

Size on disk  59.7 MB (6,26,76,992 bytes)

Contains  8,431 Files, 1,570 Folders

Hope it helps


问:
how to use plumatic schema to define a function that takes an argument that can be 2 or more different types?
I can't figure out how to use s/either or s/conditional as part of the input list.  Would like to do something like this:</p>

```<code>(s/defn parse-int :- s/Int
  [input :- ; either s/Int or s/Str]
    ; if s/Int
    input
    ; if s/Str
    (read-string input)
))
</code>```

答:
```<code>(sc/defn parse-int :- sc/Str
    [input :- (sc/cond-pre sc/Int sc/Str)]
    (if (string? input) "a string" "not a string"))

(parse-int 34545) ; "not a string"
(parse-int "34545") ; "a string"
</code>```

You could also use either, but it is deprecated.

Body:
I can't figure out how to use s/either or s/conditional as part of the input list.  Would like to do something like this:

(s/defn parse-int :- s/Int
  [input :- ; either s/Int or s/Str]
    ; if s/Int
    input
    ; if s/Str
    (read-string input)
))

Body:
(sc/defn parse-int :- sc/Str
    [input :- (sc/cond-pre sc/Int sc/Str)]
    (if (string? input) "a string" "not a string"))

(parse-int 34545) ; "not a string"
(parse-int "34545") ; "a string"

You could also use either, but it is deprecated.


问:
Is it possible to link a shared static library built in VS2019 with a VS2010 project?
I need a regex library that can return submatches for a project that has to be built on VS 2010. By submatches, I mean for this regex: "(\w+):(\d+)" applied to this input string "deer:1234", the match state is true and I want to retrieve the contents of the two submatches -- "deer" and "1234".  Visual Studio 2010 does not have regex so I tried building Google RE2 in Visual Studio 2019 as a shared static library and then making a simple interface (see below) to provide me with the bare minimum functionality that I needed.  It obviously builds fine in Visual Studio 2019, but when I copy over the re2.lib and the header shown below and try to compile it into my 2010 project, I get this error:

error LNK2038: mismatch detected for '_MSC_VER': value '1900' doesn't match value '1600'

Note that my interface below does not use any C++ standard library.  It's just a simple class with character array inputs.  I was thinking that if I compile the re2.lib as a shared statically-linked library and then link it with my 2010 project, it should work. But after spending almost 2 days trying to get this to work, I'm open to other solutions.  Will my approach work or if not can anyone recommend a good regex library that compiles in Visual Studio 2010?

```<code>class RE2;

class __declspec(dllexport) BasicRegex {
public:
    BasicRegex(const char* str);
    ~BasicRegex();

    bool fullMatch(const char* str, char**& submatches, int numsubmatches);
    bool fullMatch(const char* str);
    bool partialMatch(const char* str, char**& submatches, int numsubmatches);
    bool partialMatch(const char* str);

private:
    RE2* gre2;
};
</code>```

答:
Unfortunately, the short answer is no, at least not with older versions of Visual C++, as documented below:

C++ Binary Compatibility between Visual Studio 2015 and Visual Studio 2019
   The Great C Runtime (CRT) Refactoring

Sincerely,

Body:
I need a regex library that can return submatches for a project that has to be built on VS 2010. By submatches, I mean for this regex: "(\w+):(\d+)" applied to this input string "deer:1234", the match state is true and I want to retrieve the contents of the two submatches -- "deer" and "1234".  Visual Studio 2010 does not have regex so I tried building Google RE2 in Visual Studio 2019 as a shared static library and then making a simple interface (see below) to provide me with the bare minimum functionality that I needed.  It obviously builds fine in Visual Studio 2019, but when I copy over the re2.lib and the header shown below and try to compile it into my 2010 project, I get this error:

error LNK2038: mismatch detected for '_MSC_VER': value '1900' doesn't match value '1600'

Note that my interface below does not use any C++ standard library.  It's just a simple class with character array inputs.  I was thinking that if I compile the re2.lib as a shared statically-linked library and then link it with my 2010 project, it should work. But after spending almost 2 days trying to get this to work, I'm open to other solutions.  Will my approach work or if not can anyone recommend a good regex library that compiles in Visual Studio 2010?

class RE2;

class __declspec(dllexport) BasicRegex {
public:
    BasicRegex(const char* str);
    ~BasicRegex();

    bool fullMatch(const char* str, char**& submatches, int numsubmatches);
    bool fullMatch(const char* str);
    bool partialMatch(const char* str, char**& submatches, int numsubmatches);
    bool partialMatch(const char* str);

private:
    RE2* gre2;
};


问:
Random sampling from a stream of unknown length
Say I need to randomly sample K elements from a real-time stream of N>>K elements where I have only finite memory, and where I don’t know N in advance. Can there be an algorithm for this that would be theoretically sound, i.e., comply with the technical meaning of taking a random sample from a collection?

I know there can be an algorithm for this that would satisfy some intuitions about random sampling, but the question is, is it formally sound?

In other words, how can I prove that an algorithm I come up with indeed produces a random sample in such a setting?

For example, if I can prove that my algorithm produces K elements where each element out of the stream was included with a probability of K/N – is that a legitimate proof?

答:
We need sample k elements.

For the first k data from stream (1th to kth), we will keep it.

for the following ith element (i>k), we will have some probability p to choose it or not. Also when we choose to keep the new ith element, we need to kick out one element from the previous k data. Then we have the following formula:

$k/i (1-p/k)=p$

explain: left size, k/i the the probability for first i element from the stream. (1-p/k) is the probability each element will not be kick out. So, the multiplication will represent the probability each element (from 1th to ith) will be stored, and this should be equal to p, which is the probability we keep i+1 th element.

After solve this equation, we get p=k/(1+N), which is the probability we will keep the new coming data. and 1/1+N is the probability we will kick out the data in original k.


问:
Change class for last two rows in a while loop
I have a while loop that displays result from a MySQL query. I know how to change the output for the last row or an odd row but how can I change the output for the last two results?

For example I have a list of results in a 2x2 matrix with border-bottom: 1px on each result but I would like to display the bottom two without the border?

答:
I like the CSS way, but you'll need to know the total number of items you're listing.  Then you can use a simple condition to check for that.</p>

```<code>$total_items = [count of items];
$cnt = 0;
while($fetch as $row) {
    ...
    if(++$cnt > ($total_items - 2)) {
        // list with no border
    } else {
        // list with border
    }
}
</code>```

Body:
I like the CSS way, but you'll need to know the total number of items you're listing.  Then you can use a simple condition to check for that.

$total_items = [count of items];
$cnt = 0;
while($fetch as $row) {
    ...
    if(++$cnt > ($total_items - 2)) {
        // list with no border
    } else {
        // list with border
    }
}


问:
Error message: h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead
I'm tring to run mbin for methylation analysis. But get error message: h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.
for several attempts, while trying to extract control IPDs with buildcontrols.

Environment:

mbin version: 1.1.1

Python version:2.7.12

Operating System: centOS

running under virtualenv

I thought it was, again, caused by version.
What I've tried:
I tried on a server with both python 3 and 2. And specified virtualenv to use python 2 as interpreter. mbin was successfully installed, but buidlcontrols didn't.

```<code>(virtualenv_for_mbin) [yx@localhost virtualenv_for_mbin]$ buildcontrols -i --procs=4 --control_pkl_name=control_means_190201.pkl /data1/yuxiao/userdata1/jobs/016/016504/data/aligned_reads.cmp.h5
2019-02-01 23:36:31 [INFO] Initiating dictionary of all possible motifs...
2019-02-01 23:36:31 [INFO]   - Adding 256 4-mer motifs...
2019-02-01 23:36:31 [INFO] Done: 256 possible contiguous motifs

2019-02-01 23:36:31 [INFO]   - Adding 1024 5-mer motifs...
2019-02-01 23:36:31 [INFO] Done: 1536 possible contiguous motifs

2019-02-01 23:36:31 [INFO]   - Adding 4096 6-mer motifs...
2019-02-01 23:36:32 [INFO] Done: 7680 possible contiguous motifs

2019-02-01 23:36:32 [INFO]   - Adding bipartite motifs to search space...
2019-02-01 23:36:33 [INFO] Done: 194560 possible bipartite motifs

2019-02-01 23:36:33 [INFO]
2019-02-01 23:36:33 [INFO] Preparing to create new control data in ctrl_tmp
Traceback (most recent call last):
  File "/data2/Software/virtualenv_for_mbin/bin/buildcontrols", line 10, in <module>
    sys.exit(launch())
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 20, in launch
    extract_controls(opts, control_aln_fn)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 40, in extract_controls
    opts           = controls.scan_WGA_aligns()
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 352, in scan_WGA_aligns
    reader = openIndexedAlignmentFile(self.control_aln_fn)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/opener.py", line 52, in openIndexedAlignmentFile
    return CmpH5Reader(fname, sharedIndex=sharedIndex)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 729, in __init__
    self._loadAlignmentInfo(sharedIndex)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 745, in _loadAlignmentInfo
    rawAlignmentIndex = self.file["/AlnInfo/AlnIndex"].value
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/h5py/_hl/dataset.py", line 313, in value
    "Use dataset[()] instead.", H5pyDeprecationWarning)
h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.
</code>```

I checked python version:

```<code>(virtualenv_for_mbin) [yx@localhost virtualenv_for_mbin]$ python -V
Python 3.6.5 :: Anaconda, Inc.
</code>```

So, I immediately tried to run a new virtualenv.

```<code>[yx@localhost Software]$ mkdir venv_tmp
[yx@localhost Software]$ cd venv_tmp/
[yx@localhost venv_tmp]$ virtualenv --python=/usr/local/bin/python2.7 .
Running virtualenv with interpreter /usr/local/bin/python2.7
New python executable in /data2/Software/venv_tmp/bin/python2.7
Also creating executable in /data2/Software/venv_tmp/bin/python
Installing setuptools, pip, wheel...
done.
[yx@localhost venv_tmp]$ . bin/activate
(venv_tmp) [yx@localhost venv_tmp]$ python -V
Python 3.6.5 :: Anaconda, Inc.
</code>```

Then, I turned to another server.....with only python 2.7 installed.

```<code>(venv_for_mbin) [yuxiao@localhost data_tmp]$ buildcontrols -i --procs=4 --control_pkl_name=control_means_190202.pkl aligned_reads.cmp.h5
2019-02-02 11:06:16 [INFO] Initiating dictionary of all possible motifs...
2019-02-02 11:06:16 [INFO]   - Adding 256 4-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 256 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding 1024 5-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 1536 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding 4096 6-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 7680 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding bipartite motifs to search space...
2019-02-02 11:06:18 [INFO] Done: 194560 possible bipartite motifs

2019-02-02 11:06:18 [INFO]
2019-02-02 11:06:18 [INFO] Preparing to create new control data in ctrl_tmp
Traceback (most recent call last):
  File "/data1/yuxiao/venv_for_mbin/bin/buildcontrols", line 10, in <module>
    sys.exit(launch())
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 20, in launch
    extract_controls(opts, control_aln_fn)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 40, in extract_controls
    opts           = controls.scan_WGA_aligns()
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 352, in scan_WGA_aligns
    reader = openIndexedAlignmentFile(self.control_aln_fn)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/opener.py", line 52, in openIndexedAlignmentFile
    return CmpH5Reader(fname, sharedIndex=sharedIndex)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 729, in __init__
    self._loadAlignmentInfo(sharedIndex)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 745, in _loadAlignmentInfo
    rawAlignmentIndex = self.file["/AlnInfo/AlnIndex"].value
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/h5py/_hl/dataset.py", line 313, in value
    "Use dataset[()] instead.", H5pyDeprecationWarning)
h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.
(venv_for_mbin) [yuxiao@localhost data_tmp]$ python -V
Python 2.7.12
</code>```

Still got the same error message. And I'm here hoping someone can help me. Thx a lot.

答:
As you said, you need to use the new way of getting scalar values out.
The .value syntax still works, but who wants to see pink warnings in Jupyter?

The message is not very intuitive, as isn't the syntax. So I will spell this out here - you have a d5py.File called f:

```<code>>>> f = h5py.File('temp.h5')
>>> f['path/to/scalar'] = 5
>>> f['path/to/scalar'].value
(...)\site-packages\h5py\_hl\dataset.py:313: H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead. "Use dataset[()] instead.", H5pyDeprecationWarning)
5
</code>```

"Use dataset[()] instead" means literally "use the indexing (__getitem__) operator, and pass to it an empty tuple (()). So the last line should read:

```<code>>>> f['path/to/scalar'][()]
5
</code>```

If you feel this is a bit of a strange, exotic notation, I can only empathize.

But it makes some sense - the numpy.shape of scalar values is in fact ().

Body:
I'm tring to run mbin for methylation analysis. But get error message: h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.
for several attempts, while trying to extract control IPDs with buildcontrols.

Environment:

mbin version: 1.1.1

Python version:2.7.12

Operating System: centOS

running under virtualenv

I thought it was, again, caused by version.
What I've tried:
I tried on a server with both python 3 and 2. And specified virtualenv to use python 2 as interpreter. mbin was successfully installed, but buidlcontrols didn't.

(virtualenv_for_mbin) [yx@localhost virtualenv_for_mbin]$ buildcontrols -i --procs=4 --control_pkl_name=control_means_190201.pkl /data1/yuxiao/userdata1/jobs/016/016504/data/aligned_reads.cmp.h5
2019-02-01 23:36:31 [INFO] Initiating dictionary of all possible motifs...
2019-02-01 23:36:31 [INFO]   - Adding 256 4-mer motifs...
2019-02-01 23:36:31 [INFO] Done: 256 possible contiguous motifs

2019-02-01 23:36:31 [INFO]   - Adding 1024 5-mer motifs...
2019-02-01 23:36:31 [INFO] Done: 1536 possible contiguous motifs

2019-02-01 23:36:31 [INFO]   - Adding 4096 6-mer motifs...
2019-02-01 23:36:32 [INFO] Done: 7680 possible contiguous motifs

2019-02-01 23:36:32 [INFO]   - Adding bipartite motifs to search space...
2019-02-01 23:36:33 [INFO] Done: 194560 possible bipartite motifs

2019-02-01 23:36:33 [INFO]
2019-02-01 23:36:33 [INFO] Preparing to create new control data in ctrl_tmp
Traceback (most recent call last):
  File "/data2/Software/virtualenv_for_mbin/bin/buildcontrols", line 10, in <module>
    sys.exit(launch())
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 20, in launch
    extract_controls(opts, control_aln_fn)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 40, in extract_controls
    opts           = controls.scan_WGA_aligns()
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 352, in scan_WGA_aligns
    reader = openIndexedAlignmentFile(self.control_aln_fn)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/opener.py", line 52, in openIndexedAlignmentFile
    return CmpH5Reader(fname, sharedIndex=sharedIndex)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 729, in __init__
    self._loadAlignmentInfo(sharedIndex)
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 745, in _loadAlignmentInfo
    rawAlignmentIndex = self.file["/AlnInfo/AlnIndex"].value
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/data2/Software/virtualenv_for_mbin/lib/python2.7/site-packages/h5py/_hl/dataset.py", line 313, in value
    "Use dataset[()] instead.", H5pyDeprecationWarning)
h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.

I checked python version:

(virtualenv_for_mbin) [yx@localhost virtualenv_for_mbin]$ python -V
Python 3.6.5 :: Anaconda, Inc.

So, I immediately tried to run a new virtualenv.

[yx@localhost Software]$ mkdir venv_tmp
[yx@localhost Software]$ cd venv_tmp/
[yx@localhost venv_tmp]$ virtualenv --python=/usr/local/bin/python2.7 .
Running virtualenv with interpreter /usr/local/bin/python2.7
New python executable in /data2/Software/venv_tmp/bin/python2.7
Also creating executable in /data2/Software/venv_tmp/bin/python
Installing setuptools, pip, wheel...
done.
[yx@localhost venv_tmp]$ . bin/activate
(venv_tmp) [yx@localhost venv_tmp]$ python -V
Python 3.6.5 :: Anaconda, Inc.

Then, I turned to another server.....with only python 2.7 installed.

(venv_for_mbin) [yuxiao@localhost data_tmp]$ buildcontrols -i --procs=4 --control_pkl_name=control_means_190202.pkl aligned_reads.cmp.h5
2019-02-02 11:06:16 [INFO] Initiating dictionary of all possible motifs...
2019-02-02 11:06:16 [INFO]   - Adding 256 4-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 256 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding 1024 5-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 1536 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding 4096 6-mer motifs...
2019-02-02 11:06:16 [INFO] Done: 7680 possible contiguous motifs

2019-02-02 11:06:16 [INFO]   - Adding bipartite motifs to search space...
2019-02-02 11:06:18 [INFO] Done: 194560 possible bipartite motifs

2019-02-02 11:06:18 [INFO]
2019-02-02 11:06:18 [INFO] Preparing to create new control data in ctrl_tmp
Traceback (most recent call last):
  File "/data1/yuxiao/venv_for_mbin/bin/buildcontrols", line 10, in <module>
    sys.exit(launch())
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 20, in launch
    extract_controls(opts, control_aln_fn)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 40, in extract_controls
    opts           = controls.scan_WGA_aligns()
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/mbin/controls.py", line 352, in scan_WGA_aligns
    reader = openIndexedAlignmentFile(self.control_aln_fn)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/opener.py", line 52, in openIndexedAlignmentFile
    return CmpH5Reader(fname, sharedIndex=sharedIndex)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 729, in __init__
    self._loadAlignmentInfo(sharedIndex)
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/pbcore/io/align/CmpH5IO.py", line 745, in _loadAlignmentInfo
    rawAlignmentIndex = self.file["/AlnInfo/AlnIndex"].value
  File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
  File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
  File "/data1/yuxiao/venv_for_mbin/lib/python2.7/site-packages/h5py/_hl/dataset.py", line 313, in value
    "Use dataset[()] instead.", H5pyDeprecationWarning)
h5py.h5py_warnings.H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead.
(venv_for_mbin) [yuxiao@localhost data_tmp]$ python -V
Python 2.7.12

Still got the same error message. And I'm here hoping someone can help me. Thx a lot.

Body:
As you said, you need to use the new way of getting scalar values out.
The .value syntax still works, but who wants to see pink warnings in Jupyter?

The message is not very intuitive, as isn't the syntax. So I will spell this out here - you have a d5py.File called f:

>>> f = h5py.File('temp.h5')
>>> f['path/to/scalar'] = 5
>>> f['path/to/scalar'].value
(...)\site-packages\h5py\_hl\dataset.py:313: H5pyDeprecationWarning: dataset.value has been deprecated. Use dataset[()] instead. "Use dataset[()] instead.", H5pyDeprecationWarning)
5

"Use dataset[()] instead" means literally "use the indexing (__getitem__) operator, and pass to it an empty tuple (()). So the last line should read:

>>> f['path/to/scalar'][()]
5

If you feel this is a bit of a strange, exotic notation, I can only empathize.

But it makes some sense - the numpy.shape of scalar values is in fact ().


问:
ArgumentException was unhandled by user code : The argument 'name' cannot be null, empty or contain only white space
I want to show my table content using entity. Before that i updated the model from database. Here is my code

```<code>Dim b As New myEntities
Dim lld1 = b.LLD1_Header.ToList()
</code>```

The error occur while i'm on Dim lld1 = b.LLD1_Header.ToList() ans it says "The argument 'name' cannot be null, empty or contain only white space."

My connection string in .config file :

```<code><add name="myEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=10.65.69.103;initial catalog=ANZLLD;user id=llduser;password=P@ssw0rd1;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

And here is my stacktrace :

```<code>    at System.Data.Entity.Utilities.Check.NotEmpty(String value, String parameterName)
   at System.Data.Entity.Core.Metadata.Edm.EdmProperty..ctor(String name, TypeUsage typeUsage)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToProperty(StructuredProperty somProperty, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntityType(SchemaEntityType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.LoadSchemaElement(SchemaType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntitySet(EntityContainerEntitySet set, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntityContainer(EntityContainer element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.LoadSchemaElement(SchemaType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertSchema(Schema somSchema, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertSchema(IList`1 somSchemas, DbProviderManifest providerManifest, ItemCollection itemCollection)
   at System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.LoadItems(DbProviderManifest manifest, IList`1 somSchemas, ItemCollection itemCollection)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, IDbDependencyResolver resolver, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerInvariantName, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__4()
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadAndCheckItemCollection[T](Func`1 itemCollectionLoader)
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Lazy`1.get_Value()
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace, Boolean required)
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace)
   at System.Data.Entity.Core.Objects.ObjectContext.InitializeMappingViewCacheFactory(DbContext owner)
   at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory)
   at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at LLD_LLD_1_LLD1_Header.StoreView_ReadData(Object sender, StoreReadDataEventArgs e) in C:\Temp\Felix Nitip\v3 180319\Source Code\Web\lld\lld 1\LLD1_Header.aspx.vb:line 405
   at Ext.Net.SyncStoreBase.RaiseAjaxPostBackEvent(String eventArgument)
</code>```

Anyway what should i do to solve this? I already delete and delete the model multiple times and still get this error. Your answer will be appreciated. Thanks

答: Check if there are any [Table] or [Table("")] Dto property attributes in your project.</p>

Body:
I want to show my table content using entity. Before that i updated the model from database. Here is my code

Dim b As New myEntities
Dim lld1 = b.LLD1_Header.ToList()

The error occur while i'm on Dim lld1 = b.LLD1_Header.ToList() ans it says "The argument 'name' cannot be null, empty or contain only white space."

My connection string in .config file :

<add name="myEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=10.65.69.103;initial catalog=ANZLLD;user id=llduser;password=P@ssw0rd1;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

And here is my stacktrace :

    at System.Data.Entity.Utilities.Check.NotEmpty(String value, String parameterName)
   at System.Data.Entity.Core.Metadata.Edm.EdmProperty..ctor(String name, TypeUsage typeUsage)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToProperty(StructuredProperty somProperty, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntityType(SchemaEntityType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.LoadSchemaElement(SchemaType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntitySet(EntityContainerEntitySet set, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertToEntityContainer(EntityContainer element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.LoadSchemaElement(SchemaType element, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertSchema(Schema somSchema, DbProviderManifest providerManifest, ConversionCache convertedItemCache, Dictionary`2 newGlobalItems)
   at System.Data.Entity.Core.Metadata.Edm.Converter.ConvertSchema(IList`1 somSchemas, DbProviderManifest providerManifest, ItemCollection itemCollection)
   at System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.LoadItems(DbProviderManifest manifest, IList`1 somSchemas, ItemCollection itemCollection)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, IDbDependencyResolver resolver, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerInvariantName, String& providerManifestToken, Memoizer`2& cachedCTypeFunction)
   at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths)
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__4()
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadAndCheckItemCollection[T](Func`1 itemCollectionLoader)
   at System.Lazy`1.CreateValue()
--- End of stack trace from previous location where exception was thrown ---
   at System.Lazy`1.get_Value()
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace, Boolean required)
   at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace)
   at System.Data.Entity.Core.Objects.ObjectContext.InitializeMappingViewCacheFactory(DbContext owner)
   at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory)
   at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at LLD_LLD_1_LLD1_Header.StoreView_ReadData(Object sender, StoreReadDataEventArgs e) in C:\Temp\Felix Nitip\v3 180319\Source Code\Web\lld\lld 1\LLD1_Header.aspx.vb:line 405
   at Ext.Net.SyncStoreBase.RaiseAjaxPostBackEvent(String eventArgument)

Anyway what should i do to solve this? I already delete and delete the model multiple times and still get this error. Your answer will be appreciated. Thanks


问:
How can I share files at the Visual Studio solution level that are in different Git repos in a micro services architecture
We have a Micro-services architecture and each service is located in its own Git repo. All services are .Net Core services, and we are using Visual Studio 2017 (soon we'll start using 2019).
We want to share common files that need to be placed at the solution level like:

.editorconfig

To distribute common Visual Studio settings

*.ruleset

Analyzer ruleset settings

.dotsettings

ReSharper settings

roslynator.config

Roslynator analyzer settings

stylecop.json

Stylecop analyzer settings

Some of these files require more settings at the project level, for those we are using NuGet and props files to update the project.
But other files we just want a way to distribute them across repos at the solution level. With the ability to update them easily so if we want to update any rule at the company level, we can easily re-distribute the change across all micro-services.

Unfortunately, NuGet ability to consume/create solution-level packages was deprecated.

We also looked at Git sub-modules, but they only work in a sub-folder and we actually want these files at the solution level.

How can we distribute these files in a way that they get copied to the right place (solution level)?

答:
The submodule option is interesting, except you would need to include in it an addition script file which would then copy/update those file at the solution level.

Or put symlinks (which do exist with Windows) at the solution level back to those submodule files.

Plus, you would need to update the README of those repository to mention that particular setup/update step, which would require for the user to run that submodule script in order to get a fully operational development environment.


问:
How to disable all div content
I was under the assumption that if I disabled a div, all content got disabled too.

However, the content is grayed but I can still interact with it.

Is there a way to do that? (disable a div and get all content disabled also)

答:
Wrap the div within the form and fieldset tags:

<form>
  <fieldset disabled>

your controls

  </fieldset>
</form>
```

OwnerDisplayName: Juan Manuel

ContentLicense: CC BY-SA 2.5

Title: How to disable all div content

LastEditorDisplayName: Im safe against SQL injection

Body:
Wrap the div within the form and fieldset tags:

<form>
  <fieldset disabled>
    <div>your controls</div>
  </fieldset>
</form>


问:
Calling wxSizer.Insert()  hides item
I'm trying to insert a panel into a wxBoxSizer before the last element in that sizer using the following code:

```<code>sizer = event.EventObject.Parent.GetSizer()

# Add new panel from xrc
res = xrc.XmlResource('add_panel.xrc')
panel = res.LoadPanel(self, 'panel')
sizer.Insert(len(sizer.Children) -1, panel)

sizer.Layout()
</code>```

But when I run it the new panel shows correctly but the button which was previously the last element in the table is nowhere to be seen.  On a couple of occasions I've seen the button partially obscured, so clearly it's still where it was before but hidden behind the new panel.  Question is, having called sizer.Layout() why is it still in its old position and what am I not doing that would stop it misbehaving?

答:
Your parenting is probably wrong. Some of the object's parents do not correspond to the actual structure and / or sizers. Try this sample:</p>

```<code>import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="New")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)
        self.buttons = []
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)
        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    def OnButton(self, e):
        button = wx.Button(self.panel, label=str(len(self.buttons)))
        self.buttons.append(button)
        self.sizer.Insert(len(self.sizer.Children) - 1, button)
        self.sizer.Layout()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()
</code>```

Title: Calling wxSizer.Insert()  hides item

Body:
I'm trying to insert a panel into a wxBoxSizer before the last element in that sizer using the following code:

sizer = event.EventObject.Parent.GetSizer()

# Add new panel from xrc
res = xrc.XmlResource('add_panel.xrc')
panel = res.LoadPanel(self, 'panel')
sizer.Insert(len(sizer.Children) -1, panel)

sizer.Layout()

But when I run it the new panel shows correctly but the button which was previously the last element in the table is nowhere to be seen.  On a couple of occasions I've seen the button partially obscured, so clearly it's still where it was before but hidden behind the new panel.  Question is, having called sizer.Layout() why is it still in its old position and what am I not doing that would stop it misbehaving?

Body:
Your parenting is probably wrong. Some of the object's parents do not correspond to the actual structure and / or sizers. Try this sample:

import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="New")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)
        self.buttons = []
        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)
        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    def OnButton(self, e):
        button = wx.Button(self.panel, label=str(len(self.buttons)))
        self.buttons.append(button)
        self.sizer.Insert(len(self.sizer.Children) - 1, button)
        self.sizer.Layout()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()


问:
I have installed the package from github but when importing module name not found
I'm trying to use this github repo!

but as soon as I import the package: from pykernels.basic import RBF
the following error is displayed:

```<code>ModuleNotFoundError: No module named 'basic'
</code>```

I have double checked everything given my understanding of python, packages and how anaconda works but I don't know very much. The site-packages are in the path, the evn has the package and the init seems to be alright. I am really lost, if someone could tell me what I'm doing wrong or what else might be done to resolve this? Thank you!

for installation:

```<code>pip install git+https://github.com/gmum/pykernels#egg=pykernels
</code>```

答:
If you have installed both anaconda and original python, you will have two pip installed in your computer. The original python will have it's pip in \Python37\Scripts, and anaconda will have it's in \Users\admin\Anaconda3\Scripts. Your problem is that you used pip that is in \Python37\Scripts, the original pip. The original pip will install into the original python site-packages, not Anaconda's site-packages.

The solution is to make sure you're using Anaconda's pip when installing packages for use with Anaconda.

Body:
I'm trying to use this github repo!

but as soon as I import the package: from pykernels.basic import RBF
the following error is displayed:

ModuleNotFoundError: No module named 'basic'

I have double checked everything given my understanding of python, packages and how anaconda works but I don't know very much. The site-packages are in the path, the evn has the package and the init seems to be alright. I am really lost, if someone could tell me what I'm doing wrong or what else might be done to resolve this? Thank you!

for installation:

pip install git+https://github.com/gmum/pykernels#egg=pykernels