问:
ms-access shorten vba code
I'm using the following code alot in my project:

```<code>txtVoornaam.Locked = False
txtVoornaam.BorderStyle = 4
txtVoornaam.BorderColor = RGB(255, 165, 0

txtAchternaam.Locked = False
txtAchternaam.BorderStyle = 4
txtAchternaam.BorderColor = RGB(255, 165, 0)

txtAfdeling.Locked = False
txtAfdeling.BorderStyle = 4
txtAfdeling.BorderColor = RGB(255, 165, 0)
</code>```

I wonder if there is a way to not display this in my code or shorten this. The code gets very long if i use this a few times..

答:
An option if you have several controls that you are creating through a form would be to do the following:

```<code>Dim names() As String
names = Split("txtVoornaam,txtAchternaam,txtAfdeling", ",")

Dim ctrl As Variant
Dim ctrlName As Variant

For Each ctrl In Me.Controls
  For Each ctrlName In names
    If StrComp(ctrlName, ctrl.Name) = 0 Then
        ctrl.Locked = False
        ctrl.BorderStyle = 4
        ctrl.BorderColor = RGB(255, 165, 0)
    End If
  Next ctrlName
Next ctrl
</code>```

This code iterates through each of the control names that fit your list.

However, this is much less efficient than Mat's Mug's answer because you are iterating through the entire list of controls in your form, but it does showcase how you might take a list of static names and iterate through them and a collection.

If you wanted to change all the text controls this would be the way to do it; simply remove the ctrlName check.

As Parfait has correctly pointed out, you could shorten the code to the following if you are confident in your control names:

```<code>Dim names() As String
names = Split("txtVoornaam,txtAchternaam,txtAfdeling", ",")

Dim ctrlName As Variant

For Each ctrlName In names
  With Me.Controls(ctrlName)
      .Locked = False
      .BorderStyle = 4
      .BorderColor = RGB(255, 165, 0)
  End With
Next ctrlName
</code>```

Title: ms-access shorten vba code

Body:
I'm using the following code alot in my project:

txtVoornaam.Locked = False
txtVoornaam.BorderStyle = 4
txtVoornaam.BorderColor = RGB(255, 165, 0

txtAchternaam.Locked = False
txtAchternaam.BorderStyle = 4
txtAchternaam.BorderColor = RGB(255, 165, 0)

txtAfdeling.Locked = False
txtAfdeling.BorderStyle = 4
txtAfdeling.BorderColor = RGB(255, 165, 0)

I wonder if there is a way to not display this in my code or shorten this. The code gets very long if i use this a few times..

Body:
An option if you have several controls that you are creating through a form would be to do the following:

Dim names() As String
names = Split("txtVoornaam,txtAchternaam,txtAfdeling", ",")

Dim ctrl As Variant
Dim ctrlName As Variant

For Each ctrl In Me.Controls
  For Each ctrlName In names
    If StrComp(ctrlName, ctrl.Name) = 0 Then
        ctrl.Locked = False
        ctrl.BorderStyle = 4
        ctrl.BorderColor = RGB(255, 165, 0)
    End If
  Next ctrlName
Next ctrl

This code iterates through each of the control names that fit your list.

However, this is much less efficient than Mat's Mug's answer because you are iterating through the entire list of controls in your form, but it does showcase how you might take a list of static names and iterate through them and a collection.

If you wanted to change all the text controls this would be the way to do it; simply remove the ctrlName check.

As Parfait has correctly pointed out, you could shorten the code to the following if you are confident in your control names:

Dim names() As String
names = Split("txtVoornaam,txtAchternaam,txtAfdeling", ",")

Dim ctrlName As Variant

For Each ctrlName In names
  With Me.Controls(ctrlName)
      .Locked = False
      .BorderStyle = 4
      .BorderColor = RGB(255, 165, 0)
  End With
Next ctrlName


来源: stackexchange

问:
NodeMCU enduser setup module html file that creates another file
I have created my own enduser_setup.html file nodemcu(for the enduser setup module: https://nodemcu.readthedocs.io/en/master/en/modules/enduser-setup/#enduser_setupstart).

I have added another field (beyond the ssid\password fileds):

```<code><input id=result1 type=text autocorrect=off autocapitalize=none placeholder='Place ID' />
</code>```

I want on submit to create a lua file (result1.lua) with the Get result of this field.

Tried with php:

```<code><?php
    $myfile = fopen("result1.lua", "w") or die("Unable to open file!");
    $txt = $_GET["result1"];
    fwrite($myfile, $txt);
    fclose($myfile);
?>
</code>```

Did not work :(

答: That is currently not possible with NodeMCU. However, there is a pending pull request that'll add this feature. It's likely going to be merged to the dev branch in the next days.

ContentLicense: CC BY-SA 3.0

Body:
I have created my own enduser_setup.html file nodemcu(for the enduser setup module: https://nodemcu.readthedocs.io/en/master/en/modules/enduser-setup/#enduser_setupstart).

I have added another field (beyond the ssid\password fileds):

<input id=result1 type=text autocorrect=off autocapitalize=none placeholder='Place ID' />

I want on submit to create a lua file (result1.lua) with the Get result of this field.

Tried with php:

<?php
    $myfile = fopen("result1.lua", "w") or die("Unable to open file!");
    $txt = $_GET["result1"];
    fwrite($myfile, $txt);
    fclose($myfile);
?>

Did not work :(


问:
Can I access a class without an __init__? - Python
I want to be able to print "hello harry" from a module. This is my module (called test23):

```<code>class tool:

    def handle(self,name):
        self.name = "hello " + name
</code>```

This is my script:

```<code>import test23

harry= test23.tool().handle(" harry")
print harry.name
</code>```

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

答:
What you wanted to do is:

```<code>harry = test23.tool()  # Ok harry is a tool object
harry.handle(" harry") # Ok harry.name has been set to " harry"
print harry.name       # Ok print successfully "hello  harry"
</code>```

But what you did is: harry= test23.tool().handle(" harry")

Let's look one pass at a time:

test23.tool() : builds a new (temporary) tool object

test23.tool().handle(" harry") : sets the attribute name of the temporary and returns... None!

harry= test23.tool().handle(" harry") : sets the attribute name of a temporary tool object, set harry to the return value of the handle method which is None => same as harry = None

Alternatively, you should change handle to return the tool object:

class tool:

```<code>def handle(self,name):
    self.name = "hello " + name
    return self
</code>```

Body:
I want to be able to print "hello harry" from a module. This is my module (called test23):

class tool:

    def handle(self,name):
        self.name = "hello " + name

This is my script:

import test23

harry= test23.tool().handle(" harry")
print harry.name

I can't seem to print "hello harry" inside my script idle. How would I go about doing this?

Body:
What you wanted to do is:

harry = test23.tool()  # Ok harry is a tool object
harry.handle(" harry") # Ok harry.name has been set to " harry"
print harry.name       # Ok print successfully "hello  harry"

But what you did is: harry= test23.tool().handle(" harry")

Let's look one pass at a time:

test23.tool() : builds a new (temporary) tool object

test23.tool().handle(" harry") : sets the attribute name of the temporary and returns... None!

harry= test23.tool().handle(" harry") : sets the attribute name of a temporary tool object, set harry to the return value of the handle method which is None => same as harry = None

Alternatively, you should change handle to return the tool object:

class tool:

def handle(self,name):
    self.name = "hello " + name
    return self


问:
Unable to capture the whole URL string with Bottle web framework
I have a small Bottle hello world type code :

```<code>from bottle import route, run, template

@route('/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)
</code>```

Now when i type the below string in the browser(chrome):

```<code>http://localhost:8080/navigator?search_term=arrow/
</code>```

it comes up with the message :
Hello navigator!

My objective is to capture the term arrow inside the name argument so that i can use that to display something else using the index function .

Please help me as to how to capture the term arrow in the URL that i supplied.

Thanks in advance for any suggestions.

答:
You've confused the url's path and its query args. Here's how to get your query arg:

```<code>from bottle import route, run, template, request

@route('/navigator')
def index():
    name = request.params['search_term']
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)
</code>```

This produces the result you want:

```<code>% curl 'http://localhost:8080/navigator?search_term=arrow/'
<b>Hello arrow/</b>!
</code>```

Documentation is here. Good luck!

Body:
I have a small Bottle hello world type code :

from bottle import route, run, template

@route('/<name>')
def index(name):
    return template('Hello {{name}}!', name=name)

run(host='localhost', port=8080)

Now when i type the below string in the browser(chrome):

http://localhost:8080/navigator?search_term=arrow/

it comes up with the message :
Hello navigator!

My objective is to capture the term arrow inside the name argument so that i can use that to display something else using the index function .

Please help me as to how to capture the term arrow in the URL that i supplied.

Thanks in advance for any suggestions.

Body:
You've confused the url's path and its query args. Here's how to get your query arg:

from bottle import route, run, template, request

@route('/navigator')
def index():
    name = request.params['search_term']
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

This produces the result you want:

% curl 'http://localhost:8080/navigator?search_term=arrow/'
<b>Hello arrow/</b>!

Documentation is here. Good luck!


问:
Connecting to Boost Signals2 signal with anonymous or lambda function
I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.

```<code>signal<void (const char*)>                      UserMessageEvent;

// connect anonymous boost function to display message box on user message event
UserMessageEvent.connect(boost::bind(AfxMessageBox, _1));
</code>```

If this were C# I would do the following, leading me to believe I want to use a lambda function to convert between the calling type of the signal and the type of the AfxMessageBox arguments. However it is not clear to me how to do this.

```<code>UserMessageEvent += (c) => MessageBox.Show((some const char to LPCSTR conversion)c);
</code>```

Any suggestions?

Edit:
The error given by msvc10 is error C2914: 'boost::bind' : cannot deduce template argument as function argument is ambiguous

答:
I don't know how boost::bind behave in regard to default parameters.

Anyway, here is the syntax with lambda :

```<code>UserMessageEvent.connect( [](const char* message)
{
   // maybe need here a conversion to LPCWSTR ?
   AfxMessageBox(message);
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.

signal<void (const char*)>                      UserMessageEvent;

// connect anonymous boost function to display message box on user message event
UserMessageEvent.connect(boost::bind(AfxMessageBox, _1));

If this were C# I would do the following, leading me to believe I want to use a lambda function to convert between the calling type of the signal and the type of the AfxMessageBox arguments. However it is not clear to me how to do this.

UserMessageEvent += (c) => MessageBox.Show((some const char to LPCSTR conversion)c);

Any suggestions?

Edit:
The error given by msvc10 is error C2914: 'boost::bind' : cannot deduce template argument as function argument is ambiguous

Body:
I don't know how boost::bind behave in regard to default parameters.

Anyway, here is the syntax with lambda :

UserMessageEvent.connect( [](const char* message)
{
   // maybe need here a conversion to LPCWSTR ?
   AfxMessageBox(message);
});


问:
Rails relationship for a single user role
i'm currently working on building a site like freelancer using RoR, but i'm stuck somewhere, my user table which was generated with devise has a role column which can be admin, client or freelancer. Also i have a skills table which belongs to user but i don't want every user to have skills except from the users with the role of freelancer, how do i go about this, i'm currently using cancancan for user authorization and devise for authentication, is roles the best solution to this or STI and how would you advice me to approach this problem, here's an example code

```<code>class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,   :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :user_roles
  has_many :skills
  has_many :skills, through: :user_skills ## I don't want all users to have skills except the users with the role of freelancer
  has_many :roles, through: :user_roles

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role }
  end

end
</code>```

thank you in anticipation.

答:
You could do something like this:

```<code>class Skill < ApplicationRecord
  belongs_to :user, -> { where role: 'freelancer' }
end
</code>```

Keep in mind that this would save the skills for any role, but they would be visible only for freelancer.
You could also use cancancan to check whether the user is a freelancer.

Body:
i'm currently working on building a site like freelancer using RoR, but i'm stuck somewhere, my user table which was generated with devise has a role column which can be admin, client or freelancer. Also i have a skills table which belongs to user but i don't want every user to have skills except from the users with the role of freelancer, how do i go about this, i'm currently using cancancan for user authorization and devise for authentication, is roles the best solution to this or STI and how would you advice me to approach this problem, here's an example code

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable,   :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :user_roles
  has_many :skills
  has_many :skills, through: :user_skills ## I don't want all users to have skills except the users with the role of freelancer
  has_many :roles, through: :user_roles

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role }
  end

end

thank you in anticipation.

Body:
You could do something like this:

class Skill < ApplicationRecord
  belongs_to :user, -> { where role: 'freelancer' }
end

Keep in mind that this would save the skills for any role, but they would be visible only for freelancer.
You could also use cancancan to check whether the user is a freelancer.


问:
h2o basic parse file
I am new to h2o. I am using h2o-3.10.4.2 on Windows 7, java 1.8. I am using h2o flow. Just going through the k-modes demo. If I import seeds_dataset.txt     file from https://archive.ics.uci.edu/ml/machine-learning-databases/00236/ and try to parse it then at record number 8, parser fails to capture column 7 and 8. This is most probably due to 2 tabs. I want the parser to consider any white spaces as a separator. Please note that if i use "http://s3.amazonaws.com/h2o-public-test-data/smalldata/flow_examples/seeds_dataset.txt" then i do not face any issues as tabs are sorted out.

So finally i want to know that when i use parseFiles in h2o how do i set any whitespaces as separator. i tried using startoftext etc but i am not able to get all the columns.

答:
The data is small so a quick solution to this would be to remove the double \t's in the file prior to ingesting. There are many ways to do this, here is a quick and dirty one:

```<code>import io
f = open("seeds_dataset.txt")
s = list(f.read())
for i in range(0,len(s)-1):
    if s[i] == '\t' and s[i+1] == '\t':
        s[i+1] = ''

output = open("seeds_dataset_fixed.txt", 'w+')
output.write("".join(s))

import h2o
h2o.init()
h2o.import_file("seeds_dataset_fixed.txt")
</code>```

Hope this helps

Title: h2o basic parse file

Body:
The data is small so a quick solution to this would be to remove the double \t's in the file prior to ingesting. There are many ways to do this, here is a quick and dirty one:

import io
f = open("seeds_dataset.txt")
s = list(f.read())
for i in range(0,len(s)-1):
    if s[i] == '\t' and s[i+1] == '\t':
        s[i+1] = ''

output = open("seeds_dataset_fixed.txt", 'w+')
output.write("".join(s))

import h2o
h2o.init()
h2o.import_file("seeds_dataset_fixed.txt")

Hope this helps


问:
Core-Data: How to set up relationship from one object to specific one in many objects with same name?
I have a question in core data:

there are 2 Entities in the project, Books and Pages;
there are 3 Objects books user created in Entity Books;
there are several Objects pages user created in Entity Pages;
relationship inbetween is one page belongs to one book, one book has many pages.

and my question: there are 3 book with the same object name "book",and each has unique attribute .bookName : @"metal" ;@"plastic" ;@"glass". how to set page to the book with .bookName = @"glass" ?

```<code>    //In BookViewController
    Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
    //textView.text is user input text
    book.bookName = textView.text;

    //In PageViewController
    Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
    page.itsbook = WHAT?
</code>```

Thank you for reading, I stuck here like: a day, really appreciate your help, love you!

答:
I'm not sure what you mean. If you want to insert a page as a subset of the book you want this line of code:

```<code>[book addPageToBookObject:page]; // the method will be the relationship name
</code>```

If you want to get the book from the page object you'll need an inverse relationship from the pages to the book.

Body:
I have a question in core data:

there are 2 Entities in the project, Books and Pages;
there are 3 Objects books user created in Entity Books;
there are several Objects pages user created in Entity Pages;
relationship inbetween is one page belongs to one book, one book has many pages.

and my question: there are 3 book with the same object name "book",and each has unique attribute .bookName : @"metal" ;@"plastic" ;@"glass". how to set page to the book with .bookName = @"glass" ?

    //In BookViewController
    Books *book = (Books *)[NSEntityDescription insertNewObjectForEntityForName:@"Books" inManagedObjectContext:managedObjectContext];
    //textView.text is user input text
    book.bookName = textView.text;

    //In PageViewController
    Pages *page = (Pages *)[NSEntityDescription insertNewObjectForEntityForName:@"Pages" inManagedObjectContext:managedObjectContext];
    page.itsbook = WHAT?

Thank you for reading, I stuck here like: a day, really appreciate your help, love you!

Body:
I'm not sure what you mean. If you want to insert a page as a subset of the book you want this line of code:

[book addPageToBookObject:page]; // the method will be the relationship name

If you want to get the book from the page object you'll need an inverse relationship from the pages to the book.


问:
MySqli php UUID_SHORT
Basically what I want to do is to use MySqli to just do a query UUID_SHORT() and get the result. No INSERT,UPDATE,DELETE or anything, I just want the value of UUID_SHORT.

Haven't been able to figure it out, any help would be great!

Thanks.

答:
You can expand function created by @competent_tech to add more flexibility:

Example:

```<code>function getUuid(mysqli $db, $short=false)
{
    $query = "SELECT " . ($short ? "UUID_SHORT()" : "UUID()");
    $result = $db->query($query)->fetch_array();
    return $result[0];
}
</code>```

Title: MySqli php UUID_SHORT

Body:
You can expand function created by @competent_tech to add more flexibility:

Example:

function getUuid(mysqli $db, $short=false)
{
    $query = "SELECT " . ($short ? "UUID_SHORT()" : "UUID()");
    $result = $db->query($query)->fetch_array();
    return $result[0];
}


问:
How to Implement Calendar in CrossPlatForm(Xamarin )
How to implement android and ios default calendar in Xamarin.form.

i would like to access default iphone and android calenders.

please share any examples or tutorials its very help full to me

答:
You can implement the calendar control by writing a custom renderer as given here

Or enroll for a community license of Syncfusion and use their Calendar Control.


问:
Nodejs api call from angular2 service
I have node api that returns data to browser using this api :

```<code>app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});
</code>```

I am trying to call this api from the service class.

```<code>import { Injectable } from '@angular/core';
import { Patient } from '../patient.interface';

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor() { }

    getAllPatients(): Patient[]
    {
          // What to do here ??
    }

}
</code>```

How do i return data from node api to service ?

答:
You can first import the Angular2 Http library into your service:

```<code>import { Http } from '@angular/http';
</code>```

I also import rx/js for use of Observables and mapping.

```<code>import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
</code>```

You can then inject the library into your service:

```<code>constructor(private _http: Http) { }
</code>```

Make your http call to your node.js server like this:

```<code>getAllPatients(): Patient[]
{
      // What to do here ??
      return this._http.get('/api/patients')
           .map(this.extractData)
           .catch(this.handleError);
}
</code>```

For more information, documentation, and clarification please read the Angular 2 Http Docs

Title: Nodejs api call from angular2 service

Body:
I have node api that returns data to browser using this api :

app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});

I am trying to call this api from the service class.

import { Injectable } from '@angular/core';
import { Patient } from '../patient.interface';

@Injectable()
export class PatientDataService {

    patients : Patient[] =[];

    constructor() { }

    getAllPatients(): Patient[]
    {
          // What to do here ??
    }

}

How do i return data from node api to service ?

Body:
You can first import the Angular2 Http library into your service:

import { Http } from '@angular/http';

I also import rx/js for use of Observables and mapping.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

You can then inject the library into your service:

constructor(private _http: Http) { }

Make your http call to your node.js server like this:

getAllPatients(): Patient[]
{
      // What to do here ??
      return this._http.get('/api/patients')
           .map(this.extractData)
           .catch(this.handleError);
}

For more information, documentation, and clarification please read the Angular 2 Http Docs


问:
angular4 Routes not being kept on refresh
When reloading the page (F5 or typing the url into the address bar), the current route is not kept. I have a two separate modules, the main app module and then a dashboard module. These modules each have their own routing modules that they import. If I navigate to http://localhost it redirects to http://localhost/dashboard/overview but if I navigate to any other route though the address bar it redirects back to http://localhost/dashboard/overview

Clicking on any links on the pages that use routerlinks work fine.

I am using the latest angular 4 with the latest angular-cli. It worked before the update from angular 2 to angular 4.

Previous version of libraries:

```<code>"@angular/core": "^2.3.1",
"@angular/router": "^3.3.1",
</code>```

Current version of libraries:

```<code>"@angular/core": "^4.0.0",
"@angular/router": "^4.0.0",
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard/overview',
    pathMatch: 'full'
  },
  {path: 'logs', component: LogsComponent},
  {path: 'search', component: SearchComponent},
  {path: 'metrics', component: MetricsComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
</code>```

dashboard-routing.module.ts

```<code>const dashboardRoutes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    children: [
      {path: 'overview', component: OverviewComponent},
      {path: 'partition/:type', component: DashboardPartitionComponent},
      {path: 'latency', component: DashboardLatencyComponent},
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forChild(dashboardRoutes)],
  exports: [ RouterModule ]
})
export class DashboardRoutingModule {}
</code>```

EDIT:

tsconfig.json

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}
</code>```

答: Turns out I had a call that would hijack the router and redirect to inject parameters. Before the update this.router.url would return the correct url. Now for some reason it always returns root.</p>

Body:
When reloading the page (F5 or typing the url into the address bar), the current route is not kept. I have a two separate modules, the main app module and then a dashboard module. These modules each have their own routing modules that they import. If I navigate to http://localhost it redirects to http://localhost/dashboard/overview but if I navigate to any other route though the address bar it redirects back to http://localhost/dashboard/overview

Clicking on any links on the pages that use routerlinks work fine.

I am using the latest angular 4 with the latest angular-cli. It worked before the update from angular 2 to angular 4.

Previous version of libraries:

"@angular/core": "^2.3.1",
"@angular/router": "^3.3.1",

Current version of libraries:

"@angular/core": "^4.0.0",
"@angular/router": "^4.0.0",

app-routing.module.ts

const routes: Routes = [
  {
    path: '',
    redirectTo: '/dashboard/overview',
    pathMatch: 'full'
  },
  {path: 'logs', component: LogsComponent},
  {path: 'search', component: SearchComponent},
  {path: 'metrics', component: MetricsComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

dashboard-routing.module.ts

const dashboardRoutes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    children: [
      {path: 'overview', component: OverviewComponent},
      {path: 'partition/:type', component: DashboardPartitionComponent},
      {path: 'latency', component: DashboardLatencyComponent},
    ]
  }
];

@NgModule({
  imports: [ RouterModule.forChild(dashboardRoutes)],
  exports: [ RouterModule ]
})
export class DashboardRoutingModule {}

EDIT:

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}


问:
adding variables numical values (newb question)
Yesterday i had a look at how to set values of variables from nummbers stored in external txt files

the variables then needed to be added up so i used trial and  error first

((XVAL) + (NEWVAL))

assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20

VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30

yep its a newb question could anyone explain how to achieve what im affter

答:
You want to cast them to a number first.
Try CDbl.
See http://msdn.microsoft.com/en-us/library/Aa263426 for more.

edit: Oops, thought you were talking about VBA.
Try using Double.Parse(YOURVALUE) if you're talking about VB.NET.


问:
Compile Error on VBA code to Long
I currently have the code below. I need to run it from cell S1 to cell S5000 and everything in between. What I had done was written code for every single cell for 1 to 5000 but then when I pasted the code into the worksheet I got the message, "Compile error: Procedure too large". Is there a workaround so I can run the code for every cell to 5000 or even more if needed?

Thank you for your help!

```<code>Sub CopyPriceOver()
Application.ScreenUpdating = False

If Range("S1") = 1 Then
Range("S1").Select
Range("S1").Select
Call ScheduleCopyPriceOver

ElseIf Range("S2") = 2 Then
Range("L2").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

ElseIf Range("S3") = 3 Then
Range("L3").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

.
.
.
.

ElseIf Range("S5000") = 5000 Then
Range("5000").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

Else

Call ScheduleCopyPriceOver
End If
</code>```

答:
You can use something like the following. However, I don't know what 'ScheduleCopyPriceOver' is, so uncomment that line. AND your first example used column 'S', but then you used column 'L'. Should they all be 'L'????</p>

```<code>Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Sheet5")
Application.ScreenUpdating = False

For lRow = 1 To 5000
    If ws.Cells(lRow, 12) = lRow Then
        ws.Cells(lRow, 12).Select
        'Call ScheduleCopyPriceOver
    End If
Next lRow
</code>```

Title: Compile Error on VBA code to Long

Body:
I currently have the code below. I need to run it from cell S1 to cell S5000 and everything in between. What I had done was written code for every single cell for 1 to 5000 but then when I pasted the code into the worksheet I got the message, "Compile error: Procedure too large". Is there a workaround so I can run the code for every cell to 5000 or even more if needed?

Thank you for your help!

Sub CopyPriceOver()
Application.ScreenUpdating = False

If Range("S1") = 1 Then
Range("S1").Select
Range("S1").Select
Call ScheduleCopyPriceOver

ElseIf Range("S2") = 2 Then
Range("L2").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

ElseIf Range("S3") = 3 Then
Range("L3").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

.
.
.
.

ElseIf Range("S5000") = 5000 Then
Range("5000").Select
ActiveCell.FormulaR1C1 = "ready"
Range("L1").Select
Call ScheduleCopyPriceOver

Else

Call ScheduleCopyPriceOver
End If

Body:
You can use something like the following. However, I don't know what 'ScheduleCopyPriceOver' is, so uncomment that line. AND your first example used column 'S', but then you used column 'L'. Should they all be 'L'????

Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Sheet5")
Application.ScreenUpdating = False

For lRow = 1 To 5000
    If ws.Cells(lRow, 12) = lRow Then
        ws.Cells(lRow, 12).Select
        'Call ScheduleCopyPriceOver
    End If
Next lRow


问:
Kubernetes: single POD with many container, or many Pod with single container
I've rather a teoretical question which I can't answer  with the reousrces found online. The question is: what's the rule to decide how to compose containers in POD? . Let me explain with an example.

I've these microservices:

Authentication

Authorization

Serving content

(plus) OpenResty to forward the calls form one to the other and orhcestarate the flow. (is there a possibility to do so natively in K8?, it seems to have services base on nginx+lua, but not sure how it works)

For the sake of the example I avoid Databases and co, I assume they are external and not managed by kubernetes

Now, what's the correct way here LEFT or RIGHT of the image?

LEFT : this seems easier to make it working, everything works on "localhost" , the downside is that it looses a bit the benefit of the microservices. For example, if the auth become slows and it would need more instances, I've to duplicate the whole pod and not just that service.

RIGHT seems a bit more complex, need services to expose each POD to the other PODs. Yet, here, I could duplicate auth as I need without duplicating the other containers. On the other hand I'll have a lot of pods since each pod is basically a container.

答: Right image is better option. Easier management, upgrades, scaling.</p>


问:
Fastest way to compare 2 lists objects
I allow a user to download some data to csv. They can then edit some columns and then upload it back. I need a speed efficient way to compare certain columns between like objects to see what changed.

Currently I pull the original data from the DB and make it a list so it's all in memory. There is about 100k items so it's not that bad. That part takes less than a second. Then I load in the csv file and put it to list. Both lists have the same class type.

Then I loop over the csv data (as they probably removed some rows which they didn't change but they could still have changed a lot of rows). For each row in the csv list I query the list that came from the DB to find that object. Now I have the csv object and the object from the database as the same structure. Then I run it through a custom object compare function that looks at certain columns to see if anything changed.

If something did change I have to validate what they entered is a valid value by query another reference list for that column. If it's not valid I write it out to an exceptions list. At the end if there are no exceptions I save to db. If there are exceptions I don't save anything and I show them the list of errors.

The detail compare provides a list of columns and the old vs new values that changed. I need this to query the reference list to make sure the new value is valid before I make the change. It's fairly inefficient but it gives great detail to the user about what may be an issue with an upload which is very valuable.

This is very slow. I'm looking for ways to speed it up while still being able to give the user detailed information about why it may have failed so they can correct it.

```<code>// get all the new records from the csv
            var newData = csv.GetRecords<MyTable>().ToArray();

            // select all data from database to list
            var origData = ctx.MyTable.Select(s => s).ToList();

            // look for any changes in the new data and update the database. note we are looping over the new data so if they removed some data from the csv file it just won't loop over those and they won't change
            foreach (var d in newData)
            {
                // find data so we can compare between new (csv) and current (from db) to see what possibly changed
                var oData = (from o in origData
                             where o.id == d.id
                             select o).FirstOrDefault();

                // only the columns in the updatableColumns list are compared
                var diff = d.DetailedCompare(oData, comparableColumns.ToList());
                if (diff.Count > 0)
                {
                    // even though there are differences between the csv record and db record doesn't mean what the user input is valid. only existing ref data is valid and needs to be checked before a change is made
                    bool changed = false;

                    // make a copy of this original data and we'll check after if we actually were able to make a change to it (was the value provided valid)
                    var data = CopyRecord(oData);

                    // update this record's data fields that have changed with the new data
                    foreach (var v in diff)
                    {
                        // special check for setting a value to NULL as its always valid to do this but wouldn't show up in ref data to pass the next check below
                        if (v.valA == null)
                        {
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        // validate that the value for this column is in the ref table before allowing an update. note exception if not so we can tell the user
                        else if (refData[v.Prop].Where(a => a.value == v.valA.ToString()).FirstOrDefault() != null)
                        {
                            // update the current objects values with the new objects value as it changed and is a valid value based on the ref data defined for that column
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        else
                        {
                            // the value provided isn't valid for this column so note this to tell the user
                            exceptions.Add(string.Format("Error: ID: {0}, Value: '{1}' is not valid for column [{2}]. Add the reference data if needed and re-import.", d.id, v.valA, v.Prop));
                        }
                    }

                    // we only need to reattach and save off changes IF we actually changed something to a valid ref value and we had no exceptions for this record
                    if (changed && exceptions.Count == 0)
                    {
                        // because our current object was in memory we will reattached it to EF so we can mark it as changed and SaveChanges() will write it back to the DB
                        ctx.MyTable.Attach(oData);
                        ctx.Entry(oData).State = EntityState.Modified;

                        // add a history record for the change to this product
                        CreateHistoryRecord(data, user);
                    }
                }
            }

            // wait until the very end before making DB changed. we don't save anything if there are exceptions or nothing changed
            if (exceptions.Count == 0)
            {
                ctx.SaveChanges();
            }
</code>```

答:
The first big win would be to put your data in a dictionary so you can get to the desired value quickly by ID, without having to search for the object through thousands of objects. I'm pretty sure it'll be faster.

Beyond that I suggest you run your code through a profiler to determine exactly which parts are the slowest. It's entirely possible that DetailedCompare() does something that's terribly slow but may not be obvious.

Title: Fastest way to compare 2 lists objects

Body:
I allow a user to download some data to csv. They can then edit some columns and then upload it back. I need a speed efficient way to compare certain columns between like objects to see what changed.

Currently I pull the original data from the DB and make it a list so it's all in memory. There is about 100k items so it's not that bad. That part takes less than a second. Then I load in the csv file and put it to list. Both lists have the same class type.

Then I loop over the csv data (as they probably removed some rows which they didn't change but they could still have changed a lot of rows). For each row in the csv list I query the list that came from the DB to find that object. Now I have the csv object and the object from the database as the same structure. Then I run it through a custom object compare function that looks at certain columns to see if anything changed.

If something did change I have to validate what they entered is a valid value by query another reference list for that column. If it's not valid I write it out to an exceptions list. At the end if there are no exceptions I save to db. If there are exceptions I don't save anything and I show them the list of errors.

The detail compare provides a list of columns and the old vs new values that changed. I need this to query the reference list to make sure the new value is valid before I make the change. It's fairly inefficient but it gives great detail to the user about what may be an issue with an upload which is very valuable.

This is very slow. I'm looking for ways to speed it up while still being able to give the user detailed information about why it may have failed so they can correct it.

// get all the new records from the csv
            var newData = csv.GetRecords<MyTable>().ToArray();

            // select all data from database to list
            var origData = ctx.MyTable.Select(s => s).ToList();

            // look for any changes in the new data and update the database. note we are looping over the new data so if they removed some data from the csv file it just won't loop over those and they won't change
            foreach (var d in newData)
            {
                // find data so we can compare between new (csv) and current (from db) to see what possibly changed
                var oData = (from o in origData
                             where o.id == d.id
                             select o).FirstOrDefault();

                // only the columns in the updatableColumns list are compared
                var diff = d.DetailedCompare(oData, comparableColumns.ToList());
                if (diff.Count > 0)
                {
                    // even though there are differences between the csv record and db record doesn't mean what the user input is valid. only existing ref data is valid and needs to be checked before a change is made
                    bool changed = false;

                    // make a copy of this original data and we'll check after if we actually were able to make a change to it (was the value provided valid)
                    var data = CopyRecord(oData);

                    // update this record's data fields that have changed with the new data
                    foreach (var v in diff)
                    {
                        // special check for setting a value to NULL as its always valid to do this but wouldn't show up in ref data to pass the next check below
                        if (v.valA == null)
                        {
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        // validate that the value for this column is in the ref table before allowing an update. note exception if not so we can tell the user
                        else if (refData[v.Prop].Where(a => a.value == v.valA.ToString()).FirstOrDefault() != null)
                        {
                            // update the current objects values with the new objects value as it changed and is a valid value based on the ref data defined for that column
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        else
                        {
                            // the value provided isn't valid for this column so note this to tell the user
                            exceptions.Add(string.Format("Error: ID: {0}, Value: '{1}' is not valid for column [{2}]. Add the reference data if needed and re-import.", d.id, v.valA, v.Prop));
                        }
                    }

                    // we only need to reattach and save off changes IF we actually changed something to a valid ref value and we had no exceptions for this record
                    if (changed && exceptions.Count == 0)
                    {
                        // because our current object was in memory we will reattached it to EF so we can mark it as changed and SaveChanges() will write it back to the DB
                        ctx.MyTable.Attach(oData);
                        ctx.Entry(oData).State = EntityState.Modified;

                        // add a history record for the change to this product
                        CreateHistoryRecord(data, user);
                    }
                }
            }

            // wait until the very end before making DB changed. we don't save anything if there are exceptions or nothing changed
            if (exceptions.Count == 0)
            {
                ctx.SaveChanges();
            }


问:
How do I learn Cognos by myself without data to work on?
I have done a course in data warehousing and data mining, and I am interested in going the Cognos business intelligence way. However, I need to practice on data which I cannot find. How do I get myself aquainted better with Cognos? I need sample data to work on. Where do I find it ?</p>

答:
Why not just use the sample databases that come WITH Cognos 8? If you have access to a Cognos 8 BI installation, you can install the Great Outdoor sample databases which also come with Framework Manager (FM) models and packages for Cognos 8 deployment.

Instructions on installing the samples can be found on the IBM site: Install the IBM Cognos 8 Samples .


问:
Working with coordinates in android for different screen sizes?
In an application, let suppose we have an image of a car onto which we have mark a damage point. We can mark this point anywhere of the image as shown below.

Suppose we have marked this point on a device of screen size “5 inches” and then we calculated the coordinates of this point and sent it to the server.
Now the user is using another device of screen size “8 inches”. User wants to see those marked points in his new device. But he is not able to see the appropriate position of the points after fetching the actual value from the server.

答:
Get the height and width of the screen

```<code>    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;
</code>```

Then calculate the coordinates of the image, I assume you are currently doing this in the form of an [x,y] array

Then simply find the ratio across all screen sizes by doing:

```<code>float x_ratio = coordinatesArray[0]/width
float y_ratio = coordinatesArray[1]/height
</code>```

This will result in something along the lines of 0.25 and 0.34 (or something like that depending on the screen size)

You then simply create an array including these two floats and pass this along to the server.

Body:
Get the height and width of the screen

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

Then calculate the coordinates of the image, I assume you are currently doing this in the form of an [x,y] array

Then simply find the ratio across all screen sizes by doing:

float x_ratio = coordinatesArray[0]/width
float y_ratio = coordinatesArray[1]/height

This will result in something along the lines of 0.25 and 0.34 (or something like that depending on the screen size)

You then simply create an array including these two floats and pass this along to the server.


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
How about this simple observation based approach? Split it into two lists using list comprehension and then just zip them in the order you want it.

Using list comprehension

```<code>In [18]: neg_list = [idx for idx, el in enumerate(results) if el < 0]
In [19]: pos_list = [idx for idx, el in enumerate(results) if el > 0]

In [20]: neg_list
Out[20]: [2, 4, 5]

In [21]: pos_list
Out[21]: [0, 1, 3]

In [22]: list(zip(pos_list, neg_list))
Out[22]: [(0, 2), (1, 4), (3, 5)]
</code>```

You can also modify what index you need from the order you zip them.

NumPy Version:
  For larger lists (or arrays equivalently), the numpy version should be much faster.

```<code>In [30]: res = np.array(results)
In [38]: pos_idx = np.where(res > 0)[0]
In [39]: pos_idx
Out[39]: array([0, 1, 3])

In [40]: neg_idx = np.where(res < 0)[0]
In [42]: neg_idx
Out[42]: array([2, 4, 5])

In [44]: list(zip(pos_idx, neg_idx))
Out[44]: [(0, 2), (1, 4), (3, 5)]

# If you want to avoid using zip, then
# just use np.vstack and transpose the result
In [59]: np.vstack((pos_idx, neg_idx)).T
Out[59]:
array([[0, 2],
       [1, 4],
       [3, 5]])
</code>```

P.S.: You could also use generator comprehension to achieve the same result but please note that it will be exhausted after you convert the generator to list once.

Using generator comprehension

```<code>In [24]: neg_gen = (idx for idx, el in enumerate(results) if el < 0)
In [25]: pos_gen = (idx for idx, el in enumerate(results) if el > 0)

In [27]: list(zip(pos_gen, neg_gen))
Out[27]: [(0, 2), (1, 4), (3, 5)]

# on 2nd run, there won't be any element in the generator.
In [28]: list(zip(pos_gen, neg_gen))
Out[28]: []
</code>```

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
How about this simple observation based approach? Split it into two lists using list comprehension and then just zip them in the order you want it.

Using list comprehension

In [18]: neg_list = [idx for idx, el in enumerate(results) if el < 0]
In [19]: pos_list = [idx for idx, el in enumerate(results) if el > 0]

In [20]: neg_list
Out[20]: [2, 4, 5]

In [21]: pos_list
Out[21]: [0, 1, 3]

In [22]: list(zip(pos_list, neg_list))
Out[22]: [(0, 2), (1, 4), (3, 5)]

You can also modify what index you need from the order you zip them.

NumPy Version:
  For larger lists (or arrays equivalently), the numpy version should be much faster.

In [30]: res = np.array(results)
In [38]: pos_idx = np.where(res > 0)[0]
In [39]: pos_idx
Out[39]: array([0, 1, 3])

In [40]: neg_idx = np.where(res < 0)[0]
In [42]: neg_idx
Out[42]: array([2, 4, 5])

In [44]: list(zip(pos_idx, neg_idx))
Out[44]: [(0, 2), (1, 4), (3, 5)]

# If you want to avoid using zip, then
# just use np.vstack and transpose the result
In [59]: np.vstack((pos_idx, neg_idx)).T
Out[59]:
array([[0, 2],
       [1, 4],
       [3, 5]])

P.S.: You could also use generator comprehension to achieve the same result but please note that it will be exhausted after you convert the generator to list once.

Using generator comprehension

In [24]: neg_gen = (idx for idx, el in enumerate(results) if el < 0)
In [25]: pos_gen = (idx for idx, el in enumerate(results) if el > 0)

In [27]: list(zip(pos_gen, neg_gen))
Out[27]: [(0, 2), (1, 4), (3, 5)]

# on 2nd run, there won't be any element in the generator.
In [28]: list(zip(pos_gen, neg_gen))
Out[28]: []


问:
Visual Studio Task Runner Explorer Extension does not recognize gulpfile.js
I am trying to use the VS Task Runner Explorer to run gulp as a step during the build.

Here are the steps I took:
1) Downloaded node.js
2) ran: npm install gulp -g from the command line
3) downloaded and installed task runner
4) closed and reopened visual studio

I can now access the task runner window in visual studio but when I right click on my gulpfile.js, there is no option to open it in the task runner explorer.

All help is appreciated, thanks in advance.

答:
[I am not positive about this solution but it sounds plausible for my case.]

If you have "Lightweight solution load" activated, expand the web project.

TL;DR

My fresh VS2017 did not show anything in the Task runner explorer.  But when I expanded the web project Task runner explorer was populated and gulp files run.

I have "Lightweight solution load" activated and the web project was not loaded before I expanded it.


问:
How to get NSDate day, month and year in integer format?
I want to get the day, month and year components of NSDate in integer form i.e. if the date is 1/2/1988 then I should get 1, 2 and 1988 separately as an integer. How can I do this in iOS? I found the similar question but the method descriptionWithCalendarFormat: gives a warning and seems to be deprecated by now.

答:
Put it in an extension and live your life

```<code>extension Date{
    var day:Int {return Calendar.current.component(.day, from:self)}
    var month:Int {return Calendar.current.component(.month, from:self)}
    var year:Int {return Calendar.current.component(.year, from:self)}
}
Date().day//22
Date().month//4
Date().year//2017
</code>```

Swift 3.0 (It's an iteration of previous answers, but solves it for all your future app projects)

Body:
Put it in an extension and live your life

extension Date{
    var day:Int {return Calendar.current.component(.day, from:self)}
    var month:Int {return Calendar.current.component(.month, from:self)}
    var year:Int {return Calendar.current.component(.year, from:self)}
}
Date().day//22
Date().month//4
Date().year//2017

Swift 3.0 (It's an iteration of previous answers, but solves it for all your future app projects)


问:
spring validation: cleanest way to makeup accompanying labels of the validated input
I'm validating the input field that's bound to path. I'm using hibernate-validator 4 for this.
Now I'd like to highlight the age label so it pops out of the page (bold, red colour etc.).
However I'm wondering what the cleanest way to do this is.

<spring:hasBindErrors name="*"/> seems to be for the whole form object instead of for a specific field. Any input is appreciated.

答:
Spring provides special jsp tags for forms, which support this task (highlighing in case of error):

For example this jsp

```<code>...
<%@ taglib prefix='form' uri='http://www.springframework.org/tags/form'%>
...
<form:form method="post"
           commandName="myCommand">
  <form:input path="name"
              cssClass="normalLayout"
              cssErrorClass="normalLayout error"/>
  <form:errors path="name"
               cssClass="errorMessage"/>
</form:form>
...
</code>```

In this case: the input field uses the css class "normalLayout" if every thing is ok, and the css classes "normalLayout" and "name" if there is a validation error for the field.

form:errors is to print the error message generated while validation.

@see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib

Body:
Spring provides special jsp tags for forms, which support this task (highlighing in case of error):

For example this jsp

...
<%@ taglib prefix='form' uri='http://www.springframework.org/tags/form'%>
...
<form:form method="post"
           commandName="myCommand">
  <form:input path="name"
              cssClass="normalLayout"
              cssErrorClass="normalLayout error"/>
  <form:errors path="name"
               cssClass="errorMessage"/>
</form:form>
...

In this case: the input field uses the css class "normalLayout" if every thing is ok, and the css classes "normalLayout" and "name" if there is a validation error for the field.

form:errors is to print the error message generated while validation.

@see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib


问:
Add native files from NuGet package to project output directory
I'm trying to create NuGet package for a .Net assembly which does pinvoke to a native win32 dll.
I need to pack both the assembly and the native dll with the assembly added to the project references (no problem at this part) and the native dll should be copied into the project output directory or some other relative directory.

My questions are:

How do I pack the native dll without visual studio trying to add it into the references list?

Do I have to write an install.ps1 for copying the native dll? If so how can I access the package content for copying it?

答:
If anyone else stumbles across this.

The .targets filename MUST equal the NuGet Package Id

Anything else wont work.

Credits go to:
https://sushihangover.github.io/nuget-and-msbuild-targets/

I should've read more thoroughly as its actually noted here. Took me ages..

Add a custom <PackageName>.targets


问:
Which Native iOS API can be used to stream and play audio data in my application?
I'm interested in building a iOS application similar to wynk.The app will be having a list of songs. On clicking any option, it will start streaming that music file from the server. I don't want to use any third Party API. Any help/ suggestion will be of great help. I'm using xCode 8.0 with swift 3.</p>

答: You can use AVPlayer which is a controller object used to manage the playback and timing of a media asset. It provides the interface to control the player’s transport behavior such as its ability to play, pause, change the playback rate, and seek to various points in time within the media’s timeline. You can use an AVPlayer to play local and remote file-based media, such as QuickTime movies and MP3 audio files, as well as audiovisual media served using HTTP Live Streaming.</p>


问:
Apache mod_rewrite and hide source file simultaneously
I have a local .htaccess file on a shared hosting service that contains an individual rewrite rule to map /services to the file services.html within the document root.

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^services$ services.html [L]
</code>```

How can I prevent consumers accessing /services.html directly (if they sniffed around for it) and have them receive a 404 HTTP response instead?  I do not want any consumer knowing I have a services.html file at all, and that includes sending 302 responses that would tie back to the original /services resource.

However, I tried setting up a rule to return a 404 for /services.html but this resulted in /services also returning the 404 too.

In summary, I want consumers to only be able to see /services endpoint (200 OK) and never know what is mapped behind it, or bypass the publicly chosen endpoint (services.html return 404 Not Found).

答:
Just 'hide' your services.html in the first place and use [P]-parameter for proxying the request.

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^/services$ http://yourdomain.com/<path-to-the-file>/services.html [P,L]
</code>```

That takes a request like http://yourdomain.com/services and returns http://yourdomain.com//services.html without showing the user where it came from, the browser will still show /services

Body:
I have a local .htaccess file on a shared hosting service that contains an individual rewrite rule to map /services to the file services.html within the document root.

RewriteEngine On
RewriteBase /
RewriteRule ^services$ services.html [L]

How can I prevent consumers accessing /services.html directly (if they sniffed around for it) and have them receive a 404 HTTP response instead?  I do not want any consumer knowing I have a services.html file at all, and that includes sending 302 responses that would tie back to the original /services resource.

However, I tried setting up a rule to return a 404 for /services.html but this resulted in /services also returning the 404 too.

In summary, I want consumers to only be able to see /services endpoint (200 OK) and never know what is mapped behind it, or bypass the publicly chosen endpoint (services.html return 404 Not Found).

Body:
Just 'hide' your services.html in the first place and use [P]-parameter for proxying the request.

RewriteEngine On
RewriteBase /
RewriteRule ^/services$ http://yourdomain.com/<path-to-the-file>/services.html [P,L]

That takes a request like http://yourdomain.com/services and returns http://yourdomain.com//services.html without showing the user where it came from, the browser will still show /services


问:
"Comparison method violates its general contract!"
Can someone explain me in simple terms, why does this code throw an exception, "Comparison method violates its general contract!", and how do I fix it?</p>

```<code>private int compareParents(Foo s1, Foo s2) {
    if (s1.getParent() == s2) return -1;
    if (s2.getParent() == s1) return 1;
    return 0;
}
</code>```

答:
In my case I was doing something like the following:

```<code>if (a.someField == null) {
    return 1;
}

if (b.someField == null) {
    return -1;
}

if (a.someField.equals(b.someField)) {
    return a.someOtherField.compareTo(b.someOtherField);
}

return a.someField.compareTo(b.someField);
</code>```

What I forgot to check was when both a.someField and b.someField are null.

Body:
Can someone explain me in simple terms, why does this code throw an exception, "Comparison method violates its general contract!", and how do I fix it?

private int compareParents(Foo s1, Foo s2) {
    if (s1.getParent() == s2) return -1;
    if (s2.getParent() == s1) return 1;
    return 0;
}

Body:
In my case I was doing something like the following:

if (a.someField == null) {
    return 1;
}

if (b.someField == null) {
    return -1;
}

if (a.someField.equals(b.someField)) {
    return a.someOtherField.compareTo(b.someOtherField);
}

return a.someField.compareTo(b.someField);

What I forgot to check was when both a.someField and b.someField are null.


问:
Disable Thread.sleep()
I want to disable possibility of using Thread.sleep() in a java project and use my own method instead:

```<code>sleep(int time, String info)
</code>```

That will wait for given amount of time, and print info why is waiting necessary here.

Is disabling Thread.sleep() possible?

If yes, what's best method to do so?

答:
You can use AOP to intercept calls to Thread.sleep() and "redirect" call to your one via aroundAdvice. When original Thread.sleep() is invoked, a "default cause" is added. This one shows an example about how you can use it (remember to create a AspectJ project, or Aspects will not work):

SleepAspect.java

```<code>package org.norsam.so.sleep

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class SleepAspect
{
    @Around("call (* java.lang.Thread.sleep(..) )")
    public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable
    {
        StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
        Long ms = (Long) point.getArgs()[0];
        String m = ste.getMethodName();
        String c = ste.getClassName();
        String skip = SleepClass.class.getName();
        if (c.equals(skip) && m.equals("sleep")) {
            System.out.println("sleep well for " + ms + "ms!");
        } else {
            SleepClass.sleep(ms, "Thread.sleep invoked in " + c + "." + m + ", no cause present!");
        }
        Object toret = point.proceed();
        return toret;
    }

}
</code>```

SleepClass.java

```<code>package org.norsam.so.sleep

public class SleepClass {

    public static void sleep(long l, String cause) {
        System.out.println("CAUSE: " + cause);
        try {
            Thread.sleep(l);
        } catch (InterruptedException e) {
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SleepClass.sleep(1000, "I love to sleep 1000");
        Thread.sleep(2000L);
        System.out.println("Bye");
    }

}
</code>```

When you run it, you receive something like

```
CAUSE: I love to sleep 1000
sleep well for 1000ms!
CAUSE: Thread.sleep invoked in org.norsam.so.sleep.SleepClass.main, no cause present!
sleep well for 2000ms!
Bye
```

Title: Disable Thread.sleep()

Body:
I want to disable possibility of using Thread.sleep() in a java project and use my own method instead:

sleep(int time, String info)

That will wait for given amount of time, and print info why is waiting necessary here.

Is disabling Thread.sleep() possible?

If yes, what's best method to do so?

Body:
You can use AOP to intercept calls to Thread.sleep() and "redirect" call to your one via aroundAdvice. When original Thread.sleep() is invoked, a "default cause" is added. This one shows an example about how you can use it (remember to create a AspectJ project, or Aspects will not work):

SleepAspect.java

package org.norsam.so.sleep

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class SleepAspect
{
    @Around("call (* java.lang.Thread.sleep(..) )")
    public Object aroundAdvice(ProceedingJoinPoint point) throws Throwable
    {
        StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
        Long ms = (Long) point.getArgs()[0];
        String m = ste.getMethodName();
        String c = ste.getClassName();
        String skip = SleepClass.class.getName();
        if (c.equals(skip) && m.equals("sleep")) {
            System.out.println("sleep well for " + ms + "ms!");
        } else {
            SleepClass.sleep(ms, "Thread.sleep invoked in " + c + "." + m + ", no cause present!");
        }
        Object toret = point.proceed();
        return toret;
    }

}

SleepClass.java

package org.norsam.so.sleep

public class SleepClass {

    public static void sleep(long l, String cause) {
        System.out.println("CAUSE: " + cause);
        try {
            Thread.sleep(l);
        } catch (InterruptedException e) {
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SleepClass.sleep(1000, "I love to sleep 1000");
        Thread.sleep(2000L);
        System.out.println("Bye");
    }

}

When you run it, you receive something like

CAUSE: I love to sleep 1000
sleep well for 1000ms!
CAUSE: Thread.sleep invoked in org.norsam.so.sleep.SleepClass.main, no cause present!
sleep well for 2000ms!
Bye


问:
Cannot connect to Socket IO with Node, Express, and EJS
I am not connecting to Socket IO in my node app and I believe it has something to do with my EJS configuration and how I am rendering index.ejs and layout.ejs files:

When I connect to Socket IO I want to console log that a user has been connected:

```<code>io.sockets.on('connection', (socket) => {
  console.log('user is connected')

  socket.on('send-message', (data) => {
    io.sockets.emit('new-message', data)
  })
</code>```

Here is how I handle the backend when I go to localhost:3000 here is my code:

```<code>app.get('/', (req, res) => {
  res.render('index')
})
</code>```

But when I go to localhost:3000 it does not console that a user has been connect to Socket IO

I tried this as well:

```<code>app.get('/', (req, res) => {
  res.sendFile('index.ejs', {root:__dirname})
})
</code>```

and also

```<code>app.get('/', (req, res) => {
  res.sendFile(process.env.PWD+'/client/views/index.ejs')
})
</code>```

but I still do not connect.

Any ideas what I need to do?

More Code:

server/app.js

```<code>const
    express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    ejs = require('ejs'),
    ejsLayouts = require('express-ejs-layouts'),
    mongoose = require('mongoose'),
    ...
    ...

// environment port
const
    port = process.env.PORT || 3000,
    mongoConnectionString = process.env.MONGODB_URL || 'mongodb://localhost/context-app'

    mongoose.connect(mongoConnectionString, (err) => {
      console.log(err || "Connected to MongoDB (context-app)")
    })

// ejs configuration
app.set('view engine', 'ejs')
app.set('views', process.env.PWD+'/client/views');
app.use(ejsLayouts)

app.get('/', (req, res) => {
  res.render('index')
})

io.sockets.on('connection', (socket) => {
  console.log('user is connected');

  socket.on('send-message', (data) => {
    io.sockets.emit('new-message', data)
  })
})

server.listen(port, (err) => {
  console.log(err || 'listening on my very special port ' + port)
})
</code>```

client/views/layout.ejs

```<code><!-- /views/layout.ejs -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>React Intro</title>
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script>...</script>
  <script>...</script>
  <script>
    var socket = io();
  </script>
</head>
<body>
  <% include partials/nav %>
    <div class="container">
        <%- body %>
    </div>
</body>
</html>
</code>```

client/views/index.ejs

```<code><div id="main"></div>

<script type="text/babel" src="../app.js"></script>
</code>```

EDIT: SOLUTION

The problem was on the client side: I simply forgot to load the Socket IO script:

答:
Make sure the you are loading the socket.io script on the client side:</p>

```<code><script src="/socket.io/socket.io.js" charset="utf-8"></script>
</code>```

Body:
I am not connecting to Socket IO in my node app and I believe it has something to do with my EJS configuration and how I am rendering index.ejs and layout.ejs files:

When I connect to Socket IO I want to console log that a user has been connected:

io.sockets.on('connection', (socket) => {
  console.log('user is connected')

  socket.on('send-message', (data) => {
    io.sockets.emit('new-message', data)
  })

Here is how I handle the backend when I go to localhost:3000 here is my code:

app.get('/', (req, res) => {
  res.render('index')
})

But when I go to localhost:3000 it does not console that a user has been connect to Socket IO

I tried this as well:

app.get('/', (req, res) => {
  res.sendFile('index.ejs', {root:__dirname})
})

and also

app.get('/', (req, res) => {
  res.sendFile(process.env.PWD+'/client/views/index.ejs')
})

but I still do not connect.

Any ideas what I need to do?

More Code:

server/app.js

const
    express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server),
    ejs = require('ejs'),
    ejsLayouts = require('express-ejs-layouts'),
    mongoose = require('mongoose'),
    ...
    ...

// environment port
const
    port = process.env.PORT || 3000,
    mongoConnectionString = process.env.MONGODB_URL || 'mongodb://localhost/context-app'

    mongoose.connect(mongoConnectionString, (err) => {
      console.log(err || "Connected to MongoDB (context-app)")
    })

// ejs configuration
app.set('view engine', 'ejs')
app.set('views', process.env.PWD+'/client/views');
app.use(ejsLayouts)

app.get('/', (req, res) => {
  res.render('index')
})

io.sockets.on('connection', (socket) => {
  console.log('user is connected');

  socket.on('send-message', (data) => {
    io.sockets.emit('new-message', data)
  })
})

server.listen(port, (err) => {
  console.log(err || 'listening on my very special port ' + port)
})

client/views/layout.ejs

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>React Intro</title>

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

  <% include partials/nav %>

        <%- body %>

client/views/index.ejs

EDIT: SOLUTION

The problem was on the client side: I simply forgot to load the Socket IO script:

Body:
Make sure the you are loading the socket.io script on the client side:

<script src="/socket.io/socket.io.js" charset="utf-8"></script>


问:
In WPF 3D, How to determine whether a Cube's vertex is visible
We know that the cube has eight vertices, and we can easily build a cube using the Media3D of WPF. But how to determine whether the vertex of the cube is visible.

Just as the following pictures show, the red vertex should be invisible, while the others should be visible.

答:
If any of the faces connected to the vertex has a normal facing the camera (see back face culling), the vertex is visible. This should be pretty quick to calculate.

If you need actual visibility in a complex scene, some other solution like stencil buffer as TiberiumFusion suggested should be used.

ContentLicense: CC BY-SA 4.0


问:
How to make sure only a single checkbox remains checked out of many?
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">

    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
</div></code>```

答:
The simplest way to achieve this is to call prop('checked', false) on all the other checkboxes when any one of them is clicked, like this:

$(".duty").first().prop('checked', true).end().on('click', function(event) {
  $('.duty').not(this).prop('checked', false);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
</div></code>```

Body:
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})

  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0">

  </fieldset>

Body:
The simplest way to achieve this is to call prop('checked', false) on all the other checkboxes when any one of them is clicked, like this:

$(".duty").first().prop('checked', true).end().on('click', function(event) {
  $('.duty').not(this).prop('checked', false);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label>
        <span>Duty:</span>
        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0">
      </label>
    </div>
  </fieldset>
</div>


问:
After building TensorFlow from source, seeing libcudart.so and libcudnn errors
I'm building TensorFlow from source code.  The build appears to succeed; however, when my TensorFlow program invokes import tensorflow, one or both of the following errors appear:

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

ImportError: libcudnn.5: cannot open shared object file: No such file or directory

答:
First, for the following error:

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

make sure your LD_LIBRARY_PATH includes your lib64 directory in whichever path you installed your cuda package in. You can do this by adding an export line in your .bashrc. For Omar, it looked like the following:

I fixed this just adding the cuda path to my .bashrc

export LD_LIBRARY_PATH=/usr/local/cuda/lib64/

For me, I had to do Omar's line and also:
 export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/
because I have two directories involving cuda (probably not the best).

Second, are you sure you installed cuDNN? Note that this is different from the regular cuda package. You will need to register, then download and install the package from the following page:
https://developer.nvidia.com/cudnn

Third, I had this same problem:

ImportError: libcudnn.5: cannot open shared object file: No such file or directory

It turns out there is no libcudnn.5 in my /usr/local/cuda/lib64 or /usr/local/cuda-8.0/lib64 directories. However, I do have a libcudnn.so.6.* file. To solve the problem, I created a soft link:

```<code>ln -s libcudnn.so.6.* libcudnn.so.5
</code>```

in my /usr/local/cuda/lib64 directory. Now everything works for me. Your directory might be different if you already had cuDNN, and your libcudnn.so.6.* might be a different version, so check that.

Body:
First, for the following error:

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

make sure your LD_LIBRARY_PATH includes your lib64 directory in whichever path you installed your cuda package in. You can do this by adding an export line in your .bashrc. For Omar, it looked like the following:

I fixed this just adding the cuda path to my .bashrc

export LD_LIBRARY_PATH=/usr/local/cuda/lib64/

For me, I had to do Omar's line and also:
 export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64/
because I have two directories involving cuda (probably not the best).

Second, are you sure you installed cuDNN? Note that this is different from the regular cuda package. You will need to register, then download and install the package from the following page:
https://developer.nvidia.com/cudnn

Third, I had this same problem:

ImportError: libcudnn.5: cannot open shared object file: No such file or directory

It turns out there is no libcudnn.5 in my /usr/local/cuda/lib64 or /usr/local/cuda-8.0/lib64 directories. However, I do have a libcudnn.so.6.* file. To solve the problem, I created a soft link:

ln -s libcudnn.so.6.* libcudnn.so.5

in my /usr/local/cuda/lib64 directory. Now everything works for me. Your directory might be different if you already had cuDNN, and your libcudnn.so.6.* might be a different version, so check that.


问:
Where is Monogame "while" or "for" loop
I'm more or less new with C# and game dev in general,

I was looking at the Monogame framework and I was wondering where is the LOOP.

I mean, from what I know, to make a LOOP you have to make a WHILE(), a FOR() or by recursivity and I can't find any in Monogame, so where is the GAMELOOP ?

I used some game frameworks (in C++) such as : SFML, OpenGl (school project), and it appeared that all of them needed an explicit loop:

```<code>while(window is open) // pseudo code example
</code>```

but not in Monogame, so where is the loop made ?

The fact is that if there is some way to make the same thing without a loop, I would like to learn about, it looks like something pretty useful.

答:
There is no main "loop" in MonoGame for you to use to keep your game running. The framework instead provides two methods to give you a way to keep your game logic and display refreshes up to date:

Update() - Where the state of the game should be changed in response
to user input and other checks

Draw() - Where you actually draw things on screen to represent the current state of the game

These methods are called continually while your game is running, which is very similar to the main loop you might find in other gaming frameworks and languages.

Title: Where is Monogame "while" or "for" loop

Body:
I'm more or less new with C# and game dev in general,

I was looking at the Monogame framework and I was wondering where is the LOOP.

I mean, from what I know, to make a LOOP you have to make a WHILE(), a FOR() or by recursivity and I can't find any in Monogame, so where is the GAMELOOP ?

I used some game frameworks (in C++) such as : SFML, OpenGl (school project), and it appeared that all of them needed an explicit loop:

while(window is open) // pseudo code example

but not in Monogame, so where is the loop made ?

The fact is that if there is some way to make the same thing without a loop, I would like to learn about, it looks like something pretty useful.


问:
Display images from dropbox with javascript api
I'm trying to create a page that could show all pictures in a dropbox folder through the Javascript API.

I was able to set up my dropbox app properly, and I am able to get a list of files.

I'm stuck at the part to get a URL I could actually use to show the picture in HTML. I tried the following code, to try and get the URL for 1 image for the time being:

```<code>dbx.filesListFolder({path: ""})
    .then(function(response) {
        console.log(response);
        // ↑ this works!
        dbx.filesGetThumbnail({path: response.entries[0].path_display, format: "jpeg", size: "w64h64"})
            .then(function(result) {
                window.data = result;
                console.log(result);
            })
        // closures and rest of code...
</code>```

Inspecting the window.data or the console.log(result), I cannot seem to find any URL I could use in my HTML.

Any pointers to head me in the right direction? I'm still new to the Dropbox Javascript API.

答:
Kudos to Greg

The filesGetThumbnail method doesn't itself return a URL for the thumbnail data. It returns the raw thumbnail data directly. If you want a URL to display locally in the browser, you may want to something like this:

```<code>dbx.filesGetThumbnail({"path": "/test.jpg"})
  .then(function(response) {
    var img = document.createElement('img');
    img.src=window.URL.createObjectURL(response.fileBlob);
    document.body.appendChild(img);
  })
  .catch(function(error) {
    console.log("got error:");
    console.log(error);
  });
</code>```

BTW, you can find all of the API v2 JavaScript SDK methods documented here.

Body:
I'm trying to create a page that could show all pictures in a dropbox folder through the Javascript API.

I was able to set up my dropbox app properly, and I am able to get a list of files.

I'm stuck at the part to get a URL I could actually use to show the picture in HTML. I tried the following code, to try and get the URL for 1 image for the time being:

dbx.filesListFolder({path: ""})
    .then(function(response) {
        console.log(response);
        // ↑ this works!
        dbx.filesGetThumbnail({path: response.entries[0].path_display, format: "jpeg", size: "w64h64"})
            .then(function(result) {
                window.data = result;
                console.log(result);
            })
        // closures and rest of code...

Inspecting the window.data or the console.log(result), I cannot seem to find any URL I could use in my HTML.

Any pointers to head me in the right direction? I'm still new to the Dropbox Javascript API.

Body:
Kudos to Greg

The filesGetThumbnail method doesn't itself return a URL for the thumbnail data. It returns the raw thumbnail data directly. If you want a URL to display locally in the browser, you may want to something like this:

dbx.filesGetThumbnail({"path": "/test.jpg"})
  .then(function(response) {
    var img = document.createElement('img');
    img.src=window.URL.createObjectURL(response.fileBlob);
    document.body.appendChild(img);
  })
  .catch(function(error) {
    console.log("got error:");
    console.log(error);
  });

BTW, you can find all of the API v2 JavaScript SDK methods documented here.


问:
Values change when printing from dynamicly allocated memory
Ok quick intro. I'm doing a homework on dynamically allocated memory. We need to simulate a CPU using structs and dyn. al. memory. I was testing if my stack functions properly and doesn't overflow. The stack is supposed to be 2 KiB, didn't overflow, but while printing the numbers, few addresses contain other numbers that i didn't put in. Ill just copy it here, and get rid of instruction lists, registers and such, that are not a problem and would make this long.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

struct cpu {
    struct stack* memory;
};

struct stack {
    int32_t* values;
    int32_t* top;
};

void stackInit(struct stack* stack)
{
    stack->values = malloc(2048);
    stack->top = NULL;
}

void cpuInit (struct cpu* cpu)
{
    stackInit(cpu->memory); //initialize stack
}

void stackPush(struct stack* stack, int32_t value)
{
    if (stack->top == NULL){
        stack->top = stack->values;
        *(stack->top) = value;
    }
    else if (stack->top + sizeof(int32_t) < stack->values + 2048){
        stack->top += sizeof(int32_t);
        *(stack->top) = value;
    }
}

void cpuDebug(const struct cpu* cpu)
{
    int32_t* auxpt = cpu->memory->top;

    if (cpu->memory->top != NULL)
        for (int32_t i = 0; auxpt >= cpu->memory->values; i++){

            printf("Value on the addr %d\n", *auxpt);
            printf("Address of auxpt: %p\n", ( void * )auxpt );
            auxpt -= sizeof(int32_t);
        }

    printf("\n");
}

int main()
{
    struct cpu Cpu;

    cpuInit(&Cpu);

    for (int32_t i = 0; i < 550; i++){
        stackPush(Cpu.memory,i);
    }

    cpuDebug(&Cpu);

    return 0;
}
</code>```

And the output looks like this :

```<code>Value on the addr 133
Address of auxpt: 0x562640529880
Value on the addr 10
Address of auxpt: 0x562640529870
Value on the addr 544108298
Address of auxpt: 0x562640529860
Value on the addr 2016419898
Address of auxpt: 0x562640529850
Value on the addr 1919181889
Address of auxpt: 0x562640529840
Value on the addr 128
Address of auxpt: 0x562640529830
Value on the addr 127
</code>```

Any ideas why is this happening?
Thanks in advance

答:
Man, you must allocate struct stack before access their members (values and top). You are accessing a non mallocated memory.

```<code>void stackInit(struct stack* stack)
{
    stack = malloc(sizeof(struct stack));
    stack->values = malloc(2048);
    stack->top = NULL;
}
</code>```

Following the tricks pointed in the comments, a better solution could be:

```<code>void stackInit(struct stack** stack)
{
    (*stack) = (struct stack*)malloc(sizeof(struct stack));
    (*stack)->values = (int32_t*)malloc(2048);
    (*stack)->top = NULL;
}

void cpuInit(struct cpu* cpu)
{
    stackInit(&cpu->memory); //initialize stack
}
</code>```

In this way, the caller will see the allocated memory in the context of Cpu.memory.

Body:
Ok quick intro. I'm doing a homework on dynamically allocated memory. We need to simulate a CPU using structs and dyn. al. memory. I was testing if my stack functions properly and doesn't overflow. The stack is supposed to be 2 KiB, didn't overflow, but while printing the numbers, few addresses contain other numbers that i didn't put in. Ill just copy it here, and get rid of instruction lists, registers and such, that are not a problem and would make this long.

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

struct cpu {
    struct stack* memory;
};

struct stack {
    int32_t* values;
    int32_t* top;
};

void stackInit(struct stack* stack)
{
    stack->values = malloc(2048);
    stack->top = NULL;
}

void cpuInit (struct cpu* cpu)
{
    stackInit(cpu->memory); //initialize stack
}

void stackPush(struct stack* stack, int32_t value)
{
    if (stack->top == NULL){
        stack->top = stack->values;
        *(stack->top) = value;
    }
    else if (stack->top + sizeof(int32_t) < stack->values + 2048){
        stack->top += sizeof(int32_t);
        *(stack->top) = value;
    }
}

void cpuDebug(const struct cpu* cpu)
{
    int32_t* auxpt = cpu->memory->top;

    if (cpu->memory->top != NULL)
        for (int32_t i = 0; auxpt >= cpu->memory->values; i++){

            printf("Value on the addr %d\n", *auxpt);
            printf("Address of auxpt: %p\n", ( void * )auxpt );
            auxpt -= sizeof(int32_t);
        }

    printf("\n");
}

int main()
{
    struct cpu Cpu;

    cpuInit(&Cpu);

    for (int32_t i = 0; i < 550; i++){
        stackPush(Cpu.memory,i);
    }

    cpuDebug(&Cpu);

    return 0;
}

And the output looks like this :

Value on the addr 133
Address of auxpt: 0x562640529880
Value on the addr 10
Address of auxpt: 0x562640529870
Value on the addr 544108298
Address of auxpt: 0x562640529860
Value on the addr 2016419898
Address of auxpt: 0x562640529850
Value on the addr 1919181889
Address of auxpt: 0x562640529840
Value on the addr 128
Address of auxpt: 0x562640529830
Value on the addr 127

Any ideas why is this happening?
Thanks in advance

Body:
Man, you must allocate struct stack before access their members (values and top). You are accessing a non mallocated memory.

void stackInit(struct stack* stack)
{
    stack = malloc(sizeof(struct stack));
    stack->values = malloc(2048);
    stack->top = NULL;
}

Following the tricks pointed in the comments, a better solution could be:

void stackInit(struct stack** stack)
{
    (*stack) = (struct stack*)malloc(sizeof(struct stack));
    (*stack)->values = (int32_t*)malloc(2048);
    (*stack)->top = NULL;
}

void cpuInit(struct cpu* cpu)
{
    stackInit(&cpu->memory); //initialize stack
}

In this way, the caller will see the allocated memory in the context of Cpu.memory.


问:
Conditional redirection in JSF
is there a build-in mechanism to conditionally redirect to another view? I want the user to be redirected from the login page to the "home page" if he/she is already logged in.

I already have two basic approaches, but for the first I have no idea how to achieve and the second is sort of a dirty workaround.

Add <meta http-equiv="Refresh" content="0; URL=home.jsf" /> and let it be rendered conditionally (EL : #{login.loggedIn})

Add a <h:panelGroup /> which will also be conditionally rendered, containing some JavaScript doing the redirect.

Is there a way to achieve 1 or even another, more elegant solution? :-)

Thanks

答:
The solution set out by @BalusC doesn't work in case the view 'home.xhtml' is not the default view of the JSF portlet. For those who need to redirect to a non-default view during the render phase, I suggest the solution set out within this entry. That is, within the preRenderView method do the following:

```<code>FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "/views/nonDefaultView.xhtml?faces-redirect=true");
fc.renderResponse();
</code>```

Credits to @Frizz1977

Title: Conditional redirection in JSF

Body:
The solution set out by @BalusC doesn't work in case the view 'home.xhtml' is not the default view of the JSF portlet. For those who need to redirect to a non-default view during the render phase, I suggest the solution set out within this entry. That is, within the preRenderView method do the following:

FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "/views/nonDefaultView.xhtml?faces-redirect=true");
fc.renderResponse();

Credits to @Frizz1977