问:
How to determine the date passing the Week Number and Day Number (Week) in java
I need to get the date by passing these parameters

year

week number (in a month) i.e. 1,2,3,4,5

day number (in a week) 0 (Sunday) to 6 (Saturday)

Month

I looked for a constructor in Calendar class but does not contain these parameters.

答:
In spite of your tags I agree with Joe C’s comment, you should prefer the modern Java date and time API (AKA known as java.time or JSR-310) over the long outdated Calendar and friends. The modern classes are more programmer friendly and nicer to work with, they come with fewer surprises, lead to clearer and more natural code (at least when you get used to the fluent style) and are easier to debug should you make a bug.

I don’t know how you count your weeks of the month. I have assumed that the first week starts on the first of the month and lasts 7 days (so the second week starts on the 8th and the 5th week on the 29th day of the month). If you count differently, please see Hugo’s answer.

I suggest this method:

```<code>public static LocalDate weekNoAndDayToDate(Year year, Month month, int weekOfMonth, int dayOfWeek) {
    // find day of week: convert from 0 (Sunday) to 6 (Saturday)
    // to DayOfWeek, from 1 (Monday) to 7 (Sunday)
    DayOfWeek dow;
    if (dayOfWeek == 0) { // Sunday
        dow = DayOfWeek.SUNDAY;
    } else {
        dow = DayOfWeek.of(dayOfWeek);
    }
    return year.atMonth(month)
            .atDay(1)
            .with(TemporalAdjusters.nextOrSame(dow))
            .with(ChronoField.ALIGNED_WEEK_OF_MONTH, weekOfMonth);
}
</code>```

With this we may do for example

```<code>    LocalDate today = weekNoAndDayToDate(Year.of(2017), Month.JULY, 1, 1);
</code>```

This yields

```<code>2017-07-03
</code>```

If you need either a Date or a GregorianCalendar, for example for an old API that you cannot change, do one of the following:

```<code>    Date oldfashiondDateObject
            = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
    GregorianCalendar oldfashionedCalendarObject
            = GregorianCalendar.from(today.atStartOfDay(ZoneId.systemDefault()));
</code>```

In both cases the result will be different in different time zones (one of the inherent troubles of the old classes). On my computer the first yields a Date of

```<code>Mon Jul 03 00:00:00 CEST 2017
</code>```

The second yields a GregorianCalendar equal to the same point in time.

Body:
In spite of your tags I agree with Joe C’s comment, you should prefer the modern Java date and time API (AKA known as java.time or JSR-310) over the long outdated Calendar and friends. The modern classes are more programmer friendly and nicer to work with, they come with fewer surprises, lead to clearer and more natural code (at least when you get used to the fluent style) and are easier to debug should you make a bug.

I don’t know how you count your weeks of the month. I have assumed that the first week starts on the first of the month and lasts 7 days (so the second week starts on the 8th and the 5th week on the 29th day of the month). If you count differently, please see Hugo’s answer.

I suggest this method:

public static LocalDate weekNoAndDayToDate(Year year, Month month, int weekOfMonth, int dayOfWeek) {
    // find day of week: convert from 0 (Sunday) to 6 (Saturday)
    // to DayOfWeek, from 1 (Monday) to 7 (Sunday)
    DayOfWeek dow;
    if (dayOfWeek == 0) { // Sunday
        dow = DayOfWeek.SUNDAY;
    } else {
        dow = DayOfWeek.of(dayOfWeek);
    }
    return year.atMonth(month)
            .atDay(1)
            .with(TemporalAdjusters.nextOrSame(dow))
            .with(ChronoField.ALIGNED_WEEK_OF_MONTH, weekOfMonth);
}

With this we may do for example

    LocalDate today = weekNoAndDayToDate(Year.of(2017), Month.JULY, 1, 1);

This yields

2017-07-03

If you need either a Date or a GregorianCalendar, for example for an old API that you cannot change, do one of the following:

    Date oldfashiondDateObject
            = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
    GregorianCalendar oldfashionedCalendarObject
            = GregorianCalendar.from(today.atStartOfDay(ZoneId.systemDefault()));

In both cases the result will be different in different time zones (one of the inherent troubles of the old classes). On my computer the first yields a Date of

Mon Jul 03 00:00:00 CEST 2017

The second yields a GregorianCalendar equal to the same point in time.


来源: stackexchange

问:
ERROR for site owner: Invalid site key
I created a reCAPTCHA key and disabled Verify the origin of reCAPTCHA solutions, yet I am still getting there error ERROR for site owner: Invalid site key.

How do I fix this?

答: Same here. It seems to work for me if I add at least one domain or localhost in the Domains list, but then uncheck the option under Domain Name Validation.

ContentLicense: CC BY-SA 3.0

Title: ERROR for site owner: Invalid site key


问:
PHP date(): minutes without leading zeros
I'd like to know if there is a formatting letter for PHP's date() that allows me to print minutes without leading zeros, or whether I have to manually test for and remove leading zeros?

Body:
A quickie from me. Tell me what you think:

<?php function _wo_leading_zero($n) {
    if(!isset($n[1])) return $n;

    if(strpos($n, '.') !== false) {
    $np = explode('.', $n); $nd = '.';
    }
    if(strpos($n, ',') !== false) {
    if(isset($np)) return false;
    $np = explode(',', $n); $nd = ',';
    }
    if(isset($np) && count($np) > 2) return false;
    $n = isset($np) ? $np[0] : $n;

    $nn = ltrim($n, '0');
    if($nn == '') $nn = '0';
    return $nn.(isset($nd) ? $nd : '').(isset($np[1]) ? $np[1] : '');
}

echo '0 => '._wo_leading_zero('0').'<br/>'; // returns 0
echo '00 => '._wo_leading_zero('00').'<br/>'; // returns 0
echo '05 => '._wo_leading_zero('05').'<br/>'; // returns 5
echo '0009 => '._wo_leading_zero('0009').'<br/>'; //returns 9
echo '01 => '._wo_leading_zero('01').'<br/>'; //returns 1
echo '0000005567 => '._wo_leading_zero('0000005567').'<br/>'; //returns 5567
echo '000.5345453 => '._wo_leading_zero('000.5345453').'<br/>'; //returns 0.5345453
echo '000.5345453.2434 => '._wo_leading_zero('000.5345453.2434').'<br/>'; //returns false
echo '000.534,2434 => '._wo_leading_zero('000.534,2434').'<br/>'; //returns false

echo date('m').' => '._wo_leading_zero(date('m')).'<br/>';
echo date('s').' => '._wo_leading_zero(date('s')).'<br/>'; ?>


问:
ASP.NET Boilerplate, test cases with real databases
I am using asp.net boilerplate for a project for ASP.NET 5.x. I am trying to create test cases for this project that will call existing test databases (one db for Host and the other db for Tenant). My steps so far were to:

In TestBase class constructor I am calling a method that will work the same as MultiTenantMigrateExecuter.Run() which will Seed the data for the Test Host database and the Test Tenant database (I will be using the host db and a single Tenant db for testing). The seeding will be the same as for the real db, just with different names for the test DBs.

Also from the TestBase class constructor I am getting the TenantId from the host database.

Next I am trying to get any seeded user from the tenant database
like this: var user= UsingDbContext(context => context.Users.FirstOrDefault(t => t.UserName== "johndoe")); but of course this will be calling the HostDb not the TenantDb.

I found a way to make a call to the TenantDb by wrapping the code in a using statement like this, avoidint the context and usint the repository, to be able to get the user I need from the TenantDb:

```<code>using (this.AbpSession.Use(tenant.Id, null))
{
    // get the TenantDb.User here by using the User repository
}
</code>```

... and then like this in every test case I write:

```<code>using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
{
    // make calls to the Tenant database here by using Tenant repository
}
</code>```

but this is not the most clean solution, and it has its limitations.

The question is: Is there a better way in my case, to set in the TestBase class the context to make calls to the Tenant database by default instead of the Host database?

I tried this one too, but it doesn't work...

```<code>protected T UsingTenantDbContext<T>(Func<TestAppDbContext, T> func)
{
    T result;

    using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
    {
        using (var context = LocalIocManager.Resolve<TestAppDbContext>())
        {
            context.DisableAllFilters();
            result = func(context);
            context.SaveChanges();
        }
    }

    return result;
}
</code>```

答:
After playing a while with the code, I found the answer to my question...
In the TestBase class I've created a new static property:

```<code>internal static MyAppDbContext tenantContext;
</code>```

Static, because this class will be inherited multiple times, but the tenantContext should be set only once.

Next I've created the following method:

```<code>protected void CreateTenantDbContext()
{
    if (tenantContext == null)
    {
        using (var context = LocalIocManager.Resolve<MyAppDbContext>())
        {
            // AbpSession.TenantId is set in a previous method.
            // Usin the host context, get the Connection String for the necessary tenant
            var encryptedDbConnString = context.Tenants.FirstOrDefault(x => x.Id == AbpSession.TenantId)?.ConnectionString;

            // Decrypt the string
            var decryptedDbConnString = SimpleStringCipher.Instance.Decrypt(encryptedDbConnString);

            // Create the context for the tenant db and assign it to the static property tenantContext
            tenantContext = LocalIocManager.Resolve<MyAppDbContext>(new { nameOrConnectionString = decryptedDbConnString });
        }
    }
}
</code>```

Once created you can use it in your test cases.

Body:
I am using asp.net boilerplate for a project for ASP.NET 5.x. I am trying to create test cases for this project that will call existing test databases (one db for Host and the other db for Tenant). My steps so far were to:

In TestBase class constructor I am calling a method that will work the same as MultiTenantMigrateExecuter.Run() which will Seed the data for the Test Host database and the Test Tenant database (I will be using the host db and a single Tenant db for testing). The seeding will be the same as for the real db, just with different names for the test DBs.

Also from the TestBase class constructor I am getting the TenantId from the host database.

Next I am trying to get any seeded user from the tenant database
like this: var user= UsingDbContext(context => context.Users.FirstOrDefault(t => t.UserName== "johndoe")); but of course this will be calling the HostDb not the TenantDb.

I found a way to make a call to the TenantDb by wrapping the code in a using statement like this, avoidint the context and usint the repository, to be able to get the user I need from the TenantDb:

using (this.AbpSession.Use(tenant.Id, null))
{
    // get the TenantDb.User here by using the User repository
}

... and then like this in every test case I write:

using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
{
    // make calls to the Tenant database here by using Tenant repository
}

but this is not the most clean solution, and it has its limitations.

The question is: Is there a better way in my case, to set in the TestBase class the context to make calls to the Tenant database by default instead of the Host database?

I tried this one too, but it doesn't work...

protected T UsingTenantDbContext<T>(Func<TestAppDbContext, T> func)
{
    T result;

    using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
    {
        using (var context = LocalIocManager.Resolve<TestAppDbContext>())
        {
            context.DisableAllFilters();
            result = func(context);
            context.SaveChanges();
        }
    }

    return result;
}

Body:
After playing a while with the code, I found the answer to my question...
In the TestBase class I've created a new static property:

internal static MyAppDbContext tenantContext;

Static, because this class will be inherited multiple times, but the tenantContext should be set only once.

Next I've created the following method:

protected void CreateTenantDbContext()
{
    if (tenantContext == null)
    {
        using (var context = LocalIocManager.Resolve<MyAppDbContext>())
        {
            // AbpSession.TenantId is set in a previous method.
            // Usin the host context, get the Connection String for the necessary tenant
            var encryptedDbConnString = context.Tenants.FirstOrDefault(x => x.Id == AbpSession.TenantId)?.ConnectionString;

            // Decrypt the string
            var decryptedDbConnString = SimpleStringCipher.Instance.Decrypt(encryptedDbConnString);

            // Create the context for the tenant db and assign it to the static property tenantContext
            tenantContext = LocalIocManager.Resolve<MyAppDbContext>(new { nameOrConnectionString = decryptedDbConnString });
        }
    }
}

Once created you can use it in your test cases.


问:
Swift3 iOS -How to search for a URL inside an Array of URLs [URL?]
I have an array of urls. I want to search for a specific element inside that array and if it's there remove it.

```<code>let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: url_A){
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}
</code>```

I tried try and do-try-catch but they didn't work out. I know I'm doing this wrong and that's why I'm asking the question.

I get the error:

Cannot convert value of type 'URL' to expected arguement type '(URL)'
  throws -> Bool

How do i search for a url inside an array of urls?

答:
Based your question, you can do this:

```<code> let urls: [URL?] = [url_0, url_A, url_Purple, etc..]
 //second remove it from the array
 urls = urls.filter {$0 != url_A}
</code>```

This will search for url_A and if found it will remove it and return new array. If I am correct, that is what you are looking for.

Based on the error which you got answer would be:

```<code>let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: {$0 == url_A} ) == true {
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}
</code>```

Notice that it expects a closure as param in contains block. You were passing URL? type.

Body:
I have an array of urls. I want to search for a specific element inside that array and if it's there remove it.

let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: url_A){
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}

I tried try and do-try-catch but they didn't work out. I know I'm doing this wrong and that's why I'm asking the question.

I get the error:

Cannot convert value of type 'URL' to expected arguement type '(URL)'
  throws -> Bool

How do i search for a url inside an array of urls?

Body:
Based your question, you can do this:

 let urls: [URL?] = [url_0, url_A, url_Purple, etc..]
 //second remove it from the array
 urls = urls.filter {$0 != url_A}

This will search for url_A and if found it will remove it and return new array. If I am correct, that is what you are looking for.

Based on the error which you got answer would be:

let urls: [URL?] = [url_0, url_A, url_Purple, etc..]

//first search for url_A
if urls.contains(where: {$0 == url_A} ) == true {
     //second remove it from the array
     urls = urls.filter{$0 != url_A}
}

Notice that it expects a closure as param in contains block. You were passing URL? type.


问:
Pure CSS, div hover can affect more than one element
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

```<code> .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>
</code>```

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

答:
Yes, with sibling selectors (IF they are siblings)

.a {
  display: inline-block;
  width: 100px;
  height: 50px;
  background-color: red;
}

.b {
  display: inline-block;
  width: 100px;
  height: 30px;
  background-color: blue;
  transition: all 1s;    }

.c {
  display: inline-block;
  width: 100px;
  height: 80px;
  background-color: yellow;
  transition: all 1s;
}

.a:hover~.b {
  height: 160px;
}

.a:hover~.c {
  height: 120px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">hover me</div>
<div class="b">b b b b b</div>
<div class="c">c c c c c</div></code>```

Body:
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

 .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

Body:
Yes, with sibling selectors (IF they are siblings)

.a {
  display: inline-block;
  width: 100px;
  height: 50px;
  background-color: red;
}

.b {
  display: inline-block;
  width: 100px;
  height: 30px;
  background-color: blue;
  transition: all 1s;    }

.c {
  display: inline-block;
  width: 100px;
  height: 80px;
  background-color: yellow;
  transition: all 1s;
}

.a:hover~.b {
  height: 160px;
}

.a:hover~.c {
  height: 120px;
}

<div class="a">hover me</div>
<div class="b">b b b b b</div>
<div class="c">c c c c c</div>


问:
Identity Server - multiple STS
I have two groups of api applications (group 1: api11, api12; group 2: api21, api22) that are used by two different groups od javascript applications (group 1 and group 2). Each api group has different domain and use different instance of Identity Server (also each identity server has different domain). Business requirement is that user logged in to any application from group 1 can use any app from this group but can't use app or api from group 2.

Under the hood both api1 and api2 often needs to talk to the same microservices. What I want to achive is to make microservices accessible with access tokens issued from any of the identity servers (used by group 1 or group 2 app). Is there any way to achieve this? For one identity server I can use UseIdentityServerBearerTokenAuthentication but as argument I can pass only one Authority there.

答:
It is not directly possible (see this issue)

But you probably need to rethink your architecture. Assuming the business requirement (Business requirement is that user logged in to any application from group 1 can use any app from this group but can't use app or api from group 2.) is non negotiable, what you are trying to achieve may be dangerous if these microservices are handling something very particular to one or the other group (ie, I am talking about multitenancy here)

The right approach in your case would be to have separate instances of microservices, dedicated to different groups, ideally running in their own containers or VMs

Title: Identity Server - multiple STS


问:
EaselJS, drag and drop to container but click to child container
i have a little problem. i use easelJS to create some shape into an canvas.

i have create container class to stock circle shape with text on it. this class containe click function for the container.

i have created a other container class with a rectangular shape and a other text.

on this container, i have activate the drag and drop to move this into the canvas. that works fine, but, when i add the containers (circle shape) as a child of this container, the click function is call by the container with rectangular shape.
i know that works like this because i have set the mousechildren at false.

if i change this properties, when i move the parent container, all children in it dont move with.

i want to redirect the click function parent, to the click function of my circle container.

in fact, i just need to create a shape moveable, with others shapes inside them clickable.

thx for your help, if you need my code, i can put this here

答:
You can listen for the pressmove of the container, and the mouse events on the children, since events in EaselJS bubble.

Here is a sample:
http://jsfiddle.net/8L9wye4n/1/

```<code>// Listen for children events:
s.on("click", function(event) { event.target.scaleX = event.target.scaleY = event.target.scaleX+0.1 });

// Listen for container drag/drop
c.on("pressmove", function(event) {
    c.x = stage.mouseX;
    c.y = stage.mouseY;
});
</code>```

Hope that helps.

Body:
You can listen for the pressmove of the container, and the mouse events on the children, since events in EaselJS bubble.

Here is a sample:
http://jsfiddle.net/8L9wye4n/1/

// Listen for children events:
s.on("click", function(event) { event.target.scaleX = event.target.scaleY = event.target.scaleX+0.1 });

// Listen for container drag/drop
c.on("pressmove", function(event) {
    c.x = stage.mouseX;
    c.y = stage.mouseY;
});

Hope that helps.


问:
Augment types for imported module in TypeScript
I'm converting an existing codebase from js/react/jsx setup to TypeScript. Naturally, I'd like to do it file by file, and have a question about approaches for making TS compiler work with the existing js codebase.

I convert file index.js but want to leave foo.js in JavaScript for now:

```<code>// index.ts

import { fooFunction } from 'foo';

foo({ val: 1 });
</code>```

```<code>// foo.js

export const fooFunction = ({ val, optionalProp }) => {
  //...
}
</code>```

The problem in this example that TypeScript automatically infers argument to foo and complains that Property 'optionalProp' is missing in type { val:string, optionalProp:any }

Needing to "stub" the type of fooFunction sent me looking and I found a few ways i may be able to do it:

1) Use require instead of import

```<code>// index.ts
var fooFunction: any = require('foo').fooFunction;
</code>```

2) Merge declarations

```<code>?
</code>```

3) Add a d.ts file with custom declarations for foo - haven't attempted but seems inconvenient

Ideally I don't have to do (1) because I want to keep using import syntax and I don't have to do (3) because that will require me to add declaration files only to remove them later when I'm ready to convert foo.

(2) sounds awesome, but I can't figure out a working solution.

```<code>// index.ts

declare module 'foo' {
  function fooFunction(options: any): any
}
</code>```

Doesn't work and throws Cannot redeclare block-scoped variable 'fooFunction'

How do I do that? Are there docs that have examples of what I'm trying to do and/or have more explanation about declaration merging and how to work with namespace/interface/value?
Are there better approaches for incrementally transitioning to TypeScript?

答:
This may not work, just wanted to preface this with that - I don't know much at all about React - but I know for sure that you can use ? on a variable to make it "optional". I've used this before in functions

```<code>myFooFunction(requiredParam: typeA, optionalParam?: typeB) { ... }
</code>```

Another thing you should consider is the fact that Typescript can add some type checking at compile time, so IMO you should leverage that as much as possible.

Edit: to work with the optional parameter, you could just check that it exists.

```<code>myFooFunction(requiredParam: typeA, optionalParam?: typeB) {
  if (optionalParam) { // if this results to true, the param was given
    //do something
  }
}
</code>```

Body:
I'm converting an existing codebase from js/react/jsx setup to TypeScript. Naturally, I'd like to do it file by file, and have a question about approaches for making TS compiler work with the existing js codebase.

I convert file index.js but want to leave foo.js in JavaScript for now:

// index.ts

import { fooFunction } from 'foo';

foo({ val: 1 });

// foo.js

export const fooFunction = ({ val, optionalProp }) => {
  //...
}

The problem in this example that TypeScript automatically infers argument to foo and complains that Property 'optionalProp' is missing in type { val:string, optionalProp:any }

Needing to "stub" the type of fooFunction sent me looking and I found a few ways i may be able to do it:

1) Use require instead of import

// index.ts
var fooFunction: any = require('foo').fooFunction;

2) Merge declarations

?

3) Add a d.ts file with custom declarations for foo - haven't attempted but seems inconvenient

Ideally I don't have to do (1) because I want to keep using import syntax and I don't have to do (3) because that will require me to add declaration files only to remove them later when I'm ready to convert foo.

(2) sounds awesome, but I can't figure out a working solution.

// index.ts

declare module 'foo' {
  function fooFunction(options: any): any
}

Doesn't work and throws Cannot redeclare block-scoped variable 'fooFunction'

How do I do that? Are there docs that have examples of what I'm trying to do and/or have more explanation about declaration merging and how to work with namespace/interface/value?
Are there better approaches for incrementally transitioning to TypeScript?

Body:
This may not work, just wanted to preface this with that - I don't know much at all about React - but I know for sure that you can use ? on a variable to make it "optional". I've used this before in functions

myFooFunction(requiredParam: typeA, optionalParam?: typeB) { ... }

Another thing you should consider is the fact that Typescript can add some type checking at compile time, so IMO you should leverage that as much as possible.

Edit: to work with the optional parameter, you could just check that it exists.

myFooFunction(requiredParam: typeA, optionalParam?: typeB) {
  if (optionalParam) { // if this results to true, the param was given
    //do something
  }
}


问:
Make a list from Firebase data
I´m trying to structure my Firebasedata using this example from Stackoverflow:
Add a list item through javascript

HTML:

```<code> First name:
    <input type="text" id="firstname">
    <br>
    <p>Your first name is: <b id='boldStuff2'></b>
    </p>
    <p>Other people's names:</p>
    <ol id="demo"></ol>
    <input type='button' onclick='changeText2();' value='Submit' />
</code>```

Fiddle

When I try to copy the code straight into my project for testing, I´m getting the error:
 Uncaught ReferenceError: changeText2 is not defined
    at HTMLInputElement.onclick"

Also, when I try to copy the code to a new Fiddle, it doesn't work.

Any help is much appreciated

答:
Did you define the changeText2() function? It seems like you are not declaring this function in your code.

Try to add the code below and check if this solves your error.

```<code>function changeText2(){
    var firstname = document.getElementById('firstname').value;
    document.getElementById('boldStuff2').innerHTML = firstname;
    x.push(firstname);
    document.getElementById('demo').innerHTML = x;
}
</code>```

Title: Make a list from Firebase data

Body:
I´m trying to structure my Firebasedata using this example from Stackoverflow:
Add a list item through javascript

HTML:

 First name:
    <input type="text" id="firstname">

Your first name is:

Other people's names:

    <input type='button' onclick='changeText2();' value='Submit' />

Fiddle

When I try to copy the code straight into my project for testing, I´m getting the error:
 Uncaught ReferenceError: changeText2 is not defined
    at HTMLInputElement.onclick"

Also, when I try to copy the code to a new Fiddle, it doesn't work.

Any help is much appreciated

Body:
Did you define the changeText2() function? It seems like you are not declaring this function in your code.

Try to add the code below and check if this solves your error.

function changeText2(){
    var firstname = document.getElementById('firstname').value;
    document.getElementById('boldStuff2').innerHTML = firstname;
    x.push(firstname);
    document.getElementById('demo').innerHTML = x;
}


问:
Find specific table using BeautifulSoup with specific caption
I am attempting to locate the specific table below in the given HTML:

```<code><table class="sidearm-table collapse-on-medium accordion" accordion-table="" sortable-table="">
                        <caption>Tennessee Tech<span class="hide"> - Pitching Stats</span></caption>
</code>```

My approach was to find the caption, then proceed to find the parent table, from which I will iterate through the rows to find my desired text (I can accomplish this part on my own). I believe my error is buried in the fact that the caption text continues into the span tag, however not sure if this is the case. My code to do so is given below, however it continues to return None because it cannot locate the table (something with my syntax is likely incorrect):

```<code>from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

test = soup.find('caption', text = 'Tennessee Tech').find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})
</code>```

答:
I would try to find all captions and then to match the caption text like this: </p>

```<code>from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

for caption in soup.find_all('caption'):
    if caption.get_text() == 'Tennessee Tech - Pitching Stats':
        table = caption.find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})
</code>```

Body:
I am attempting to locate the specific table below in the given HTML:

Tennessee Tech - Pitching Stats

My approach was to find the caption, then proceed to find the parent table, from which I will iterate through the rows to find my desired text (I can accomplish this part on my own). I believe my error is buried in the fact that the caption text continues into the span tag, however not sure if this is the case. My code to do so is given below, however it continues to return None because it cannot locate the table (something with my syntax is likely incorrect):

from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

test = soup.find('caption', text = 'Tennessee Tech').find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})

Body:
I would try to find all captions and then to match the caption text like this:

from bs4 import BeautifulSoup
import re
import requests

header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}

redirect = requests.get('http://goblueraiders.com/boxscore.aspx?path=baseball&id=6117', headers = header).text
soup = BeautifulSoup(redirect, 'html.parser')

for caption in soup.find_all('caption'):
    if caption.get_text() == 'Tennessee Tech - Pitching Stats':
        table = caption.find_parent('table', {'class': 'sidearm-table collapse-on-medium accordion'})


问:
JSON data to HTML table with JQUERY
Someone knows how i can send all the values of the "User" object in my JS file ("User 1" for example) to the header of my HTML Table?

I will only put one column structured by JSON data, but I need that the code push all my JSON data to the html file like the next  structure:

```<code><div class="table-responsive">
  <table class="table">
    <thead>
      <tr>
        <th>Name</th>
        <th>Role</th>
        <th>Age</th>
        <th>skillsTable2</th>
        <th>biopicURL</th>
    </thead>

    <tbody>
      <tr>
        <td>Usuario 1</td>
        <td>Web Developer</td>
        <td>28</td>
        <td>SEO</td>
        <td>../images/fry.jpg</td>
      </tr>
    </tbody>

  </table>
  </div>
</code>```

Here is my JS code:

```<code>// JSON Metadata Structure //

    var skillsTable = ["SEO","Front end Developemetnt","Story Telling"];
    var metadataContext = {"Context" : { "itemscope":"itemscope",  "itemtype":"http://schema.org/VisualArtwork" } };

    var dataX = {
        "User 1":[{
            "Name" : "Usuario 1",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 2":[{
            "Name" : "Usuario 2",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 3":[{
            "Name" : "Usuario 3",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 4":[{
            "Name" : "Usuario 4",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 5":[{
            "Name" : "Usuario 5",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 6":[{
            "Name" : "Usuario 6",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 7":[{
            "Name" : "Usuario 7",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 8":[{
            "Name" : "Usuario 8",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }]
    };

// Metadata variables //
    var itemscopeVar = 'itemscope';
    var itemtypeVar =' itemtype=';
    var itempropVar = 'itemprop=';

  // Table Structuring Variable //
    var tableTagVar = '<table %metadataL0% id="table" class="table">%Inside%</table>';
    var theadVar = '<thead %metadataL1% ><tr id="tableHeader"></tr></thead>';
    var tbodyVar = '<tbody %metadataL2% ><tr id="tableColums">%trColumnsContent%</tr></tbody>';
    var tdHeaderVar = '<th>%tdDataHeader%</th>';
    var tdColumnsVar = '<td>%tdDataColumns%</td>';

  // Print Table + Metadata //
    function myFunction() {

        var formatTableTagVar = tableTagVar.replace('%metadataL0%', itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        var formatTheadVar = theadVar.replace("%metadataL1%", itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        //var formattbodyVarVar = tbodyVar.replace("%metadataL2%", itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        var formatTableTagVarIn = formatTableTagVar.replace("%Inside%", formatTheadVar );

        var tableInit = $('#tableBox').append(formatTableTagVarIn);

        var switcherTable = 0;
        if( switcherTable < 1 ){
            var trThead = $('#tableHeader');
            var trTbody = $('#tableColums');

            $.each(dataX, function (key, value) {
                //$('#dataGuide').append($('<div></div><br>').html(key.length + ' (' + value.length + ' results)'));
                 $.each(value, function (index, titleObj) {
                    $('#table').append('<tbody>' + tdColumnsVar + '</tbody>');  // Columns
                    console.log( index + titleObj );
                 });

                 trThead.prepend('<th>' + value[0].Name + '</th>'); // Header
                console.log( value + key);
            });
        }
        else{};

        console.log( itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
    };
</code>```

Here is the HTML:

```<code><button type="button" onclick="myFunction()">Put the TABLE</button>
<div id="tableBox" class="table-responsive"></div>

<div id="dataGuide" class="box"></div><br>
</code>```

答:
If I've understand correctly: Javascript and Jquery will do the job..</p>

```<code>var text = "";
for (i=0;i<dataX.length;i++) {

   text += "<tr>";
   text += "<td>"+ dataX[i].Name +"</td>";
   text += "<td>"+ dataX[i].Role +"</td>";
   text += "<td>"+ dataX[i].Age +"</td>";
   text += "<td>"+ dataX[i].skillsTable2[0] +"</td>";
   text += "<td>"+ dataX[i].bioPicURL +"</td>";
   text+= "</tr>";

}
$("#tableBox").append(text);
</code>```

Title: JSON data to HTML table with JQUERY

Body:
Someone knows how i can send all the values of the "User" object in my JS file ("User 1" for example) to the header of my HTML Table?

I will only put one column structured by JSON data, but I need that the code push all my JSON data to the html file like the next  structure:

        Name
        Role
        Age
        skillsTable2
        biopicURL

        Usuario 1
        Web Developer
        28
        SEO
        ../images/fry.jpg

Here is my JS code:

// JSON Metadata Structure //

    var skillsTable = ["SEO","Front end Developemetnt","Story Telling"];
    var metadataContext = {"Context" : { "itemscope":"itemscope",  "itemtype":"http://schema.org/VisualArtwork" } };

    var dataX = {
        "User 1":[{
            "Name" : "Usuario 1",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 2":[{
            "Name" : "Usuario 2",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 3":[{
            "Name" : "Usuario 3",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 4":[{
            "Name" : "Usuario 4",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 5":[{
            "Name" : "Usuario 5",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 6":[{
            "Name" : "Usuario 6",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 7":[{
            "Name" : "Usuario 7",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }],

        "User 8":[{
            "Name" : "Usuario 8",
            "Role" : "Web Developer",
            "Contacts" : {
                        "Mobile" : "044 55 4346 3478",
                        "E-mail" : "roadluac@gmail.com",
                        "GitHub" : "https://github.com/roadluac2016",
                        "Facebook" : "https://www.facebook.com/profile.php?id=100017132474848",
                        "Location" : "Mexico City"
            },
            "Welcome Message" : "Pnly Don't Stop",
            "Age" : 29,
            "skillsTable" : skillsTable,
            "skillsTable2" : ["SEO","Front end Developemetnt","Story Telling"],
            "bioPicURL" : "../images/fry.jpg"
        }]
    };

// Metadata variables //
    var itemscopeVar = 'itemscope';
    var itemtypeVar =' itemtype=';
    var itempropVar = 'itemprop=';

  // Table Structuring Variable //
    var tableTagVar = '
%Inside%
';
    var theadVar = '

';
    var tbodyVar = '

%trColumnsContent%

';
    var tdHeaderVar = '%tdDataHeader%	';
    var tdColumnsVar = '%tdDataColumns%	';

  // Print Table + Metadata //
    function myFunction() {

        var formatTableTagVar = tableTagVar.replace('%metadataL0%', itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        var formatTheadVar = theadVar.replace("%metadataL1%", itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        //var formattbodyVarVar = tbodyVar.replace("%metadataL2%", itemscopeVar + itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
        var formatTableTagVarIn = formatTableTagVar.replace("%Inside%", formatTheadVar );

        var tableInit = $('#tableBox').append(formatTableTagVarIn);

        var switcherTable = 0;
        if( switcherTable < 1 ){
            var trThead = $('#tableHeader');
            var trTbody = $('#tableColums');

            $.each(dataX, function (key, value) {
                //$('#dataGuide').append($('

').html(key.length + ' (' + value.length + ' results)'));
                 $.each(value, function (index, titleObj) {
                    $('#table').append('
' + tdColumnsVar + '
');  // Columns
                    console.log( index + titleObj );
                 });

                 trThead.prepend('' + value[0].Name + '	'); // Header
                console.log( value + key);
            });
        }
        else{};

        console.log( itemtypeVar + "'" + metadataContext.Context.itemtype + "'" );
    };

Here is the HTML:

<button type="button" onclick="myFunction()">Put the TABLE</button>

Body:
If I've understand correctly: Javascript and Jquery will do the job..

var text = "";
for (i=0;i<dataX.length;i++) {

   text += "<tr>";
   text += "<td>"+ dataX[i].Name +"</td>";
   text += "<td>"+ dataX[i].Role +"</td>";
   text += "<td>"+ dataX[i].Age +"</td>";
   text += "<td>"+ dataX[i].skillsTable2[0] +"</td>";
   text += "<td>"+ dataX[i].bioPicURL +"</td>";
   text+= "</tr>";

}
$("#tableBox").append(text);


问:
What is the specific reason for the runtime error I'm getting here?
```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}
</code>```

What is the specific reason for the runtime error I'm getting here?

答:
The specific reason for the runtime error is this line:

```<code>scanf("%s\n%s\n%s\n",a,b,c);
</code>```

The %s conversion specifier tells scanf to read a sequence of non-whitespace characters from the input stream (skipping over leading whitespace) and store that sequence to an array of char pointed to by the corresponding argument.  The problem is that a, b, and c are not pointers to char; they're single char objects that haven't been initialized.  The odds of any of them containing a value that corresponds to an address that scanf can write to is almost non-existant.

First, change the declarations of a, b, and c to```<code>char a[<em>SOME_LENGTH</em>] = {0}; // initialize array contents to 0<sup>1</sup>
char b[<em>SOME_LENGTH</em>] = {0};
char c[<em>SOME_LENGTH</em>] = {0};
</code>```
where SOME_LENGTH is a number that's long enough to contain the longest string you expect to enter plus one extra space for the string terminator.  IOW, if the longest string you intend to read is 10 characters long, then your declarations need to be

```<code>char a[11] = {0};
char b[11] = {0};
char c[11] = {0};
</code>```

Secondly, change your scanf call to

```<code>scanf( "%<em>(SOME_LENGTH-1)</em>s %<em>(SOME_LENGTH-1)</em>s %<em>(SOME_LENGTH-1)</em>s", a, b, c );
</code>```

where (SOME_LENGTH-1) is the length of your buffer minus 1.  Again, assuming SOME_LENGTH is 11:

```<code>scanf( "%10s %10s %10s", a, b, c );
</code>```

This will help prevent a buffer overrun in the event you enter a string longer than what the buffer is sized to hold.

Both the %s conversion specifier and a blank space in the format string tell scanf to consume and discard any leading whitespace.  You can run into trouble specifying whitespace characters in the format string.

Additional notes:

main returns int, not void - change your main to

```<code>int main (void)
{
  ...
}
</code>```

If there are fewer elements in the initializer than there are in the array, then excess elements are initialized to 0.  So in this case, the first element is *explicitly* initialized to 0, and the remaining elements are *implicitly* initialized to 0.

Body:
#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?

Body:
The specific reason for the runtime error is this line:

scanf("%s\n%s\n%s\n",a,b,c);

The %s conversion specifier tells scanf to read a sequence of non-whitespace characters from the input stream (skipping over leading whitespace) and store that sequence to an array of char pointed to by the corresponding argument.  The problem is that a, b, and c are not pointers to char; they're single char objects that haven't been initialized.  The odds of any of them containing a value that corresponds to an address that scanf can write to is almost non-existant.

First, change the declarations of a, b, and c to
char a[SOME_LENGTH] = {0}; // initialize array contents to 01
char b[SOME_LENGTH] = {0};
char c[SOME_LENGTH] = {0};

where SOME_LENGTH is a number that's long enough to contain the longest string you expect to enter plus one extra space for the string terminator.  IOW, if the longest string you intend to read is 10 characters long, then your declarations need to be

char a[11] = {0};
char b[11] = {0};
char c[11] = {0};

Secondly, change your scanf call to

scanf( "%(SOME_LENGTH-1)s %(SOME_LENGTH-1)s %(SOME_LENGTH-1)s", a, b, c );

where (SOME_LENGTH-1) is the length of your buffer minus 1.  Again, assuming SOME_LENGTH is 11:

scanf( "%10s %10s %10s", a, b, c );

This will help prevent a buffer overrun in the event you enter a string longer than what the buffer is sized to hold.

Both the %s conversion specifier and a blank space in the format string tell scanf to consume and discard any leading whitespace.  You can run into trouble specifying whitespace characters in the format string.

Additional notes:

main returns int, not void - change your main to

int main (void)
{
  ...
}

If there are fewer elements in the initializer than there are in the array, then excess elements are initialized to 0.  So in this case, the first element is *explicitly* initialized to 0, and the remaining elements are *implicitly* initialized to 0.


问:
Planning an exception handling strategy in advance
When I look at a method in the .NET Framework, it can throw several possible exceptions.

From a planning perspective, what do I need to ask to plan and handle these exceptions? I understand that depending on the impact of an exception, that would influence showing it in the UI layer. For example, if a process at the back end which is opaque to the user experience throws an exception, you would not want to show that to the user as s/he would have no idea what that is.

Thanks

答:
I wanted to write it as a comment but it is to long for the comment textbox...

There are exceptions that are important to show the users because they can handle it by themselves, for example: file name is illegal.

There are exceptions that i find important to show the users because they (the users) will function as my QA team, for example: some method will not update the GUI and they probably will get to the conclusion that they should report that further on, they will show me the exception and i will discover that my array is out of bounds...

there are exceptions that promoting them to the user will just confuse them and like you said

"s/he would have no idea what that is"

for example, For example:

"if a process at the back end which is opaque throws an exception".

those exception i am saving for myself (in database..)..

I am always reminding myself that the end user has a different psychology compare to a developer (-:

I hope i understood your question in the right manner.


问:
WP7 - get compile/build date from code?
In Windows Phone 7, is there a way to get the application build or compile date in code?
I would like to display the date, along with the version number, for support purposes for my application.

If it isn't immediately available, any hints or alternatives?  (I guess one is making it an app setting, which is hokey).

答:
The date (& time) of the build isn't included in an assembly.

If you could get to the file system on the phone you may be able to get a date from this but it may be affected by the marketplace ingestion process (when the code is signed) and so you may not be able to guarantee this.

If you used a * for the build part of the version number and then work out the build date from that. (It's the number of days since 2000-01-01.)

Or, you could add something to your build process to set a property or setting.

Or, if using SVN for your version control system, you could use $WCDATE$ in a template with SubWcRev.exe to set this.

Or, you could add this to the app through the use of T4.

The following in a TT file should do the trick:

```<code><#@ template language="C#" #>
<#@ import namespace="System" #>
using System.Windows;

namespace MyNamespace
{
    public partial class App : Application
    {
        public string BuildDate { get { return "<#= DateTime.Now #>"; } }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: WP7 - get compile/build date from code?

Body:
The date (& time) of the build isn't included in an assembly.

If you could get to the file system on the phone you may be able to get a date from this but it may be affected by the marketplace ingestion process (when the code is signed) and so you may not be able to guarantee this.

If you used a * for the build part of the version number and then work out the build date from that. (It's the number of days since 2000-01-01.)

Or, you could add something to your build process to set a property or setting.

Or, if using SVN for your version control system, you could use $WCDATE$ in a template with SubWcRev.exe to set this.

Or, you could add this to the app through the use of T4.

The following in a TT file should do the trick:

<#@ template language="C#" #>
<#@ import namespace="System" #>
using System.Windows;

namespace MyNamespace
{
    public partial class App : Application
    {
        public string BuildDate { get { return "<#= DateTime.Now #>"; } }
    }
}


问:
J2V8 ReferenceError : process is not defined, when trying to execute script
I'm using J2V8 to call a javascript function from my Java code. When I try to execute my script it gives me ReferenceError : process is not defined. The script uses reactDomServer to transform a hash map into an html object.

I'm initializing my V8 as follows:

```<code>V8 v8 = v8.createV8Runtime("global");
</code>```

Also, is there a way to pass a hashmap as parameter when you want to call a JS function using V8?

```<code>v8.executeJsScript("myFunction", myHashMap)
</code>```

This was working with nashorn but im not able to make it work with V8. It seems my parameters need to be V8 values or primitives. All the examples I find are very simple and pass only strings or integers as parameters.. If my parameters are a few objects, should I declare them as V8 values and then push them in a V8 array and pass that array as my function parameters?

Thanks!

答: You can use V8ObjectUtils.toV8Object to create a V8Object from a HashMap.

Body:
I'm using J2V8 to call a javascript function from my Java code. When I try to execute my script it gives me ReferenceError : process is not defined. The script uses reactDomServer to transform a hash map into an html object.

I'm initializing my V8 as follows:

V8 v8 = v8.createV8Runtime("global");

Also, is there a way to pass a hashmap as parameter when you want to call a JS function using V8?

v8.executeJsScript("myFunction", myHashMap)

This was working with nashorn but im not able to make it work with V8. It seems my parameters need to be V8 values or primitives. All the examples I find are very simple and pass only strings or integers as parameters.. If my parameters are a few objects, should I declare them as V8 values and then push them in a V8 array and pass that array as my function parameters?

Thanks!


问:
Python Function returning string with quotes
I have a function and returning three values, The return value for my function is

```<code>(1, 3, "<class 'int'>")
</code>```

while I want to return

```<code>(1, 3, <class 'int'>)
</code>```

How do I remove the quotes from my return value.str(type(element)) is the value which is returning the 3rd value

```<code>def is_list_permutation(L1, L2):
    L1set = set(L1)
    L2set = set(L2)
    count = 0
    element = ''
    if L1 == [] and L2 == []:
        return(None,None,None)
    elif len(L1) == len(L2) and L1set == L2set:
       for a in L1:
          if L1.count(a) == L2.count(a):
              if L1.count(a) > count:
                  count = L1.count(a)
                  element = a
                  return(element,count,str(type(element)))
          else:
              return False
              break

    else:
       return False
</code>```

so if i give

```<code>L1 = [1, 'b', 1, 'c', 'c', 1]
L2 = ['c', 1, 'b', 1, 1, 'c']
</code>```

then the result is (1, 3, "<class 'int'>") while I want (1, 3, <class 'int'>)

答:
There will always be some quotes around it because it is a string!

If you want to return None when the string is "" then you could do this:

```<code>x = str(type(s))
return(element, count, x if x else None)
</code>```

Body:
I have a function and returning three values, The return value for my function is

(1, 3, "<class 'int'>")

while I want to return

(1, 3, <class 'int'>)

How do I remove the quotes from my return value.str(type(element)) is the value which is returning the 3rd value

def is_list_permutation(L1, L2):
    L1set = set(L1)
    L2set = set(L2)
    count = 0
    element = ''
    if L1 == [] and L2 == []:
        return(None,None,None)
    elif len(L1) == len(L2) and L1set == L2set:
       for a in L1:
          if L1.count(a) == L2.count(a):
              if L1.count(a) > count:
                  count = L1.count(a)
                  element = a
                  return(element,count,str(type(element)))
          else:
              return False
              break

    else:
       return False

so if i give

L1 = [1, 'b', 1, 'c', 'c', 1]
L2 = ['c', 1, 'b', 1, 1, 'c']

then the result is (1, 3, "<class 'int'>") while I want (1, 3, <class 'int'>)

Body:
There will always be some quotes around it because it is a string!

If you want to return None when the string is "" then you could do this:

x = str(type(s))
return(element, count, x if x else None)


问:
If NOT EXISTS in SQL not function
I put this in the SQL Query editor of SQL Server 2008 and doesn't work:

```<code>If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
else
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'
</code>```

Error I am getting:

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword
  'else'.

答:
Your if statement only acts on the first statement after the IF unless you put a BEGIN/END around the statements.  This is the reason I like to have BEGIN/ENDs around even one statement IFs.</p>

```<code>If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
BEGIN
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
END
ELSE
BEGIN
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'
END
</code>```

Title: If NOT EXISTS in SQL not function

Body:
I put this in the SQL Query editor of SQL Server 2008 and doesn't work:

If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
else
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'

Error I am getting:

Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword
  'else'.

Body:
Your if statement only acts on the first statement after the IF unless you put a BEGIN/END around the statements.  This is the reason I like to have BEGIN/ENDs around even one statement IFs.

If not EXISTS (Select * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA= 'dbo' AND TABLE_NAME='PK01')
BEGIN
    CREATE TABLE [dbo].['PK01'] (Articulo varchar(MAX),Referencia varchar(MAX),Lote varchar(MAX),Cantidad Int,Ubicacion varchar(MAX));
    INSERT INTO [UBICACIONES].[dbo].['PK01'] (Articulo,Referencia,Lote,Cantidad,Ubicacion)VALUES ('998','kk','ll',0,'pp')
END
ELSE
BEGIN
    UPDATE [UBICACIONES].[dbo].['PK01'] Set Cantidad = (Cantidad + 23) WHERE Articulo LIKE '998'
END


问:
I keep getting a 404 error when I try to add a background image to a div in jQuery
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

```<code>function appendToDom(poster) {
    var aPoster = $('<div>');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);
</code>```

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.

答:
I find it easier/better to use relative directories. Similar to how you have in your commented out section of your example.  In my opinion, files or assets that the program will use should be somewhere inside your project folder anyway.

Try url(./../images/question.png)depending on your file system.

Body:
I am trying to create a div as I press enter in my search bar. That part works for me and if I keep pressing enter a new div is created. However, I cannot give the created div a background image. My console keeps giving me a 404 error. Here is my code:

function appendToDom(poster) {
    var aPoster = $('
');
    aPoster.css({
        display: 'inline block',
        float: 'left',
        margin: '10px',
        marginLeft: '37px',
        marginTop: '20px',
        width: '200px',
        height: '300px',
        fontSize: '36px',
        color: 'black'
        //backgroundImage: '../services/images/1425663956-outline.png'
    })
    $(aPoster).css("background-image", "url(~/desktop/MyMovies/public/js/images/1425663956-outline.png)");
    $(main).append(aPoster);

I tried to put my images file in a bunch of places and I changed the path a bunch of times. My ultimate goal is to add the image provided by the api I'm using as the background image of each div and have the image I am currently trying to use as the default for when the api has no image for a given data point.

I am working in node if that helps.


问:
UIAlertController example - Swift - IOS
I would create something like this with an UIAlertController:

Thanks in advance for your answers.

答:
My Suggestion is you can use library, which shows modal presentation of view controller, or you can directly show it as modal presentation.

if this is my case then i should use https://github.com/m1entus/MZFormSheetPresentationController

It's really a cool library

Title: UIAlertController example - Swift - IOS


问:
AJAX page load returns [object object]
I'm currently trying to do a simple AJAX page transition in my local host.

Here is the  tag on my home.html

```<code><a href="/blank.html">go to blank</a>
</code>```

Should take me to the blank.html page.

Here is my AJAX:

```<code>$(function(){
  jQuery(function ($) {
      $(document).on('click', "a", function (event) {
          event.preventDefault();
          $.when($("body").fadeOut(1000).promise(), $.ajax({
              url: this.href,
              type: 'get',
              dataType: 'html'
          })).done(function (html) {
              var newDoc = document.open("text/html", "replace");
              newDoc.write(html);
              newDoc.close();
              $("body").fadeIn(1000);
          });
      });
  });
});
</code>```

Without the javascript my redirect works fine, but with the javascript, after the fadeOut it returns [object Object] on the page (and does not redirect)

I have looked around for a solution but cannot seem to find one.

Any help or advice is appreciated, thank you in advance!

EDIT:

console.log(html); returns:

答:
Try this:

```<code>$(function(){
  jQuery(function ($) {
      $(document).on('click', "a", function (event) {
          event.preventDefault();
          $("body").fadeOut(1000);
          $.ajax({
              url: this.href,
              type: 'get',
              dataType: 'html',
              success: function(html){
                var newDoc = document.open("text/html", "replace");
                  newDoc.write(html);
                  newDoc.close();
                  $("body").fadeIn(1000);
              }
          })

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

Title: AJAX page load returns [object object]

Body:
I'm currently trying to do a simple AJAX page transition in my local host.

Here is the  tag on my home.html

go to blank

Should take me to the blank.html page.

Here is my AJAX:

$(function(){
  jQuery(function ($) {
      $(document).on('click', "a", function (event) {
          event.preventDefault();
          $.when($("body").fadeOut(1000).promise(), $.ajax({
              url: this.href,
              type: 'get',
              dataType: 'html'
          })).done(function (html) {
              var newDoc = document.open("text/html", "replace");
              newDoc.write(html);
              newDoc.close();
              $("body").fadeIn(1000);
          });
      });
  });
});

Without the javascript my redirect works fine, but with the javascript, after the fadeOut it returns [object Object] on the page (and does not redirect)

I have looked around for a solution but cannot seem to find one.

Any help or advice is appreciated, thank you in advance!

EDIT:

console.log(html); returns:

Body:
Try this:

$(function(){
  jQuery(function ($) {
      $(document).on('click', "a", function (event) {
          event.preventDefault();
          $("body").fadeOut(1000);
          $.ajax({
              url: this.href,
              type: 'get',
              dataType: 'html',
              success: function(html){
                var newDoc = document.open("text/html", "replace");
                  newDoc.write(html);
                  newDoc.close();
                  $("body").fadeIn(1000);
              }
          })

      });
  });
});


问:
Google Cloud Endpoints + Firebase Auth: method_info is not set
So I am running the sample code provided by Google:

```<code>package com.neat.backend;
/**
 * An endpoint class we are exposing
 */
@Api(
        name = "myApi",
        version = "v1",
        namespace = @ApiNamespace(
                ownerDomain = "backend.neat.com",
                ownerName = "backend.neat.com",
                packagePath = ""
        ),
        issuers = {
        @ApiIssuer(
                name = "firebase",
                issuer = "https://securetoken.google.com/" + PROJECT_ID,
                jwksUri = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com")
})
public class MyEndpoint {

    @ApiMethod(
            path = "firebase_user",
            httpMethod = ApiMethod.HttpMethod.GET,
            authenticators = {EspAuthenticator.class},
            issuerAudiences = {@ApiIssuerAudience(name = "firebase", audiences = {PROJECT_ID})}
    )
    public Email getUserEmailFirebase(User user) throws UnauthorizedException {
        if (user == null) {
            throw new UnauthorizedException("Invalid credentials");
        }

        Email response = new Email(user.getEmail());
        return response;
    }

}
</code>```

I am getting a Firebase token from my Android client and try to send it to the backend by:

```<code>curl -H "Authorization: Bearer FIREBASE_JWT_TOKEN" \
     -X GET \
     http://localhost:8080/_ah/api/echo/v1/firebase_user
</code>```

The error I see in the logs is the following:

```<code>[INFO] java.lang.IllegalStateException: method_info is not set in the request
[INFO]  at com.google.api.server.spi.auth.EspAuthenticator.authenticate(EspAuthenticator.java:67)
[INFO]  at com.google.api.server.spi.request.Auth.authenticate(Auth.java:100)
[INFO]  at com.google.api.server.spi.request.ServletRequestParamReader.getUser(ServletRequestParamReader.java:191)
[INFO]  at com.google.api.server.spi.request.ServletRequestParamReader.deserializeParams(ServletRequestParamReader.java:136)
[INFO]  at com.google.api.server.spi.request.RestServletRequestParamReader.read(RestServletRequestParamReader.java:123)
[INFO]  at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:350)
[INFO]  at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:114)
[INFO]  at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:102)
[INFO]  at com.google.api.server.spi.dispatcher.PathDispatcher.dispatch(PathDispatcher.java:49)
[INFO]  at com.google.api.server.spi.EndpointsServlet.service(EndpointsServlet.java:71)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</code>```

I have tried deploying the exact same code to App Engine and it works perfectly. I have tried debugging EspAuthenticator and it seems that it is expecting the Servlet filters to inject some attributes in the request.

答:
I got the same error message, and eventually tracked it down to making a request with a trailing / in the URL where my API did not specify one. The trailing slash only causes an error for calls that provide an authorization token.

Apparently ControlFilter (and therefore also GoogleAppEngineControlFilter) did not recognize it as a valid endpoint and therefore did not bother attaching method_info to the request. But then EndpointsServlet thought it was valid and tried to authenticate without all the needed info!

The fix was easy: remove the trailing slash from the URL in my request. Tracking down the problem, however, was not! I see this was not your problem, but maybe this answer will help someone else.

Body:
So I am running the sample code provided by Google:

package com.neat.backend;
/**
 * An endpoint class we are exposing
 */
@Api(
        name = "myApi",
        version = "v1",
        namespace = @ApiNamespace(
                ownerDomain = "backend.neat.com",
                ownerName = "backend.neat.com",
                packagePath = ""
        ),
        issuers = {
        @ApiIssuer(
                name = "firebase",
                issuer = "https://securetoken.google.com/" + PROJECT_ID,
                jwksUri = "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com")
})
public class MyEndpoint {

    @ApiMethod(
            path = "firebase_user",
            httpMethod = ApiMethod.HttpMethod.GET,
            authenticators = {EspAuthenticator.class},
            issuerAudiences = {@ApiIssuerAudience(name = "firebase", audiences = {PROJECT_ID})}
    )
    public Email getUserEmailFirebase(User user) throws UnauthorizedException {
        if (user == null) {
            throw new UnauthorizedException("Invalid credentials");
        }

        Email response = new Email(user.getEmail());
        return response;
    }

}

I am getting a Firebase token from my Android client and try to send it to the backend by:

curl -H "Authorization: Bearer FIREBASE_JWT_TOKEN" \
     -X GET \
     http://localhost:8080/_ah/api/echo/v1/firebase_user

The error I see in the logs is the following:

[INFO] java.lang.IllegalStateException: method_info is not set in the request
[INFO]  at com.google.api.server.spi.auth.EspAuthenticator.authenticate(EspAuthenticator.java:67)
[INFO]  at com.google.api.server.spi.request.Auth.authenticate(Auth.java:100)
[INFO]  at com.google.api.server.spi.request.ServletRequestParamReader.getUser(ServletRequestParamReader.java:191)
[INFO]  at com.google.api.server.spi.request.ServletRequestParamReader.deserializeParams(ServletRequestParamReader.java:136)
[INFO]  at com.google.api.server.spi.request.RestServletRequestParamReader.read(RestServletRequestParamReader.java:123)
[INFO]  at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:350)
[INFO]  at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:114)
[INFO]  at com.google.api.server.spi.handlers.EndpointsMethodHandler$RestHandler.handle(EndpointsMethodHandler.java:102)
[INFO]  at com.google.api.server.spi.dispatcher.PathDispatcher.dispatch(PathDispatcher.java:49)
[INFO]  at com.google.api.server.spi.EndpointsServlet.service(EndpointsServlet.java:71)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

I have tried deploying the exact same code to App Engine and it works perfectly. I have tried debugging EspAuthenticator and it seems that it is expecting the Servlet filters to inject some attributes in the request.


问:
writing to res from another function in express
I didn't know how to describe my problem better.
maybe the code will (it's pretty basic)

```<code>// in users route
var LIST = require('list.json')

/* GET users listing. */
router.get('/', function(req, res, next) {

  res.write('beginning list')
  writeList(function() {
    res.end('list printed')
  })

})

function writeList(cb) {
  // some stuff
  res.write(LIST)
  cb()
}
</code>```

so in tldr:

I want to write to the res object in a function other than the main routing handler. why doesn't this work? (Error: Can't set headers after they are sent.)
How is it done properly?

Thanks :)

答:
You are not passing res to your function, but trying to write to it, so there is an exception thrown which closes the response object and sets headers to error, and when you calling res.end(), it is already closed, so you are getting headers already set error.</p>

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

    res.write('beginning list');
    writeList( function(err, writeResult) {
        if (err){
            console.log(err);
            res.end('Error');
        }
        else{
            res.write(writeResult)
            res.end('list printed')
        }
    })

});

function writeList(cb) {
    // some stuff
    cb(null, LIST)
}
</code>```

Body:
I didn't know how to describe my problem better.
maybe the code will (it's pretty basic)

// in users route
var LIST = require('list.json')

/* GET users listing. */
router.get('/', function(req, res, next) {

  res.write('beginning list')
  writeList(function() {
    res.end('list printed')
  })

})

function writeList(cb) {
  // some stuff
  res.write(LIST)
  cb()
}

so in tldr:

I want to write to the res object in a function other than the main routing handler. why doesn't this work? (Error: Can't set headers after they are sent.)
How is it done properly?

Thanks :)

Body:
You are not passing res to your function, but trying to write to it, so there is an exception thrown which closes the response object and sets headers to error, and when you calling res.end(), it is already closed, so you are getting headers already set error.

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

    res.write('beginning list');
    writeList( function(err, writeResult) {
        if (err){
            console.log(err);
            res.end('Error');
        }
        else{
            res.write(writeResult)
            res.end('list printed')
        }
    })

});

function writeList(cb) {
    // some stuff
    cb(null, LIST)
}

ContentLicense: CC BY-SA 4.0


问:
Angular 2: default radio button selection
I have two radio buttons (they're not dynamically generated):

```<code><input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending<br>
<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['-recordStartDate']">Descending
</code>```

How do I make one of the radio buttons checked by default?

Thank you!

Edit

The button's values are being passed through this pipe (i.e. not a component, per se...not sure this is worth mentioning?). The app is pretty simple, and the radio buttons are just hardcoded into app.component. Is the pipe the correct place to initialize which radio button is checked by default?

```<code>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class OrderByPipe implements PipeTransform {

static _OrderByPipeComparator(a:any, b:any):number{

  if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
    //Isn't a number so lowercase the string to properly compare
    if(a.toLowerCase() < b.toLowerCase()) return -1;
    if(a.toLowerCase() > b.toLowerCase()) return 1;
  }
  else{
    //Parse strings as numbers to compare properly
    if(parseFloat(a) < parseFloat(b)) return -1;
    if(parseFloat(a) > parseFloat(b)) return 1;
  }

  return 0; //equal each other
}

transform(input:any, [config = '+']): any{

    if(!Array.isArray(input)) return input;

    if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
        var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
        var desc = propertyToCheck.substr(0, 1) == '-';

        //Basic array
        if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
            return !desc ? input.sort() : input.sort().reverse();
        }
        else {
            var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                ? propertyToCheck.substr(1)
                : propertyToCheck;

            return input.sort(function(a:any,b:any){
                return !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);
            });
        }
    }
    else {
        //Loop over property of the array in order and sort
        return input.sort(function(a:any,b:any){
            for(var i:number = 0; i < config.length; i++){
                var desc = config[i].substr(0, 1) == '-';
                var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                    ? config[i].substr(1)
                    : config[i];

                var comparison = !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);

                //Don't return 0 yet in case of needing to sort by next property
                if(comparison != 0) return comparison;
            }

            return 0; //equal each other
        });
    }
 }
</code>```

Edit 2

So in component.app.ts I've edited my export class AppComponent{ to the following:

```<code>export class AppComponent {
  artists = ARTISTS;
  currentArtist: Artist;
  orderbydescending = ['-recordStartDate'];

showArtist(item) {
  this.currentArtist = item;
</code>```

}
 }

This works in terms of preventing the previous errors, but it doesn't actually make the radio button selected. It still appears as though it's unselected - even though it functions as though it is. Does this make sense?

答:
Try this in the component

```<code>radioValue = {valueAsc: 'Asc', valueDesc: 'Desc'} ;
orderbydescending = 'Asc';
</code>```

and in the template put this

```<code><input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueAsc">Ascending

<input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueDesc">Descending
</code>```

With this the first radio button is checked, if you don't want any radio button selected assign to the variable orderbydescending null.

```<code>orderbydescending = 'null;
</code>```

Body:
I have two radio buttons (they're not dynamically generated):

<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['+recordStartDate']">Ascending

<input type="radio" name="orderbydescending" [(ngModel)]="orderbydescending" [value]="['-recordStartDate']">Descending

How do I make one of the radio buttons checked by default?

Thank you!

Edit

The button's values are being passed through this pipe (i.e. not a component, per se...not sure this is worth mentioning?). The app is pretty simple, and the radio buttons are just hardcoded into app.component. Is the pipe the correct place to initialize which radio button is checked by default?

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'orderBy', pure: false})
export class OrderByPipe implements PipeTransform {

static _OrderByPipeComparator(a:any, b:any):number{

  if((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))){
    //Isn't a number so lowercase the string to properly compare
    if(a.toLowerCase()  b.toLowerCase()) return 1;
  }
  else{
    //Parse strings as numbers to compare properly
    if(parseFloat(a) < parseFloat(b)) return -1;
    if(parseFloat(a) > parseFloat(b)) return 1;
  }

  return 0; //equal each other
}

transform(input:any, [config = '+']): any{

    if(!Array.isArray(input)) return input;

    if(!Array.isArray(config) || (Array.isArray(config) && config.length == 1)){
        var propertyToCheck:string = !Array.isArray(config) ? config : config[0];
        var desc = propertyToCheck.substr(0, 1) == '-';

        //Basic array
        if(!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+'){
            return !desc ? input.sort() : input.sort().reverse();
        }
        else {
            var property:string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
                ? propertyToCheck.substr(1)
                : propertyToCheck;

            return input.sort(function(a:any,b:any){
                return !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);
            });
        }
    }
    else {
        //Loop over property of the array in order and sort
        return input.sort(function(a:any,b:any){
            for(var i:number = 0; i < config.length; i++){
                var desc = config[i].substr(0, 1) == '-';
                var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
                    ? config[i].substr(1)
                    : config[i];

                var comparison = !desc
                    ? OrderByPipe._OrderByPipeComparator(a[property], b[property])
                    : -OrderByPipe._OrderByPipeComparator(a[property], b[property]);

                //Don't return 0 yet in case of needing to sort by next property
                if(comparison != 0) return comparison;
            }

            return 0; //equal each other
        });
    }
 }

Edit 2

So in component.app.ts I've edited my export class AppComponent{ to the following:

export class AppComponent {
  artists = ARTISTS;
  currentArtist: Artist;
  orderbydescending = ['-recordStartDate'];

showArtist(item) {
  this.currentArtist = item;

}
 }

This works in terms of preventing the previous errors, but it doesn't actually make the radio button selected. It still appears as though it's unselected - even though it functions as though it is. Does this make sense?

Body:
Try this in the component

radioValue = {valueAsc: 'Asc', valueDesc: 'Desc'} ;
orderbydescending = 'Asc';

and in the template put this

<input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueAsc">Ascending

<input type="radio" name="radioGroup" [(ngModel)]="orderbydescending" [value]="radioValue.valueDesc">Descending

With this the first radio button is checked, if you don't want any radio button selected assign to the variable orderbydescending null.

orderbydescending = 'null;


问:
DTD download/caching
I have the following directive on top of my master page

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</code>```

As per the following article from W3C they are starting to block DTD download based on a per User Agent string pattern.

Which is the best way to cache the DTD locally or, better more, download it once and then reference a local copy?

I am using IIS 7.5.

答:
Install it in your local catalog of DTDs. How you do that depends on the software you are using. OpenSP, for example, uses the SGML_CATALOG_FILES environment variable.

You do not need to worry about this unless you are running some sort of XML parser over your documents. If you are just serving them up from a web server, then you won't be touching DTDs.

Title: DTD download/caching

Body:
I have the following directive on top of my master page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

As per the following article from W3C they are starting to block DTD download based on a per User Agent string pattern.

Which is the best way to cache the DTD locally or, better more, download it once and then reference a local copy?

I am using IIS 7.5.


问:
How to rebuild the object with repr?
My code works perfectly except the last part. I want to recreate the object with repr function but it clearly doesn't work. I tried everything here and on the web but i'm still so confuse. Is there any way to do it and if so what is the syntax ?</p>

```<code>class Modulo(object):

    def __init__(self, grondtal, waarde = 0):
        self.grondtal = grondtal
        self.waarde = waarde % grondtal

    def __call__(self, m):
        return Modulo(self.grondtal, m)

    def __add__(self, other):
        return Modulo(self.grondtal, self.waarde + other.waarde)

    def __sub__(self, other):
        return Modulo(self.grondtal, self.waarde - other.waarde)

    def __mul__(self, other):
        return Modulo(self.grondtal, self.waarde * other.waarde)

    def __eq__(self, other):
        return self.waarde == other.waarde and self.grondtal == other.grondtal

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return  '[%s %% %s]' % (str(self.grondtal), str(self.waarde))

    def __repr__(self):
        return '%s' %Modulo(self.grondtal, self.waarde)
</code>```

答:
You probably want this:

```<code>def __repr__(self):
    return "Modulo(%d,%d)" % (self.grondtal, self.waarde)
</code>```

Or, a little bit more generic:

```<code>def __repr__(self):
    return "%s(%d,%d)" % (self.__class__.__name__, self.grondtal, self.waarde)
</code>```

For example:

```<code>>>> m = Modulo(3,2)
>>> repr(m)
'Modulo(3,2)'
</code>```

Title: How to rebuild the object with repr?

Body:
My code works perfectly except the last part. I want to recreate the object with repr function but it clearly doesn't work. I tried everything here and on the web but i'm still so confuse. Is there any way to do it and if so what is the syntax ?

class Modulo(object):

    def __init__(self, grondtal, waarde = 0):
        self.grondtal = grondtal
        self.waarde = waarde % grondtal

    def __call__(self, m):
        return Modulo(self.grondtal, m)

    def __add__(self, other):
        return Modulo(self.grondtal, self.waarde + other.waarde)

    def __sub__(self, other):
        return Modulo(self.grondtal, self.waarde - other.waarde)

    def __mul__(self, other):
        return Modulo(self.grondtal, self.waarde * other.waarde)

    def __eq__(self, other):
        return self.waarde == other.waarde and self.grondtal == other.grondtal

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return  '[%s %% %s]' % (str(self.grondtal), str(self.waarde))

    def __repr__(self):
        return '%s' %Modulo(self.grondtal, self.waarde)

Body:
You probably want this:

def __repr__(self):
    return "Modulo(%d,%d)" % (self.grondtal, self.waarde)

Or, a little bit more generic:

def __repr__(self):
    return "%s(%d,%d)" % (self.__class__.__name__, self.grondtal, self.waarde)

For example:

>>> m = Modulo(3,2)
>>> repr(m)
'Modulo(3,2)'


问:
Output a linux command to a url/port or scocket instead of writing it to a file
I have a command which out outputs certain data which i store in a ext file using a '>>' command.Now Instead of doing that I want to have a socket or a port on any server which will catch the output of the command.Basically i want to output all my script data to a socket or url which ever is possible.

Any help in this direction is most welcomed.

答:
You can use socat to listening on a port 12345 and echo any data sent to it like this:

```<code>socat -u TCP-LISTEN:12345,keepalive,reuseaddr,fork STDOUT
</code>```

If you want to capture it to a file as well (file.log), you can use the same command with tee:

```<code>socat -u TCP-LISTEN:12345,keepalive,reuseaddr,fork STDOUT | tee file.log
</code>```

You can run your program to output to bash's TCP virtual device:

```<code>./prog > /dev/tcp/localhost/12345
</code>```

If you don't want to use bash magic then you can also use socat to send the data:

```<code>./prog | socat - TCP-CONNECT:localhost:12345
</code>```

The above example assume you are running your program and "logger" on the same system but you can replace "localhost" with the hostname or address of the system you wish to send to (where the socat is listening).

Body:
You can use socat to listening on a port 12345 and echo any data sent to it like this:

socat -u TCP-LISTEN:12345,keepalive,reuseaddr,fork STDOUT

If you want to capture it to a file as well (file.log), you can use the same command with tee:

socat -u TCP-LISTEN:12345,keepalive,reuseaddr,fork STDOUT | tee file.log

You can run your program to output to bash's TCP virtual device:

./prog > /dev/tcp/localhost/12345

If you don't want to use bash magic then you can also use socat to send the data:

./prog | socat - TCP-CONNECT:localhost:12345

The above example assume you are running your program and "logger" on the same system but you can replace "localhost" with the hostname or address of the system you wish to send to (where the socat is listening).