问:
C linking error (with tcc)
I'm trying to run the example from tiny cc (tcc-0.9.26-win64-bin.zip) called libtcc_test.c.

I've copied libtcc.h from libtcc into include and libtcc.def into lib.

Then I ran tcc ./examples/libtcc_test.c and got a linking error :/

```<code>tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'
</code>```

What am I missing ?

More info:

```<code>P:\cpp\tcc>tcc ./examples/libtcc_test.c -vv
tcc version 0.9.26 (i386 Win32)
-> ./examples/libtcc_test.c
-> p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/_mingw.h
->   p:/cpp/tcc/include/stddef.h
->   p:/cpp/tcc/include/stdarg.h
->  p:/cpp/tcc/include/limits.h
->  p:/cpp/tcc/include/sec_api/stdlib_s.h
->   p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/malloc.h
-> p:/cpp/tcc/include/stdio.h
->  p:/cpp/tcc/include/vadefs.h
->  p:/cpp/tcc/include/sec_api/stdio_s.h
->   p:/cpp/tcc/include/stdio.h
-> p:/cpp/tcc/include/string.h
->  p:/cpp/tcc/include/sec_api/string_s.h
->   p:/cpp/tcc/include/string.h
-> p:/cpp/tcc/include/libtcc.h
-> p:/cpp/tcc/lib/libtcc1.a
-> p:/cpp/tcc/lib/msvcrt.def
-> p:/cpp/tcc/lib/kernel32.def
tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'
</code>```

答:
The following command worked on Windows:

```<code>cd your-tcc-directory
tcc -Ilibtcc -L. -ltcc examples/libtcc_test.c
</code>```

You might want to add -run to skip generating exe file and running the source code directly.

I tried it on Linux, but it couldn't find libtcc.h. I guess the following will work (note -ltcc1 instead of -ltcc):

```<code>tcc -I/path/to/libtcc.h/location -L/usr/lib/tcc/x86-64 -ltcc1 path/to/libtcc_test.c
</code>```

Title: C linking error (with tcc)

Body:
I'm trying to run the example from tiny cc (tcc-0.9.26-win64-bin.zip) called libtcc_test.c.

I've copied libtcc.h from libtcc into include and libtcc.def into lib.

Then I ran tcc ./examples/libtcc_test.c and got a linking error :/

tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'

What am I missing ?

More info:

P:\cpp\tcc>tcc ./examples/libtcc_test.c -vv
tcc version 0.9.26 (i386 Win32)
-> ./examples/libtcc_test.c
-> p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/_mingw.h
->   p:/cpp/tcc/include/stddef.h
->   p:/cpp/tcc/include/stdarg.h
->  p:/cpp/tcc/include/limits.h
->  p:/cpp/tcc/include/sec_api/stdlib_s.h
->   p:/cpp/tcc/include/stdlib.h
->  p:/cpp/tcc/include/malloc.h
-> p:/cpp/tcc/include/stdio.h
->  p:/cpp/tcc/include/vadefs.h
->  p:/cpp/tcc/include/sec_api/stdio_s.h
->   p:/cpp/tcc/include/stdio.h
-> p:/cpp/tcc/include/string.h
->  p:/cpp/tcc/include/sec_api/string_s.h
->   p:/cpp/tcc/include/string.h
-> p:/cpp/tcc/include/libtcc.h
-> p:/cpp/tcc/lib/libtcc1.a
-> p:/cpp/tcc/lib/msvcrt.def
-> p:/cpp/tcc/lib/kernel32.def
tcc: error: undefined symbol 'tcc_new'
tcc: error: undefined symbol 'tcc_set_lib_path'
tcc: error: undefined symbol 'tcc_set_output_type'
tcc: error: undefined symbol 'tcc_compile_string'
tcc: error: undefined symbol 'tcc_add_symbol'
tcc: error: undefined symbol 'tcc_relocate'
tcc: error: undefined symbol 'tcc_get_symbol'
tcc: error: undefined symbol 'tcc_delete'

Body:
The following command worked on Windows:

cd your-tcc-directory
tcc -Ilibtcc -L. -ltcc examples/libtcc_test.c

You might want to add -run to skip generating exe file and running the source code directly.

I tried it on Linux, but it couldn't find libtcc.h. I guess the following will work (note -ltcc1 instead of -ltcc):

tcc -I/path/to/libtcc.h/location -L/usr/lib/tcc/x86-64 -ltcc1 path/to/libtcc_test.c


来源: stackexchange

问:
How can I output data from spreadsheet so it fits a single page for web publishing
I have a reporting program that generates a standard report for all regions. There are 16 regions and each contains many areas (typically between 60 and 250).  I would like to format this report in a manner that makes it easy to publish to the web.

Currently I format the report in Excel and print 16 PDFs (using vba). This works OK except that some of the regions have sufficient areas to warrant a second (or even third) page and this looks 'untidy'

If I define a special paper to the PDF printer then regions with a small number of areas have a lot of blank space at the bottom of the report

Is there some way I can output the information to a 'page' that is just long enough to hold all the information

答:
If the rows in your spreadsheet are of a standard height it would be easy to work out how many fit on a standard page then calculate the number of pages it should fit on and modify your code to use .FitToPagesTall

e.g.

```<code>With ActiveSheet.PageSetup
    .FitToPagesWide = 1
    .FitToPagesTall = 3
End With
</code>```

If the rows are of variable height, write some code to measure the accumulated height, then calculate the number of pages.

Finally, as implicitly the required print area must be changing dynamically you may want to add some code to fit the print area to the active data.

ContentLicense: CC BY-SA 3.0

Body:
If the rows in your spreadsheet are of a standard height it would be easy to work out how many fit on a standard page then calculate the number of pages it should fit on and modify your code to use .FitToPagesTall

e.g.

With ActiveSheet.PageSetup
    .FitToPagesWide = 1
    .FitToPagesTall = 3
End With

If the rows are of variable height, write some code to measure the accumulated height, then calculate the number of pages.

Finally, as implicitly the required print area must be changing dynamically you may want to add some code to fit the print area to the active data.


问:
Increment var each time an event is triggered and display value
I'm trying to increment a variable each time I write 'yes' in the input field, but the n value always stays at '1' in the console.

```<code>$('#txt').on('keyup', function() {
    let n = 0;
    if($(this).val() == 'yes') {
        n++;
        console.log("You wrote 'yes' " + n + " times");
    }
});
</code>```

I'm missing something here but I don't know what. How do I keep incrementing n?

答:
You reset the n variable every time you click because it's inside the handler. So every time that handler is run, a new variable is created with the initial value. Declare and initialize it outside the event handler:

```<code>let n = 0;
$('#txt').on('keyup', function() {
  if($(this).val() == 'yes') {
    n++;
    console.log("You wrote 'yes' " + n + " times");
  }
});
</code>```

This way, the variable is not redeclared and initialized to 0 every time you click, it exists outside the handler.

Body:
I'm trying to increment a variable each time I write 'yes' in the input field, but the n value always stays at '1' in the console.

$('#txt').on('keyup', function() {
    let n = 0;
    if($(this).val() == 'yes') {
        n++;
        console.log("You wrote 'yes' " + n + " times");
    }
});

I'm missing something here but I don't know what. How do I keep incrementing n?

Body:
You reset the n variable every time you click because it's inside the handler. So every time that handler is run, a new variable is created with the initial value. Declare and initialize it outside the event handler:

let n = 0;
$('#txt').on('keyup', function() {
  if($(this).val() == 'yes') {
    n++;
    console.log("You wrote 'yes' " + n + " times");
  }
});

This way, the variable is not redeclared and initialized to 0 every time you click, it exists outside the handler.


问:
How to retrieve currently logged in username in Windows?
I wish to retrieve the username of the currently logged in user in Windows (preferably some solution that works from Windows XP to W10) in a Delphi 7 project.

I tried both solutions given in this question, but they all give the name of the user, not the actual "username" that is used to log into Windows.

For example, the "username" I use to log into Windows is "joao.victor" (using a local Windows account), or my e-mail when I use a Microsoft account. But when I tried those 2 solutions, the string it returned was "João", which is my first name and the name configured in those accounts.

Does anyone know of a solution where I can retrieve the username that is used to log into Windows instead of the first name of the user?

答:
i don't have windows XP to test it but i tried it  on delphi 7  and delphi 10 Seattle</p>

```<code>ShowMessage(GetEnvironmentVariable('USERNAME'));
</code>```

Body:
i don't have windows XP to test it but i tried it  on delphi 7  and delphi 10 Seattle

ShowMessage(GetEnvironmentVariable('USERNAME'));


答: It's because you're declaring the variable inside of your listener. Put it outside of your listener.</p>

Title: Increment var each time an event is triggered and display value


问:
JWT Authentication in ASP.Net Core with ASP Identity
A couple of years ago I implemented a web application using .Net 4.6 and ASP Identity and I used JWT for authorization and authentication on the backend and used AngularJS for the client. As I recall, I used a series of posts on BitOfTech.net as a basis for the implementation. I used VS2015 community for the implementation.

I am now trying to re-implement this application in VS2017 Community using ASP Identity Core, .Net Core and Angular 4.

I have parts of the Angular working and have re-implemented the JWT tokens, and while it responds to the .well-known/openid-configuration end point with the correct data and the AuthorizationController is called with the Token Endpoint the login fails.

I have worked through a number of the problems, the biggest of these being upgrading that database using a SQL Query but the AccountController fails when it calls _userManager.CheckPasswordAsync() which returns false. I am using Postman to run the test and the username and password are correct because the old version running against the same aspnet Identity DB works.

In the earlier project I had to implement a SQLPasswordHasher derived from PasswordHasher which overrode VerifyHashedPassword(). I forget the reasons why I needed to do this but I seem to recall that because the DB was initially built using ASP.Net Membership the stored passwords were generated using an older algorithm.

So I decided to re-implement this and found that I needed to create a class based on IPasswordHasher which implemented VerifyHashedPassword() and HashPassword()

Then all I had to do was during startup inject my SQLPasswordHasher into the UserManager by assigning userManager.PasswordHasher = SQLPasswordHasher

But that is where I am stuck. In my old implementation there was a place in my code where I created a UserManager but the startup has changed so much that I can't find where I would do this. Google suggested modifying IdentityConfig.cs but this no longer appears to be used.

If someone could explain to me how I inject my own PasswordHasher into the UserManager as it is created I would be eternally grateful.

I'm not sure if this is relevant, but I am using OpenIddict.

Thanks for reading this far.

答:
I was correct. I needed to override PasswordHasher and not create a totally new class.

This can be closed


答:
declare n outside event handler, like this:

```<code>let n =0;
$('#txt').on('keyup',function(){
    if($(this).val()=='yes'){
        n++;
        console.log("You wrote 'yes' " +n+ " times");
    }
})
</code>```

Body:
declare n outside event handler, like this:

let n =0;
$('#txt').on('keyup',function(){
    if($(this).val()=='yes'){
        n++;
        console.log("You wrote 'yes' " +n+ " times");
    }
})


答: Scope? just put the variable n outside the event callback ;)</p>


问:
Custom grouping for legend in ggplot
In R, I am trying to create a custom line chart where all the lines are shown on the chart, but the legend for chart is customized to only show two things.

Right now my code:

```<code>x = data.frame(runif(20),runif(20)*2,runif(20)*3)
names(x) = c("Run 1", "Run 2", "Run 3")
x$Avg = apply(x, 1, mean)
x$Step = row.names(x)
df = melt(x, id=c("Step"))
ggplot(df, aes(x=Step, y=value, group=variable, color=variable)) +
  geom_line()
</code>```

Result:

I would like to have the chart show all 4 lines (runs 1,2,3  and avg), but for the legend, I want it to read "Avg" and "Individual Runs", where "Avg" is any color I choose, and each of the "Individual Runs" is in gray or some neutral color. This way when I have lots of runs, I see visually see the data but the legend doesnt go off the screen. How do I accomplish this?

答:
We can use the subset function, and specify colors using two different calls to geom_line:

```<code>ggplot()+
    geom_line(data = subset(df, variable != 'Avg'),
              aes(x = Step, y = value, group = variable, colour = 'Individual Runs'))+
    geom_line(data = subset(df, variable == 'Avg'),
              aes(x = Step, y = value, colour = 'Avg', group = variable))+
    scale_colour_manual(values = c('Avg' = 'red', 'Individual Runs' = 'grey'))
</code>```

Title: Custom grouping for legend in ggplot

Body:
In R, I am trying to create a custom line chart where all the lines are shown on the chart, but the legend for chart is customized to only show two things.

Right now my code:

x = data.frame(runif(20),runif(20)*2,runif(20)*3)
names(x) = c("Run 1", "Run 2", "Run 3")
x$Avg = apply(x, 1, mean)
x$Step = row.names(x)
df = melt(x, id=c("Step"))
ggplot(df, aes(x=Step, y=value, group=variable, color=variable)) +
  geom_line()

Result:

I would like to have the chart show all 4 lines (runs 1,2,3  and avg), but for the legend, I want it to read "Avg" and "Individual Runs", where "Avg" is any color I choose, and each of the "Individual Runs" is in gray or some neutral color. This way when I have lots of runs, I see visually see the data but the legend doesnt go off the screen. How do I accomplish this?

Body:
We can use the subset function, and specify colors using two different calls to geom_line:

ggplot()+
    geom_line(data = subset(df, variable != 'Avg'),
              aes(x = Step, y = value, group = variable, colour = 'Individual Runs'))+
    geom_line(data = subset(df, variable == 'Avg'),
              aes(x = Step, y = value, colour = 'Avg', group = variable))+
    scale_colour_manual(values = c('Avg' = 'red', 'Individual Runs' = 'grey'))


问:
Changing a .click function button to load right away instead?
I'm loading html2canvas which has the following script:

```<code> $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });
</code>```

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

答:
You could probably just run this on the onload function of the body.  This is a pretty good example.

Alternatively

Update your body to be

In your js you can use the following

```<code>function load() {
  html2canvas($(".widget"), {
    onrendered: function(canvas) {
      theCanvas = canvas;
      document.body.appendChild(canvas);

      // Convert and download as image
      Canvas2Image.saveAsPNG(canvas);
      $("#img-out").append(canvas);
      // Clean up
      //document.body.removeChild(canvas);
    }
  });
}
</code>```

Body:
I'm loading html2canvas which has the following script:

 $(function() {
             $("#btnSave").click(function() {
                                 html2canvas($(".widget"), {
                                             onrendered: function(canvas) {
                                             theCanvas = canvas;
                                             document.body.appendChild(canvas);

                                             // Convert and download as image
                                             Canvas2Image.saveAsPNG(canvas);
                                             $("#img-out").append(canvas);
                                             // Clean up
                                             //document.body.removeChild(canvas);
                                             }
                                             });
                                 });
             });

I have a button with the id "btnSave" that when clicked it generates my canvas image. Now, instead of having to click the button I would prefer it to load on the page automatically. Is this possible?

jsFiddle to what I'm working with: https://jsfiddle.net/h5ase09f/

Thanks in advance!

Body:
You could probably just run this on the onload function of the body.  This is a pretty good example.

Alternatively

Update your body to be  <body onload="load">

In your js you can use the following

function load() {
  html2canvas($(".widget"), {
    onrendered: function(canvas) {
      theCanvas = canvas;
      document.body.appendChild(canvas);

      // Convert and download as image
      Canvas2Image.saveAsPNG(canvas);
      $("#img-out").append(canvas);
      // Clean up
      //document.body.removeChild(canvas);
    }
  });
}


问:
How to disable button(s) when another button is pressed?
I have a GUI calcualtor, and I want to disable the digit buttons when the equal button is pressed.

Here is the HTML for the button which contains the digit 1:

```<code><td>
  <button type="button" name="digit" value="1" value2 = "disabled">
    1
  </button>
</td>
</code>```

This is the HTML for the equals button:

```<code><button type="button" name="equals" value="=">
  =
</button>
</code>```

Here is my JavaScript code attempting to disable it...

```<code>document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit").disabled = true;
});
</code>```

Why is this not working? The event listener should disable it.

答:
document.getElementsByName() returns a NodeList collection of elements.

Instead of document.getElementsByName("digit"), you're looking for document.getElementsByName("digit")[0] in order to access the first element in that collection.

document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit")[0].disabled = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td>
  <button type="button" name="digit" value="1" value2="disabled">
    1
  </button>
</td>

<button type="button" name="equals" value="=">
  =
</button></code>```

Hope this helps! :)

ContentLicense: CC BY-SA 4.0

Body:
I have a GUI calcualtor, and I want to disable the digit buttons when the equal button is pressed.

Here is the HTML for the button which contains the digit 1:

  <button type="button" name="digit" value="1" value2 = "disabled">
    1
  </button>

This is the HTML for the equals button:

<button type="button" name="equals" value="=">
  =
</button>

Here is my JavaScript code attempting to disable it...

document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit").disabled = true;
});

Why is this not working? The event listener should disable it.

Body:
document.getElementsByName() returns a NodeList collection of elements.

Instead of document.getElementsByName("digit"), you're looking for document.getElementsByName("digit")[0] in order to access the first element in that collection.

document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit")[0].disabled = true;
});

<td>
  <button type="button" name="digit" value="1" value2="disabled">
    1
  </button>
</td>

<button type="button" name="equals" value="=">
  =
</button>

Hope this helps! :)


问:
How do I render high quality monochrome text with SDL2_TTF?
I'm writing a game with old school low resolution graphics. I'm using SDL2_TTF to render monochrome text but it doesn't seem to be hinted properly. I set the hinting with TTF_SetFontHinting(font, TTF_HINTING_MONO) and rendered the text with all three rendering functions (TTF_RenderText_Solid, TTF_RenderText_Shaded and TTF_RenderText_Blended) but I'm not happy with the results. Here's the output I'm getting from TTF_RenderText_Solid. The other functions output antialiased text.

And here's the output I want. This is Andale Mono 12pt (same as above) rendered by the Mac Terminal emulator and scaled up 4x.

The quality of the output does matter because the text is scaled up 4x when shown to the player. Why are they different? I thought that FreeType was the de-facto font rendering library so SDL2_TTF and Terminal would both be using it.

Am I simply using the SDL2_TTF library incorrectly?

答: I didn't want to mess with the SDL2_TTF library to achieve the effect I was looking for so I decided to find a different font that looks better. I found that if I chose a font that looks pixelated and render it at just the right point size everything looks fine.


问:
Using jquery append or remove on an element with child input elements changes them?
Using jquery 1.9.1; maybe later versions differ?
But the problem seems to be that the input elements revert to their original values, even though the user has changed them. I have the same problem if I do something equivalent in straight javascript using innerHTML. The problem seems to be that the html shows the defaultValue (for type=text) or the defaultChecked (for type=checkbox), and those end up being instantiated as the value or checked in the modified child elements. This seems like a bug; in any case it violates the principle of least surprise.

答:
My workaround is to perform:

```<code>$(element).find('input[type=text]').each(function(i, o) {
  o.defaultValue = o.value;
})
</code>```

and

```<code>$(element).find('input[type=checkbox]').each(function(i, o) {
  o.defaultChecked = o.checked;
})
</code>```

before doing the $(element).append or $(element).remove.

Body:
My workaround is to perform:

$(element).find('input[type=text]').each(function(i, o) {
  o.defaultValue = o.value;
})

and

$(element).find('input[type=checkbox]').each(function(i, o) {
  o.defaultChecked = o.checked;
})

before doing the $(element).append or $(element).remove.


问:
Grouping visits by a number ID
I want to group visits by certain id number because every id represents a different client (think of a subdomain or something like that), for example:

```<code>http://site.com/234/home
http://site.com/234/search/something
</code>```

are URL's for client 234, while...

```<code>http://site.com/155/home
http://site.com/155/search/something
</code>```

are URL's for client 155.

I'm a total noob on this, thx!

答:
No exactly what you asked, but you can go to:

Content

Content Drilldown

See the aggregated unique pageviews and other info for each client /id/

ContentLicense: CC BY-SA 2.5

Title: Grouping visits by a number ID

Body:
I want to group visits by certain id number because every id represents a different client (think of a subdomain or something like that), for example:

http://site.com/234/home
http://site.com/234/search/something

are URL's for client 234, while...

http://site.com/155/home
http://site.com/155/search/something

are URL's for client 155.

I'm a total noob on this, thx!


问:
CLI error on an amazon ec2 when trying to copy file from s3
An error occurred (InvalidRequest) when calling the ListObjects operation:

Missing required header for this request: x-amz-content-sha256

答:
This misleading error shows up when you haven’t authenticated properly. Validate that either

* your ~/.aws/config is correct.

* you’re providing API keys properly at invocation time.

* your environment variables are passing your credentials properly.

* the instance you’re running this from has the proper permissions assigned to its IAM role.


问:
How make association on Rails 4 and Up?
After created the association on user new view and after created the user

the Location did not associated with the user, and in Console show

irb(main):001:0> Location.last ArgumentError: No association found for
  name `user'. Has it been defined yet?

I'm new on Rails 4 and instead of use attr_accessible  i placed the location_attributes on strong params
to see if solve, but did not solved.

someone have a hint to spare?

```<code> def user_params
      params.require(:user).permit(:name, :email,:location_id, :password, :password_confirmation, :slug,
                                   location_attributes:[:id, :location_id])
    end
</code>```

User Model

```<code>belongs_to :location
</code>```

Location Model

```<code>  has_many :users

  accepts_nested_attributes_for :user, allow_destroy: true
</code>```

User new view

```<code><%= simple_form_for @user do |f| %>

  <%= f.input :name, label: 'Your Name please', error: 'Name is mandatory' %>
  <%= f.input :email, placeholder: 'user@domain.com' %>
    <%= f.input :password, hint: 'No special characters.' %>

    <%= f.input :password_confirmation, inline_label: 'Yes, remember me' %>

<%= f.simple_fields_for :location do |l| %>

      <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
<%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>

      <% end %>
    <%= f.button :submit %>
<% end
</code>```

%>

答:
In your Location you define a has_many :users and then you accepts_nested_attributes_for :user, allow_destroy: true (:users vs :user) so it's looking for a different association than the you created.

It also seems like you're creating a user form which will go through the User model to try and create locations but your models are set up such that you create users through a location (so your model doesn't match your view).

I believe what you're wanting to do would be to change your models to

User Controller

```<code>def user_params
  ...location_attributes:[:id, :country, :state])
end
</code>```

User Model

```<code>belongs_to :location

accepts_nested_attributes_for :location, allow_destroy: true
</code>```

Location Model

```<code>has_many :users
</code>```

and that should work. (I haven't done nested forms in years, but looking at the wiki for Simple Form which you appear to be using, this should do it). If that doesn't work, it should at least be a step in the right direction.

Title: How make association on Rails 4 and Up?

Body:
After created the association on user new view and after created the user

the Location did not associated with the user, and in Console show

irb(main):001:0> Location.last ArgumentError: No association found for
  name `user'. Has it been defined yet?

I'm new on Rails 4 and instead of use attr_accessible  i placed the location_attributes on strong params
to see if solve, but did not solved.

someone have a hint to spare?

 def user_params
      params.require(:user).permit(:name, :email,:location_id, :password, :password_confirmation, :slug,
                                   location_attributes:[:id, :location_id])
    end

User Model

belongs_to :location

Location Model

  has_many :users

  accepts_nested_attributes_for :user, allow_destroy: true

User new view

<%= simple_form_for @user do |f| %>

  <%= f.input :name, label: 'Your Name please', error: 'Name is mandatory' %>
  <%= f.input :email, placeholder: 'user@domain.com' %>
    <%= f.input :password, hint: 'No special characters.' %>

    <%= f.input :password_confirmation, inline_label: 'Yes, remember me' %>

<%= f.simple_fields_for :location do |l| %>

      <%= l.input :country, label: "Country", collection: CountryStateSelect.countries_collection %>
<%= l.input :state, CountryStateSelect.state_options(label: "State / Province", form: f, field_names: { :country => :country, :state => :state } ) %>

      <% end %>
    <%= f.button :submit %>
<% end

%>

Body:
In your Location you define a has_many :users and then you accepts_nested_attributes_for :user, allow_destroy: true (:users vs :user) so it's looking for a different association than the you created.

It also seems like you're creating a user form which will go through the User model to try and create locations but your models are set up such that you create users through a location (so your model doesn't match your view).

I believe what you're wanting to do would be to change your models to

User Controller

def user_params
  ...location_attributes:[:id, :country, :state])
end

User Model

belongs_to :location

accepts_nested_attributes_for :location, allow_destroy: true

Location Model

has_many :users

and that should work. (I haven't done nested forms in years, but looking at the wiki for Simple Form which you appear to be using, this should do it). If that doesn't work, it should at least be a step in the right direction.


问:
Podio: Can I set a reminder on a date field through the API/SDK?
I've got an app in Podio that represents Meetings. One of the fields is time/date and it allows a reminder to be set for that time/date (much like you can with tasks).

I've also got an iOS app that can create Meeting items and I was hoping there was a way to programatically create a reminder when the item is created (or that a workflow could be created to handle it) but it doesn't seem to be possible. The Reminders API only works for tasks, according to the documentation, and there doesn't seem to be another way to do this?

答:
It might be missing in documentation, but reminders should also work for items.

Please try to create one using details from here: https://developers.podio.com/doc/reminders/create-or-update-reminder-3315055 and use item as ref_type and your item id as ref_id


问:
Not condition in NLTK Regex Parser
I need to create a not condition as part of my grammar in NLTK's regex parser. I would like to chunk those words which are of structure 'Coffee & Tea' but it should not chunk if there is a word of type <IN> before the sequence. For example 'in London and Paris' should not be chunked by the parser.

My code is as follows:

```<code>grammar = r'''NP: {(^<IN>)<NNP>+<CC><NN.*>+}'''
</code>```

I tried the above grammar to solve the problem but it is not working could someone please tell me what I am doing wrong.

Example:

```<code>def parse_sentence(sentence):
    pos_sentence = nltk.pos_tag(nltk.word_tokenize(sentence))
    grammar = r'''NP: {<NNP>+<CC><NN.*>+}'''
    parser = nltk.RegexpParser(grammar)
    result = parser.parse(pos_sentence)
    print result

sentence1 = 'Who is the front man of the band that wrote Coffee & TV?'
parse_sentence(sentence1)

sentence2 = 'Who of those resting in Westminster Abbey wrote a book set in London and Paris?'
parse_sentence(sentence2)

Result for sentence 1 is:
(S
  Who/WP
  is/VBZ
  the/DT
  front/JJ
  man/NN
  of/IN
  the/DT
  band/NN
  that/WDT
  wrote/VBD
  (NP Coffee/NNP &/CC TV/NN)
  ?/.)

Result for sentence2 is:
(S
  Who/WP
  of/IN
  those/DT
  resting/VBG
  in/IN
  Westminster/NNP
  Abbey/NNP
  wrote/VBD
  a/DT
  book/NN
  set/VBN
  in/IN
  (NP London/NNP and/CC Paris/NNP)
  ?/.)
</code>```

As can be seen in both sentence1 and sentence2 the phrases Coffee & Tea and London and Paris get chunked as a group although I do not wish to chunk London and Paris. One way of doing that is to ignore those patterns which are preceded by a <IN> POS Tag.

In a nutshell I need to know how to add NOT(negation) conditions for POS tags in a regex parser's grammar. Standard syntax of using '^' followed by the tag definition does not seem to work

答:
cp.2.5   "Chinking"

"We can define a chink to be a sequence of tokens that is not included in a chunk"

http://www.nltk.org/book/ch07.html

See inverse curly braces for exclusion

```<code>grammar =
        r"""
          NP:
            {<.*>+}          # Chunk everything
            }<VBD|IN>+{      # Chink sequences of VBD and IN

         """
</code>```

Title: Not condition in NLTK Regex Parser

Body:
I need to create a not condition as part of my grammar in NLTK's regex parser. I would like to chunk those words which are of structure 'Coffee & Tea' but it should not chunk if there is a word of type <IN> before the sequence. For example 'in London and Paris' should not be chunked by the parser.

My code is as follows:

grammar = r'''NP: {(^<IN>)<NNP>+<CC><NN.*>+}'''

I tried the above grammar to solve the problem but it is not working could someone please tell me what I am doing wrong.

Example:

def parse_sentence(sentence):
    pos_sentence = nltk.pos_tag(nltk.word_tokenize(sentence))
    grammar = r'''NP: {<NNP>+<CC><NN.*>+}'''
    parser = nltk.RegexpParser(grammar)
    result = parser.parse(pos_sentence)
    print result

sentence1 = 'Who is the front man of the band that wrote Coffee & TV?'
parse_sentence(sentence1)

sentence2 = 'Who of those resting in Westminster Abbey wrote a book set in London and Paris?'
parse_sentence(sentence2)

Result for sentence 1 is:
(S
  Who/WP
  is/VBZ
  the/DT
  front/JJ
  man/NN
  of/IN
  the/DT
  band/NN
  that/WDT
  wrote/VBD
  (NP Coffee/NNP &/CC TV/NN)
  ?/.)

Result for sentence2 is:
(S
  Who/WP
  of/IN
  those/DT
  resting/VBG
  in/IN
  Westminster/NNP
  Abbey/NNP
  wrote/VBD
  a/DT
  book/NN
  set/VBN
  in/IN
  (NP London/NNP and/CC Paris/NNP)
  ?/.)

As can be seen in both sentence1 and sentence2 the phrases Coffee & Tea and London and Paris get chunked as a group although I do not wish to chunk London and Paris. One way of doing that is to ignore those patterns which are preceded by a <IN> POS Tag.

In a nutshell I need to know how to add NOT(negation) conditions for POS tags in a regex parser's grammar. Standard syntax of using '^' followed by the tag definition does not seem to work

Body:
cp.2.5   "Chinking"

"We can define a chink to be a sequence of tokens that is not included in a chunk"

http://www.nltk.org/book/ch07.html

See inverse curly braces for exclusion

grammar =
        r"""
          NP:
            {<.*>+}          # Chunk everything
            }<VBD|IN>+{      # Chink sequences of VBD and IN

         """


问:
SVG animation Round Trip?
I'd like to make my svg shrinking onclick, and growing on click when shrinked.

How is this achievable ? I tried some stuff in Javascript but couldn't find an easy way to proceed.

For example this SVG :

```<code>    <svg id="MyRect" width="100" height="100" viewbox="0 0 100 100">
        <polygon fill="#000000" points="0,0 0,100 100,100 100,0">
            <animate id="shrink" attributeName="points" begin="undefined" restart="whenNotActive" dur="1s" from="0,0 0,100 100,100 100,0" to="30,30 30,70 70,70 70,30" fill="freeze" />
            <animate id="grow" attributeName="points" begin="undefined" restart="whenNotActive" dur="1s" from="30,30 30,70 70,70 70,30" to="0,0 0,100 100,100 100,0" fill="freeze" />
        </polygon>
    </svg>
</code>```

How Can I manage to trigger an animation or the other according to his "state" ?

Thanks.

答:
You can't change the animation each time you click with pure SMIL so I swap between two polygons with different animation. There's no javascript required in my solution.

    <svg id="MyRect" width="100" height="100" viewBox="0 0 100 100">
        <polygon fill="#000000" points="0,0 0,100 100,100 100,0">
            <animate id="shrink" attributeName="points" begin="click" restart="whenNotActive" dur="1s" to="30,30 30,70 70,70 70,30" fill="freeze" />
            <set attributeName="display" begin="shrink.end" to="none" />
            <set attributeName="display" begin="grow.end" to="block" />
            <set attributeName="points" begin="grow.end" to="0,0 0,100 100,100 100,0" />
        </polygon>
        <polygon fill="#000000"  points="30,30 30,70 70,70 70,30" display="none">
            <animate id="grow" attributeName="points" begin="click" restart="whenNotActive" dur="1s" to="0,0 0,100 100,100 100,0" fill="freeze" />
            <set attributeName="display" begin="grow.end" to="none" />
            <set attributeName="display" begin="shrink.end" to="block" />
            <set attributeName="points" begin="grow.end" to="30,30 30,70 70,70 70,30" />
        </polygon>
    </svg>```

Title: SVG animation Round Trip?

Body:
I'd like to make my svg shrinking onclick, and growing on click when shrinked.

How is this achievable ? I tried some stuff in Javascript but couldn't find an easy way to proceed.

For example this SVG :

    <svg id="MyRect" width="100" height="100" viewbox="0 0 100 100">
        <polygon fill="#000000" points="0,0 0,100 100,100 100,0">
            <animate id="shrink" attributeName="points" begin="undefined" restart="whenNotActive" dur="1s" from="0,0 0,100 100,100 100,0" to="30,30 30,70 70,70 70,30" fill="freeze" />
            <animate id="grow" attributeName="points" begin="undefined" restart="whenNotActive" dur="1s" from="30,30 30,70 70,70 70,30" to="0,0 0,100 100,100 100,0" fill="freeze" />
        </polygon>
    </svg>

How Can I manage to trigger an animation or the other according to his "state" ?

Thanks.


问:
dotnetopenauth Realm protocol exception
Using dotnetopenauth, my code worked fine when using openId.CreateRequest(openIdIdentifier). The return url was /default.aspx which i didnt want so to specify the return_to param i had to fill in realm. The desc of the 2nd param is

```<code>    //   realm:
    //     The shorest URL that describes this relying party web site's address.  For
    //     example, if your login page is found at https://www.example.com/login.aspx,
    //     your realm would typically be https://www.example.com/.
</code>```

So logically the correct code is

```<code>var request = openId.CreateRequest(openIdIdentifier, new Uri("http://localdev.com:8844/"), new Uri("http://localdev.com:8844/login"));
</code>```

However i get this ProtocolException

The openid.return_to parameter
  (http://localdev.com:8844/login?dnoa.userSuppliedIdentifier=http://myid.myopenid.com/)
  does not match the actual URL
  (http://localdev.com:8844/Default.aspx?dnoa.userSuppliedIdentifier=http://myid.myopenid.com/&openid.assoc_handle=...)
  the request was made with.

WTF

How do i return to /login without an exception? and bonus points if you can tell me how to have it use POST instead of GET

答:
I assume you get this error after the OpenID Provider appears on the browser, and during the redirect back to the RP, is that right?

It looks like the Provider you're testing with is sending the browser to the wrong URL.  But since it's very unlikely for a Provider to manufacture "default.aspx" out of nowhere, we need to look at the logs to find out exactly what's going on.

You can obtain logs locally by following these instructions.
or by trying to log into your own RP site with this OpenID identifier: http://test-id.org/RP/POSTAssertion.aspx  This is a diagnostic identifier that will produce log messages at http://test-id.org/TracePage.aspx.  Either way you collect them, please add the relevant logs to your question so we can better analyze what's going on.

Title: dotnetopenauth Realm protocol exception

Body:
Using dotnetopenauth, my code worked fine when using openId.CreateRequest(openIdIdentifier). The return url was /default.aspx which i didnt want so to specify the return_to param i had to fill in realm. The desc of the 2nd param is

    //   realm:
    //     The shorest URL that describes this relying party web site's address.  For
    //     example, if your login page is found at https://www.example.com/login.aspx,
    //     your realm would typically be https://www.example.com/.

So logically the correct code is

var request = openId.CreateRequest(openIdIdentifier, new Uri("http://localdev.com:8844/"), new Uri("http://localdev.com:8844/login"));

However i get this ProtocolException

The openid.return_to parameter
  (http://localdev.com:8844/login?dnoa.userSuppliedIdentifier=http://myid.myopenid.com/)
  does not match the actual URL
  (http://localdev.com:8844/Default.aspx?dnoa.userSuppliedIdentifier=http://myid.myopenid.com/&openid.assoc_handle=...)
  the request was made with.

WTF

How do i return to /login without an exception? and bonus points if you can tell me how to have it use POST instead of GET


问:
How to create a dataframe by applying a function on two vectors
I have two different sized character vectors, say a and b, which I would like to form the row names and column names of a new dataframe (df).

If I have a function which takes 2 arguments, an element from each of these vectors, which gives the data to go into the dataframe, how can I create it?

I've tried looking at map2 but it needs the two arguments to be the same size, and I can't quite see how I could use an apply function.

答:
Here is an option using tidyverse

```<code>library(tidyverse)
crossing(a, col1 = b) %>%
      unite(val, a, col1, sep="", remove = FALSE) %>%
      spread(a, val)
# A tibble: 3 x 6
#   col1     a     b     c     d     e
#* <chr> <chr> <chr> <chr> <chr> <chr>
#1     g    ag    bg    cg    dg    eg
#2     h    ah    bh    ch    dh    eh
#3     i    ai    bi    ci    di    ei
</code>```

data

```<code>a <- letters[1:5]
b <- letters[7:9]
</code>```

Body:
Here is an option using tidyverse

library(tidyverse)
crossing(a, col1 = b) %>%
      unite(val, a, col1, sep="", remove = FALSE) %>%
      spread(a, val)
# A tibble: 3 x 6
#   col1     a     b     c     d     e
#* <chr> <chr> <chr> <chr> <chr> <chr>
#1     g    ag    bg    cg    dg    eg
#2     h    ah    bh    ch    dh    eh
#3     i    ai    bi    ci    di    ei

data

a <- letters[1:5]
b <- letters[7:9]


问:
Use a variable to reference a partial view's location
I am new to asp.net core and am trying to render a partial view in an ASP.Net Core application. The address of the partial view is determined at run time. I have constructed a view model which is parsed into the view from the controller and contains the desired file address.

The following code throws the following compiler error:

```<code>@Html.Partial(Model.File);
</code>```

Error CS1973 'IHtmlHelper' has no applicable method named 'Partial'
   but appears to have an extension method by that name. Extension methods
   cannot be dynamically dispatched. Consider casting the dynamic arguments or
   calling the extension method without the extension method syntax.

Any help would be greatly appreciated.

答:
The solution in the end was to specify the type in the Razor file. The following line worked:</p>

```<code>@Html.Partial((string) Model.File)
</code>```

Body:
I am new to asp.net core and am trying to render a partial view in an ASP.Net Core application. The address of the partial view is determined at run time. I have constructed a view model which is parsed into the view from the controller and contains the desired file address.

The following code throws the following compiler error:

@Html.Partial(Model.File);

Error CS1973 'IHtmlHelper' has no applicable method named 'Partial'
   but appears to have an extension method by that name. Extension methods
   cannot be dynamically dispatched. Consider casting the dynamic arguments or
   calling the extension method without the extension method syntax.

Any help would be greatly appreciated.

Body:
The solution in the end was to specify the type in the Razor file. The following line worked:

@Html.Partial((string) Model.File)


问:
CSS max-height and overflow auto always displays vertical scroll
I have a div class set up with the following CSS style:

```<code>div.multiple_choice{
    border: 1px solid black;
    max-width: 300px;
    max-height: 200px;
    overflow: auto;
}
</code>```

The problem is, when the text inside doesn't force the DIV to reach the maximum height of 200px, the vertical scroll bar still shows up.  I can click on the up and down arrows but it only moves the contents up and down by about a pixel or two.

This is occuring in Google Chrome (version 18.0) and Iceweasel 11.

答:
I had this problem when trying to wrap a list (flex column) of react components in a div, I resolved it by changing margin of elements within each list item to be 0.

The approach to troubleshoot this for me was to inspect the list items (perhaps each
 in OP) and see what styles were making the div think each list item was larger than what was visible to the human eye.

Here is an example of inspecting a rogue margin on an icon within a list item in my project:

Solution is to set the style of that icon to have a vertical margin of 0, though in my application I just made all the margin 0 and added some padding-right.

Body:
I have a div class set up with the following CSS style:

div.multiple_choice{
    border: 1px solid black;
    max-width: 300px;
    max-height: 200px;
    overflow: auto;
}

The problem is, when the text inside doesn't force the DIV to reach the maximum height of 200px, the vertical scroll bar still shows up.  I can click on the up and down arrows but it only moves the contents up and down by about a pixel or two.

This is occuring in Google Chrome (version 18.0) and Iceweasel 11.

Body:
I had this problem when trying to wrap a list (flex column) of react components in a div, I resolved it by changing margin of elements within each list item to be 0.

The approach to troubleshoot this for me was to inspect the list items (perhaps each <li> in OP) and see what styles were making the div think each list item was larger than what was visible to the human eye.

Here is an example of inspecting a rogue margin on an icon within a list item in my project:

Solution is to set the style of that icon to have a vertical margin of 0, though in my application I just made all the margin 0 and added some padding-right.


问:
Fragment Cache a user control in asp.net webform Masterpage
I had a Masterpage which uses as sidebar for navigation .I created a user control for that sidebar  as each user will have their own set of navigation menus.

Inside my UserMenu I use Infragistic webexplorer and Iam creating each item  of webexplorer using ado.net result from database dynamically.

Everything is working fine .in high bandwidth but in low bandwidth it takes 3-4 seconds for the menubar to load.causing users to wait so much on each postback.

So I tried fragment caching .but i seems not working.can you suggest me whats wrong

In masterpage I did

```<code>    <div>
    //this is my usercontrol
                         <uc1:DynamicMenuBar runat="server" id="DynamicMenuBar" />
    </div>
     <div id="main" class="content" >

       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
                    <div class="bodybackground">
                    </div>

                </asp:ContentPlaceHolder>
  </div>
</code>```

In my usercontrol .ascx

```<code><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenuBar.ascx.cs" Inherits="ArtWebApp.DynamicMenuBar" %>
<%@ Register assembly="Infragistics35.Web.v12.1, Version=12.1.20121.2236, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.NavigationControls" tagprefix="ig" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
<ig:WebExplorerBar ID="WebExplorerBar1" runat="server" Width="250px">
</ig:WebExplorerBar>
</code>```

And in my usercontrol .ascx.cs I had done the below

```<code>   public partial class DynamicMenuBar : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadexplorerebar(); //this function creates the groups and childs based on the database result dynamically
                this.WebExplorerBar1.EnableViewState = true;
            }
        }
</code>```

答:
I believe Page_Load will still be called even if the uc is cached.  Try checking to see if it's in the cache before calling loadexplorerebar().  It'll be null if it's not in the cache.

So try changing:

```<code>if (!IsPostBack)
</code>```

to:

```<code>if (!IsPostBack && WebExplorerBar1 == null)
</code>```

Body:
I had a Masterpage which uses as sidebar for navigation .I created a user control for that sidebar  as each user will have their own set of navigation menus.

Inside my UserMenu I use Infragistic webexplorer and Iam creating each item  of webexplorer using ado.net result from database dynamically.

Everything is working fine .in high bandwidth but in low bandwidth it takes 3-4 seconds for the menubar to load.causing users to wait so much on each postback.

So I tried fragment caching .but i seems not working.can you suggest me whats wrong

In masterpage I did

    //this is my usercontrol
                         <uc1:DynamicMenuBar runat="server" id="DynamicMenuBar" />

       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                </asp:ContentPlaceHolder>

In my usercontrol .ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DynamicMenuBar.ascx.cs" Inherits="ArtWebApp.DynamicMenuBar" %>
<%@ Register assembly="Infragistics35.Web.v12.1, Version=12.1.20121.2236, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" namespace="Infragistics.Web.UI.NavigationControls" tagprefix="ig" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
<ig:WebExplorerBar ID="WebExplorerBar1" runat="server" Width="250px">
</ig:WebExplorerBar>

And in my usercontrol .ascx.cs I had done the below

   public partial class DynamicMenuBar : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                loadexplorerebar(); //this function creates the groups and childs based on the database result dynamically
                this.WebExplorerBar1.EnableViewState = true;
            }
        }

Body:
I believe Page_Load will still be called even if the uc is cached.  Try checking to see if it's in the cache before calling loadexplorerebar().  It'll be null if it's not in the cache.

So try changing:

if (!IsPostBack)

to:

if (!IsPostBack && WebExplorerBar1 == null)


问:
python anti_vowel function error
Hi I'm doing the anti_vowel function, which basically takes out all of the vowels from the input. I'm confused about this code. Why doesn't it work? (For the last word "word")  The output for "Hey look words!" is:
Hy lk words!
If anyone can help, thank you so so much!

```<code>def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)

    for i in l:
        if i in "aeiouAEIOU":
            x = l.index(i)
            l.pop(x)
    print l
    print "".join(l)

anti_vowel("Hey look words!")
</code>```

The output is:
Hy lk Wrds!

答:
You're deleting elements from the list as you iterate over it. You're actually shortening the list before the loop can even reach the '...words' part.

A couple of other things. If you want to convert a string to a list, you can just do:

```<code>myList = list(myString)
</code>```

Next, when iterating, do iterate over a copy of the list.

```<code>for i in l[:]:
</code>```

The [:] operator creates a spliced copy, and iterates over that. This is the big fix, and it'll get your code running as expected. For that particular input, you get Hy lk wrds!.

Simpler alternative? Don't even use a list. You can work with strings, using the str.replace function:

```<code>def anti_vowel(text):
    newText = text[:]
    for i in 'aeiouAEIOU':
        newText = newText.replace(i, '')

    print(newText)
    return newText

newText = anti_vowel("Hey look words!")
print(newText)
</code>```

Output:

```<code>Hy lk wrds!
</code>```

An even simpler version? You can use str.translate:

```<code>>>> x = {c : '' for c in 'aeiouAEIOU'}
>>> "Hey look words!".translate(str.maketrans(x))
'Hy lk wrds!'
</code>```

Title: python anti_vowel function error

Body:
Hi I'm doing the anti_vowel function, which basically takes out all of the vowels from the input. I'm confused about this code. Why doesn't it work? (For the last word "word")  The output for "Hey look words!" is:
Hy lk words!
If anyone can help, thank you so so much!

def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)

    for i in l:
        if i in "aeiouAEIOU":
            x = l.index(i)
            l.pop(x)
    print l
    print "".join(l)

anti_vowel("Hey look words!")

The output is:
Hy lk Wrds!

Body:
You're deleting elements from the list as you iterate over it. You're actually shortening the list before the loop can even reach the '...words' part.

A couple of other things. If you want to convert a string to a list, you can just do:

myList = list(myString)

Next, when iterating, do iterate over a copy of the list.

for i in l[:]:

The [:] operator creates a spliced copy, and iterates over that. This is the big fix, and it'll get your code running as expected. For that particular input, you get Hy lk wrds!.

Simpler alternative? Don't even use a list. You can work with strings, using the str.replace function:

def anti_vowel(text):
    newText = text[:]
    for i in 'aeiouAEIOU':
        newText = newText.replace(i, '')

    print(newText)
    return newText

newText = anti_vowel("Hey look words!")
print(newText)

Output:

Hy lk wrds!

An even simpler version? You can use str.translate:

>>> x = {c : '' for c in 'aeiouAEIOU'}
>>> "Hey look words!".translate(str.maketrans(x))
'Hy lk wrds!'


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答:
'Turing Completeness' describes the property of being able to express any arbitrary algorithmic computation, which was the point of Turing's Machine in the first place.  A language or logical system can be described as 'Turing Complete' if it has this property.  From a practical perspective all general purpose programming languages - and a surprisingly large number of special purpose ones - can do this for a suitably loose definition (see below).

However, a strict definition of Turing Completeness implies infinite storage capacity, which is of course not physically possible.  Given this, no physical machine can possibly be Turing Complete, but this constraint is usually relaxed (at least informally) when ascribing Turing Completeness to a programming language.  One trivial test of Turing Completeness for a language is whether the language can be used to implement a Turing Machine simulator.

An example of a widespread system that is not Turing Complete is Relational Algebra, the theoretical basis behind SQL as described in Codd's paper A relational model for large shared data banks.  Relational Algebra has the property of Godel Completeness, which means that it can express any computation that can be defined in terms of first-order predicate calculus (i.e. ordinary logical expressions).  However, it is not Turing-Complete as it cannot express an arbitrary algorithmic computation.

Note that most if not all all practical SQL dialects extend the pure relational model with procedural constructs  to the extent that they are Turing Complete by the definition as normally applied to programming languages.  However, an individual SQL query by and large is not.

Some more egregious examples of Turing Complete domain-specific languages are TeX and sendmail.cf,.  In the latter case there is actually a famous-ish example of someone using sendmail.cf to implement a universal Turing Machine simulator.

OwnerDisplayName: AShelly

LastEditorDisplayName: AShelly

OwnerDisplayName: NXC

LastEditorDisplayName: NXC


问:
MATLAB offset surface
I want to offset surfaces which have grid points. I have some grid points for my goemetrical problem I can plot it with matlab but I can not offset surfaces.

Thanks for your interest

Aliis

答:
I don't fully understand your question, but if you want arbitrary 3D plots not on the grid, you can try delaunay and trisurf.

```<code>N = 300;
X = randn(N,1);
Y = randn(N,1);
Z = sin(X+Y.^2);
tri = delaunay(X,Y);
trisurf(tri,X,Y,Z);
</code>```

Title: MATLAB offset surface

Body:
I don't fully understand your question, but if you want arbitrary 3D plots not on the grid, you can try delaunay and trisurf.

N = 300;
X = randn(N,1);
Y = randn(N,1);
Z = sin(X+Y.^2);
tri = delaunay(X,Y);
trisurf(tri,X,Y,Z);


问:
Traefik https redirect (via kubernetes deployment)
I'm running traefik on AWS via kubernetes. It all works, except for my http=>https redirect configuration.

I have the following .toml file

```<code>defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
</code>```

With the Kubernetes Deployment + Service configurations below.

https requests work file, but http requests return:

```<code>> curl http://www.myserver.com
curl: (52) Empty reply from server
</code>```

Kubernetes config files:

```<code>kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: traefik-proxy
  labels:
    app: traefik-proxy
    tier: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: traefik-proxy
      tier: proxy
  template:
    metadata:
      labels:
        app: traefik-proxy
        tier: proxy
    spec:
      terminationGracePeriodSeconds: 60

      # kubectl create configmap traefik-conf --from-file=./conf/k8s/traefik.toml
      volumes:
      - name: config
        configMap:
          name: traefik-conf

      containers:
      - image: traefik:v1.2.0-rc1-alpine
        name: traefik-proxy
        resources:
          limits:
            cpu: "200m"
            memory: "30Mi"
          requests:
            cpu: "100m"
            memory: "20Mi"
        volumeMounts:
        - mountPath: "/conf"
          name: config
        ports:
        - containerPort: 80
          hostPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --configFile=/conf/traefik.toml
        - --kubernetes
        - --web
---
apiVersion: v1
kind: Service
metadata:
  name: traefik-proxy
  annotations:
    # SSL certificate.
    # https://console.aws.amazon.com/acm (alienlabs.io)
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-east-1:861694698401:certificate/28204a9f-69ec-424d-8f56-ac085b7bdad8"
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
spec:
  type: LoadBalancer
  selector:
    app: traefik-proxy
    tier: proxy
  ports:
  - port: 80
    targetPort: 80
    name: http
  - port: 443
    targetPort: 80
    name: https
</code>```

答:
You want to state your EntryPoints slightly differently:</p>

```<code>defaultEntryPoints = ["http","https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    regex = "^http://(.*)"
    replacement = "https://$1"
  [entryPoints.https]
  address = ":443"
</code>```

Body:
I'm running traefik on AWS via kubernetes. It all works, except for my http=>https redirect configuration.

I have the following .toml file

defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"

With the Kubernetes Deployment + Service configurations below.

https requests work file, but http requests return:

> curl http://www.myserver.com
curl: (52) Empty reply from server

Kubernetes config files:

kind: Deployment
apiVersion: extensions/v1beta1
metadata:
  name: traefik-proxy
  labels:
    app: traefik-proxy
    tier: proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: traefik-proxy
      tier: proxy
  template:
    metadata:
      labels:
        app: traefik-proxy
        tier: proxy
    spec:
      terminationGracePeriodSeconds: 60

      # kubectl create configmap traefik-conf --from-file=./conf/k8s/traefik.toml
      volumes:
      - name: config
        configMap:
          name: traefik-conf

      containers:
      - image: traefik:v1.2.0-rc1-alpine
        name: traefik-proxy
        resources:
          limits:
            cpu: "200m"
            memory: "30Mi"
          requests:
            cpu: "100m"
            memory: "20Mi"
        volumeMounts:
        - mountPath: "/conf"
          name: config
        ports:
        - containerPort: 80
          hostPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --configFile=/conf/traefik.toml
        - --kubernetes
        - --web
---
apiVersion: v1
kind: Service
metadata:
  name: traefik-proxy
  annotations:
    # SSL certificate.
    # https://console.aws.amazon.com/acm (alienlabs.io)
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: "arn:aws:acm:us-east-1:861694698401:certificate/28204a9f-69ec-424d-8f56-ac085b7bdad8"
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: "http"
spec:
  type: LoadBalancer
  selector:
    app: traefik-proxy
    tier: proxy
  ports:
  - port: 80
    targetPort: 80
    name: http
  - port: 443
    targetPort: 80
    name: https

Body:
You want to state your EntryPoints slightly differently:

defaultEntryPoints = ["http","https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
    regex = "^http://(.*)"
    replacement = "https://$1"
  [entryPoints.https]
  address = ":443"


答:
Modifying an iterator (your list) while looping over it will end up yielding very unexpected results, and should always be avoided. In your particular case, as you delete your list, you are actually reducing it, and therefore actually ending it "earlier" than you should.

What you should be doing instead is collecting your data in a new list based on what you are trying to filter. So, instead of popping, instead you should check for non-vowels and append to a new list. Taking your exact code and changing just that logic, you should be good:

```<code>def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)
    new_l = []
    for i in l:
        if i not in "aeiouAEIOU":
            new_l.append(i)

    print("".join(new_l))
</code>```

So, running that code now, will yield the following output:

```<code>Hy lk wrds!
</code>```

Now, to go over some areas in your code where you are doing some unnecessary steps that you can simplify. You do not need to loop through your string like that and create a new list at the beginning of your function. Your string can already be iterated over, so simply do exactly that using your string. In other words you do not need this:

```<code>    l = []
    s = ""
    for i in text:
        l.append(i)
</code>```

So, instead, you can just start from:

```<code>    new_l = []
    for i in text:
        if i not in "aeiouAEIOU":
            new_l.append(i)
    print("".join(new_l))
</code>```

So, the above code now simply iterates over your string text, character-by-character, and we will check to make sure that each character does not match the vowels, and append it to our new list.

Finally, for the sake of really making this short. We can throw this in to a pretty little line making an expression that we can then call join on to create our string. Also! you don't need to check all cases since you can just keep your characters to a single casing by calling the lower method on your string you are iterating through to keep all under a single case, to make it simpler to check:

```<code>def anti_vowel(text):
    return ''.join(c for c in text if c.lower() not in "aeiou")

print(anti_vowel("Hey look words!"))
</code>```

Title: python anti_vowel function error

Body:
Modifying an iterator (your list) while looping over it will end up yielding very unexpected results, and should always be avoided. In your particular case, as you delete your list, you are actually reducing it, and therefore actually ending it "earlier" than you should.

What you should be doing instead is collecting your data in a new list based on what you are trying to filter. So, instead of popping, instead you should check for non-vowels and append to a new list. Taking your exact code and changing just that logic, you should be good:

def anti_vowel(text):
    l = []
    s = ""
    for i in text:
        l.append(i)
    new_l = []
    for i in l:
        if i not in "aeiouAEIOU":
            new_l.append(i)

    print("".join(new_l))

So, running that code now, will yield the following output:

Hy lk wrds!

Now, to go over some areas in your code where you are doing some unnecessary steps that you can simplify. You do not need to loop through your string like that and create a new list at the beginning of your function. Your string can already be iterated over, so simply do exactly that using your string. In other words you do not need this:

    l = []
    s = ""
    for i in text:
        l.append(i)

So, instead, you can just start from:

    new_l = []
    for i in text:
        if i not in "aeiouAEIOU":
            new_l.append(i)
    print("".join(new_l))

So, the above code now simply iterates over your string text, character-by-character, and we will check to make sure that each character does not match the vowels, and append it to our new list.

Finally, for the sake of really making this short. We can throw this in to a pretty little line making an expression that we can then call join on to create our string. Also! you don't need to check all cases since you can just keep your characters to a single casing by calling the lower method on your string you are iterating through to keep all under a single case, to make it simpler to check:

def anti_vowel(text):
    return ''.join(c for c in text if c.lower() not in "aeiou")

print(anti_vowel("Hey look words!"))


答:
You should never alter an iterable (list in this case) while you're iterating over it. Bad things can and do happen.

Here's a different and a bit simpler way to do it. Instead of removing vowels from a list, instead, we create an empty list, and put the constants into it:

```<code>def anti_vowel(text):
    consts = []

    for letter in text:
        if letter not in "aeiouAEIOU":
            consts.append(letter)

    print "".join(consts)

anti_vowel("Hey look words!")
</code>```

Output:

```<code>Hy lk wrds!
</code>```

Title: python anti_vowel function error

Body:
You should never alter an iterable (list in this case) while you're iterating over it. Bad things can and do happen.

Here's a different and a bit simpler way to do it. Instead of removing vowels from a list, instead, we create an empty list, and put the constants into it:

def anti_vowel(text):
    consts = []

    for letter in text:
        if letter not in "aeiouAEIOU":
            consts.append(letter)

    print "".join(consts)

anti_vowel("Hey look words!")

Output:

Hy lk wrds!


问:
fade in and fade out div onclick with jQuery
I have a div on left and right of the page. Currently the div on the right is being hidden.

I'm trying to use jQuery to fadeout the div that is currently being displayed and replace it by fading in the hidden div.

What am I doing wrong? I followed the example on this similar question.

It should happen when you click the About link in the code snippet:

$("a").on('click', function() {
  $("#feed-show").fadeIn();
  $(".feed").fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: rgba(255, 80, 70, 1) !important;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255, 80, 70, 1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float: left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255, 80, 70, 1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float: left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top: 2.5%;
}

.feed-show {
  position: absolute !important;
  top: -9999px !important;
  left: -9999px !important;
  background: red;
}</code>```

    About

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.

      Find out more about Creatives of Colour..

        Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.

        Find out more about Creatives of Colour..

```

Here is a codepen

Many thanks!

答:
You have some problems on your code.

First, your feed-show div is inside your feed div. So if you fadeOut() your feed div, everything inside will be hidden.

And second, in your CSS you have absolute position and top and left properties set for your feed-show, so even if you fadeIn() that element, you're not gonna be able to see it.

I've made a couple of changes on your code, so you can see how one div is fade out and the other one is fade in.

Cheers!

$("a").on('click', function() {
   $("#feed-show").fadeIn();
   $(".feed").fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: rgba(255,80,70,1) !important ;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255,80,70,1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float:left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255,80,70,1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float:left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top:2.5%;
}

.feed-show {
  display: none;
  background:red;
}</code>```

    About

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.

      Find out more about Creatives of Colour..

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.

      Find out more about Creatives of Colour..

```

Body:
I have a div on left and right of the page. Currently the div on the right is being hidden.

I'm trying to use jQuery to fadeout the div that is currently being displayed and replace it by fading in the hidden div.

What am I doing wrong? I followed the example on this similar question.

It should happen when you click the About link in the code snippet:

$("a").on('click', function() {
  $("#feed-show").fadeIn();
  $(".feed").fadeOut();
});

a {
  color: rgba(255, 80, 70, 1) !important;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255, 80, 70, 1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float: left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255, 80, 70, 1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float: left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top: 2.5%;
}

.feed-show {
  position: absolute !important;
  top: -9999px !important;
  left: -9999px !important;
  background: red;
}

    About

      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.

      Find out more about Creatives of Colour..

        Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.

        Find out more about Creatives of Colour..

Here is a codepen

Many thanks!

Body:
You have some problems on your code.

First, your feed-show div is inside your feed div. So if you fadeOut() your feed div, everything inside will be hidden.

And second, in your CSS you have absolute position and top and left properties set for your feed-show, so even if you fadeIn() that element, you're not gonna be able to see it.

I've made a couple of changes on your code, so you can see how one div is fade out and the other one is fade in.

Cheers!

$("a").on('click', function() {
   $("#feed-show").fadeIn();
   $(".feed").fadeOut();
});

a {
  color: rgba(255,80,70,1) !important ;
  text-decoration: none;
}

.nav a {
  font-size: 13px;
  color: rgba(255,80,70,1);
  text-decoration: none;
  font-weight: bold;
}

/* Content ---------------------*/

/* nav */
.nav {
  position: fixed;
  float:left;
  width: 96%;
  left: 2%;
  margin-left: -2px;
  border-bottom: 2px solid rgba(255,80,70,1);
  padding-bottom: 18px;
  background: white;
  z-index: 999;
  top: 0px;
  padding-top: 18px;
}

.c1 {
  max-width: 24%;
}

.column {
  position: relative;
  float:left;
  padding-right: 1%;
  width: 585px;
}

/* feed */
.feed {
  width: 96%;
  left: 2%;
  margin-top: 75px;
  padding-left: 2px;
}

.c2 {
  max-width: 49%;
}

.feed-item {
  position: relative;
  width: 100%;
  height: auto;
  padding-bottom: 25px;
  padding-top:2.5%;
}

.feed-show {
  display: none;
  background:red;
}

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

<div class="nav">
  <div class="column c1">
    <a href="#" rel="click">About</a>
  </div>
</div>

<div id="feed" class="feed" style="margin-top: 54px;">
  <div class="column c2">
    <p>
      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK. C-oC aims to contribute to the necessary exaltation of talented artists
      within the various ethnic minorities within the UK.
    </p>
    <p>
      <a href="#">Find out more about Creatives of Colour..</a>
    </p>
  </div>
</div>

<!-- Show on click -->
<div id="feed-show" class="feed-show" style="margin-top: 54px;">
  <div class="column c2">
    <p>
      Creatives of Colour (C-oC) is an independent directory that provides you with up to date information on current, and future work of creatives of colour being showcased in the UK.
    </p>
    <p>
      <a href="#">Find out more about Creatives of Colour..</a>
    </p>
  </div>
</div>


问:
A more elegant way to reject array if it contains only empty strings
I have to sort through a (rows)array of (row)arrays. The (row)arrays contain an arbitrary number of strings. If a (row)array contains only empty strings I want to remove it from the (rows)array.

I'm currently doing this:

```<code>rows.each do |row|

  row.each_index do |i|

   if row[i].length > 0
    break
   elsif i == row.count-1
    rows.delete(row)
   end

  end

end
</code>```

But is there a more elegant way to do it?

答: Here: rows.all?(&:blank?).

Body:
I have to sort through a (rows)array of (row)arrays. The (row)arrays contain an arbitrary number of strings. If a (row)array contains only empty strings I want to remove it from the (rows)array.

I'm currently doing this:

rows.each do |row|

  row.each_index do |i|

   if row[i].length > 0
    break
   elsif i == row.count-1
    rows.delete(row)
   end

  end

end

But is there a more elegant way to do it?

Body: Here: rows.all?(&:blank?).


问:
Vue-resource and http-proxy-middleware not routing to backend
I am new to Vue js and writing a front end for a simple task tracker app. I am trying to use vue-resource and http-proxy-middleware to have the app connect to my backend. Backend is on port 3000, and the Vue js front end is on port 8080.

I used the proxy set up described on the Vue docs.

The method:

```<code>saveTask() {
    this.$http.get('/api', {title: this.taskTitle})
      .then(response => {
        console.log("success");
      }, response => {
        console.log("error");
      });
  }
</code>```

My Proxy Table: (in config.index.js under dev)

```<code> proxyTable: {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  }
},
</code>```

When I start up the server I see:

```<code>[HPM] Proxy created: /api  ->  http://localhost:3000
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...
</code>```

On the request:

```<code>GET http://localhost:8080/api 404 (Not Found)
</code>```

So it looks like the proxy is not working. Any help greatly appreciated.

答:
Your setup looks good and the requests should look like they're coming from 8080 since it is a proxy.

Are you sure something should be returning where you're looking? I have literally the same setup and it works.

My guess is since http://localhost:8080/api can't be found either can http://localhost:3000 since they're the same thing.

If that doesn't solve your problem you can dig a little deeper and debug and see if anything looks funny there.

```<code>proxyTable: {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    logLevel: 'debug',
    pathRewrite: {
      '^/api': '',
    },
  },
},
</code>```

Here goes a shot of everything working with my stuff:

Body:
I am new to Vue js and writing a front end for a simple task tracker app. I am trying to use vue-resource and http-proxy-middleware to have the app connect to my backend. Backend is on port 3000, and the Vue js front end is on port 8080.

I used the proxy set up described on the Vue docs.

The method:

saveTask() {
    this.$http.get('/api', {title: this.taskTitle})
      .then(response => {
        console.log("success");
      }, response => {
        console.log("error");
      });
  }

My Proxy Table: (in config.index.js under dev)

 proxyTable: {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': ''
    }
  }
},

When I start up the server I see:

[HPM] Proxy created: /api  ->  http://localhost:3000
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...

On the request:

GET http://localhost:8080/api 404 (Not Found)

So it looks like the proxy is not working. Any help greatly appreciated.

Body:
Your setup looks good and the requests should look like they're coming from 8080 since it is a proxy.

Are you sure something should be returning where you're looking? I have literally the same setup and it works.

My guess is since http://localhost:8080/api can't be found either can http://localhost:3000 since they're the same thing.

If that doesn't solve your problem you can dig a little deeper and debug and see if anything looks funny there.

proxyTable: {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    logLevel: 'debug',
    pathRewrite: {
      '^/api': '',
    },
  },
},

Here goes a shot of everything working with my stuff:


问:
Connect to Cosmos Graph DB through NodeJs
I want to connect into the cosmos graph db in NodeJs. The implemented sample is coming from documentation. I've changed the example to connect into the emulator like the following:

```<code>var Gremlin = require("gremlin-secure");

const client = Gremlin.createClient(
    8081,
    "localhost", // or 127.0.0.1
    {
        "session": false,
        "ssl": false,
        "user": "/dbs/graphdb/colls/graphcollz",
        "password": "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
    });

console.log('Running Drop');
client.on('error', (err) => {
     console.log(err.message);
});
</code>```

I should mention that in the above documentation mentioned that:

The Gremlin endpoint must be only the host name without the protocol/port number, like mygraphdb.graphs.azure.com (not https://mygraphdb.graphs.azure.com or mygraphdb.graphs.azure.com:433).

Hence, the endpoint address for db is localhost without any protocol/port.
Also, ssl is set to false to prevent "self signed certificate" error, and graphdb and graphcollz were created before in emulator.

In this way, I've gotten the following error when try to execute the following query:

```<code>client.execute('g.V().drop()', {}, (err, results) => {
     if (err) return console.error(err);
     console.log(results);
});
</code>```

The error is:

read ECONNRESET

Also, Node js ECONNRESET post cannot help to solve the problem to connect into the emulator.

Now, the question is how can I connect into the cosmos graph db emulator through the NodeJS?

答:
The CosmosDB Emulator only emulates the DocumentDb endpoint. You can use the emulator with the .NET GraphDb SDK, but not the Node gremlin-secure module.

Here is the difference:

The .NET GraphDb SDK translates the Gremlin query to a DocumentDb query on the client side. It then calls the DocumentDb endpoint in Azure (your-site.documents.azure.com).

The Node GraphDb SDK sends the Gremlin query, as a string, to a GraphDB endpoint in Azure (your-site.graphs.azure.com). This endpoint appears to run code similar to the .NET SDK, but on the server side, translating the Gremlin query to a DocumentDb query.

Edit: Looks like Azure added a blurb on the emulator page that states they aren't currently supporting graphdb and tables. Nevertheless, I believe my answer is still correct: you could use the .NET GraphDB SDK and the emulator. (but the product is pre-release, so this may also be subject to change...):

Body:
I want to connect into the cosmos graph db in NodeJs. The implemented sample is coming from documentation. I've changed the example to connect into the emulator like the following:

var Gremlin = require("gremlin-secure");

const client = Gremlin.createClient(
    8081,
    "localhost", // or 127.0.0.1
    {
        "session": false,
        "ssl": false,
        "user": "/dbs/graphdb/colls/graphcollz",
        "password": "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
    });

console.log('Running Drop');
client.on('error', (err) => {
     console.log(err.message);
});

I should mention that in the above documentation mentioned that:

The Gremlin endpoint must be only the host name without the protocol/port number, like mygraphdb.graphs.azure.com (not https://mygraphdb.graphs.azure.com or mygraphdb.graphs.azure.com:433).

Hence, the endpoint address for db is localhost without any protocol/port.
Also, ssl is set to false to prevent "self signed certificate" error, and graphdb and graphcollz were created before in emulator.

In this way, I've gotten the following error when try to execute the following query:

client.execute('g.V().drop()', {}, (err, results) => {
     if (err) return console.error(err);
     console.log(results);
});

The error is:

read ECONNRESET

Also, Node js ECONNRESET post cannot help to solve the problem to connect into the emulator.

Now, the question is how can I connect into the cosmos graph db emulator through the NodeJS?


问:
how to copy downloaded file in tmp folder of aws lambda to s3 specific folder within bucket
I download image from S3(Lambda trigger) and did some operations on image and saved to aws lambda tmp folder then I want to copy that image to same bucket and to specific folder.How can I do That(I don't want to upload into another bucket)
I want implement with python boro3 or any otherway to download image to specific folder do some image anupulation ,save,copy to other folder of s3 within bucket </p>

答: Generally, you'll want to bypass saving the image to /tmp; have your code write the object wherever you want it to wind up (same bucket or different bucket, it doesn't much matter) via boto3's put action.</p>


问:
Javascript promise confusion for executing two functions in order
Right now I have funcA, funcB, arrayA and arrayB. In funcA, arrayB will populate itself by requesting some external information and the time for doing this is varied. I want it to execute funcB after arrayB.length == arrayA.length, and arrayB is a global variable that its content will be used in funcB. I assume that I need to use JQuery deferred and promise..so I tried this

```<code>     var arrayB = [];
     var hi = funcA();
     hi.then(funcB());

     funcA(){
            var Dfd = $.Deferred();
            arrayB.forEach(function(x, i){
                   some external retrieval;
                   if (arrayB.length == arrayA.length){
                         Dfd.resolve(arrayB);
                   }
             })

        return Dfd;
     }
</code>```

But this doesn't help. How should I change it?

答:
arrayB.forEach won't do a thing. It's empty. Forget all this functions and deferred.

```<code>fetch('/mydata.json')
  .then(function(response) {
    //save your data from response to arrayB
    //call your funcA
  })
  .catch((error) => {
    console.log(error);
});
</code>```

I don't know why you needed that:

```<code>if (arrayB.length == arrayA.length){
   Dfd.resolve(arrayB);
}
</code>```

But feel free to make a check before calling funcA.

Body:
Right now I have funcA, funcB, arrayA and arrayB. In funcA, arrayB will populate itself by requesting some external information and the time for doing this is varied. I want it to execute funcB after arrayB.length == arrayA.length, and arrayB is a global variable that its content will be used in funcB. I assume that I need to use JQuery deferred and promise..so I tried this

     var arrayB = [];
     var hi = funcA();
     hi.then(funcB());

     funcA(){
            var Dfd = $.Deferred();
            arrayB.forEach(function(x, i){
                   some external retrieval;
                   if (arrayB.length == arrayA.length){
                         Dfd.resolve(arrayB);
                   }
             })

        return Dfd;
     }

But this doesn't help. How should I change it?

Body:
arrayB.forEach won't do a thing. It's empty. Forget all this functions and deferred.

fetch('/mydata.json')
  .then(function(response) {
    //save your data from response to arrayB
    //call your funcA
  })
  .catch((error) => {
    console.log(error);
});

I don't know why you needed that:

if (arrayB.length == arrayA.length){
   Dfd.resolve(arrayB);
}

But feel free to make a check before calling funcA.


问:
Struts 2 using getText in action class or beans
Is there a way to use getText() in action class or beans? I cannot find example of java coding in google search but can find in JSP coding. My example is as below:

```<code>public class LoanForm extends ActionSupport {

    public void validate(){
        if(this.getNameOfApplicant().equals("")){
            addFieldError(getText("error.card"), getText("error.invalid.name"));
        }
    }
}
</code>```

答: You only add extends ActionSupport to your action class or beans, or create an instance of ActionSupport and call getText(). getText() is a method of ActionSupport.

Body:
Is there a way to use getText() in action class or beans? I cannot find example of java coding in google search but can find in JSP coding. My example is as below:

public class LoanForm extends ActionSupport {

    public void validate(){
        if(this.getNameOfApplicant().equals("")){
            addFieldError(getText("error.card"), getText("error.invalid.name"));
        }
    }
}


问:
Send Push Notification to iOS PushSharp certificate
I'm using PushSharp 4.0.10 in my push notification server.

I can send push notifications to Android, but when I'm trying to send push notifications to ios, an error occurs:

```<code>Something went wrong in Comunications Worker:
Method name -> PushNotifications.DispatchPushNotifications()
Message -> There is an error sending iOS push notifications.
Exception - > Specified argument was out of the range of valid values.
Parameter name: You are using a certificate created for connecting only to the Sandbox APNS server but have selected a different server environment to connect to.
</code>```

I already created a certificate "Apple Push Notification service SSL (Sandbox & Production)" and also the individuals certificates "iOS App Development" and "App Store and Ad Hoc". In both cases I get the same error.

Is there any correct way to generate the certificate?

Can you point me the correct way, or is there any other bug or missing update?

Thank you, for your time.

答:
That error message is generated when creating an ApnsConfiguration object (see source code: https://github.com/Redth/PushSharp/blob/master/PushSharp.Apple/ApnsConfiguration.cs).

If you check how this particular exception is raised, you'll note it's based on the name of the certificate. You can remove the check by passing in false for the validateIsApnsCertificate argument when creating an ApnsConfiguration object.

This might not resolve your issue entirely (if there's something else wrong with the certificate) but if it's just the certificate's name that is the issue then this might help.

Body:
I'm using PushSharp 4.0.10 in my push notification server.

I can send push notifications to Android, but when I'm trying to send push notifications to ios, an error occurs:

Something went wrong in Comunications Worker:
Method name -> PushNotifications.DispatchPushNotifications()
Message -> There is an error sending iOS push notifications.
Exception - > Specified argument was out of the range of valid values.
Parameter name: You are using a certificate created for connecting only to the Sandbox APNS server but have selected a different server environment to connect to.

I already created a certificate "Apple Push Notification service SSL (Sandbox & Production)" and also the individuals certificates "iOS App Development" and "App Store and Ad Hoc". In both cases I get the same error.

Is there any correct way to generate the certificate?

Can you point me the correct way, or is there any other bug or missing update?

Thank you, for your time.


问:
CGImage, NSArray and Memory
This is a multiple part question, mostly because my ignorance on the matter has multiple layers.

First, I put together a caching system for caching CGImageRef objects. I keep it at the CGImageRef level (rather than UIImage) as I am loading images in background threads. When an image is loaded I put it into a NSMutableDictionary. I had to do a bit of arm twisting to get CGImageRef's into the array:

```<code>//Bunch of stuff drawing into a context
CGImageRef imageRef = CGBitmapContextCreateImage(context);

CGContextRelease(context);
[(id)imageRef autorelease];
[self.cache setObject:(id)imageRef forKey:@"SomeKey"];
</code>```

So, as you can see, I'm trying to treat the Image Ref as an NSObject, setting it to autorelease then placing it in the dictionary. My expectation is this will allow the image to be cleaned up after being removed from the dictionary. Now, I am beginning to have my doubts.

My application clears the cache array when the user "restarts" to play with different images. Running the application in Instruments shows that the memory is not dropping back to the "start" level on restart, but instead remains steady. My gut tells me that when the array has all objects removed the CGImageRef is not being cleared.

However, I'm unable to confirm this as I don't quite know how to track down the actual source of the memory in instruments. It's just a list of (Malloc 16 Bytes, Malloc 32 Bytes, etc), drilling into them just show a list of dyld callers. Not sure how to properly read it.

So, first question, is my way of caching CGImageRef objects completely flawed? And is there a better way to confirm such things in instruments?

答:
First of all, caching CGImages is OK and I don't see any problems with the code you posted.

Am I correctly assuming you use an NSMutableDictionary as the cache? If so, you can clear it by sending it -removeAllObjects, which should release all the keys and values. If you just set different images for the same keys, memory usage may remain roughly the same because you replace previous images with new ones. If the images have the same size, memory usage should be constant except brief spikes when you create a new batch of images.

As for Instruments, I've seen it both report false positives and miss real leaks. Try running it several times, making pauses, if possible, for the Leaks instrument to "catch up". This sounds crazy, but I think it may make it a bit more reliable.

If all else fails, you can log the contents of the cache before and after loading a set of images to make sure the cache itself works as expected.

Title: CGImage, NSArray and Memory

Body:
This is a multiple part question, mostly because my ignorance on the matter has multiple layers.

First, I put together a caching system for caching CGImageRef objects. I keep it at the CGImageRef level (rather than UIImage) as I am loading images in background threads. When an image is loaded I put it into a NSMutableDictionary. I had to do a bit of arm twisting to get CGImageRef's into the array:

//Bunch of stuff drawing into a context
CGImageRef imageRef = CGBitmapContextCreateImage(context);

CGContextRelease(context);
[(id)imageRef autorelease];
[self.cache setObject:(id)imageRef forKey:@"SomeKey"];

So, as you can see, I'm trying to treat the Image Ref as an NSObject, setting it to autorelease then placing it in the dictionary. My expectation is this will allow the image to be cleaned up after being removed from the dictionary. Now, I am beginning to have my doubts.

My application clears the cache array when the user "restarts" to play with different images. Running the application in Instruments shows that the memory is not dropping back to the "start" level on restart, but instead remains steady. My gut tells me that when the array has all objects removed the CGImageRef is not being cleared.

However, I'm unable to confirm this as I don't quite know how to track down the actual source of the memory in instruments. It's just a list of (Malloc 16 Bytes, Malloc 32 Bytes, etc), drilling into them just show a list of dyld callers. Not sure how to properly read it.

So, first question, is my way of caching CGImageRef objects completely flawed? And is there a better way to confirm such things in instruments?