问:
Prolog - Counting the amount of times a number appears in a list
So I am pretty much new to Prolog. I need to write a code segment that will count all the times any number appears in a list, no matter how deeply nested. For example,
    countNums ([1, a, 2, [3, b, 4, [5, c, 6]]], N)
should return N = 6

Here's my code:

```<code>listp([]).                        %define listp's
listp([H|T]).
countNums([],0).                    %base case for empty list
countNums([H|T], N) :- listp(H).    %check if head is a list
countNums([[H|T]|T1], N) :- countNums([H|T], N).
%check if head is not a number, if not do func with tail and dont increment
%if it is, do func with tail and increment N
countNums([H|T], N):- (
    number(H) ->
    countNums(T, N1),
    N is N1+1;
    countNums(T, N1),
    N is N1).
</code>```

So, this code will work if the list is just a one level list (i.e. [1,2,3]), but if it encounters any new levels (i.e. [1,2,[3]]), it fails and exits.

I know a lot of this code probably doesn't make sense, but maybe you fine folks can help me out?

答:
Try this:

```<code>countNums([],0). %1
countNums([H|T],N) :- number(H), !, countNums(T,N1), N is N1 + 1. %2
countNums([[H|T1]|T2],N) :- !, countNums([H|T1],N1), countNums(T2,N2), N is N1 + N2. %3
countNums([_|T],N) :- countNums(T,N). %4
</code>```

To break it down, predicate (1) is the base case for an empty list; predicate (2) matches on a list and, if the first goal of number(H) succeeds then we've found a number so there is no point in trying any of the other predicates so hence the cut (!); (3) matches when we have a list where the head of the list is also a list, and again, in this case, we don't want to try the remaining predicate, so we now recurse in to the head list and count the tail, and then add together both results; and finally we've hit the case with (4) that the head is neither a number nor a list so we just skip past the head and count the tail.

Then:

```<code>?- countNums([1, a, 2, [3, b, 4, [5, c, 6]]], N), write(N), nl, fail.
</code>```

gives me this:

```
6
No.
```

One solution only and failure because of the fail.

Body:
So I am pretty much new to Prolog. I need to write a code segment that will count all the times any number appears in a list, no matter how deeply nested. For example,
    countNums ([1, a, 2, [3, b, 4, [5, c, 6]]], N)
should return N = 6

Here's my code:

listp([]).                        %define listp's
listp([H|T]).
countNums([],0).                    %base case for empty list
countNums([H|T], N) :- listp(H).    %check if head is a list
countNums([[H|T]|T1], N) :- countNums([H|T], N).
%check if head is not a number, if not do func with tail and dont increment
%if it is, do func with tail and increment N
countNums([H|T], N):- (
    number(H) ->
    countNums(T, N1),
    N is N1+1;
    countNums(T, N1),
    N is N1).

So, this code will work if the list is just a one level list (i.e. [1,2,3]), but if it encounters any new levels (i.e. [1,2,[3]]), it fails and exits.

I know a lot of this code probably doesn't make sense, but maybe you fine folks can help me out?

Body:
Try this:

countNums([],0). %1
countNums([H|T],N) :- number(H), !, countNums(T,N1), N is N1 + 1. %2
countNums([[H|T1]|T2],N) :- !, countNums([H|T1],N1), countNums(T2,N2), N is N1 + N2. %3
countNums([_|T],N) :- countNums(T,N). %4

To break it down, predicate (1) is the base case for an empty list; predicate (2) matches on a list and, if the first goal of number(H) succeeds then we've found a number so there is no point in trying any of the other predicates so hence the cut (!); (3) matches when we have a list where the head of the list is also a list, and again, in this case, we don't want to try the remaining predicate, so we now recurse in to the head list and count the tail, and then add together both results; and finally we've hit the case with (4) that the head is neither a number nor a list so we just skip past the head and count the tail.

Then:

?- countNums([1, a, 2, [3, b, 4, [5, c, 6]]], N), write(N), nl, fail.

gives me this:

6
No.

One solution only and failure because of the fail.


来源: stackexchange

问:
Is it OK to prolong a non-significant A/B test?
We know from this article that ending an A/B test early due to "significant" results is a mistake.

But what about when a test runs for the desired time period and shows insignificant results – is it fine to prolong it? What are the risks?

It would be great with a simple mathematical example of any risks, similar to the example in that linked article.

I have only a basic knowledge of probability theory and maths, so I would appreciate an answer I can understand with that knowledge.

My intuition is that it could be problematic, because you had an experiment with a calculated reliability (will show false positives in X% and false negatives in Y% of such experiments), but now you're effectively waiting indefinitely for the first true-positive or false-positive significance.

So I should think you get more false positives than you accounted for when setting up the original experiment. But presumably the likelihood of false positives also decreases as we get more data. I would love to get specific numbers on this, if it's true at all.

答:
This is an area of current research. We've done some modeling and advise our customers to follow this principle:

• If the experiment reaches statistical significance, i.e. when the CI
  ribbon entirely rises above zero or entirely falls below it, and
  remains significant for 50% more observations than it took to get to
  significance for 0.10 level tests (65% more observations than it took
  to get to significance for .05 level tests), the experiment is called
  by accepting the alternative hypothesis, or, in other words, the
  treatment wins.

• If the experiment does not reach statistical significance, while the
  CI ribbon has narrowed to where its width represents a difference
  between the treatment and the control that is not consequential to the
  application semantics, the experiment is called by rejecting the
  research hypothesis, or, in other words, the treatment fails to win
  and we stick with the control.

For more, here's the White Paper.

ContentLicense: CC BY-SA 3.0


问:
EZ USB Suite Cypress FX3 (Eclipse)
I installed the latest version of the EZ USB FX3 suite. I am using Windows 7 64 bit. After importing the project as described in the user maunual and building the examples on Eclipse I get the following error

```<code>C:/Program Files (x86)/Cypress/EZ-USB FX3 SDK/1.3/ARM GCC/bin/cs-make --no-
print-directory post-build
/usr/bin/sh: -c: line 0: syntax error near unexpected token `('
/usr/bin/sh: -c: line 0: `C:/Program Files (x86)/Cypress/EZ-USB FX3
SDK/1.3/ARM GCC/bin/cs-make --no-print-directory post-build'
cs-make: *** [USBBulkSourceSink.elf] Error 1
</code>```

How do I resolve this?

答: Funny enough we resolved this issue by just changing the main install directory.</p>

ContentLicense: CC BY-SA 4.0

Title: EZ USB Suite Cypress FX3 (Eclipse)

Body:
I installed the latest version of the EZ USB FX3 suite. I am using Windows 7 64 bit. After importing the project as described in the user maunual and building the examples on Eclipse I get the following error

C:/Program Files (x86)/Cypress/EZ-USB FX3 SDK/1.3/ARM GCC/bin/cs-make --no-
print-directory post-build
/usr/bin/sh: -c: line 0: syntax error near unexpected token `('
/usr/bin/sh: -c: line 0: `C:/Program Files (x86)/Cypress/EZ-USB FX3
SDK/1.3/ARM GCC/bin/cs-make --no-print-directory post-build'
cs-make: *** [USBBulkSourceSink.elf] Error 1

How do I resolve this?


问:
Mercurial: Indicating that a branch has passed testing?
I am working on establishing a workflow at my company if we were to migrate to DVCS (most likely Mercurial).  One of the things I would like to do is to have a repository for QA.  The idea being that each developer works on a branch and when they are done the branch is pushed to QA.  From there the test team can do their testing and report back any bugs.  Once the branch is fully tested and acceptable it will be pushed to a staging repository where the merge back to the mainline will happen before pushing to the central repository.

This can work quite easily if everyone just communicates the status of their work in some way, but I know this doesn't always happen as you would want it to.  What I am worried about is branches in the QA repo waiting around but nobody knows if it is waiting to be tested, currently being tested, waiting for fixes, waiting to be pushed to the staging area etc.  So what I am looking for are ideas of how a status can be added to a branch?  What would also be good would be to do it in a way that we could use hooks to also notify people of changes in the status.

Any ideas would be appreciated.

答:
I'm not completely sure how your workflow works, but here are a few ideas:

Tags.

Use named branches and close the branch when tested.Typing hg branches will show you which branches are still pending.

You could probably use an incoming hook for the automatic notification of new changesets being added to the QA repo.

ContentLicense: CC BY-SA 2.5


问:
mallocing same variable multiple times in c
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

```<code>int* var;
int i;
for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}
</code>```

Does this allocate a new space, this is not how I would actually use it, I would use in a situation where the address would be reassigned to a linked list so it could be freed and would not cause a memory address.

答:
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

malloc allocates a block of size bytes of memory, returning a pointer to the beginning of the block. So, in this for loop:

```<code>for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}
</code>```

in every iteration, malloc is allocating a new block of memory and returning a pointer to the beginning of the block which is getting assigned to var variable. But you have mentioned in the question - "address would be reassigned to a linked list.." so, assuming you are keeping the allocated memory references somewhere.

This is as good as this:

```<code>int somevalue;

for(i = 0; i < 5; i++)
{
    somevalue = i+10; //Just assigning a value to variable
}
</code>```

In every iteration, a new value is getting assigned to somevalue variable. After loop finishes, the variable somevalue will have the value assigned in the last iteration of the loop.

Does this allocate a new space..

Yes, as long as malloc is successful.

Additional note:

Do not cast the malloc return. Check this.

So, you should:

```<code>for(i = 0; i < 5; i++)
{
    var = malloc(sizeof(int));
}
</code>```

Body:
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

int* var;
int i;
for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}

Does this allocate a new space, this is not how I would actually use it, I would use in a situation where the address would be reassigned to a linked list so it could be freed and would not cause a memory address.

Body:
Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

malloc allocates a block of size bytes of memory, returning a pointer to the beginning of the block. So, in this for loop:

for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}

in every iteration, malloc is allocating a new block of memory and returning a pointer to the beginning of the block which is getting assigned to var variable. But you have mentioned in the question - "address would be reassigned to a linked list.." so, assuming you are keeping the allocated memory references somewhere.

This is as good as this:

int somevalue;

for(i = 0; i < 5; i++)
{
    somevalue = i+10; //Just assigning a value to variable
}

In every iteration, a new value is getting assigned to somevalue variable. After loop finishes, the variable somevalue will have the value assigned in the last iteration of the loop.

Does this allocate a new space..

Yes, as long as malloc is successful.

Additional note:

Do not cast the malloc return. Check this.

So, you should:

for(i = 0; i < 5; i++)
{
    var = malloc(sizeof(int));
}


问:
Validation between two date rails
I am trying to create a reservation/booking appointment, the user select two dates the starting date and the end date, how can I validate the date from the starting and the end date and also validate the dates in between those two dates preventing the user from choosing again the starting, end date and the dates in between.

Database

```<code> date_start   |  date_end
 14/11/2017      14/18/2017
</code>```

View:

Date field for the dates

```<code> <%= f.label :'date_start:' %>
 <%= f.date_field :date_start %>

 <%= f.label :'date_end:' %>
 <%= f.date_field :date_end %>
</code>```

Model

```<code>class Reservation < ApplicationRecord
 belongs_to: user
 validates :date_start, uniqueness: true
 validates :date_end, uniqueness: true
end
</code>```

I used validates :date_start, uniqueness: true and validates :date_end, uniqueness: true but it only checks for the date start and the date_end but it does not check the dates in between them.

答:
```<code>     validate :check_overlapping

     scope :overlaps, ->(date_start, date_end) do
        where "((date_start <= ?) and (date_end >= ?))", date_end, date_start
     end

     def check_overlapping
       errors.add(:date_start, 'your error messages') if overlaps(date_start, date_end).any?
     end
</code>```

end

Title: Validation between two date rails

Body:
I am trying to create a reservation/booking appointment, the user select two dates the starting date and the end date, how can I validate the date from the starting and the end date and also validate the dates in between those two dates preventing the user from choosing again the starting, end date and the dates in between.

Database

 date_start   |  date_end
 14/11/2017      14/18/2017

View:

Date field for the dates

 <%= f.label :'date_start:' %>
 <%= f.date_field :date_start %>

 <%= f.label :'date_end:' %>
 <%= f.date_field :date_end %>

Model

class Reservation < ApplicationRecord
 belongs_to: user
 validates :date_start, uniqueness: true
 validates :date_end, uniqueness: true
end

I used validates :date_start, uniqueness: true and validates :date_end, uniqueness: true but it only checks for the date start and the date_end but it does not check the dates in between them.

Body:
     validate :check_overlapping

     scope :overlaps, ->(date_start, date_end) do
        where "((date_start <= ?) and (date_end >= ?))", date_end, date_start
     end

     def check_overlapping
       errors.add(:date_start, 'your error messages') if overlaps(date_start, date_end).any?
     end

end


问:
Unable to generate an explicit migration in entity framework
I am adding a new migration but this message shows:

Unable to generate an explicit migration because the following
  explicit migrations are pending: [201203170856167_left]. Apply the
  pending explicit migrations before attempting to generate a new
  explicit migration.

Can any one help me?

答: My local database did not have the __MigrationHistory populated, or existing. I manually created the table, and then migrated the data in that table from PROD to my local database. This caused VS to think the migrations had been applied (which they had been).


问:
VBA in Outlook not replacing string containing slashes
I have the text xx/xx/xxxx in an Outlook template (.oft) as a placeholder for the current short form date. However, Replace() doesn't seem to work on it, and I can't find any evidence of needing to escape the slashes in a string for VBA.

The following does not work for me:

.HTMLBody = Replace(.HTMLBody, "xx/xx/xxxx", Format(Date, "Short Date"))

But if I swap out the placeholder with the text "PLACEHOLDER", the script works fine and the text is replaced as desired:

.HTMLBody = Replace(.HTMLBody, "PLACEHOLDER", Format(Date, "Short Date"))

Can anyone advise why this might be happening?

答:
Word editor adds spellE class for spelling errors (GramE for grammar). Either you change your place holder to something meaningful (dictionary complaint) such as date/month/year or change your replace string to consider that span while replacing.

Alternatively, change your all x to uppercase, that will get rid of spell check errors. and then check if you still get the SpellE class or it’s just a single string?


问:
Getting accented characters in a custom NSView
In Mac OSX text views, it's possible to enter accented  characters with a sequence of key presses (e.g. option-e e to get e-acute). Is there a way to access this functionality in a custom NSView. In my case I have class derived from NSOpenGLView. I've implemented a responder for keyDown: so I can get the unicode characters that come from a single press, but with the sequences I just get events for the individual presses. I hoped that interpretKeyEvents: from NSResponder would help but it doesn't seem to.

I could implement it myself by copying what NSTextView does but I imagine it will be tricky, especially if people use a different keyboard setup to mine.

答:
Calling interpretKeyEvents: is the right way to go, but you need to also implement other methods that will notify you when marked text (which I always called 'in progress text') or text to be inserted arrives in your view.

Your NSView must implement NSTextInputClient. See the Cocoa reference here. A search for some of the methods in that protocol found this chunk of code on github. which looks like a very good starting point.

For what you're asking for, it will be sufficient to test with English and at least one other Western language (French is a good one). But longer term, you'll also want to test with at least one of the Kotoeri and Hangul layouts. The code I linked to above, however, looks like it will handle the vast majority of text you can throw at it.


问:
How do I print the mysqli result of SUM() with PHP?
I have a table called "hours", with the following columns:

id, int(11)

date, date

hours, int(11)

I'm running this query on the table:

```<code>SELECT SUM(hours) as value_total FROM hours
</code>```

Which returns the correct sum of the values in the hours column - 68586

The result of this gets passed to an array, however when I try to print the index of the array that contains the sum 68586, it does not appear on the screen.

Here is my code in PHP

```<code>if($result = $conn->query("SELECT SUM(hours) as value_total FROM hours") or die(mysql_error())) {
    if ($result->num_rows) {

        while ($rows = $result->fetch_assoc())
        echo '```', print_r($rows), '```';

        print_r($rows['value_total']);
    }
} else {
    die($conn->error);
}
</code>```

the print_r was an attempt to print the index of the sum amount passed to the array but there is no output from it :(

right now, what's on my screen is :

```<code>Array
(
    [value_total] => 68586
)
1
</code>```

This is honestly a noob mistake I'm making somewhere I know it, but how do I print the "value_total" to the page with php?

答:
To understand your mistake, change:

```<code>while ($rows = $result->fetch_assoc())
echo '```', print_r($rows), '```';
print_r($rows['value_total']);
</code>```

to:

```<code>while ($rows = $result->fetch_assoc())
{
    echo '```', print_r($rows), '```';
    print_r($rows['value_total']);
}
</code>```

as your print_r is outside of the while loop because only the immediate next command is part of the loop and is $rows actually null on the second line.

However as @Phil has pointed out, If you're expecting a single row result, don't bother with the while loop...

```<code>if( $rows = $result->fetch_assoc())
{
  echo '```', print_r($rows), '```';
  print_r($rows['value_total']);
}
</code>```

Body:
I have a table called "hours", with the following columns:

id, int(11)

date, date

hours, int(11)

I'm running this query on the table:

SELECT SUM(hours) as value_total FROM hours

Which returns the correct sum of the values in the hours column - 68586

The result of this gets passed to an array, however when I try to print the index of the array that contains the sum 68586, it does not appear on the screen.

Here is my code in PHP

if($result = $conn->query("SELECT SUM(hours) as value_total FROM hours") or die(mysql_error())) {
    if ($result->num_rows) {

        while ($rows = $result->fetch_assoc())
        echo '
', print_r($rows), '
';

        print_r($rows['value_total']);
    }
} else {
    die($conn->error);
}

the print_r was an attempt to print the index of the sum amount passed to the array but there is no output from it :(

right now, what's on my screen is :

Array
(
    [value_total] => 68586
)
1

This is honestly a noob mistake I'm making somewhere I know it, but how do I print the "value_total" to the page with php?

Body:
To understand your mistake, change:

while ($rows = $result->fetch_assoc())
echo '<pre>', print_r($rows), '</pre>';
print_r($rows['value_total']);

to:

while ($rows = $result->fetch_assoc())
{
    echo '<pre>', print_r($rows), '</pre>';
    print_r($rows['value_total']);
}

as your print_r is outside of the while loop because only the immediate next command is part of the loop and is $rows actually null on the second line.

However as @Phil has pointed out, If you're expecting a single row result, don't bother with the while loop...

if( $rows = $result->fetch_assoc())
{
  echo '<pre>', print_r($rows), '</pre>';
  print_r($rows['value_total']);
}


答:
You're going to have to have a separate method to hold the complex validation code. Use validate :method_name (without an 's') to call it.

The method should add error(s) to the object if it finds a problem.

Something like this:

```<code>validate :no_reservation_overlap

 scope :overlapping, ->(period_start, period_end) do
    where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
 end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end
</code>```

Title: Validation between two date rails

Body:
You're going to have to have a separate method to hold the complex validation code. Use validate :method_name (without an 's') to call it.

The method should add error(s) to the object if it finds a problem.

Something like this:

validate :no_reservation_overlap

 scope :overlapping, ->(period_start, period_end) do
    where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
 end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end


问:
Redirect user to login page when session expires in Laravel
I am trying to redirect a user back to the login page if their session has expired. I am using Laravel 5.5. I have edited my RedirectIfAuthenticated file to include the following code in the handle function:

```<code>if (!Auth::check()) {
    return redirect()->route('login', ['account' => 'demo']);
}
</code>```

When I do this, I am receiving the following error message:

Missing required parameters for [Route: login] [URI: /].

My login route is inside a subdomain route group which is why I am passing the account parameter. Here is part of my code in web.php

```<code>// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
    Route::get('/', 'LoginController@show')->name('login');
}
</code>```

And here is my LoginController@show code:

```<code>/*
 * Show the login form
 */
public function show($account) {
    // Validate this is a valid subdomain
    $organization = Organization::where('subdomain', $account)->first();

    if ($organization) {
        return view('login');
    } else {
        return 'This account does not exist.';
    }
}
</code>```

Nothing I have tried works. I keep getting the exact same error message even though I am passing in the required parameters.

Update #1

Screenshot of error page:

Update #2

After a little digging around the Whoops! error page, I see this, protected function unauthenticated is what is causing the problem:

How do I override this function to add the missing parameter?

答:
You can override the unauthenticated() method in your app/Exceptions/Handler.php file to add the missing route parameter.

```<code>use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('login', ['account' => $request->route('account')]));
    }
}
</code>```

Body:
I am trying to redirect a user back to the login page if their session has expired. I am using Laravel 5.5. I have edited my RedirectIfAuthenticated file to include the following code in the handle function:

if (!Auth::check()) {
    return redirect()->route('login', ['account' => 'demo']);
}

When I do this, I am receiving the following error message:

Missing required parameters for [Route: login] [URI: /].

My login route is inside a subdomain route group which is why I am passing the account parameter. Here is part of my code in web.php

// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
    Route::get('/', 'LoginController@show')->name('login');
}

And here is my LoginController@show code:

/*
 * Show the login form
 */
public function show($account) {
    // Validate this is a valid subdomain
    $organization = Organization::where('subdomain', $account)->first();

    if ($organization) {
        return view('login');
    } else {
        return 'This account does not exist.';
    }
}

Nothing I have tried works. I keep getting the exact same error message even though I am passing in the required parameters.

Update #1

Screenshot of error page:

Update #2

After a little digging around the Whoops! error page, I see this, protected function unauthenticated is what is causing the problem:

How do I override this function to add the missing parameter?

Body:
You can override the unauthenticated() method in your app/Exceptions/Handler.php file to add the missing route parameter.

use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('login', ['account' => $request->route('account')]));
    }
}


问:
How to get direction of a language by its local code? (RTL or LTR)
Using PHP builtin functions and extensions (in particular intl) how to get direction of a language by its local code? (RTL or LTR)</p>

答:
There is something from Unicode called "Unicode Common Locale Data Repository", i.e. CLDR, which provide exactly this piece of information.

You can see this page which introduce what kind of features are available in CLDR, which include script direction.

As a note, script direction aren't just ltr or rtl, there are other directions as well.

And then, for access via PHP, you can look at e.g. Punic or any other library that would come up when you search PHP and CLDR together on google.

```<code>/**
 * Retrieve the character order (right-to-left or left-to-right).
 *
 * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
 *
 * @return string Return 'left-to-right' or 'right-to-left'
 */
public static function getCharacterOrder($locale = '')
{
    $data = Data::get('layout', $locale);
    return $data['characterOrder'];
}
</code>```

Body:
There is something from Unicode called "Unicode Common Locale Data Repository", i.e. CLDR, which provide exactly this piece of information.

You can see this page which introduce what kind of features are available in CLDR, which include script direction.

As a note, script direction aren't just ltr or rtl, there are other directions as well.

And then, for access via PHP, you can look at e.g. Punic or any other library that would come up when you search PHP and CLDR together on google.

/**
 * Retrieve the character order (right-to-left or left-to-right).
 *
 * @param string $locale The locale to use. If empty we'll use the default locale set in \Punic\Data
 *
 * @return string Return 'left-to-right' or 'right-to-left'
 */
public static function getCharacterOrder($locale = '')
{
    $data = Data::get('layout', $locale);
    return $data['characterOrder'];
}


问:
What is causing the none to appear?
In making a program to have a visual of the dice face appear, I was testing it and it seems to work except that there is a none that prints after each dice face.
The code is:

```<code>def visual (x):
    types= ['+-------+','|       |','|   *   |','| *   * |']
    if x == 1:
        print (types[0])
        print (types[1])
        print (types[2])
        print (types[1])
        print (types[0])
    if x == 2:
        print (types[0])
        print (types[2])
        print (types[1])
        print (types[2])
        print (types[0])
    if x == 3:
        print (types[0])
        print (types[2])
        print (types[2])
        print (types[2])
        print (types[0])
    if x == 4:
        print (types[0])
        print (types[3])
        print (types[1])
        print (types[3])
        print (types[0])
    if x == 5:
        print (types[0])
        print (types[3])
        print (types[2])
        print (types[3])
        print (types[0])
    if x == 6:
        print (types[0])
        print (types[3])
        print (types[3])
        print (types[3])
        print (types[0])

def main():
    x = [1,2,3,4,5,6]
    for a in x:
        print (a)
        print (visual(a))

main()
</code>```

it returns:

```<code>1
+-------+
|       |
|   *   |
|       |
+-------+
None
2
+-------+
|   *   |
|       |
|   *   |
+-------+
None
3
+-------+
|   *   |
|   *   |
|   *   |
+-------+
None
4
+-------+
| *   * |
|       |
| *   * |
+-------+
None
5
+-------+
| *   * |
|   *   |
| *   * |
+-------+
None
6
+-------+
| *   * |
| *   * |
| *   * |
+-------+
None
</code>```

As you can see the 'None' appears after every dice face gets printed. It obviously has to be in the for loop but I don't know what is causing it.

答:
You needn't to print (visual(a)). You just need to call visual(a).

print (visual(a)) will print visual(a)'s return value. As it doesn't return anything, None will be printed.

Title: What is causing the none to appear?

Body:
In making a program to have a visual of the dice face appear, I was testing it and it seems to work except that there is a none that prints after each dice face.
The code is:

def visual (x):
    types= ['+-------+','|       |','|   *   |','| *   * |']
    if x == 1:
        print (types[0])
        print (types[1])
        print (types[2])
        print (types[1])
        print (types[0])
    if x == 2:
        print (types[0])
        print (types[2])
        print (types[1])
        print (types[2])
        print (types[0])
    if x == 3:
        print (types[0])
        print (types[2])
        print (types[2])
        print (types[2])
        print (types[0])
    if x == 4:
        print (types[0])
        print (types[3])
        print (types[1])
        print (types[3])
        print (types[0])
    if x == 5:
        print (types[0])
        print (types[3])
        print (types[2])
        print (types[3])
        print (types[0])
    if x == 6:
        print (types[0])
        print (types[3])
        print (types[3])
        print (types[3])
        print (types[0])

def main():
    x = [1,2,3,4,5,6]
    for a in x:
        print (a)
        print (visual(a))

main()

it returns:

1
+-------+
|       |
|   *   |
|       |
+-------+
None
2
+-------+
|   *   |
|       |
|   *   |
+-------+
None
3
+-------+
|   *   |
|   *   |
|   *   |
+-------+
None
4
+-------+
| *   * |
|       |
| *   * |
+-------+
None
5
+-------+
| *   * |
|   *   |
| *   * |
+-------+
None
6
+-------+
| *   * |
| *   * |
| *   * |
+-------+
None

As you can see the 'None' appears after every dice face gets printed. It obviously has to be in the for loop but I don't know what is causing it.


问:
Hosting Python Twilio server online?
I'm trying to complete an iOS Swift app that send SMS with custom body. I found the following tutorial and it worked for me, however, it requires having a running python server. Is there any site that you recommend where I can host the python server and access it remotely through the web? Are there any alternatives for doing this by skipping the python server and directly sending an HTTP request from the app?

Note: This is in iOS 11 and Xcode 9 with latest version of Swift. I am also a beginner with HTTP requests and server stuff.

答: Your best bet is to host it through heroku (initially). the pricing structure is built on activity (great if you are testing and need hosting to be as inexpensive as possible), auto recognition of python code, and they give you a url that you can access remotely (i.e. someapp.heroku.com) that should allow you to access in your app.</p>

Title: Hosting Python Twilio server online?


问:
If you can decode JWT, how are they secure?
If I get a JWT and I can decode the payload, how is that secure? Couldn't I just grab the token out of the header, decode and change the user information in the payload, and send it back with the same correct encoded secret?

I know they must be secure, but I just would really like to understand the technologies. What am I missing?

答:
Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.

Hide the privateKey in a secure location in your server and never tell anyone the privateKey.


问:
In React, Is it possible to get access to Redux action creators from inside a utility function?
I have a form input validation function that just returns an empty errors object or a populated errors object.

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate
</code>```

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

```<code>const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)
</code>```

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

```<code>export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)
</code>```

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?

答:
You can access the redux store directly yes.

Step 1: Export the store

In the file where you initially configure your store, make sure you export it as well so you can have a reference to it from anywhere inside your app:

```<code>import {createStore} from 'redux'

const store = createStore([... your config]);

export default store;
</code>```

Step 2: Use it anywhere in your code

```<code>import {reduxStore} from './store'; // your previous created file

const yourEntireReduxState = reduxStore.getState();
// use it whichever way you want here
</code>```

Step 3: Dispatch actions

```<code>import {reduxStore} from './store'; // your previous created file

store.dispatch({type: 'YOUR_ACTION', payload: {...}});
</code>```

Body:
I have a form input validation function that just returns an empty errors object or a populated errors object.

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  return errors
}

export default validate

Is there a way to hook an action creator into this function?

This is what I am trying to achieve:

const validate = function validateSomeInput({ field1, field2 }) {
  const errors = {}
  // some logic
  props.onErrorEvent('do something')
  return errors
}

export default connect(null, { onErrorEvent })(validate)

My issue is that since it's not a class, I don't have access to this.props, and I have never tried to make a container before that doesn't render any JSX.

I also can't create a callback into the parent because the validate function is controlled by Redux-Form.

It's used like this in the parent container:

export default compose(
  connect(mapStateToProps, {
    onErrorEvent,      // this is the action creator I want to access from validate
    onLoginSuccess,
  }),
  graphql(LOGIN_MUTATION),
  reduxForm({
    validate,           // how do I get an action creator into this function?
    form: 'LoginForm',
  }),
)(LoginForm)

Is it possible to wire an action creator into a utility function that doesn't render JSX and can't callback to parent?

I'd also like to know if this is bordering into any kind of horrendous anti-pattern territory because I can't find any information about allowing random utility functions to call action creators.

I didn't see a solution with bindActionCreators, but maybe I just didn't see how it relates to this scenario.

Is there a way I can create a HOC in this scenario?

Body:
You can access the redux store directly yes.

Step 1: Export the store

In the file where you initially configure your store, make sure you export it as well so you can have a reference to it from anywhere inside your app:

import {createStore} from 'redux'

const store = createStore([... your config]);

export default store;

Step 2: Use it anywhere in your code

import {reduxStore} from './store'; // your previous created file

const yourEntireReduxState = reduxStore.getState();
// use it whichever way you want here

Step 3: Dispatch actions

import {reduxStore} from './store'; // your previous created file

store.dispatch({type: 'YOUR_ACTION', payload: {...}});


问:
'profile name is not valid' error when executing the sp_send_dbmail command
I have a windows account with users group and trying to exec sp_send_dbmail but getting an error:

profile name is not valid.

However, when I logged in as administrator and execute the sp_send_dbmail, it managed to send the email so obviously the profile name does exist on the server.

答:
Did you enable the profile for SQL Server Agent? This a common step that is missed when creating Email profiles in DatabaseMail.

Steps:

Right-click on SQL Server Agent in Object Explorer (SSMS)

Click on Properties

Click on the Alert System tab in the left-hand navigation

Enable the mail profile

Set Mail System and Mail Profile

Click OK

Restart SQL Server Agent


问:
Selenium (Nunit) with MTM (Microsoft Test Manager)
I want to perform automated test with Selenium,Nunit,TFS and MTM.

As i'm trying to find a way to run my selenium code using Nunit with MTM, i've searched alot regarding this but didn't find required solution as most of the people gave solution using MStest not with nunit after this i want to see my test case result on MTM.

Answer will be highly appreciated.

答:
Based on my experience (lots of trial and error), you can only Associate Automation with an MSTest Test Method, to test cases in MTM.

A solution I've used with Selenium, NUnit and TFS is to use the VNext builds to run my tests, and use the build status to track the test results (including widgets on the dashboard).


问:
Scala string formatting: escape sequences
How do I fix the following string formatting problem involving escape sequences?</p>

```<code>[~] 17:34:04$ scala
Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_151).
Type in expressions for evaluation. Or try :help.

scala> val fullFootnoteId = "asdf"
fullFootnoteId: String = asdf

scala> val footnoteId = 1
footnoteId: Int = 1

scala>  val footnoteTag = s"<sup id=\"ref_${fullFootnoteId}\"><a href=\"#foot_${fullFootnoteId}\">${footnoteId}</a></sup>"
<console>:12: error: value ref_$ is not a member of String
        val footnoteTag = s"<sup id=\"ref_${fullFootnoteId}\"><a href=\"#foot_${fullFootnoteId}\">${footnoteId}</a></sup>"
                                      ^
<console>:12: error: value \ is not a member of String
        val footnoteTag = s"<sup id=\"ref_${fullFootnoteId}\"><a href=\"#foot_${fullFootnoteId}\">${footnoteId}</a></sup>"
                                                           ^
</code>```

答:
Following the tip in scala string formatting with interpolator S not working , replacing with triple quotes """ fixed the problem.</p>

```<code>  val footnoteTag = s"""<sup id=\"ref_${fullFootnoteId}\"><a href=\"#foot_${fullFootnoteId}\">${footnoteId}</a></sup>"""
</code>```

Body:
How do I fix the following string formatting problem involving escape sequences?

[~] 17:34:04$ scala
Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_151).
Type in expressions for evaluation. Or try :help.

scala> val fullFootnoteId = "asdf"
fullFootnoteId: String = asdf

scala> val footnoteId = 1
footnoteId: Int = 1

scala>  val footnoteTag = s"${footnoteId}"
<console>:12: error: value ref_$ is not a member of String
        val footnoteTag = s"${footnoteId}"
                                      ^
<console>:12: error: value \ is not a member of String
        val footnoteTag = s"${footnoteId}"
                                                           ^

Body:
Following the tip in scala string formatting with interpolator S not working , replacing with triple quotes """ fixed the problem.

  val footnoteTag = s"""<sup id=\"ref_${fullFootnoteId}\"><a href=\"#foot_${fullFootnoteId}\">${footnoteId}</a></sup>"""


问:
Docker for Windows cleanup
I'm using docker for Windows to launch a MSSQL server. Everything is working fine except for the fact that my harddrive is now full. I've used all the cleanup commands that docker has, removing all images and containers:

```<code>docker kill $(docker ps -q)
docker rm $(docker ps -a -q)
docker rmi $(docker images -q -f dangling=true)
docker rmi $(docker images -q)
</code>```

This will not remove any contents in the c:\ProgramData\Docker\windowsfilter folder, where there are still a lot of file. Roughly 130gb worth's of storage, without any running containers or stored images.

```<code>Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.24)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      windows/amd64
 Experimental: true
</code>```

I tried to use the docker-ci-zap (https://github.com/jhowardmsft/docker-ci-zap) , but running that tool is not recommended so I would rather use an alternative solution

答:
Since Docker 1.13 (January 2017), Docker has some new canonical pruning subcommands (use with care):

docker image prune

docker container prune

docker volume prune

docker network prune

docker system prune

all stopped containers

all networks not used by at least one container

all dangling images

all build cache

However, Docker Desktop has had some sketchy upgrades that left things behind, which required manual file removal or "factory resets" for some folks.

Manual Deletion

Mac - https://github.com/docker/for-mac/issues/371 (This one got me a week or so ago. I resorted to pruning and deleting data with rm -rf ~/Library/Containers/com.docker.docker/Data/*)

Win - https://github.com/docker/for-win/issues/745#issuecomment-319930974

Factory Reset In the Docker Preferences GUI, there is a "reset to factory defaults" option. (In Docker Desktop for Mac v3.3, the option is in the "troubleshoot" tab, the icon for which looks like a bug. )

Title: Docker for Windows cleanup

Body:
I'm using docker for Windows to launch a MSSQL server. Everything is working fine except for the fact that my harddrive is now full. I've used all the cleanup commands that docker has, removing all images and containers:

docker kill $(docker ps -q)
docker rm $(docker ps -a -q)
docker rmi $(docker images -q -f dangling=true)
docker rmi $(docker images -q)

This will not remove any contents in the c:\ProgramData\Docker\windowsfilter folder, where there are still a lot of file. Roughly 130gb worth's of storage, without any running containers or stored images.

Client:
 Version:      17.03.1-ce
 API version:  1.27
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      windows/amd64

Server:
 Version:      17.03.1-ce
 API version:  1.27 (minimum version 1.24)
 Go version:   go1.7.5
 Git commit:   c6d412e
 Built:        Tue Mar 28 00:40:02 2017
 OS/Arch:      windows/amd64
 Experimental: true

I tried to use the docker-ci-zap (https://github.com/jhowardmsft/docker-ci-zap) , but running that tool is not recommended so I would rather use an alternative solution


问:
change css link and wait till new css is loaded
I wonder whether it's possible to change stylesheet link of the loaded document, then wait till the new css is loaded, and then run appropriate js code

thanks for any suggestions

答:
Here's a gist I wrote that works perfect in just 47 LOC:

https://gist.github.com/aleclarson/ac6456c75edae9fe9d9b6938142a065b

It uses requestAnimationFrame to check document.styleSheets on every frame until every given URL fragment has been loaded.

Example:

```<code>const styles = require('./styles')
const promise = styles.onLoad('foo.css', 'bar.css')
promise.then(() => console.log('Styles loaded!'))
</code>```

Pure javascript, too!

Body:
Here's a gist I wrote that works perfect in just 47 LOC:

https://gist.github.com/aleclarson/ac6456c75edae9fe9d9b6938142a065b

It uses requestAnimationFrame to check document.styleSheets on every frame until every given URL fragment has been loaded.

Example:

const styles = require('./styles')
const promise = styles.onLoad('foo.css', 'bar.css')
promise.then(() => console.log('Styles loaded!'))

Pure javascript, too!


问:
Trying to make an automated table right-alligned - Python 3
So this is what I got so far...

```<code>r = int(input("How many rows?\n"))#Inputs amount of row
c = int(input("How many columns?\n"))#Input amount of columns
largest = (len(str(r**c)))#Multiplying r, c amount of times

for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print(numb, end=space)
    print ()
</code>```

And this prints like so

```<code>How many rows?
5
How many columns?
6
1    1    1    1    1    1
2    4    8    16   32   64
3    9    27   81   243  729
4    16   64   256  1024 4096
5    25   125  625  3125 15625
</code>```

Trying to make it right-aligned so it looks something like this

```<code>1      1     1     1     1     1
2      4     8    16    32    64
3      9    27    81   243   729
4     16    64   256  1024  4096
5     25   125   625  3125 15625
</code>```

答:
This should solve your problem</p>

```<code>for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print("{}{}".format(space, numb))
</code>```

Body:
So this is what I got so far...

r = int(input("How many rows?\n"))#Inputs amount of row
c = int(input("How many columns?\n"))#Input amount of columns
largest = (len(str(r**c)))#Multiplying r, c amount of times

for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print(numb, end=space)
    print ()

And this prints like so

How many rows?
5
How many columns?
6
1    1    1    1    1    1
2    4    8    16   32   64
3    9    27   81   243  729
4    16   64   256  1024 4096
5    25   125  625  3125 15625

Trying to make it right-aligned so it looks something like this

1      1     1     1     1     1
2      4     8    16    32    64
3      9    27    81   243   729
4     16    64   256  1024  4096
5     25   125   625  3125 15625

Body:
This should solve your problem

for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print("{}{}".format(space, numb))


问:
Java: Read text from a file that was previously selected in another class
Using JavaFX, I have  the user input information into text fields.
My MainController class allows the user to save that inputted text to a txt file and save it at a given location.

Im wondering if its possible to pass what was entered in that text file into another class so I can parse and have my program use its data.

I used strings and .getText() then used a filewriter and bufferedWriter.
Can I get the .getText input into another class?

答: If your class is public than yes,you can use it in any class in your application;</p>


问:
How can I serve assets in /public that are not part of the asset pipeline with puma/nginx?
This is an AWS question, I'm using the Ruby 2.2 (Puma) platform.

My compiled assets (in /public/assets) are served as expected. The other assets in /public are not being served (404).

Where do I configure this? Is this an nginx problem? or a puma problem?

Or is this just an AWS image issue?

Here's a live example (robots.txt should be served from the root):
http://staging.us-west-2.elasticbeanstalk.com/public/robots.txt

It's also worth mentioning that the default Passenger platform image works out of the box.

答: I needed to simply run bundle exec rake assets:precompile


问:
String search breaking when wrapping .jar with JSmooth
I've got an oddball problem here.  I've got a little java program that filters Minecraft log files to make them easier to read.  On each line of these logs, there are usually multiple instances of the character "§", which returns a hex value of FFFD.

I am filtering out this character (as well as the character following it) using:

```<code>currentLine = currentLine.replaceAll("\uFFFD.", "");
</code>```

Now, when I run the program through NetBeans, it works swell.  My lines get outputted looking like this:

```<code>CxndyAnnie: Mhm
CxndyAnnie: Sorry
</code>```

But when I build the .jar file and wrap it into a .exe file using JSmooth, that character no longer gets filtered out when I run the .exe, and my lines come out looking like this:

```<code>§e§7[§f$65§7] §1§nCxndyAnnie§e: Mhm
§e§7[§f$65§7] §1§nCxndyAnnie§e: Sorry
</code>```

(note: the additional square brackets and $65 show up because their filtering is dependent on the special character and it's following character being removed first)

Any ideas why this would no longer work after putting it through JSmooth?  Is there a different way to do the text replace that would preserve its function?

By the way, I also attempted to remove this character using

```<code>currentLine = currentLine.replaceAll("§.", "");
</code>```

but that didn't work in Netbeans nor as a .exe.

I'll go ahead and past the full method below:

```<code> public static String[] filterLines(String[] allLines, String filterType, Boolean timeStamps) throws IOException {
    String currentLine = null;
    FileWriter saveFile = new FileWriter("readable.txt");
    String heading;
    String string1 = "[L]";
    String string2 = "[A]";
    String string3 = "[G]";
    if (filterType.equals(string1)) {
        heading = "LOCAL CHAT LOGS ONLY \r\n\r\n";
    }
    else if (filterType.equals(string2)) {
        heading = "ADVERTISING CHAT LOGS ONLY \r\n\r\n";
    }
    else if (filterType.equals(string3)) {
        heading = "GLOBAL CHAT LOGS ONLY \r\n\r\n";
    }
    else {
        heading = "CHAT LINES CONTAINING \"" + filterType + "\" \r\n\r\n";
    }
    saveFile.write(heading);

    for (int i = 0; i < allLines.length; i++) {
        if ((allLines[i] != null ) && (allLines[i].contains(filterType))) {
            currentLine = allLines[i];
            if (!timeStamps) {
                currentLine = currentLine.replaceAll("\\[..:..:..\\].", "");
            }
            currentLine = currentLine.replaceAll("\\[Client thread/INFO\\]:.", "");
            currentLine = currentLine.replaceAll("\\[CHAT\\].", "");
            currentLine = currentLine.replaceAll("\uFFFD.", "");
            currentLine = currentLine.replaceAll("\\[A\\].", "");
            currentLine = currentLine.replaceAll("\\[L\\].", "");
            currentLine = currentLine.replaceAll("\\[G\\].", "");
            currentLine = currentLine.replaceAll("\\[\\$..\\].", "");
            currentLine = currentLine.replaceAll(".>", ":");
            currentLine = currentLine.replaceAll("\\[\\$100\\].", "");
            saveFile.write(currentLine + "\r\n");
            //System.out.println(currentLine);
        }
    }
    saveFile.close();
    ProcessBuilder openFile = new ProcessBuilder("Notepad.exe", "readable.txt");
    openFile.start();
    return allLines;
}
</code>```

FINAL EDIT

Just in case anyone stumbles across this and needs to know what finally worked, here's the snippet of code where I pull the lines from the file and re-encode it to work:

```<code>    BufferedReader fileLines;
    fileLines = new BufferedReader(new FileReader(file));
    String[] allLines = new String[numLines];
    int i=0;
    while ((line = fileLines.readLine()) != null) {
        byte[] bLine = line.getBytes();
        String convLine = new String(bLine, Charset.forName("UTF-8"));
        allLines[i] = convLine;
        i++;
    }
</code>```

答:
I also had a problem like this in the past with minecroft logs, I don’t remember the exact details, but the issue came down to a file format problem, where UTF8 encoding worked correctly but some other text encoding including the system default did not work correctly.

First:

Make sure that you specify UTF8 encoding when reading the byteArray from file so that allLines contains the correct info like so:

```<code>Path fileLocation = Paths.get("C:/myFileLocation/logs.txt");
byte[] data = Files.readAllBytes(fileLocation);
String allLines = new String(data , Charset.forName("UTF-8"));
</code>```

Second:

Using \uFFFD is not going to work, because \uFFFD is only used to replace an incoming character whose value is unknown or unrepresentable in Unicode.

However if you used the correct encoding (shown in my first point) then \uFFFD is not necessary because the value § is known in unicode so you can simply use

currentLine.replaceAll("§", "");

or specifically use the actual unicode string for that character U+00A7 like so

currentLine.replaceAll("\u00A7", "");

or just use both those lines in your code.

Body:
I've got an oddball problem here.  I've got a little java program that filters Minecraft log files to make them easier to read.  On each line of these logs, there are usually multiple instances of the character "§", which returns a hex value of FFFD.

I am filtering out this character (as well as the character following it) using:

currentLine = currentLine.replaceAll("\uFFFD.", "");

Now, when I run the program through NetBeans, it works swell.  My lines get outputted looking like this:

CxndyAnnie: Mhm
CxndyAnnie: Sorry

But when I build the .jar file and wrap it into a .exe file using JSmooth, that character no longer gets filtered out when I run the .exe, and my lines come out looking like this:

§e§7[§f$65§7] §1§nCxndyAnnie§e: Mhm
§e§7[§f$65§7] §1§nCxndyAnnie§e: Sorry

(note: the additional square brackets and $65 show up because their filtering is dependent on the special character and it's following character being removed first)

Any ideas why this would no longer work after putting it through JSmooth?  Is there a different way to do the text replace that would preserve its function?

By the way, I also attempted to remove this character using

currentLine = currentLine.replaceAll("§.", "");

but that didn't work in Netbeans nor as a .exe.

I'll go ahead and past the full method below:

 public static String[] filterLines(String[] allLines, String filterType, Boolean timeStamps) throws IOException {
    String currentLine = null;
    FileWriter saveFile = new FileWriter("readable.txt");
    String heading;
    String string1 = "[L]";
    String string2 = "[A]";
    String string3 = "[G]";
    if (filterType.equals(string1)) {
        heading = "LOCAL CHAT LOGS ONLY \r\n\r\n";
    }
    else if (filterType.equals(string2)) {
        heading = "ADVERTISING CHAT LOGS ONLY \r\n\r\n";
    }
    else if (filterType.equals(string3)) {
        heading = "GLOBAL CHAT LOGS ONLY \r\n\r\n";
    }
    else {
        heading = "CHAT LINES CONTAINING \"" + filterType + "\" \r\n\r\n";
    }
    saveFile.write(heading);

    for (int i = 0; i < allLines.length; i++) {
        if ((allLines[i] != null ) && (allLines[i].contains(filterType))) {
            currentLine = allLines[i];
            if (!timeStamps) {
                currentLine = currentLine.replaceAll("\\[..:..:..\\].", "");
            }
            currentLine = currentLine.replaceAll("\\[Client thread/INFO\\]:.", "");
            currentLine = currentLine.replaceAll("\\[CHAT\\].", "");
            currentLine = currentLine.replaceAll("\uFFFD.", "");
            currentLine = currentLine.replaceAll("\\[A\\].", "");
            currentLine = currentLine.replaceAll("\\[L\\].", "");
            currentLine = currentLine.replaceAll("\\[G\\].", "");
            currentLine = currentLine.replaceAll("\\[\\$..\\].", "");
            currentLine = currentLine.replaceAll(".>", ":");
            currentLine = currentLine.replaceAll("\\[\\$100\\].", "");
            saveFile.write(currentLine + "\r\n");
            //System.out.println(currentLine);
        }
    }
    saveFile.close();
    ProcessBuilder openFile = new ProcessBuilder("Notepad.exe", "readable.txt");
    openFile.start();
    return allLines;
}

FINAL EDIT

Just in case anyone stumbles across this and needs to know what finally worked, here's the snippet of code where I pull the lines from the file and re-encode it to work:

    BufferedReader fileLines;
    fileLines = new BufferedReader(new FileReader(file));
    String[] allLines = new String[numLines];
    int i=0;
    while ((line = fileLines.readLine()) != null) {
        byte[] bLine = line.getBytes();
        String convLine = new String(bLine, Charset.forName("UTF-8"));
        allLines[i] = convLine;
        i++;
    }

Body:
I also had a problem like this in the past with minecroft logs, I don’t remember the exact details, but the issue came down to a file format problem, where UTF8 encoding worked correctly but some other text encoding including the system default did not work correctly.

First:

Make sure that you specify UTF8 encoding when reading the byteArray from file so that allLines contains the correct info like so:

Path fileLocation = Paths.get("C:/myFileLocation/logs.txt");
byte[] data = Files.readAllBytes(fileLocation);
String allLines = new String(data , Charset.forName("UTF-8"));

Second:

Using \uFFFD is not going to work, because \uFFFD is only used to replace an incoming character whose value is unknown or unrepresentable in Unicode.

However if you used the correct encoding (shown in my first point) then \uFFFD is not necessary because the value § is known in unicode so you can simply use

currentLine.replaceAll("§", "");

or specifically use the actual unicode string for that character U+00A7 like so

currentLine.replaceAll("\u00A7", "");

or just use both those lines in your code.


问:
b'Recode from ANSI 1252 to UTF-8 failed with the error: "Invalid argument".' geopandas python
I am trying to read in a shapefile into a GeoDataFrame.

Normally I just do this and it works:

```<code>import pandas as pd

import geopandas as gpd
from shapely.geometry import Point

df = gpd.read_file("wild_fires/nbac_2016_r2_20170707_1114.shp")
</code>```

But this time it gives me the error: b'Recode from ANSI 1252 to UTF-8 failed with the error: "Invalid argument".'

Full error:

```<code>---------------------------------------------------------------------------
CPLE_AppDefinedError                      Traceback (most recent call last)
<ipython-input-14-adcad0275d30> in <module>()
----> 1 df_wildfires_2016 = gpd.read_file("wild_fires/nbac_2016_r2_20170707_1114.shp")

/usr/local/lib/python3.6/site-packages/geopandas/io/file.py in read_file(filename, **kwargs)
     19     """
     20     bbox = kwargs.pop('bbox', None)
---> 21     with fiona.open(filename, **kwargs) as f:
     22         crs = f.crs
     23         if bbox is not None:

/usr/local/lib/python3.6/site-packages/fiona/__init__.py in open(path, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt)
    163         c = Collection(path, mode, driver=driver, encoding=encoding,
    164                        layer=layer, vsi=vsi, archive=archive,
--> 165                        enabled_drivers=enabled_drivers)
    166     elif mode == 'w':
    167         if schema:

/usr/local/lib/python3.6/site-packages/fiona/collection.py in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, **kwargs)
    151             if self.mode == 'r':
    152                 self.session = Session()
--> 153                 self.session.start(self)
    154             elif self.mode in ('a', 'w'):
    155                 self.session = WritingSession()

fiona/ogrext.pyx in fiona.ogrext.Session.start (fiona/ogrext2.c:8432)()

fiona/_err.pyx in fiona._err.GDALErrCtxManager.__exit__ (fiona/_err.c:1861)()

CPLE_AppDefinedError: b'Recode from ANSI 1252 to UTF-8 failed with the error: "Invalid argument".'
</code>```

I've been trying to figure out why I am getting the error for a while but can't seem to find the answer.

The data was obtained from this webpage I downloaded only the 2016 link: http://cwfis.cfs.nrcan.gc.ca/datamart/download/nbac?token=78e9bd6af67f71204e18cb6fa4e47515

Would anybody be able to help me? Thank you.

答:
Seems that your shapefile contains non-UTF characters that causes the Fiona.open() call to fail (geopandas uses Fiona to open files).

What I did that solved this error was to open the Shapefile (with QGis for example), then selecting save as, and specifying the Encoding option as "UTF-8":

After doing this, I got no error when calling df = gpd.read_file("convertedShape.shp").

Another way to do this without having to use QGis or similar, is to read and save your Shapefile again (effectively converting to the desired format). With OGR you can do something like this:

```<code>from osgeo import ogr

driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.Open("nbac_2016_r2_20170707_1114.shp", 0) #open your shapefile
#get its layer
layer = ds.GetLayer()

#create new shapefile to convert
ds2 = driver.CreateDataSource('convertedShape.shp')
#create a Polygon layer, as the one your Shapefile has
layer2 = ds2.CreateLayer('', None, ogr.wkbPolygon)
#iterate over all features of your original shapefile
for feature in layer:
   #and create a new feature on your converted shapefile with those features
   layer2.CreateFeature(feature)

ds = layer = ds2 = layer2 = None
</code>```

This also enabled to successfully open with df = gpd.read_file("convertedShape.shp") after conversion. Hope this helps.

Body:
I am trying to read in a shapefile into a GeoDataFrame.

Normally I just do this and it works:

import pandas as pd

import geopandas as gpd
from shapely.geometry import Point

df = gpd.read_file("wild_fires/nbac_2016_r2_20170707_1114.shp")

But this time it gives me the error: b'Recode from ANSI 1252 to UTF-8 failed with the error: "Invalid argument".'

Full error:

---------------------------------------------------------------------------
CPLE_AppDefinedError                      Traceback (most recent call last)
<ipython-input-14-adcad0275d30> in <module>()
----> 1 df_wildfires_2016 = gpd.read_file("wild_fires/nbac_2016_r2_20170707_1114.shp")

/usr/local/lib/python3.6/site-packages/geopandas/io/file.py in read_file(filename, **kwargs)
     19     """
     20     bbox = kwargs.pop('bbox', None)
---> 21     with fiona.open(filename, **kwargs) as f:
     22         crs = f.crs
     23         if bbox is not None:

/usr/local/lib/python3.6/site-packages/fiona/__init__.py in open(path, mode, driver, schema, crs, encoding, layer, vfs, enabled_drivers, crs_wkt)
    163         c = Collection(path, mode, driver=driver, encoding=encoding,
    164                        layer=layer, vsi=vsi, archive=archive,
--> 165                        enabled_drivers=enabled_drivers)
    166     elif mode == 'w':
    167         if schema:

/usr/local/lib/python3.6/site-packages/fiona/collection.py in __init__(self, path, mode, driver, schema, crs, encoding, layer, vsi, archive, enabled_drivers, crs_wkt, **kwargs)
    151             if self.mode == 'r':
    152                 self.session = Session()
--> 153                 self.session.start(self)
    154             elif self.mode in ('a', 'w'):
    155                 self.session = WritingSession()

fiona/ogrext.pyx in fiona.ogrext.Session.start (fiona/ogrext2.c:8432)()

fiona/_err.pyx in fiona._err.GDALErrCtxManager.__exit__ (fiona/_err.c:1861)()

CPLE_AppDefinedError: b'Recode from ANSI 1252 to UTF-8 failed with the error: "Invalid argument".'

I've been trying to figure out why I am getting the error for a while but can't seem to find the answer.

The data was obtained from this webpage I downloaded only the 2016 link: http://cwfis.cfs.nrcan.gc.ca/datamart/download/nbac?token=78e9bd6af67f71204e18cb6fa4e47515

Would anybody be able to help me? Thank you.

Body:
Seems that your shapefile contains non-UTF characters that causes the Fiona.open() call to fail (geopandas uses Fiona to open files).

What I did that solved this error was to open the Shapefile (with QGis for example), then selecting save as, and specifying the Encoding option as "UTF-8":

After doing this, I got no error when calling df = gpd.read_file("convertedShape.shp").

Another way to do this without having to use QGis or similar, is to read and save your Shapefile again (effectively converting to the desired format). With OGR you can do something like this:

from osgeo import ogr

driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.Open("nbac_2016_r2_20170707_1114.shp", 0) #open your shapefile
#get its layer
layer = ds.GetLayer()

#create new shapefile to convert
ds2 = driver.CreateDataSource('convertedShape.shp')
#create a Polygon layer, as the one your Shapefile has
layer2 = ds2.CreateLayer('', None, ogr.wkbPolygon)
#iterate over all features of your original shapefile
for feature in layer:
   #and create a new feature on your converted shapefile with those features
   layer2.CreateFeature(feature)

ds = layer = ds2 = layer2 = None

This also enabled to successfully open with df = gpd.read_file("convertedShape.shp") after conversion. Hope this helps.


问:
Teams doesn't display hero image
I've been trying to send cards to Teams channels through a connector. The cards do appear but any hero image I try to send isn't displayed.
The Message Card Playground displays the image correctly but it simply doesn't show up in Teams. I have no issues with the "normal" images.

Here is the JSON that I'm sending through the webhook, but I've also tried the Twitter - Hero image sample card and it doesn't work either :

```<code>{
  "@type": "MessageCard",
  "@context": "http://schema.org/extensions",
  "summary": "Hero card testing",
  "title": null,
  "text": null,
  "themeColor": "19b5fe",
  "sections": [
    {
      "title": null,
      "activityImage": "https://pbs.twimg.com/profile_images/862653089916096512/ljJwcmFp_bigger.jpg",
      "activityTitle": "Hero image card",
      "activitySubtitle": "This is a test",
      "facts": [],
      "text": null,
      "heroImage": {
        "image": "https://pbs.twimg.com/media/DFv74A0XkAEdwQ_.jpg"
      },
      "images": []
    }
  ]
}
</code>```

Am I missing something ?

答:
Hero Images ('heroImage') are currently support only in Outlook. Would be available in Teams sometime in future.

Card with a hero image

Try the sample Twitter markup for in the card playground: https://aka.ms/messagecardplayground

Title: Teams doesn't display hero image

Body:
I've been trying to send cards to Teams channels through a connector. The cards do appear but any hero image I try to send isn't displayed.
The Message Card Playground displays the image correctly but it simply doesn't show up in Teams. I have no issues with the "normal" images.

Here is the JSON that I'm sending through the webhook, but I've also tried the Twitter - Hero image sample card and it doesn't work either :

{
  "@type": "MessageCard",
  "@context": "http://schema.org/extensions",
  "summary": "Hero card testing",
  "title": null,
  "text": null,
  "themeColor": "19b5fe",
  "sections": [
    {
      "title": null,
      "activityImage": "https://pbs.twimg.com/profile_images/862653089916096512/ljJwcmFp_bigger.jpg",
      "activityTitle": "Hero image card",
      "activitySubtitle": "This is a test",
      "facts": [],
      "text": null,
      "heroImage": {
        "image": "https://pbs.twimg.com/media/DFv74A0XkAEdwQ_.jpg"
      },
      "images": []
    }
  ]
}

Am I missing something ?


问:
how to get key as words in dictionary?
If I have this dictionary how can I do to get the key instead value but reading words.
Example if I write 2 22 1 response must be A B .

```<code>value= {"A": 2, "B": 22, "C": 222, "D": 3, "E": 33,"F":333, "G": 4, "H": 44, "I": 444, "J": 5, "K": 55, "L": 555, "M": 6, "N": 66, "O": 666, "P": 7, "Q": 77, "R": 777, "S": 7777, "T": 8, "U": 88, "V": 888, "W": 9, "X": 99, "Y": 999, "Z": 9999}
</code>```

I was trying with this loop but there´s something wrong:

```<code>for i in r:
  key= n[i]
  print key
</code>```

Title: how to get key as words in dictionary?

Body:
If I have this dictionary how can I do to get the key instead value but reading words.
Example if I write 2 22 1 response must be A B .

value= {"A": 2, "B": 22, "C": 222, "D": 3, "E": 33,"F":333, "G": 4, "H": 44, "I": 444, "J": 5, "K": 55, "L": 555, "M": 6, "N": 66, "O": 666, "P": 7, "Q": 77, "R": 777, "S": 7777, "T": 8, "U": 88, "V": 888, "W": 9, "X": 99, "Y": 999, "Z": 9999}

I was trying with this loop but there´s something wrong:

for i in r:
  key= n[i]
  print key

Body:
You can reverse the dictionary:

value= {"A": 2, "B": 22, "C": 222, "D": 3, "E": 33,"F":333, "G": 4, "H": 44, "I": 444, "J": 5, "K": 55, "L": 555, "M": 6, "N": 66, "O": 666, "P": 7, "Q": 77, "R": 777, "S": 7777, "T": 8, "U": 88, "V": 888, "W": 9, "X": 99, "Y": 999, "Z": 9999}
new_value = {b:a for a, b in value.items()}
print(new_value[2])

Output:

A

Regarding your latest comment, you can try this:

final_results = [a for a, b in value.items() if b == 22]


问:
Convert Raw string to MimeMessage
I want to convert a Gmail Raw Message into Mimekit.MimeMessage. Can convert MimeMessage to Raw string but can't reverse it.

Code for getting Raw message from gmail:

```<code>var emailInfoReq = service.Users.Messages.Get("me", email.Id);
emailInfoReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
var emailInfoResponse = emailInfoReq.Execute();
if (emailInfoResponse != null)
  {
    var message = emailInfoResponse.Raw;
    //string Msg = DecodeBase64String(message);
    //byte[] Msg = Base64UrlDecode(message);
    MimeKit.MimeMessage Message1 = new MimeKit.MimeMessage();
    // MimeMessage not taking string as well as byte[] input
  }
</code>```

Any help would be appreciated. Thanks.

答:
It was easy, Thanks to Sir Rufo for idea!

Just posting it if anybody wants: Converted byte[] to memory stream and load it into MimeMessage:

```<code> var message = emailInfoResponse.Raw;
 byte[] Msg = Base64UrlDecode(message);
 MemoryStream mm = new MemoryStream(Msg);
 MimeKit.MimeMessage Message1  = MimeKit.MimeMessage.Load(mm);
</code>```

Title: Convert Raw string to MimeMessage

Body:
I want to convert a Gmail Raw Message into Mimekit.MimeMessage. Can convert MimeMessage to Raw string but can't reverse it.

Code for getting Raw message from gmail:

var emailInfoReq = service.Users.Messages.Get("me", email.Id);
emailInfoReq.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Raw;
var emailInfoResponse = emailInfoReq.Execute();
if (emailInfoResponse != null)
  {
    var message = emailInfoResponse.Raw;
    //string Msg = DecodeBase64String(message);
    //byte[] Msg = Base64UrlDecode(message);
    MimeKit.MimeMessage Message1 = new MimeKit.MimeMessage();
    // MimeMessage not taking string as well as byte[] input
  }

Any help would be appreciated. Thanks.

Body:
It was easy, Thanks to Sir Rufo for idea!

Just posting it if anybody wants: Converted byte[] to memory stream and load it into MimeMessage:

 var message = emailInfoResponse.Raw;
 byte[] Msg = Base64UrlDecode(message);
 MemoryStream mm = new MemoryStream(Msg);
 MimeKit.MimeMessage Message1  = MimeKit.MimeMessage.Load(mm);


问:
Looking for a drop-in replacement for a java.util.Map

Problem

Following up on this question, it seems that a file- or disk-based Map implementation may be the right solution to the problems I mentioned there. Short version:

Right now, I have a Map implemented as a ConcurrentHashMap.

Entries are added to it continually, at a fairly fixed rate. Details on this later.

Eventually, no matter what, this means the JVM runs out of heap space.

At work, it was (strongly) suggested that I solve this problem using SQLite, but after asking that previous question, I don't think that a database is the right tool for this job. So - let me know if this sounds crazy - I think a better solution would be a Map stored on disk.

Bad idea: implement this myself. Better idea: use someone else's library! Which one?

Requirements

Must-haves:

Free.

Persistent. The data needs to stick around between JVM restarts.

Some sort of searchability. Yes, I need the ability to retrieve this darn data as well as put it away. Basic result set filtering is a plus.

Platform-independent. Needs to be production-deployable on Windows or Linux machines.

Purgeable. Disk space is finite, just like heap space. I need to get rid of entries that are n days old. It's not a big deal if I have to do this manually.

Nice-to-haves:

Easy to use. It would be great if I could get this working by the end of the week.

Better still: the end of the day. It would be really, really great if I could add one JAR to my classpath, change new ConcurrentHashMap<Foo, Bar>(); to new SomeDiskStoredMap<Foo, Bar>();

and be done.

Decent scalability and performance. Worst case: new entries are added (on average) 3 times per second, every second, all day long, every day. However, inserts won't always happen that smoothly. It might be (no inserts for an hour) then (insert 10,000 objects at once).

Possible Solutions

Ehcache? I've never used it before. It was a suggested solution to my previous question.

Berkeley DB? Again, I've never used it, and I really don't know anything about it.

Hadoop (and which subproject)? Haven't used it. Based on these docs, its cross-platform-readiness is ambiguous to me. I don't need distributed operation in the foreseeable future.

A SQLite JDBC driver after all?

???

Ehcache and Berkeley DB both look reasonable right now. Any particular recommendations in either direction?

答:
I came accross jdbm2 a few weeks ago. The usage is very simple. You should be able to get it to work in half an hour.  One drawback is that the object which is put into the map must be serializable, i.e. implement Serializable. Other Cons are given in their website.

However, all object persistence database are not a permanent solution for storing objects of you own java class. If you decide to make change to the fields of the class, you will no longer be able to reteive the object from the map collection. It is ideal to store standard serializable classes line String, Integer, etc.


问:
How can I serve the html, css, and js all while keeping the routes inside a module.export in a different file? Right now only html is served
I am a newbie to use express and as a result am bungling my way through making this web app.

I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?

app.js

```<code>//setup
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash    = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');

//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);

// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');

//routes
//app.use('/', index);
//app.use('/users', users);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

//routes
require('./app/routes.js')(app, passport);

// catch 404 and forward to error handler
/*app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});*/

// error handler
/*app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});*/

module.exports = app;

//launch
app.listen(port);
console.log('Website starting on port ' + port);
</code>```

routes.js

```<code>module.exports = function(app,passport) {
...
    //--timesheet section---
    app.get('/timesheet', function(req, res) {
        var path = require('path');
        res.sendFile(path.resolve('public/timesheet.html'));
    });
...
}
</code>```

答:
You want to use a view engine and a static directory.  You have some of the code already.

Your view engine using .ejs:

```<code>app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
</code>```

And you can define your static and specify a path prefix:

```<code>app.use('/assets', express.static(path.join(__dirname, 'public')));
</code>```

In your   views directory, put your htmls with .ejs extension, such as timesheet.ejs.  You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.

Finally, in your route, you'll want to render the template:

```<code>res.render('timesheet')
</code>```

Body:
I am a newbie to use express and as a result am bungling my way through making this web app.

I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?

app.js

//setup
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash    = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');

//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);

// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');

//routes
//app.use('/', index);
//app.use('/users', users);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

//routes
require('./app/routes.js')(app, passport);

// catch 404 and forward to error handler
/*app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});*/

// error handler
/*app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});*/

module.exports = app;

//launch
app.listen(port);
console.log('Website starting on port ' + port);

routes.js

module.exports = function(app,passport) {
...
    //--timesheet section---
    app.get('/timesheet', function(req, res) {
        var path = require('path');
        res.sendFile(path.resolve('public/timesheet.html'));
    });
...
}

Body:
You want to use a view engine and a static directory.  You have some of the code already.

Your view engine using .ejs:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

And you can define your static and specify a path prefix:

app.use('/assets', express.static(path.join(__dirname, 'public')));

In your   views directory, put your htmls with .ejs extension, such as timesheet.ejs.  You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.

Finally, in your route, you'll want to render the template:

res.render('timesheet')


问:
Is there a method to automatically attach a .natvis to debug session started using -DebugExe?
I am working with a solution that includes a .natvis in its tree. The workflow requires that I often start debug sessions of various solution's executables using devenv.exe's /DebugExe switch. But when started this way, the .natvis file isn't used by debugger.

I have tried to use /Command switch with Add Existing Item command, but it looks like since the debugged .exe isn't a proper solution or project, it's impossible to add anything to it (at least I have failed).

So the question is: is there a method to use the .natvis placed in an arbitrary path (not in user's profile where VisualStudio would automatically use it) in /DebugExe sessions?

答:
You could use /NATVIS:filename to add your .native file to the .pdb file. It will embed the debugger visualizations defined in the Natvis file filename into the PDB file generated by LINK.

In addition, you could refer to the Deploying .natvis files part in the link Jack provided. We also could add the .natvis file to user directory or to a system directory. The order in which .natvis files are evaluated is as follows:

natvis files embedded in a .pdb you are debugging (unless a file of the same name exists in a loaded project)

natvis files that are part of a loaded C++ projects or a top-level solution item. This includes all loaded C++ projects, including class libraries, but it does not include projects of other languages (e.g. you can’t load a .natvis file from a C# project). For executable projects, you should use the solution items to host any .natvis files that are not already present in a .pdb, since there is no C++ project available.

The user-specific natvis directory (%USERPROFILE%\My Documents\Visual Studio 2015\Visualizers

The system-wide Natvis directory (%VSINSTALLDIR%\Common7\Packages\Debugger\Visualizers). This is where .natvis files that are installed with Visual Studio are copied. You can add other files to this directory as well if you have administrator permissions.