问:
Add reference to .dll asp.net
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

```<code>[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]
</code>```

What am i missing, why do i get this error?

答: Have you added the DLL under references in your project so it will be included in the build?</p>

Title: Add reference to .dll asp.net

Body:
I have a simple question about adding references to a .NET project. I'm adding reCAPTCHA to a website and i have downloaded the dll.

After setting the reference to the dll i build and run the project and gets this error:

[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
   System.Reflection.Module._GetTypesInternal(StackCrawlMark& stackMark) +0
   System.Reflection.Assembly.GetTypes() +96
   StarSuite.Core.Settings.GetSingletonInstancesOfBaseType(Type baseType, String staticMethodName, Type returnType) +149

[ApplicationException: Unable to load types from 'Recaptcha, Version=1.0.5.0, Culture=neutral, PublicKeyToken=9afc4d65b28c38c2'. LoaderExceptions: [FileNotFoundException: Could not load file or assembly 'System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
]

What am i missing, why do i get this error?


来源: stackexchange

问:
Allow user to access only his/her dashboard
I have four different layouts.

HomeLayout - Homepage

AdminLayout

UserLayout

AgentLayout

AdminLayout is the parent for admin related pages and UserLayout for user
related and so on. I have used Higher Order Component for checking if the
user is unauthenticated, redirect them to homepage. There is another condition too. That is if the user is authenticated but if the role of user is not admin and the user tries to access AdminDashboard, he/she should be redirected to the Home page and similiarly same with others. But Agent can access UserDashboard.

The role I get is in the form

```<code>user_role = ['superadmin'] or ['enduser'] or ['agent'] or
['enduser', 'agent'].
</code>```

One should not access other dashboard except agent can access agent dashboard and user dashboard too. For unauthenticated user I could redirect to homepage when accessing dashboard without loggin in

The code for redirecting to unauthenticated user is working and i have done the following way

```<code>const Redirection = prop => WrappedComponent => {
  return class Redirection extends React.PureComponent {
    render() {
      const user_instance = JSON.parse(localStorage.getItem("user"));
      if (!user_instance) {
        return <Redirect to="/" />;
      } else {
        return <WrappedComponent {...this.props} />;
      }
    }
  };
};

export default props => WrappedComponent =>
  connect(null, mapDispatchToProps)(Redirection(props)(WrappedComponent));
</code>```

AdminLayout

```<code>class AdminLayout extends React.Component {
  render() {
    return (
      <div>
        {this.props.children}
      </div>
    );
  }
}

export default Redirection()(AdminLayout);
</code>```

The user_role I get from localStorage is as JSON.parse(localStorage.getItem("user"))['userInfo]['user_role']

答:
you can do this using lodash intersection. Here is the link for it

https://lodash.com/docs/4.17.4#intersection

In your case, the check will be following

```<code>if (
        user_instance &&
        intersection(prop, user_instance["userInfo"]["user_role"])
          .length > 0
      ) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <Redirect to="/" />;
      }
</code>```

you can glue the following snippet.Also don't forgot to check lodash documentation as it can be very helpful for you down the line

ContentLicense: CC BY-SA 3.0

Body:
I have four different layouts.

HomeLayout - Homepage

AdminLayout

UserLayout

AgentLayout

AdminLayout is the parent for admin related pages and UserLayout for user
related and so on. I have used Higher Order Component for checking if the
user is unauthenticated, redirect them to homepage. There is another condition too. That is if the user is authenticated but if the role of user is not admin and the user tries to access AdminDashboard, he/she should be redirected to the Home page and similiarly same with others. But Agent can access UserDashboard.

The role I get is in the form

user_role = ['superadmin'] or ['enduser'] or ['agent'] or
['enduser', 'agent'].

One should not access other dashboard except agent can access agent dashboard and user dashboard too. For unauthenticated user I could redirect to homepage when accessing dashboard without loggin in

The code for redirecting to unauthenticated user is working and i have done the following way

const Redirection = prop => WrappedComponent => {
  return class Redirection extends React.PureComponent {
    render() {
      const user_instance = JSON.parse(localStorage.getItem("user"));
      if (!user_instance) {
        return <Redirect to="/" />;
      } else {
        return <WrappedComponent {...this.props} />;
      }
    }
  };
};

export default props => WrappedComponent =>
  connect(null, mapDispatchToProps)(Redirection(props)(WrappedComponent));

AdminLayout

class AdminLayout extends React.Component {
  render() {
    return (

        {this.props.children}

    );
  }
}

export default Redirection()(AdminLayout);

The user_role I get from localStorage is as JSON.parse(localStorage.getItem("user"))['userInfo]['user_role']

Body:
you can do this using lodash intersection. Here is the link for it

https://lodash.com/docs/4.17.4#intersection

In your case, the check will be following

if (
        user_instance &&
        intersection(prop, user_instance["userInfo"]["user_role"])
          .length > 0
      ) {
        return <WrappedComponent {...this.props} />;
      } else {
        return <Redirect to="/" />;
      }

you can glue the following snippet.Also don't forgot to check lodash documentation as it can be very helpful for you down the line


问:
HTML svg animation issues
I am trying to create simple animation with SVG and HTML only.
The goal is:

Take the first picture and move it from position (80,100) to (100,100)

Take the second picture and move it from position (80,100) to (95,100)

Take the third picture and move it from position (80,100) to (90,100)

Hide all three pictures

Repeat steps 1-4

I have something like this :

```<code><svg width="500" height="500">
   <image xlink:href="pic.png" height="30" width="30"/>
    <path id="path1" d="M 80 100 l 20 0" />
    <animateMotion dur="1" repeatCount="indefinite" rotate="0" >
       <mpath xlink:href="#path1"/>
    </animateMotion>
</svg>
</code>```

In this case, first picture moved from (80,100) to (100,100) but as soon as it reached the final position it started moving again from (80,100).

How can I make every following picture 'wait' for all the rest pics and then start moving first picture from (80,100) again?

答:
I'm not sure what step 4 is about since it means step 5 will move invisible items but you make animations wait by setting their begin to the previous animations end event like so...

<svg width="500" height="500">
    <defs>
        <path id="path1" d="M 0 0 l 20 0"/>
    </defs>
    <rect width="50" height="50" fill="blue">
      <animateMotion id="motion1" begin="0s;motion2.end" dur="1" rotate="0" fill="freeze">
         <mpath xlink:href="#path1"/>
      </animateMotion>
    </rect>
    <rect y="80" width="50" height="50" fill="blue">
      <animateMotion id="motion2" begin="motion1.end" dur="1" rotate="0" fill="freeze">
         <mpath xlink:href="#path1"/>
      </animateMotion>
    </rect>
</svg>```

Title: HTML svg animation issues

Body:
I am trying to create simple animation with SVG and HTML only.
The goal is:

Take the first picture and move it from position (80,100) to (100,100)

Take the second picture and move it from position (80,100) to (95,100)

Take the third picture and move it from position (80,100) to (90,100)

Hide all three pictures

Repeat steps 1-4

I have something like this :

<svg width="500" height="500">
   <image xlink:href="pic.png" height="30" width="30"/>
    <path id="path1" d="M 80 100 l 20 0" />
    <animateMotion dur="1" repeatCount="indefinite" rotate="0" >
       <mpath xlink:href="#path1"/>
    </animateMotion>
</svg>

In this case, first picture moved from (80,100) to (100,100) but as soon as it reached the final position it started moving again from (80,100).

How can I make every following picture 'wait' for all the rest pics and then start moving first picture from (80,100) again?


问:
Core data custom migration
My old core data model has an NSDate field, which I would like to change to a NSNumber. I read the Apple documentation and several similar questions on SO and other blogs (see references at end of question)

But no matter what I do, I keep getting the same error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Mismatch between mapping and source/destination models'

I only have 2 versions of the model, and I have verified time and again that the source and destination models are correct.

I even discarded all my changes and recreated a new model, mappings and entities (NSManagedObject subclasses). I've been stuck on this for almost 2 days now, and have no clue anymore as to what I'm doing. Any pointers on what I'm doing wrong will be greatly appreciated.

```<code>- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Old.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSString *sourceStoreType = NSSQLiteStoreType;
    NSURL *sourceStoreURL = storeURL;

    NSURL *destinationStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"New.sqlite"];
    NSString *destinationStoreType = NSSQLiteStoreType;
    NSDictionary *destinationStoreOptions = nil;

    NSDictionary *sourceMetadata =
    [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:sourceStoreType
                                                               URL:sourceStoreURL
                                                             error:&error];

    if (sourceMetadata == nil) {
        NSLog(@"source metadata is nil");
    }

    NSManagedObjectModel *destinationModel = [_persistentStoreCoordinator managedObjectModel];
    BOOL pscCompatibile = [destinationModel
                           isConfiguration:nil
                           compatibleWithStoreMetadata:sourceMetadata];

    if (pscCompatibile) {
        // no need to migrate
        NSLog(@"is compatible");
    } else {
        NSLog(@"is not compatible");

        NSManagedObjectModel *sourceModel =
        [NSManagedObjectModel mergedModelFromBundles:nil
                                    forStoreMetadata:sourceMetadata];

        if (sourceModel != nil) {
            NSLog(@"source model is not nil");

            NSMigrationManager *migrationManager =
            [[NSMigrationManager alloc] initWithSourceModel:sourceModel
                                           destinationModel:destinationModel];

            NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"MyMigrationMapping" withExtension:@"cdm"];
            NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:fileURL];

            NSArray *newEntityMappings = [NSArray arrayWithArray:mappingModel.entityMappings];
            for (NSEntityMapping *entityMapping in newEntityMappings) {
                entityMapping.entityMigrationPolicyClassName = NSStringFromClass([ConvertDateToNumberTransformationPolicy class]);
            }
            mappingModel.entityMappings = newEntityMappings;

            BOOL ok = [migrationManager migrateStoreFromURL:sourceStoreURL
                                                       type:sourceStoreType
                                                    options:nil
                                           withMappingModel:mappingModel
                                           toDestinationURL:destinationStoreURL
                                            destinationType:destinationStoreType
                                         destinationOptions:nil
                                                      error:&error];

            if (ok) {
                storeURL = destinationStoreURL;
            }
        } else {
            NSLog(@"e nil source model");
        }
    }

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}
</code>```

My custom NSEntityMigration class:

```<code>
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError **)error
{
    // Create a new object for the model context
    NSManagedObject *newObject =
    [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName]
                                  inManagedObjectContext:[manager destinationContext]];

    NSArray *arrayOfKeys = @[@"startDate", @"endDate", @"creationTime", @"timeStamp"];

    for (NSString *key in arrayOfKeys) {
        // do our transfer of NSDate to NSNumber
        NSDate *date = [sInstance valueForKey:key];
        NSLog(@"Key: %@, value: %@", key, [date description]);

        // set the value for our new object
        [newObject setValue:[NSNumber numberWithDouble:[date timeIntervalSince1970]] forKey:key];
    }

    // do the coupling of old and new
    [manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];

    return YES;
}
</code>```

Some references:

Example or explanation of Core Data Migration with multiple passes?

Core Data - Default Migration ( Manual )

http://www.preenandprune.com/cocoamondo/?p=468

http://www.timisted.net/blog/archive/core-data-migration/

答:
Everything you are doing is way more complicated than it has to be.  You can do all of this without migrating you database at all.  You can add another property to your subclass that implements it:

```<code>///in your .h
@property(nonatomic, copy) NSNumber* startDateNumber
/// in you .m
-(NSNumber*) startDateNumber{
    if (self.startDate) {
        return @(self.startDate.timeIntervalSince1970);
    }
    return nil;
}
-(void)setStartDateNumber:(NSNumber*)startDateNumber{
    if(startDateNumber){
        self.startDate =[NSDate dateWithTimeIntervalSince1970:startDateNumber.doubleValue];
    }else{
        self.startDate = nil;
    }
}
</code>```

It is a little annoying to have duplicate properties (startDate and startDateNumber) but it is so much simpler and doesn't have any of the migration issues.

Title: Core data custom migration

Body:
My old core data model has an NSDate field, which I would like to change to a NSNumber. I read the Apple documentation and several similar questions on SO and other blogs (see references at end of question)

But no matter what I do, I keep getting the same error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Mismatch between mapping and source/destination models'

I only have 2 versions of the model, and I have verified time and again that the source and destination models are correct.

I even discarded all my changes and recreated a new model, mappings and entities (NSManagedObject subclasses). I've been stuck on this for almost 2 days now, and have no clue anymore as to what I'm doing. Any pointers on what I'm doing wrong will be greatly appreciated.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Old.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    NSString *sourceStoreType = NSSQLiteStoreType;
    NSURL *sourceStoreURL = storeURL;

    NSURL *destinationStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"New.sqlite"];
    NSString *destinationStoreType = NSSQLiteStoreType;
    NSDictionary *destinationStoreOptions = nil;

    NSDictionary *sourceMetadata =
    [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:sourceStoreType
                                                               URL:sourceStoreURL
                                                             error:&error];

    if (sourceMetadata == nil) {
        NSLog(@"source metadata is nil");
    }

    NSManagedObjectModel *destinationModel = [_persistentStoreCoordinator managedObjectModel];
    BOOL pscCompatibile = [destinationModel
                           isConfiguration:nil
                           compatibleWithStoreMetadata:sourceMetadata];

    if (pscCompatibile) {
        // no need to migrate
        NSLog(@"is compatible");
    } else {
        NSLog(@"is not compatible");

        NSManagedObjectModel *sourceModel =
        [NSManagedObjectModel mergedModelFromBundles:nil
                                    forStoreMetadata:sourceMetadata];

        if (sourceModel != nil) {
            NSLog(@"source model is not nil");

            NSMigrationManager *migrationManager =
            [[NSMigrationManager alloc] initWithSourceModel:sourceModel
                                           destinationModel:destinationModel];

            NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"MyMigrationMapping" withExtension:@"cdm"];
            NSMappingModel *mappingModel = [[NSMappingModel alloc] initWithContentsOfURL:fileURL];

            NSArray *newEntityMappings = [NSArray arrayWithArray:mappingModel.entityMappings];
            for (NSEntityMapping *entityMapping in newEntityMappings) {
                entityMapping.entityMigrationPolicyClassName = NSStringFromClass([ConvertDateToNumberTransformationPolicy class]);
            }
            mappingModel.entityMappings = newEntityMappings;

            BOOL ok = [migrationManager migrateStoreFromURL:sourceStoreURL
                                                       type:sourceStoreType
                                                    options:nil
                                           withMappingModel:mappingModel
                                           toDestinationURL:destinationStoreURL
                                            destinationType:destinationStoreType
                                         destinationOptions:nil
                                                      error:&error];

            if (ok) {
                storeURL = destinationStoreURL;
            }
        } else {
            NSLog(@"e nil source model");
        }
    }

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

My custom NSEntityMigration class:

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance
                                      entityMapping:(NSEntityMapping *)mapping
                                            manager:(NSMigrationManager *)manager
                                              error:(NSError **)error
{
    // Create a new object for the model context
    NSManagedObject *newObject =
    [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName]
                                  inManagedObjectContext:[manager destinationContext]];

    NSArray *arrayOfKeys = @[@"startDate", @"endDate", @"creationTime", @"timeStamp"];

    for (NSString *key in arrayOfKeys) {
        // do our transfer of NSDate to NSNumber
        NSDate *date = [sInstance valueForKey:key];
        NSLog(@"Key: %@, value: %@", key, [date description]);

        // set the value for our new object
        [newObject setValue:[NSNumber numberWithDouble:[date timeIntervalSince1970]] forKey:key];
    }

    // do the coupling of old and new
    [manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];

    return YES;
}

Some references:

Example or explanation of Core Data Migration with multiple passes?

Core Data - Default Migration ( Manual )

http://www.preenandprune.com/cocoamondo/?p=468

http://www.timisted.net/blog/archive/core-data-migration/

Body:
Everything you are doing is way more complicated than it has to be.  You can do all of this without migrating you database at all.  You can add another property to your subclass that implements it:

///in your .h
@property(nonatomic, copy) NSNumber* startDateNumber
/// in you .m
-(NSNumber*) startDateNumber{
    if (self.startDate) {
        return @(self.startDate.timeIntervalSince1970);
    }
    return nil;
}
-(void)setStartDateNumber:(NSNumber*)startDateNumber{
    if(startDateNumber){
        self.startDate =[NSDate dateWithTimeIntervalSince1970:startDateNumber.doubleValue];
    }else{
        self.startDate = nil;
    }
}

It is a little annoying to have duplicate properties (startDate and startDateNumber) but it is so much simpler and doesn't have any of the migration issues.


问:
How to get Year and Month of a DATE using Oracle
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

```<code>SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017
</code>```

however it gives ORA-30076 Error

答:
Have you tried EXTRACT()?

```<code>SELECT EXTRACT(YEAR FROM DATE '2017-12-01') FROM DUAL;
2017

SELECT EXTRACT(MONTH FROM DATE '2017-12-01') FROM DUAL;
12
</code>```

I tried this in sql fiddle with 11g and it works in WHERE clause too.

http://sqlfiddle.com/#!4/fb2b09/2

Body:
How can I get the year and month of a date in the where clause using Oracle.

I used to be working with SQL server and it was as simple as YEAR(FIELDNAME) and MONTH(FIELDNAME).

I have tried the following:

SELECT *
FROM myschema.mytablename
WHERE   EXTRACT(YEAR FROM  myDATE)  = 2017

however it gives ORA-30076 Error

Body:
Have you tried EXTRACT()?

SELECT EXTRACT(YEAR FROM DATE '2017-12-01') FROM DUAL;
2017

SELECT EXTRACT(MONTH FROM DATE '2017-12-01') FROM DUAL;
12

I tried this in sql fiddle with 11g and it works in WHERE clause too.

http://sqlfiddle.com/#!4/fb2b09/2


问:
Dagger 2 static provider methods in kotlin
With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:

```<code>@Provides
static A providesA() {
  return A();
}
</code>```

I was wondering how does one go about doing this in kotlin? I've tried

```<code>@Module
class AModule {
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }
}
</code>```

But I get the error message:

```<code>@Provides methods can only be present within a @Module or @ProducerModule
</code>```

I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?

Thanks!

答:
Although I think zsmb13's solution is better, I found another solution which works

```<code>@Module
class AModule {
  @Module
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }

  // add other non-static provides here
}
</code>```

However, note that there will be two generated classes: AModule_ProvidesAFactory and AModule_Companion_ProvidesAFactory rather than the one AModule_ProvidesAFactory class for the case with an object instead of a class with a companion object

Body:
With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:

@Provides
static A providesA() {
  return A();
}

I was wondering how does one go about doing this in kotlin? I've tried

@Module
class AModule {
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }
}

But I get the error message:

@Provides methods can only be present within a @Module or @ProducerModule

I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?

Thanks!

Body:
Although I think zsmb13's solution is better, I found another solution which works

@Module
class AModule {
  @Module
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }

  // add other non-static provides here
}

However, note that there will be two generated classes: AModule_ProvidesAFactory and AModule_Companion_ProvidesAFactory rather than the one AModule_ProvidesAFactory class for the case with an object instead of a class with a companion object


问:
Chaining Maybe in rxjava for "else" or "coallesce"
I'm fairly new to rxjava, so apologies if this is a silly question.  I have two Maybes (call them A and B) that I want to compose in such a way that I get a 3rd Maybe.

If A succeeds, I want my composite to succeed with that same value.  If A errors, I want my composite to error with that same throwable.  If A completes without emitting a value, I want to then delegate to B.

Is there an easy way to achieve this?

答:
If you don't care about specific errors in A, you can use the following:</p>

```<code>A
.onErrorResumeNext(Observable.empty())
.switchIfEmpty(B)
</code>```

Body:
If you don't care about specific errors in A, you can use the following:

A
.onErrorResumeNext(Observable.empty())
.switchIfEmpty(B)


问:
RegEx - reusing subexpressions
Say I have a regex matching a hexadecimal 32 bit number:

```<code>([0-9a-fA-F]{1,8})
</code>```

When I construct a regex where I need to match this multiple times, e.g.

```<code>(?<from>[0-9a-fA-F]{1,8})\s*:\s*(?<to>[0-9a-fA-F]{1,8})
</code>```

Do I have to repeat the subexpression definition every time, or is there a way to "name and reuse" it?

I'd imagine something like (warning, invented syntax!)

```<code>(?<from>{hexnum=[0-9a-fA-F]{1,8}})\s*:\s*(?<to>{=hexnum})
</code>```

where hexnum= would define the subexpression "hexnum", and {=hexnum} would reuse it.

Since I already learnt it matters: I'm using .NET's System.Text.RegularExpressions.Regex, but a general answer would be interesting, too.

答:
.NET regex does not support pattern recursion, and if you can use (?<from>(?<hex>[0-9a-fA-F]{1,8}))\s*:\s*(?<to>(\g<hex>)) in Ruby and PHP/PCRE (where hex is a "technical" named capturing group whose name should not occur in the main pattern), in .NET, you may just define the block(s) as separate variables, and then use them to build a dynamic pattern.

Starting with C#6, you may use an interpolated string literal that looks very much like a PCRE/Onigmo subpattern recursion, but is actually cleaner and has no potential bottleneck when the group is named identically to the "technical" capturing group:

C# demo:

```<code>using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var block = "[0-9a-fA-F]{1,8}";
        var pattern = $@"(?<from>{block})\s*:\s*(?<to>{block})";
        Console.WriteLine(Regex.IsMatch("12345678  :87654321", pattern));
    }
}
</code>```

The $@"..."  is a verbatim interpolated string literal, where escape sequences are treated as combinations of a literal backslash and a char after it. Make sure to define literal { with {{ and } with }} (e.g. $@"(?:{block}){{5}}" to repeat a block 5 times).

For older C# versions, use string.Format:

```<code>var pattern = string.Format(@"(?<from>{0})\s*:\s*(?<to>{0})", block);
</code>```

as is suggested in Mattias's answer.

Title: RegEx - reusing subexpressions

Body:
Say I have a regex matching a hexadecimal 32 bit number:

([0-9a-fA-F]{1,8})

When I construct a regex where I need to match this multiple times, e.g.

(?<from>[0-9a-fA-F]{1,8})\s*:\s*(?<to>[0-9a-fA-F]{1,8})

Do I have to repeat the subexpression definition every time, or is there a way to "name and reuse" it?

I'd imagine something like (warning, invented syntax!)

(?<from>{hexnum=[0-9a-fA-F]{1,8}})\s*:\s*(?<to>{=hexnum})

where hexnum= would define the subexpression "hexnum", and {=hexnum} would reuse it.

Since I already learnt it matters: I'm using .NET's System.Text.RegularExpressions.Regex, but a general answer would be interesting, too.

Body:
.NET regex does not support pattern recursion, and if you can use (?<from>(?<hex>[0-9a-fA-F]{1,8}))\s*:\s*(?<to>(\g<hex>)) in Ruby and PHP/PCRE (where hex is a "technical" named capturing group whose name should not occur in the main pattern), in .NET, you may just define the block(s) as separate variables, and then use them to build a dynamic pattern.

Starting with C#6, you may use an interpolated string literal that looks very much like a PCRE/Onigmo subpattern recursion, but is actually cleaner and has no potential bottleneck when the group is named identically to the "technical" capturing group:

C# demo:

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var block = "[0-9a-fA-F]{1,8}";
        var pattern = $@"(?<from>{block})\s*:\s*(?<to>{block})";
        Console.WriteLine(Regex.IsMatch("12345678  :87654321", pattern));
    }
}

The $@"..."  is a verbatim interpolated string literal, where escape sequences are treated as combinations of a literal backslash and a char after it. Make sure to define literal { with {{ and } with }} (e.g. $@"(?:{block}){{5}}" to repeat a block 5 times).

For older C# versions, use string.Format:

var pattern = string.Format(@"(?<from>{0})\s*:\s*(?<to>{0})", block);

as is suggested in Mattias's answer.


问:
Unable to change the value of a property of an Object - JavaScript
I have a module in my code and I'm unable to change the value of a property of an Object. I have a more detailed explanation in code, see below:

```<code>var network = (function(){ // Created a closure.
  var ajax = {
    response: 0, // I set the initial value of response to 0
    parse: function(x){
             var y = JSON.parse(x);
             ajax.response = y; // This is where things don't seem to work. Value of response is still 0.
           }
    // Some other code.

    } // End of ajax object.

    return { // I return an Object .
     invoke: function(x){ ajax.parse(x); },
     reply: ajax.response
     }

})();

network.invoke(valid_argument); // I invoke the function and pass a valid json string received from a server via ajax.
console.log(network.reply); // I get 0, which is the initial value. Why?
</code>```

As mentioned in the Code this issue feels weird, any help is appreciated.

答:
@Teja: Felix King has show you the technical aspect and it's true. I want to give my 2 cents about code quality.
Javascript allow we to code in a very flexible way, and it really look confusing, Javascript code is very hard to read. So does you code snippet, look over complicated. Avoid too much use of function.

@Felix King: I think pass by value or pass by reference is not relevant here. These concepts are applied for the case the parameters passed to a function, not in an assignment operation.

Body:
I have a module in my code and I'm unable to change the value of a property of an Object. I have a more detailed explanation in code, see below:

var network = (function(){ // Created a closure.
  var ajax = {
    response: 0, // I set the initial value of response to 0
    parse: function(x){
             var y = JSON.parse(x);
             ajax.response = y; // This is where things don't seem to work. Value of response is still 0.
           }
    // Some other code.

    } // End of ajax object.

    return { // I return an Object .
     invoke: function(x){ ajax.parse(x); },
     reply: ajax.response
     }

})();

network.invoke(valid_argument); // I invoke the function and pass a valid json string received from a server via ajax.
console.log(network.reply); // I get 0, which is the initial value. Why?

As mentioned in the Code this issue feels weird, any help is appreciated.


问:
How to get text from unmanaged application to a c# application?
I have a 3rd party application, which creates several windows of which each has a textbox with text I want. I then want to use that information within my application, so I just need to obtain that information (possible trigger some commands back to it later on by pressing buttons)

The 3rd party application is un-managed C++.
My application is C# (.NET 4.0).

I have seen that you can do 'hooks' into other application but I'll be honest I am completely lost of which route to take and how to go about it.

Some advice would be great.

答: I wonder if all this talk of managed code and unmanaged code and Interop isn't a red herring.  Are you able to interface with this other app at all or are you just going to have to use FindWindow to find that other app and then enumerate it's child windows till you find the text boxes you're after, then just call GetWindowText ?</p>

ContentLicense: CC BY-SA 2.5


问:
Error while trying show crystal report on ASP.NET Page
I got this error when i try to show it

An error has occurred while attempting to load the Crystal Reports runtime. Either the Crystal Reports registry key permissions are insufficient, or the Crystal Reports runtime is not installed correctly. Please install the appropriate Crystal Reports redistributable (CRRedist*.msi) containing the correct version of the Crystal Reports runtime (x86, x64, or Itanium) required.  Please go to http://www.businessobjects.com/support for more information.

This is my first web application with ASP.NET. And i have a big problem to show asp.net. When i tried to send Crystal - Report via mail i get this error.

An error has occurred while attempting to load the Crystal Reports runtime. Either the Crystal Reports registry key permissions are insufficient, or the Crystal Reports runtime is not installed correctly. Please install the appropriate Crystal Reports redistributable (CRRedist*.msi) containing the correct version of the Crystal Reports runtime (x86, x64, or Itanium) required.  Please go to http://www.businessobjects.com/support for more information.

is there any way to solve this problem ? Thanks .

答:
Application-level setting:

Go to IIS Click on “Application Pools”

Select the application you want to modify (e.g.: SuperApp)

Right click on that application

Left click on Advanced Settings

Set Enable 32-Bit Applications to “True”


问:
Interpolating missing contour lines between existing contour lines
Contour lines (aka isolines) are curves that trace constant values across a 2D scalar field. For example, in a geographical map you might have contour lines to illustrate the elevation of the terrain by showing where the elevation is constant. In this case, let's store contour lines as lists of points on the map.

Suppose you have map that has several contour lines at known elevations, and otherwise you know nothing about the elevations of the map. What algorithm would you use to fill in additional contour lines to approximate the unknown elevations of the map, assuming the landscape is continuous and doesn't do anything surprising?

It is easy to find advise about interpolating the elevation of an individual point using contour lines. There are also algorithms like Marching Squares for turning point elevations into contour lines, but none of these exactly capture this use case. We don't need the elevation of any particular point; we just want the contour lines. Certainly we could solve this problem by filling an array with estimated elevations and then using Marching Squares to estimate the contour lines based on the array, but the two steps of that process seem unnecessarily expensive and likely to introduce artifacts. Surely there is a better way.

答:
IMO, about all methods will amount to somehow reconstructing the 3D surface by interpolation, even if implicitly.

You may try by flattening the curves (turning them to polylines) and triangulating the resulting polygons thay they will define. (There will be a step of closing the curves that end on the border of the domain.)

By intersection of the triangles with a new level (unsing linear interpolation along the sides), you will obtain new polylines corresponding to new isocurves. Notice that the intersections with the old levels recreates the old polylines, which is sound.

You may apply a post-smoothing to the curves, but you will have no guarantee to retrieve the original old curves and cannot prevent close surves to cross each other.

Beware that increasing the density of points along the curves will give you a false feeling of accuracy, as the error due to the spacing of the isolines will remain (indeed the reconstructed surface will be cone-like, with one of the curvatures being null; the surface inside the bottommost and topmost lines will be flat).

Alternatively to using flat triangles, one may think of a scheme where you compute a gradient vector at every vertex (f.i. from a least square fit of a plane on the vertex and its neighbors), and use this information to generate a bivariate polynomial surface in the triangle. You must do this in such a way that the values along a side will coincide for the two triangles that share it. (Unfortunately, I have no formula to give you.)

The isolines are then obtained by a further subdivision of the triangle in smaller triangles, with a flat approximation.

Actually, this is not very different from getting sample points, (Delaunay) triangulating them and fitting picewise continuous patches to the triangles.

Whatever method you will use, be it 2D or 3D, it is useful to reason on what happens if you sweep the range of z values in a continous way. This thought experiment does reconstruct a 3D surface, which will possess continuity and smoothness properties.

A possible improvement over the crude "flat triangulation" model could be to extend every triangle side between to iso-polylines with sides leading to the next iso-polylines. This way, higher order interpolation (cubic) can be achieved, giving a smoother reconstruction.

Anyway, you can be sure that this will introduce discontinuities or other types of artifacts.


问:
Game show buzzer screens
I'm doing a training class right now and one of the games I plan on doing is a Jeopardy style of Q & A. The problem I'm trying to figure out is the buzzer. My idea is to use the projector as the question board I control. The trainees would go to an HTML page with nothing more than a single button. They would turn their monitors around to face me up front. As soon as I read the question they would click the button and it would change their screens the color red.

The button and background color change is easy enough, I got that. There are two problems I'm facing: 1) I need it so that they can't click the button until I'm done reading the question - this one isn't as important, I can just make up a rule. 2) Only the fastest person will have a red screen. To show me who clicked first. The others' buttons will be disabled.

I just have no idea how to even Google these two things. Like: "Disable button for other users"...? Or maybe, "only one click"...?

Any direction to search is appreciated. Eventually, I'd like to add other aspects to like the presenter could click an "incorrect button" then it would clear the screen and enable all the buttons again, for the answer steal.

答:
You can do it with modern WebSocket or applications interact via TCP. However, WebSocket may be overkill for the simple application with a few teams. I faced the same problem before and developed a simple solution with PHP using Flock to write into a shared file on disk. Only request from one team gets the chance to write into that file. Stick to not to use WebSocket, the web page on client site does some polling to receive the "restart" signal from the server for the new question/round. It can run in LAN, different team gets different site, i.e. http://[server-ip]/team1, http://[server-ip]/team2.
You can have control over the round: allow them to press button/ restart, start a new question in http://[server-ip]/admin.
Further improvement can be made in several ways to facilitate your needs (i.e. assign team name, register team, use database instead of a flock file). The code is available here : https://github.com/minhhn2910/buzzergameshow </p>

Title: Game show buzzer screens


问:
send AJAX json array mail with PHP mailer
I am trying to send a php form mailer with data array using Json and AJAX, but for some reason, the mail is sent without the data...
(I tested the jason string and validated it to make sure it contains data)

Here is the code I have:

json:

```<code> function submitFields() {
    form_elements = [];
    $('.dataField').each(function () {
        frm_name = $(this).attr('name');
        frm_qty = $(this).val();
        frm_price = $(this).data('price');
        current_frm_obj = {name:frm_name, qty:frm_qty, price:frm_price};
        form_elements.push(current_frm_obj);
    });

    $.ajax({
        type: "POST",
        url: "mailer.php",
        data: { result:JSON.stringify(form_elements) },
        success : function(response) {
            console.log(form_elements);
            alert(response);
        }
    });
}
</code>```

PHP mailer:

```<code>$data = $_POST["result"];
$decoded = json_decode($data);
$errors = '';
$myemail = 'office@studiodeshe.com';

$to = $myemail;
$email_subject = "Form info";
$email_body =
$decoded = json_decode($data);
foreach ($decoded as $curr_element) {
    $fieldName = $curr_element->name;
    $fieldQty = $curr_element->qty;
    $fieldPrice = $curr_element->price;

    if ( $fieldQty != 0 ) {
        $fieldName .': <br />' .  $fieldQty;
        if ($fieldPrice != 0) {
            'Qty: ' . $fieldQty . '<br />';
            'Price: ' . $fieldPrice . '<br />';
            'Total: ' . ($fieldPrice*$fieldQty) . '<br /><br />';
            }
    }
}

$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';

mail($to,$email_subject,$email_body,$headers);
header('Location: ty.html');
</code>```

I am guessing that there is some problem with the way I am trying to decode the data in the mailer but can't find a solution...

答:
OK I solved it. If anyone will need the solution in the future here it is:

The data from json should be parsed at the beginning, and saved into var, like this:

```<code>$data = $_POST["result"];
$decoded = json_decode($data);
$mailData = "";
foreach ($decoded as $curr_element) {
    $fieldName = $curr_element->name;
    $fieldQty = $curr_element->qty;
    $fieldPrice = $curr_element->price;
    if ( $fieldQty != 0 ) {
        if ($fieldPrice != 0) {
            $input = $fieldName .': <br />
            Qty: ' .$fieldQty. '<br />
            Price: ' . $fieldPrice . '<br />
            Total: ' . ($fieldPrice*$fieldQty) .
            '<br /><br />';
            $mailData .= $input;
            }
    }

}

$errors = '';
$myemail = 'studio@studiodeshe.com';//<-----Put Your email address here.

$to = $myemail;
$email_subject = "Configurator Lead";
$email_body = $mailData;

$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';

mail($to,$email_subject,$email_body,$headers);
</code>```

Body:
I am trying to send a php form mailer with data array using Json and AJAX, but for some reason, the mail is sent without the data...
(I tested the jason string and validated it to make sure it contains data)

Here is the code I have:

json:

 function submitFields() {
    form_elements = [];
    $('.dataField').each(function () {
        frm_name = $(this).attr('name');
        frm_qty = $(this).val();
        frm_price = $(this).data('price');
        current_frm_obj = {name:frm_name, qty:frm_qty, price:frm_price};
        form_elements.push(current_frm_obj);
    });

    $.ajax({
        type: "POST",
        url: "mailer.php",
        data: { result:JSON.stringify(form_elements) },
        success : function(response) {
            console.log(form_elements);
            alert(response);
        }
    });
}

PHP mailer:

$data = $_POST["result"];
$decoded = json_decode($data);
$errors = '';
$myemail = 'office@studiodeshe.com';

$to = $myemail;
$email_subject = "Form info";
$email_body =
$decoded = json_decode($data);
foreach ($decoded as $curr_element) {
    $fieldName = $curr_element->name;
    $fieldQty = $curr_element->qty;
    $fieldPrice = $curr_element->price;

    if ( $fieldQty != 0 ) {
        $fieldName .':
' .  $fieldQty;
        if ($fieldPrice != 0) {
            'Qty: ' . $fieldQty . '
';
            'Price: ' . $fieldPrice . '
';
            'Total: ' . ($fieldPrice*$fieldQty) . '

';
            }
    }
}

$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';

mail($to,$email_subject,$email_body,$headers);
header('Location: ty.html');

I am guessing that there is some problem with the way I am trying to decode the data in the mailer but can't find a solution...

Body:
OK I solved it. If anyone will need the solution in the future here it is:

The data from json should be parsed at the beginning, and saved into var, like this:

$data = $_POST["result"];
$decoded = json_decode($data);
$mailData = "";
foreach ($decoded as $curr_element) {
    $fieldName = $curr_element->name;
    $fieldQty = $curr_element->qty;
    $fieldPrice = $curr_element->price;
    if ( $fieldQty != 0 ) {
        if ($fieldPrice != 0) {
            $input = $fieldName .': <br />
            Qty: ' .$fieldQty. '<br />
            Price: ' . $fieldPrice . '<br />
            Total: ' . ($fieldPrice*$fieldQty) .
            '<br /><br />';
            $mailData .= $input;
            }
    }

}

$errors = '';
$myemail = 'studio@studiodeshe.com';//<-----Put Your email address here.

$to = $myemail;
$email_subject = "Configurator Lead";
$email_body = $mailData;

$headers = "From: studiodeshe <office@studiodeshe.com> \n";
$headers .= 'Content-type: text/html; charset=utf-8';

mail($to,$email_subject,$email_body,$headers);


问:
How to see if you're clicking the same element twice? Jquery
How can you detect if the user is clicking the same div?

I've tried this with no success:

```<code>    _oldthis = null;

    var _this = $(this);

    if(_oldthis == _this) {
        alert('You clicked this last');
    }

    _oldthis = _this;
</code>```

答:
```<code>var clickHandler;
$('a').click(function(){
    if(clickHandler) {
        clickHandler = alert('click twice');
    } else {
        clickHandler = alert('click once');
    }
});
</code>```

Body:
How can you detect if the user is clicking the same div?

I've tried this with no success:

    _oldthis = null;

    var _this = $(this);

    if(_oldthis == _this) {
        alert('You clicked this last');
    }

    _oldthis = _this;


问:
Add custom attributes of layout to children
I have layout

```<code><android.support.v7.widget.GridLayout
    android:id="@+id/grid_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/default_grid_height"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--I need add to this child attribute "app:layout_*"-->
    <Button
        android:text="1"
        app:layout_columnSpan="2"
        app:layout_columnWeight="2"
        app:layout_rowWeight="3"/>

</android.support.v7.widget.GridLayout>
</code>```

I need to programmatically add child to this layout container (support.v7.widget.GridLayout) with custom attributes supported by this layout. How i can do this?
Assume I can do something like that, but not found something method like tihs.

```<code>widget = CustomWidget(context)
widget.addParam("app:layout_rowWeight", 3) // how??
</code>```

答:
My suggestion is, we can make it very simple, Just create one method in your custom class for that,

If you are setting in XML you can call like this app:layout_rowWeight so that you can get in your Custom class in TypedArray.

But for Jave, you can create a separate method and you can achieve same.

Ex Check TextView Android source code, and search setTextColor method.

Body:
I have layout

<android.support.v7.widget.GridLayout
    android:id="@+id/grid_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/default_grid_height"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Button
        android:text="1"
        app:layout_columnSpan="2"
        app:layout_columnWeight="2"
        app:layout_rowWeight="3"/>

</android.support.v7.widget.GridLayout>

I need to programmatically add child to this layout container (support.v7.widget.GridLayout) with custom attributes supported by this layout. How i can do this?
Assume I can do something like that, but not found something method like tihs.

widget = CustomWidget(context)
widget.addParam("app:layout_rowWeight", 3) // how??


问:
Different image rendering in Chrome/Edge and Firefox
I'm doing a website for a homework and I'm having trouble with rendering an image. It looks as intended on Chrome and Edge browsers, but on Firefox it looks displaced.

This is the page on Chrome/Edge: Chrome/Edge Image

And this is a screenshot of the same page on Firefox: Firefox image

I can't seem to understand why are they different?

/* STRUTTURA BASE PER TUTTI GLI HTML */
@import url('https://fonts.googleapis.com/css?family=Advent Pro');
html, body {
    margin: 0;
    padding: 0;
}

html {
    font - size: 10 px;
    background - color: #ABCDEF;
}

body {
    font - family: 'Advent Pro';
}

div.all {
    position: relative;
    width: 70 % ;
    min - width: 800 px;
    margin: 0 auto;
}

/* CAMERA.html */

div.immDx {
    position: relative;
    overflow: hidden;
    margin - top: 6 % ;
    font - size: 170 % ;
}

img.imgDx {
    position: relative;
    overflow: visible;
    float: right;
    height: 60 % ;

}

span.nameDx {
    position: relative;
    margin - left: 20 % ;
}

span.descDx {
    position: relative;
    margin - left: 20 % ;
    text - decoration: underline;
}

span.listaDx {
    position: relative;
    margin - left: 40 % ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <body>
        <meta charset="utf-8">
        <title> QM-D_2_CAMERA </title>
        <link href="https://fonts.googleapis.com/css?family=Advent Pro"/>
        <link rel="stylesheet" href="mystyle.css">
        <div class="all">
            <div class="immDx">
                <img src="http://i.imgur.com/YZe0gad.jpg" class="imgDx"/>
                <span class="nameDx"> HEMNES no. 202.004.56 </span> <BR/> <BR/>
                <span class="descDx"> DESCRIZIONE DEL PRODOTTO</span> <BR/> <BR/>
                <span class="nameDx"> Parti principali/ Ripiano: </span><BR/>
                <span class="listaDx"> Pino massiccio</span><BR/>
                <span class="listaDx"> Mordente</span><BR/>
                <span class="listaDx"> Vernice acrilica trasparente</span><BR/>
                <span class="nameDx"> Lati del cassetto/Parte posteriore: </span><BR/>
                <span class="listaDx"> Pino massiccio</span><BR/>
                <span class="nameDx"> Base del cassetto: </span><BR/>
                <span class="listaDx">Fibra di legno</span><BR/>
                <span class="listaDx">Lamina</span><BR/>
                <span class="descDx"> MISURE DEL PRODOTTO</span> <BR/> <BR/>
                <span class="nameDx"> Larghezza: 46 cm </span><BR/>
                <span class="nameDx"> Profondità: 35 cm </span><BR/>
                <span class="nameDx"> Altezza: 70 cm </span><BR/>
                <span class="nameDx"> Profondità cassetto (interna): 23 cm </span><BR/>
            </div>
        </div>
    </body>
</html></code>```

答:
I found the issue here!

The problem is that you are missing the <!DOCTYPE> declaration of your HTML code.

The  declaration must be the very first thing in your HTML document, before the  tag.
  The  declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.

In your case you should use the HTML5 declaration which is:

<!DOCTYPE html>

Adding it at the beginning of the document should solve this annoying problem.

Fun fact is that Stackoverflow's code snippet feature adds it by default and that's why some of the users did not notice the different rendering in Chrome and Firefox!

Body:
I'm doing a website for a homework and I'm having trouble with rendering an image. It looks as intended on Chrome and Edge browsers, but on Firefox it looks displaced.

This is the page on Chrome/Edge: Chrome/Edge Image

And this is a screenshot of the same page on Firefox: Firefox image

I can't seem to understand why are they different?

/* STRUTTURA BASE PER TUTTI GLI HTML */
@import url('https://fonts.googleapis.com/css?family=Advent Pro');
html, body {
    margin: 0;
    padding: 0;
}

html {
    font - size: 10 px;
    background - color: #ABCDEF;
}

body {
    font - family: 'Advent Pro';
}

div.all {
    position: relative;
    width: 70 % ;
    min - width: 800 px;
    margin: 0 auto;
}

/* CAMERA.html */

div.immDx {
    position: relative;
    overflow: hidden;
    margin - top: 6 % ;
    font - size: 170 % ;
}

img.imgDx {
    position: relative;
    overflow: visible;
    float: right;
    height: 60 % ;

}

span.nameDx {
    position: relative;
    margin - left: 20 % ;
}

span.descDx {
    position: relative;
    margin - left: 20 % ;
    text - decoration: underline;
}

span.listaDx {
    position: relative;
    margin - left: 40 % ;
}

        <meta charset="utf-8">
        <title> QM-D_2_CAMERA </title>
        <link href="https://fonts.googleapis.com/css?family=Advent Pro"/>
        <link rel="stylesheet" href="mystyle.css">

                 HEMNES no. 202.004.56

                 DESCRIZIONE DEL PRODOTTO

                 Parti principali/ Ripiano:

                 Pino massiccio

                 Mordente

                 Vernice acrilica trasparente

                 Lati del cassetto/Parte posteriore:

                 Pino massiccio

                 Base del cassetto:

                Fibra di legno

                Lamina

                 MISURE DEL PRODOTTO

                 Larghezza: 46 cm

                 Profondità: 35 cm

                 Altezza: 70 cm

                 Profondità cassetto (interna): 23 cm


问:
Google Map not loading with separate files
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap"
    ></script>
  </body>
</html>
</code>```

Script.js file is:

```<code>function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }
</code>```

style.css file is:

```<code>* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</code>```

答:
```<code>#map { width:100%; height:200px;}
</code>```

or to fill whole window:

```<code>#map { width:100%; min-height:100%;}
</code>```

if it's first child with min-height property. PS. You can also try to add overflow:hidden; for second example.

Body:
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

<!DOCTYPE html>

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">

Script.js file is:

function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }

style.css file is:

* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }

Body:
#map { width:100%; height:200px;}

or to fill whole window:

#map { width:100%; min-height:100%;}

if it's first child with min-height property. PS. You can also try to add overflow:hidden; for second example.


问:
bitfinex api v2 error, invalid key
I am trying to make a basic authenticated api call to their new v2 api and getting an invalid api key error returned.

I reissued the api key just to verify, same error.

```<code>from time import time
import urllib.request
import urllib.parse
import hashlib
import hmac

APIkey = b'myapikeyyouarenotsupposedtosee'
secret = b'myceeeeecretkeyyyy'

url = 'https://api.bitfinex.com/v2/auth/r/wallets'

payload = {
    #'request':'/auth/r/wallets',
    'nonce': int(time() * 1000),
}

paybytes = urllib.parse.urlencode(payload).encode('utf8')
print(paybytes)

sign = hmac.new(secret, paybytes, hashlib.sha512).hexdigest()
print(sign)

headers = {
    'Key': APIkey,
    'Sign': sign
}

req = urllib.request.Request(url, headers=headers, data=paybytes)
with urllib.request.urlopen(req) as response:
    the_page = response.read()
    print(the_page)
</code>```

How do I make an authenticated api call to the new v2 API for bitfinex?

答:
Why not use one of the open source api clients out there ? and you can compare to your work .
https://github.com/scottjbarr/bitfinex
https://github.com/tuberculo/bitfinex</p>

Title: bitfinex api v2 error, invalid key

Body:
I am trying to make a basic authenticated api call to their new v2 api and getting an invalid api key error returned.

I reissued the api key just to verify, same error.

from time import time
import urllib.request
import urllib.parse
import hashlib
import hmac

APIkey = b'myapikeyyouarenotsupposedtosee'
secret = b'myceeeeecretkeyyyy'

url = 'https://api.bitfinex.com/v2/auth/r/wallets'

payload = {
    #'request':'/auth/r/wallets',
    'nonce': int(time() * 1000),
}

paybytes = urllib.parse.urlencode(payload).encode('utf8')
print(paybytes)

sign = hmac.new(secret, paybytes, hashlib.sha512).hexdigest()
print(sign)

headers = {
    'Key': APIkey,
    'Sign': sign
}

req = urllib.request.Request(url, headers=headers, data=paybytes)
with urllib.request.urlopen(req) as response:
    the_page = response.read()
    print(the_page)

How do I make an authenticated api call to the new v2 API for bitfinex?


问:
Log user input and time to text file using PHP
I've been trying to create a HTML form to collect user data and log it into a text file. What do I put inside "store.php" such that a log of the date/time and what was inside the text box is written to a text file inside a dir called "log"?

In addition, how do I use JS (or jQuery) to hide the entire form once the user has clicked done to prevent them from submitting the form again, but still allow them to see the rest of the page?

The existing HTML for the form is:

```<code>  <form method="post" action="store.php">
   <input placeholder="Name" id="Name" type="text"/><br>
   <input type="submit" value="Done"/>
  </form>
</code>```

答:
You should use PHPs fread and fwrite functions.

In order to hide the form you'll first need to disable the forms default action, then pass the parameters through AJAX and then hide it.

```<code>$("#myForm").submit(function(e){
    e.preventDefault();
    $.ajax(...)
    .done(function(){
        $("#myForm").fadeOut();
    });
});
</code>```

Body:
I've been trying to create a HTML form to collect user data and log it into a text file. What do I put inside "store.php" such that a log of the date/time and what was inside the text box is written to a text file inside a dir called "log"?

In addition, how do I use JS (or jQuery) to hide the entire form once the user has clicked done to prevent them from submitting the form again, but still allow them to see the rest of the page?

The existing HTML for the form is:

  <form method="post" action="store.php">
   <input placeholder="Name" id="Name" type="text"/>

   <input type="submit" value="Done"/>
  </form>

Body:
You should use PHPs fread and fwrite functions.

In order to hide the form you'll first need to disable the forms default action, then pass the parameters through AJAX and then hide it.

$("#myForm").submit(function(e){
    e.preventDefault();
    $.ajax(...)
    .done(function(){
        $("#myForm").fadeOut();
    });
});


问:
Conditional build based on environment using Webpack
I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.

In RequireJS you can pass a config in a plugin file and conditonally require things in based on that.

For webpack there doesn't seem to be a way of doing this. Firstly to create a runtime config for an environment I have used resolve.alias to repoint a require depending on the environment, e.g:

```<code>// All settings.
var all = {
    fish: 'salmon'
};

// `envsettings` is an alias resolved at build time.
module.exports = Object.assign(all, require('envsettings'));
</code>```

Then when creating the webpack config I can dynamically assign which file envsettings points to (i.e. webpackConfig.resolve.alias.envsettings = './' + env).

However I would like to do something like:

```<code>if (settings.mock) {
    // Short-circuit ajax calls.
    // Require in all the mock modules.
}
</code>```

But obviously I don't want to build in those mock files if the environment isn't mock.

I could possibly manually repoint all those requires to a stub file using resolve.alias again - but is there a way that feels less hacky?

Any ideas how I can do that? Thanks.

答:
Not sure why the "webpack.DefinePlugin" answer is the top one everywhere for defining Environment based imports/requires.

The problem with that approach is that you are still delivering all those modules to the client -> check with webpack-bundle-analyezer for instance. And not reducing your bundle.js's size at all :)

So what really works well and much more logical is: NormalModuleReplacementPlugin

So rather than do a on_client conditional require -> just not include not needed files to the bundle in the first place

Hope that helps

Body:
I have some things for development - e.g mocks which I would like to not bloat my distributed build file with.

In RequireJS you can pass a config in a plugin file and conditonally require things in based on that.

For webpack there doesn't seem to be a way of doing this. Firstly to create a runtime config for an environment I have used resolve.alias to repoint a require depending on the environment, e.g:

// All settings.
var all = {
    fish: 'salmon'
};

// `envsettings` is an alias resolved at build time.
module.exports = Object.assign(all, require('envsettings'));

Then when creating the webpack config I can dynamically assign which file envsettings points to (i.e. webpackConfig.resolve.alias.envsettings = './' + env).

However I would like to do something like:

if (settings.mock) {
    // Short-circuit ajax calls.
    // Require in all the mock modules.
}

But obviously I don't want to build in those mock files if the environment isn't mock.

I could possibly manually repoint all those requires to a stub file using resolve.alias again - but is there a way that feels less hacky?

Any ideas how I can do that? Thanks.


问:
Send ajax data to server on unload, with a timeout
I need to send some data to the server when user leaves my web app. The best way is using navigator.sendBeacon , but the browser support is poor. I tried synchronous ajax requests, but I learned it's a bad practice the hard way - the tab will be just frozen if server doesn't return a response and there's no way to set a timeout. So I need to send the data reliably on all browsers, without a timeout in case server fails to respond fast enough.

I have implemented it already and I'm going to answer this question, but any suggestions or other solutions are very welcome.

答:
Ok, so it can be done with async XHR and 2 events: beforeunload and unload.

I tried to do it in one event, but the request won't be send until the loop finishes, even though the request was sent before the loop.

In the beforeunload handler, you send an async request and save the current time. Then in the unload handler, you put a while loop that continues if not enough time have passed or the server responded (checking readyState).
When the loop ends, the browser is free to unload the window.

Here's the code. I also enabled sending beacon instead if the browser supports it.

```<code>var unloadRequest = null,
       requestStartTime = null,
       isBeaconSupported = (navigator && typeof navigator.sendBeacon === 'function');

  window.onbeforeunload = function() {

     if (isBeaconSupported) {

            unloadRequest = new XMLHttpRequest();
            unloadRequest.withCredentials = true;
            unloadRequest.open('POST', '/beacon', true);
            unloadRequest.setRequestHeader("Content-Type", "text/plain");

            requestStartTime = performance.now();
            unloadRequest.send(JSON.stringify({ test: true, _sentBy: 'XMLHttpRequest' }));

  }

  //return true;

};

window.onunload = function() {

  if (isBeaconSupported) {

    navigator.sendBeacon('/beacon', JSON.stringify({ test: true, _sentBy: 'beacon' }))

  } else if (unloadRequest) {

    //continue the loop if time is left and the request havent finished
    while (requestStartTime + 3000 > performance.now() && unloadRequest.readyState !== XMLHttpRequest.DONE) {

      //console.log(unloadRequest.readyState);

      }

      console.log('request finished or timed out')
      console.log('it took: ' + (performance.now() - requestStartTime) + 'ms');

  }

};
</code>```

Body:
Ok, so it can be done with async XHR and 2 events: beforeunload and unload.

I tried to do it in one event, but the request won't be send until the loop finishes, even though the request was sent before the loop.

In the beforeunload handler, you send an async request and save the current time. Then in the unload handler, you put a while loop that continues if not enough time have passed or the server responded (checking readyState).
When the loop ends, the browser is free to unload the window.

Here's the code. I also enabled sending beacon instead if the browser supports it.

var unloadRequest = null,
       requestStartTime = null,
       isBeaconSupported = (navigator && typeof navigator.sendBeacon === 'function');

  window.onbeforeunload = function() {

     if (isBeaconSupported) {

            unloadRequest = new XMLHttpRequest();
            unloadRequest.withCredentials = true;
            unloadRequest.open('POST', '/beacon', true);
            unloadRequest.setRequestHeader("Content-Type", "text/plain");

            requestStartTime = performance.now();
            unloadRequest.send(JSON.stringify({ test: true, _sentBy: 'XMLHttpRequest' }));

  }

  //return true;

};

window.onunload = function() {

  if (isBeaconSupported) {

    navigator.sendBeacon('/beacon', JSON.stringify({ test: true, _sentBy: 'beacon' }))

  } else if (unloadRequest) {

    //continue the loop if time is left and the request havent finished
    while (requestStartTime + 3000 > performance.now() && unloadRequest.readyState !== XMLHttpRequest.DONE) {

      //console.log(unloadRequest.readyState);

      }

      console.log('request finished or timed out')
      console.log('it took: ' + (performance.now() - requestStartTime) + 'ms');

  }

};


问:
why do I get a truncated .txt file
I'm trying to generate a file containing a short list of random numbers.  Every time I run this code I get a file where the list is truncated, usually in the middle of a number.  I'm using PyCharm.</p>

```<code>import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst
test = generate_test(100, 10**12)
test_file = open("test.txt", "wb")
test_file = open("test.txt", "r+")
test_file.write(str(test))
</code>```

答:
You don't create the file correctly, this might be a cleaner code: </p>

```<code>import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst

test = generate_test(100, 10**12)

with open("test.txt", "w") as output:
    output.write(str(test))
</code>```

Title: why do I get a truncated .txt file

Body:
I'm trying to generate a file containing a short list of random numbers.  Every time I run this code I get a file where the list is truncated, usually in the middle of a number.  I'm using PyCharm.

import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst
test = generate_test(100, 10**12)
test_file = open("test.txt", "wb")
test_file = open("test.txt", "r+")
test_file.write(str(test))

Body:
You don't create the file correctly, this might be a cleaner code:

import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst

test = generate_test(100, 10**12)

with open("test.txt", "w") as output:
    output.write(str(test))


问:
How to save and restore state of process in Activiti framework
My aim is to save state of process before Activiti application will be redeployed with new futures. So I can restore all not finished process in state which they had before stopping. Is there a way how I can do it by using Activiti functionality?</p>

答: Activiti framework saves all tasks  and processes into DB. After activiti angine was terminated and lunched again all not finished tasks will be restored. </p>


问:
How to show all decimal digits in an Excel cell programatically using VBA
I have an Excel macro which stores some business values.

For one of the cell the value should display 999.999999 but it shows 1000 and in formula bar i see the value shown as 999.999999. Since these are converted values from one type to another, the customer wants me to show the value as it is without the decimal places getting rounded.

One workaround i thought was to convert the cell into text format before populating the value but this doesn't work as i need to support this in various regional settings.

Any suggestions on how to get the Excel VBA to know the number of digits after decimal to be displayed will be a great help.

Current code to populate cell value :

Range.Offset(0,0).Value = Response

Here, Response is the converted value i.e 999.999999 in string format.

答:
one way would be a check for the # of decimals like:

```<code>Dim str As String
str = Response

If Len(str) - InStr(str, ".") > 2 Then
  Range.Offset(0, 0).Value = "'" & str
Else
  Range.Offset(0, 0).Value = str
End If
</code>```

Or simply do always the Range.Offset(0, 0).Value = "'" & Response to see the whole number ;)

Another way is the change of the number format like:

```<code>Dim str As String, x As Byte
str = Response
x = Len(str) - InStr(str, ".")
Range.Offset(0, 0).Value = str

If x < 2 Then x = 2
Range.Offset(0, 0).NumberFormat = "0." & Application.Rept("0", x)
</code>```

EDIT:
For the localization you can use Application.DecimalSeparator to get the right one like:

```<code>Range.Offset(0, 0).NumberFormat = "0" & Application.DecimalSeparator & Application.Rept("0", x)
</code>```

Also a change later on can be done like

```<code>If Len(Range.Offset(0, 0).Text) - Len(Range.Offset(0, 0).Value) Then
  Range.Offset(0, 0).NumberFormat = "0" & Application.DecimalSeparator & Application.Rept("0", x)
End If
</code>```

Edit 2:

For automatic cell fomating, you can use the approach from Ron and directly set the cells number format to

```<code>0.0###############
</code>```

Only using # will lead to 3 shown as 3. and 0.3 to be .3. Also if changing to a location which uses , as separator should change the number format automatically.

Body:
one way would be a check for the # of decimals like:

Dim str As String
str = Response

If Len(str) - InStr(str, ".") > 2 Then
  Range.Offset(0, 0).Value = "'" & str
Else
  Range.Offset(0, 0).Value = str
End If

Or simply do always the Range.Offset(0, 0).Value = "'" & Response to see the whole number ;)

Another way is the change of the number format like:

Dim str As String, x As Byte
str = Response
x = Len(str) - InStr(str, ".")
Range.Offset(0, 0).Value = str

If x < 2 Then x = 2
Range.Offset(0, 0).NumberFormat = "0." & Application.Rept("0", x)

EDIT:
For the localization you can use Application.DecimalSeparator to get the right one like:

Range.Offset(0, 0).NumberFormat = "0" & Application.DecimalSeparator & Application.Rept("0", x)

Also a change later on can be done like

If Len(Range.Offset(0, 0).Text) - Len(Range.Offset(0, 0).Value) Then
  Range.Offset(0, 0).NumberFormat = "0" & Application.DecimalSeparator & Application.Rept("0", x)
End If

Edit 2:

For automatic cell fomating, you can use the approach from Ron and directly set the cells number format to

0.0###############

Only using # will lead to 3 shown as 3. and 0.3 to be .3. Also if changing to a location which uses , as separator should change the number format automatically.


问:
How to save a custom colormap and use it again in Matlab?
I have created a colormap that resembles the human connectome project colormap ROY-BIG-BL, doing it manually on the colormap editor see here.

However, I am not able to save this as a colormap.
I tried different commands such as

```<code>mycmap = get(gcf,'colormap')
</code>```

I read that with Matlab 2015 one should use gca, but this gives an error.

Error using matlab.graphics.axis.Axes/get
  There is no colormap property on the Axes class.

When I then try to use the saved mycmap for another figure, it ignores all modifications und uses the basic colormap parula.

Thanks for help. How can I save it and use it as another colormap in any figure I want?

答:
The definition of colormaps is deeply hidden inside the figure class, which is not accessible. So you can't save your colormap "with a name" in Matlab and access it like a normal colormap. But a colormap is nothin else than a Yx3 matrix, you can store on disk.

```<code>%// custom colormap
n = 50;               %// number of colors
R = linspace(1,0,n);  %// Red from 1 to 0
B = linspace(0,1,n);  %// Blue from 0 to 1
G = zeros(size(R));   %// Green all zero
myCustomColormap = [R(:), G(:), B(:)];

%// save colormap on disk
save('myCustomColormap','myCustomColormap');

%// clear for explanation purposes
clear
%%%%%%%%%%%%%%%%%%%

%// load colormap saved on disk
load myCustomColormap

%// assign colormap
colormap( myCustomColormap );
</code>```

You used the colormap editor to create your colormap. After you applied it, use the following code to get the required matrix for further reference:

```<code>myCustomColormap = colormap(gca)
save('myCustomColormap','myCustomColormap');
</code>```

If you want to make the colormap generally available to all your functions, no matter where, add it to your Matlab search path.

Body:
I have created a colormap that resembles the human connectome project colormap ROY-BIG-BL, doing it manually on the colormap editor see here.

However, I am not able to save this as a colormap.
I tried different commands such as

mycmap = get(gcf,'colormap')

I read that with Matlab 2015 one should use gca, but this gives an error.

Error using matlab.graphics.axis.Axes/get
  There is no colormap property on the Axes class.

When I then try to use the saved mycmap for another figure, it ignores all modifications und uses the basic colormap parula.

Thanks for help. How can I save it and use it as another colormap in any figure I want?

Body:
The definition of colormaps is deeply hidden inside the figure class, which is not accessible. So you can't save your colormap "with a name" in Matlab and access it like a normal colormap. But a colormap is nothin else than a Yx3 matrix, you can store on disk.

%// custom colormap
n = 50;               %// number of colors
R = linspace(1,0,n);  %// Red from 1 to 0
B = linspace(0,1,n);  %// Blue from 0 to 1
G = zeros(size(R));   %// Green all zero
myCustomColormap = [R(:), G(:), B(:)];

%// save colormap on disk
save('myCustomColormap','myCustomColormap');

%// clear for explanation purposes
clear
%%%%%%%%%%%%%%%%%%%

%// load colormap saved on disk
load myCustomColormap

%// assign colormap
colormap( myCustomColormap );

You used the colormap editor to create your colormap. After you applied it, use the following code to get the required matrix for further reference:

myCustomColormap = colormap(gca)
save('myCustomColormap','myCustomColormap');

If you want to make the colormap generally available to all your functions, no matter where, add it to your Matlab search path.


问:
Django Templates: Display a date only if it's in the future
How do I compare dates in a Django template? I thought of several possible avenues:

Send today's date in the context to be compared at the template

Create my own template tag

Have some logic in the view to only pass the date if it's in the future

Although the last option seems easier, I rather leave the display logic in the template than in the view. I also do not want to pass something that seems so trivial like today's date in the template context.

Perhaps someone has another option or could share their implementation of one of the options I mentioned above and why they decided to go that route.

答: IMO it is cleaner to do that kind of things in a view or in a helper module, and pass it in the context. The templates are better left with no logic or the very least possible (that's the MVC pattern after all). </p>


问:
How to Upload Any file from internal or External Storage in Xamarin?
I have written code for Picking Image & Uploading Image and getting a particular image with it's location in emulator but how do i access any file from Android File System using Xamarin so what should i use to do that ?.</p>

```<code>namespace XAFileUpload_2._0
{
    [Activity(Label = "XAFileUpload 2.0", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        //Pick Id to know the pick item no.
        public static readonly int PickImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.Browse);
            button.Click += BrowseButtonOnClick;

        }

        void BrowseButtonOnClick(object sender, EventArgs eventArs)
        {
            Intent = new Intent();
            Intent.SetType("image/*");
            Intent data = Intent.SetAction(Intent.ActionGetContent);

            try
            {
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
            {
                UploadFile(data);

            }
        }

        void UploadFile(Intent data)
        {
            ICursor cursor = null;

            try
            {
                Button upButton = FindViewById<Button>(Resource.Id.Upload);

                // assuming image
                var docID = DocumentsContract.GetDocumentId(data.Data);
                var id = docID.Split(':')[1];
                var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                // Try internal storage first
                cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                if (cursor.Count == 0)
                {
                    // not found on internal storage, try external storage
                    cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                }
                var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                cursor.MoveToFirst();
                var fullPathToImage = cursor.GetString(colData);
                string fpti = cursor.GetString(colData);

                string address = "http://192.168.3.157:82/Values/DownFile";

                upButton.Click += (sender, args) =>
                {
                    try
                    {
                        ProgressDialog progressDialog = new ProgressDialog(this);
                        progressDialog.SetTitle("Please wait...");
                        progressDialog.SetCancelable(false);

                        Task.Run(() =>
                        {

                            RunOnUiThread(() =>
                            {
                                progressDialog.Show();
                            });

                            using (WebClient client = new WebClient())
                            {
                                client.UploadFile(address, fullPathToImage);

                            }

                            RunOnUiThread(() =>
                            {

                                progressDialog.Dismiss();

                                string msg = "Upload Completed";
                                Toast.MakeText(this, msg, ToastLength.Long).Show();

                            });
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("MediaPath", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);
            }
            finally
            {

                cursor?.Close();
                cursor?.Dispose();
            }
        }
    }
}
</code>```

答:
```<code>Intent = new Intent();
            Intent.SetType("image/*");
            Intent.SetAction(Intent.ActionGetContent);
            StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
</code>```

It opens image pickup dialog and after choosing an image it automatically calls OnActivityResult method

```<code>protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
        //Your code to upload image.
        //image uri is in data object.
        }
    }
</code>```

Body:
I have written code for Picking Image & Uploading Image and getting a particular image with it's location in emulator but how do i access any file from Android File System using Xamarin so what should i use to do that ?.

namespace XAFileUpload_2._0
{
    [Activity(Label = "XAFileUpload 2.0", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        //Pick Id to know the pick item no.
        public static readonly int PickImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.Browse);
            button.Click += BrowseButtonOnClick;

        }

        void BrowseButtonOnClick(object sender, EventArgs eventArs)
        {
            Intent = new Intent();
            Intent.SetType("image/*");
            Intent data = Intent.SetAction(Intent.ActionGetContent);

            try
            {
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
            {
                UploadFile(data);

            }
        }

        void UploadFile(Intent data)
        {
            ICursor cursor = null;

            try
            {
                Button upButton = FindViewById<Button>(Resource.Id.Upload);

                // assuming image
                var docID = DocumentsContract.GetDocumentId(data.Data);
                var id = docID.Split(':')[1];
                var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                // Try internal storage first
                cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                if (cursor.Count == 0)
                {
                    // not found on internal storage, try external storage
                    cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                }
                var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                cursor.MoveToFirst();
                var fullPathToImage = cursor.GetString(colData);
                string fpti = cursor.GetString(colData);

                string address = "http://192.168.3.157:82/Values/DownFile";

                upButton.Click += (sender, args) =>
                {
                    try
                    {
                        ProgressDialog progressDialog = new ProgressDialog(this);
                        progressDialog.SetTitle("Please wait...");
                        progressDialog.SetCancelable(false);

                        Task.Run(() =>
                        {

                            RunOnUiThread(() =>
                            {
                                progressDialog.Show();
                            });

                            using (WebClient client = new WebClient())
                            {
                                client.UploadFile(address, fullPathToImage);

                            }

                            RunOnUiThread(() =>
                            {

                                progressDialog.Dismiss();

                                string msg = "Upload Completed";
                                Toast.MakeText(this, msg, ToastLength.Long).Show();

                            });
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("MediaPath", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);
            }
            finally
            {

                cursor?.Close();
                cursor?.Dispose();
            }
        }
    }
}

Body:
Intent = new Intent();
            Intent.SetType("image/*");
            Intent.SetAction(Intent.ActionGetContent);
            StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);

It opens image pickup dialog and after choosing an image it automatically calls OnActivityResult method

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
        {
        //Your code to upload image.
        //image uri is in data object.
        }
    }


问:
Request.URL shows another domain. How it is possible?
I have a running website (based on ASP.NET MVC) on some domain, let's say mydomain.com

Yesterday I was looking into site access logs and I noticed very weird logs: inside it, I saw different domain!

Something like anotherdomain.com/somePage

And I saw exception text in my log saying that 404 - anotherdomain.com/somePage can't be found. It looks like somehow my code running on some other domain (Request.URL show different domain).

How it is possible? Does that means that someone somehow got access to my host (I running on Azure) and steal my binaries and deployed on another host? Or maybe my website opened from iframe?

I need to understand in order to determine whether I have a breach.

答:
It's actually possible to make a GET request to access other domains, via your domain, to check if there's a badly configured proxy. Since you're not, it simply returns a 404 Not Found because you are not actually hosting those pages.

Scans like these happen all the time and is an unfortunate side effect of being connected to the internet, but does not mean that you are under attack or that someone has access to your host.


答:
When you execute script.js it tries to find the div with the id="map". But it's not initialized yet .So, you need to do two things:

Include the script.js file after your

Call initMap() after the page has loaded. E.g. like this (at the end)

Title: Google Map not loading with separate files

Body:
When you execute script.js it tries to find the div with the id="map". But it's not initialized yet .So, you need to do two things:

Include the script.js file after your <div id="map"></div>

Call initMap() after the page has loaded. E.g. like this (at the end) <script>initMap()</script>


问:
Arranging people in queue (Uva - 10128)
I am trying to solve problem Uva-10128 (Queue) on UVa Online Judge. I am not able find a way to approach this problem. I searched on internet and found that most of people has solved this problem by precalulating using DP.

```<code>DP[1][1][1] = 1;
for(N = 2; N <= 13; N++)
    for(P = 1; P <= N; P++)
        for(R = 1; R <= N; R++)
           DP[N][P][R] = DP[N-1][P][R]*(N-2) + DP[N-1][P-1][R] + DP[N-1][P][R-1];
</code>```

Above code snippet is taken from https://github.com/morris821028/UVa/blob/master/volume101/10128%20-%20Queue.cpp.

Can someone please explain formula used in above code.

Thanks

答:
When you calculate DP[N][P][R] you look at the position of the smallest person in the queue. Because he is the smallest, he can't block anybody. But he will get blocked if he doesn't stand at either end of the queue.

If he is the first person in the queue he is seen from the beginning of the line. So if we remove him, the queue contains N-1 people and you can only see P-1 people from the beginning, but still R people from the end. Therefore there are DP[N-1][P-1][R] combinations.

If he is in the middle, then by removing him we still can see P and R people. And since there are N-2 positions in the middle, there are DP[N-1][P][R] * (N-2) combinations.

And if he is the last person in the queue we get DP[N-1][P][R-1] combinations. The reasoning is identically to the first case.

So the total number of combinations for DP[N][P][R] is the sum of all three cases.

Title: Arranging people in queue (Uva - 10128)

Body:
I am trying to solve problem Uva-10128 (Queue) on UVa Online Judge. I am not able find a way to approach this problem. I searched on internet and found that most of people has solved this problem by precalulating using DP.

DP[1][1][1] = 1;
for(N = 2; N <= 13; N++)
    for(P = 1; P <= N; P++)
        for(R = 1; R <= N; R++)
           DP[N][P][R] = DP[N-1][P][R]*(N-2) + DP[N-1][P-1][R] + DP[N-1][P][R-1];

Above code snippet is taken from https://github.com/morris821028/UVa/blob/master/volume101/10128%20-%20Queue.cpp.

Can someone please explain formula used in above code.

Thanks


问:
Destroy session or cookie in django when user get offline
I have a website and i want to destroy some session or cookie in django when user discoonet suddenly or get offline (wifi discoonect or disconnect mobil data).
But i dont know to how do this!
Is there any default library to do this?

答:
Well you can't know if users disconnected their internet or WiFi.
But you can check if user is still online and browsing the website.

to achieve that you can use javascript to send a request every 10 second (less or more) and check if user is still on the site. and if user is not online anymore you can make some changes or etc but in general you can't access to the users device and check the status for wifi or ...


问:
LAC and CID on LTE android
I used this method to read cell id and Lac(tac) on a LTE network but now it fails with NullPointer exception. Here is my code:

```<code>CellInfoLte cellinfolte = (CellInfoLte) mTelephonyMgr.getAllCellInfo().get(0);
String ssignal = cellinfolte.toString();
String[] parts = ssignal.split(" ");
</code>```

答:
You should use the followings in LTE networks:

cellinfolte.getCellIdentity().getCi()

cellinfolte.getCellIdentity().getTac()

Title: LAC and CID on LTE android

Body:
I used this method to read cell id and Lac(tac) on a LTE network but now it fails with NullPointer exception. Here is my code:

CellInfoLte cellinfolte = (CellInfoLte) mTelephonyMgr.getAllCellInfo().get(0);
String ssignal = cellinfolte.toString();
String[] parts = ssignal.split(" ");


问:
C# process start focus issue

When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

```<code>string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);
</code>```

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda

答:
can you do

```<code>myForm.Focus();
</code>```

where myForm is the form on your main application

Title: C# process start focus issue

Body:
When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda

Body:
can you do

myForm.Focus();

where myForm is the form on your main application


问:
How to pass the value of variable when next page loads in JavaScript?
I have a variable named collar whose value is either red or green. It is used for random order as on or off. But in next page,it wont retain its previous value. How to do that. I am beginner in JavaScript.</p>

答:
All of the variables in Javascript only valid in an html page.

- When coming the another page, You may named same variable name but actually different variable.

- When the page is reloaded, the variable value is reset, current value is not kept.

If you really need previous value to be passed through next page, you can rely on server or local storage to keep the value and to be retrieve by the next page.