问:
Why is this IMPORTRANGE formula not working?
I keep getting an error while using the IMPORTRANGE formula:

```<code>=importrange(“1uUbz2HAzgwBwY3zMXqcLJM_Z8qVQZHNP0wzRaNHceTc”, “Sheet1!A:B”)
</code>```

I changed the name of my sheets several times to make sure everything matches but see a:

Formula parse error

and I am not sure what I am doing wrong. The original sheet has several tabs as well.

Can you see where the error is?

答:
This worked for me:

=importrange(“1uUbz2HAzgwBwY3zMXqcLJM_Z8qVQZHNP0wzRaNHceTc”; “Sheet1!A:B”)

Maybe try it with a semicolon

Body:
I keep getting an error while using the IMPORTRANGE formula:

=importrange(“1uUbz2HAzgwBwY3zMXqcLJM_Z8qVQZHNP0wzRaNHceTc”, “Sheet1!A:B”)

I changed the name of my sheets several times to make sure everything matches but see a:

Formula parse error

and I am not sure what I am doing wrong. The original sheet has several tabs as well.

Can you see where the error is?


来源: stackexchange

问:
How set background drawable programmatically in Android

To set Background:

```<code>RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
</code>```

Is the best way to do it?

答:
Inside the app/res/your_xml_layout_file.xml

Assign a name to your parent layout.

Go to your MainActivity and find your RelativeLayout by calling the findViewById(R.id."given_name").

Use the layout as a classic Object, by calling the method setBackgroundColor().

ContentLicense: CC BY-SA 4.0

Body:
To set Background:

RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

Is the best way to do it?

ContentLicense: CC BY-SA 3.0


问:
Joomla main menu html output
I'm trying to edit the output joomla main_menu module so I can make a custom dropdown menu.  At the moment it currently outputs html like this:

```<code><ul class="menu">
<li class="active item1" id="current"><a href="#"><span>First Level Item </span</a></li>
<li class="parent item63"><a href="#"><span>First Level Item Parent</span></a>
<ul>
  <li class="item60"><a href="#"><span>Second Level Item</span></a></li>
  <li class="item69"><a href="#"><span>Second Level Item</span></a></li>
</ul>
</li>
<li class="item64"><a href="#"><span>First Level Item</span></a></li>
<li class="item66"><a href="#"><span>First Level Item</span></a></li>
</code>```

What I would like to do is remove the span tags for the output.

What I know so far is that if I want to edit the output;  in my template folder I make a directory called 'html' and then inside that a new directory called 'mod___mainmenu' and then a make copy the default.php file from the existing mod_mainmenu folder from the modules directory. All the changes to I make to take file will change the output.

The problem that I'm having is that I can't understand what is happening with the code that is written in the default.php file as it use some XML system that I'm unfamilar with and there are no comments.

If anyone has any ideas that would be super helpful!

Here is the code from the default.php file for the menu:

```<code>defined('_JEXEC') or die('Restricted access');

if ( ! defined('modMainMenuXMLCallbackDefined') )
{

function modMainMenuXMLCallback(&$node, $args)

{
    $user   = &JFactory::getUser();
    $menu   = &JSite::getMenu();
    $active = $menu->getActive();
    $path   = isset($active) ? array_reverse($active->tree) : null;

    if (($args['end']) && ($node->attributes('level') >= $args['end']))
    {
        $children = $node->children();
        foreach ($node->children() as $child)
        {
            if ($child->name() == 'ul') {
                $node->removeChild($child);
            }
        }
    }

    if ($node->name() == 'ul') {
        foreach ($node->children() as $child)
        {
            if ($child->attributes('access') > $user->get('aid', 0)) {
                $node->removeChild($child);
            }
        }
    }

    if (($node->name() == 'li') && isset($node->ul)) {
        $node->addAttribute('class', 'parent');
    }

    if (isset($path) && in_array($node->attributes('id'), $path))
    {
        if ($node->attributes('class')) {
            $node->addAttribute('class', $node->attributes('class').' active');
        } else {
            $node->addAttribute('class', 'active');
        }
    }
    else
    {
        if (isset($args['children']) && !$args['children'])
        {
            $children = $node->children();
            foreach ($node->children() as $child)
            {
                if ($child->name() == 'ul') {
                    $node->removeChild($child);
                }
            }
        }
    }

    if (($node->name() == 'li') && ($id = $node->attributes('id'))) {
        if ($node->attributes('class')) {
            $node->addAttribute('class', $node->attributes('class').' item'.$id);
        } else {
            $node->addAttribute('class', 'item'.$id);
        }
    }

    if (isset($path) && $node->attributes('id') == $path[0]) {
        $node->addAttribute('id', 'current');
    } else {
        $node->removeAttribute('id');
    }
    $node->removeAttribute('level');
    $node->removeAttribute('access');
}

define('modMainMenuXMLCallbackDefined', true);
}
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');
</code>```

答:
You should avoid editing core files whenever possible to avoid having your changes overwritten when you upgrade.  Use template override files instead.

When I ran into this, I wanted to add and empty em tag to each menu item to allow for Gilder/Levin image replacement.  In my html override ({templatedir}\html\mod_mainmenu\default.php) I surrounded the call to modMainMenuHelper::render (the last line, basically) with an output buffer, and used a simple str_replace to add the em tag:

```<code>ob_start();
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');
$mainMenuContent = ob_get_clean();
echo str_replace('</span>', '</span><em></em>', $mainMenuContent);
</code>```

Since you just want to get rid of the span tag, you could do:

```<code>ob_start();
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');
$mainMenuContent = ob_get_clean();
echo str_replace(array('<span>','</span>'), array('',''), $mainMenuContent);
</code>```

OwnerDisplayName: Paul Sheldrake

ContentLicense: CC BY-SA 2.5

Title: Joomla main menu html output

Body:
I'm trying to edit the output joomla main_menu module so I can make a custom dropdown menu.  At the moment it currently outputs html like this:

First Level Item </span

First Level Item Parent

Second Level Item

Second Level Item

First Level Item

First Level Item

What I would like to do is remove the span tags for the output.

What I know so far is that if I want to edit the output;  in my template folder I make a directory called 'html' and then inside that a new directory called 'mod___mainmenu' and then a make copy the default.php file from the existing mod_mainmenu folder from the modules directory. All the changes to I make to take file will change the output.

The problem that I'm having is that I can't understand what is happening with the code that is written in the default.php file as it use some XML system that I'm unfamilar with and there are no comments.

If anyone has any ideas that would be super helpful!

Here is the code from the default.php file for the menu:

defined('_JEXEC') or die('Restricted access');

if ( ! defined('modMainMenuXMLCallbackDefined') )
{

function modMainMenuXMLCallback(&$node, $args)

{
    $user   = &JFactory::getUser();
    $menu   = &JSite::getMenu();
    $active = $menu->getActive();
    $path   = isset($active) ? array_reverse($active->tree) : null;

    if (($args['end']) && ($node->attributes('level') >= $args['end']))
    {
        $children = $node->children();
        foreach ($node->children() as $child)
        {
            if ($child->name() == 'ul') {
                $node->removeChild($child);
            }
        }
    }

    if ($node->name() == 'ul') {
        foreach ($node->children() as $child)
        {
            if ($child->attributes('access') > $user->get('aid', 0)) {
                $node->removeChild($child);
            }
        }
    }

    if (($node->name() == 'li') && isset($node->ul)) {
        $node->addAttribute('class', 'parent');
    }

    if (isset($path) && in_array($node->attributes('id'), $path))
    {
        if ($node->attributes('class')) {
            $node->addAttribute('class', $node->attributes('class').' active');
        } else {
            $node->addAttribute('class', 'active');
        }
    }
    else
    {
        if (isset($args['children']) && !$args['children'])
        {
            $children = $node->children();
            foreach ($node->children() as $child)
            {
                if ($child->name() == 'ul') {
                    $node->removeChild($child);
                }
            }
        }
    }

    if (($node->name() == 'li') && ($id = $node->attributes('id'))) {
        if ($node->attributes('class')) {
            $node->addAttribute('class', $node->attributes('class').' item'.$id);
        } else {
            $node->addAttribute('class', 'item'.$id);
        }
    }

    if (isset($path) && $node->attributes('id') == $path[0]) {
        $node->addAttribute('id', 'current');
    } else {
        $node->removeAttribute('id');
    }
    $node->removeAttribute('level');
    $node->removeAttribute('access');
}

define('modMainMenuXMLCallbackDefined', true);
}
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');

LastEditorDisplayName: Dimitre Novatchev

Body:
You should avoid editing core files whenever possible to avoid having your changes overwritten when you upgrade.  Use template override files instead.

When I ran into this, I wanted to add and empty em tag to each menu item to allow for Gilder/Levin image replacement.  In my html override ({templatedir}\html\mod_mainmenu\default.php) I surrounded the call to modMainMenuHelper::render (the last line, basically) with an output buffer, and used a simple str_replace to add the em tag:

ob_start();
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');
$mainMenuContent = ob_get_clean();
echo str_replace('</span>', '</span><em></em>', $mainMenuContent);

Since you just want to get rid of the span tag, you could do:

ob_start();
modMainMenuHelper::render($params, 'modMainMenuXMLCallback');
$mainMenuContent = ob_get_clean();
echo str_replace(array('<span>','</span>'), array('',''), $mainMenuContent);

OwnerDisplayName: Jerph


问:
Precedence Function
I'm trying to write a function, that goes within my main program, that will compare the precedence of operators being input by the user. The function would look for the following operators:

+, -, * , / with *, / having the highest precedence and +, - having the lowest precedence.

The operators with the lowest precedence go on the bottom of a stack while those with the highest precedence go on the top of the stack. So if a user types in +-*/, */+- should be displayed in the terminal.

Any ideas on how I should go about this?

答:
Just sort them using std::sort with a custom predicate.

```<code>int precedence(char op)
{
    if (op == '*' || op == '/') return 0;
    return 1;
}

bool comparePrecedence(char a, char b)
{
    return precedence(a) < precedence(b);
}

int main()
{
    char input[] = "+-/";
    std::sort(input, input + 3, &comparePrecedence);
}
</code>```

Obviously, you can add other operators simply by adding them into the precedence function.

Title: Precedence Function

Body:
Just sort them using std::sort with a custom predicate.

int precedence(char op)
{
    if (op == '*' || op == '/') return 0;
    return 1;
}

bool comparePrecedence(char a, char b)
{
    return precedence(a) < precedence(b);
}

int main()
{
    char input[] = "+-/";
    std::sort(input, input + 3, &comparePrecedence);
}

Obviously, you can add other operators simply by adding them into the precedence function.


问:
Issue testing Accept request header in Spring MockMvc
I am trying to unit test SpringBoot Controller. Objective is to test that we return 406 Not Acceptable when request header contains Accept as anything other than application/json. But I find its not working with MockMvc. I am getting 200 OK instead of 406. Any ideas please! Of course, service returns 406 as expected when I test using Postman or any rest client.

```<code>@Test
public void shouldRejectIfInvalidAcceptHeaderIsPassed() throws Exception {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Accept","application/xml");
    httpHeaders.add("Authorization", "some jwt token");

    this.mockMvc.perform(post("/sample/test")
            .contentType(MediaType.APPLICATION_JSON)
            .headers(httpHeaders)
            .content(toJson("")))
            .andExpect(status().isNotAcceptable());

    // Then
    verify(mockSampleService).getSampleOutput();
}
</code>```

And my controller looks like,

```<code>@RestController
@Validated
@RequestMapping(PATH_PREFIX)
public class SampleController {

    public static final String PATH_PREFIX = “/sample”;

    private final SampleService sampleService;

    @Autowired
    public SampleController(SampleService sampleService) {
        sampleService = sampleService;
    }

    @RequestMapping(value = “/test”, method = RequestMethod.POST))
    public SampleResponse createSession() {
        return sampleService.getSampleOutput();
    }

}
</code>```

答: Ahh! I have identified and fixed the issue. In the controller we need to have, @RequestMapping(headers="Accept=application/json"). Else MockMvc is not able to identify the expected format.

Body:
I am trying to unit test SpringBoot Controller. Objective is to test that we return 406 Not Acceptable when request header contains Accept as anything other than application/json. But I find its not working with MockMvc. I am getting 200 OK instead of 406. Any ideas please! Of course, service returns 406 as expected when I test using Postman or any rest client.

@Test
public void shouldRejectIfInvalidAcceptHeaderIsPassed() throws Exception {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Accept","application/xml");
    httpHeaders.add("Authorization", "some jwt token");

    this.mockMvc.perform(post("/sample/test")
            .contentType(MediaType.APPLICATION_JSON)
            .headers(httpHeaders)
            .content(toJson("")))
            .andExpect(status().isNotAcceptable());

    // Then
    verify(mockSampleService).getSampleOutput();
}

And my controller looks like,

@RestController
@Validated
@RequestMapping(PATH_PREFIX)
public class SampleController {

    public static final String PATH_PREFIX = “/sample”;

    private final SampleService sampleService;

    @Autowired
    public SampleController(SampleService sampleService) {
        sampleService = sampleService;
    }

    @RequestMapping(value = “/test”, method = RequestMethod.POST))
    public SampleResponse createSession() {
        return sampleService.getSampleOutput();
    }

}


问:
email client for app engine
GAE supports both incoming and outgoing emails: http://code.google.com/appengine/docs/python/mail/

Have any open source email clients been written for GAE? Something that handles encoding issues, attachments, grouping by conversations, etc.

答:
The Google App Engine SDK can send and receive email; however, there are certain limitations in place that would prevent an actual email client from being built:

The App Engine receives email at the following address:  string@appid.appspotmail.com

http://code.google.com/appengine/docs/python/mail/receivingmail.html

The problem I see with this is that you would need to have your users setup forwarding rules in their Google Accounts so that incoming mail is forwarded to your app using the above format.  This means that they would need to rely on another email service, which would beg the question of what value yours would add over top of the existing service.

Sending is not quite so bad.  The Google App Engine App can send mail on behalf of users logged in with their Google Account, so one could build an outbound email client using a user's Google Account.

http://code.google.com/appengine/docs/python/mail/sendingmail.html

For receiving mail, there are instructions here on how to do that by forwarding mail from an existing email client.  It is currently not possible to use your own domain to receive emails without forwarding:

Custom Incoming Mail Domain With Google App Engine

In summary, to answer your question, if someone has built an email client on App Engine, they have not made it public or done enough marketing to appear in search results.  Even so, their implementation would be subject to the limitations described above.

Title: email client for app engine


问:
how to pass variables to an include file from every parent file laravel
i am an absolute beginner in laravel so far i have created a basic structure of my website in laravel, there are some views in resources/views now there is a folder inside view named as includes and inside that folder there is a file named as banner.blade.php now this banner is included in almost every file which is in resources/views what i want to do is pass a variable containing the name of the banner and echo that variable inside the banner file. here's my code

this is the parent blade from where i need to send a variable e.g $banner_name="contact us"

```<code>@extends("app")

@section("content")

    @include("includes.banner-others")
</code>```

and this is my banner-others file

```<code><div class="banner-others">
    <div class="container">
        <div class="row">
            <h1>{{"uneeb"}}</h1>// i need to echo the $banner_name here.
        </div>
    </div>
</div>
</code>```

答:
In the controller where you call this view, you can pass a variable through like:

```<code>public function index()
{
    $banner_name = 'something';

    return view('your.view.name', compact('banner_name'));
}
</code>```

You also could do it through view composer in AppServiceProvider.php:

```<code>view()->composer('your-view', function ($view) {
        $banner_name = 'something';
        return $view->with('banner_name', $banner_name);
    });
</code>```

And via route:

```<code>Route::get('/', function () {
    return view('your-view', ['banner_name' => 'Something']);
});
</code>```

Body:
i am an absolute beginner in laravel so far i have created a basic structure of my website in laravel, there are some views in resources/views now there is a folder inside view named as includes and inside that folder there is a file named as banner.blade.php now this banner is included in almost every file which is in resources/views what i want to do is pass a variable containing the name of the banner and echo that variable inside the banner file. here's my code

this is the parent blade from where i need to send a variable e.g $banner_name="contact us"

@extends("app")

@section("content")

    @include("includes.banner-others")

and this is my banner-others file

{{"uneeb"}}
// i need to echo the $banner_name here.

Body:
In the controller where you call this view, you can pass a variable through like:

public function index()
{
    $banner_name = 'something';

    return view('your.view.name', compact('banner_name'));
}

You also could do it through view composer in AppServiceProvider.php:

view()->composer('your-view', function ($view) {
        $banner_name = 'something';
        return $view->with('banner_name', $banner_name);
    });

And via route:

Route::get('/', function () {
    return view('your-view', ['banner_name' => 'Something']);
});


问:
Rendering difference in custom control
I'm currently facing problems rendering an sap.suite.ui.microchart.InteractiveDonutChart. I want to render it in a custom control. When I try to render a simple control like sap.m.Text, it works just fine. However, it doesn't with the donut chart. Generating the donut chart like this in a controller works just fine, though. Any ideas as to why this doesn't work? It doesn't give me any errors...

aggregations

```<code>aggregations: {
                content: {
                    type: "sap.ui.core.Control",
                    multiple: true,
                    singluarName: "content"
                }
            }
</code>```

renderer

```<code>        //start of content
        oRM.write("<div ");
        oRM.addClass("cardContent");
        oRM.writeClasses();
        oRM.write(">");
        oRM.renderControl(oControl.getChosenControl());
        oRM.renderControl(oControl.getChosenControl2());
        oRM.write("</div>"); // close div 3
        //end of content
</code>```

functions

```<code>getChosenControl: function() {
        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var textField = new sap.m.Text({
            text: "Dynamically created textfield"
        });

        flexBox.addItem(textField);
        return flexBox;
    },

    getChosenControl2: function() {

        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var donutChart = new sap.suite.ui.microchart.InteractiveDonutChart();

        for (var i = 0; i < 3; i++) {
            var segment = new sap.suite.ui.microchart.InteractiveDonutChartSegment();
            segment.setLabel("Parter");
            segment.setValue(50);
            segment.setDisplayedValue("50 %");

            donutChart.addSegment(segment);
        }

        flexBox.addItem(donutChart);
        return flexBox;
    }
</code>```

答:
I actually found a solution myself. I first added it to my aggregation 'content' with the 'AddContent' method. The next step is to get the content with the 'getContent' method. The last step is to render the returned content.</p>

```<code>            //start of content
                oRM.write("<div ");
                oRM.addClass("cardContent");
                oRM.writeClasses();
                oRM.write(">");

                //add content
                oControl.addContent(oControl.getChosenControl2());

                //get content
                var items = oControl.getContent();

                //render items
                for (var i = 0; i < items.length; i++) {
                    oRM.renderControl(oControl.getContent()[i]);
                }

                oRM.write("</div>"); // close div 3
                //end of content
</code>```

Title: Rendering difference in custom control

Body:
I'm currently facing problems rendering an sap.suite.ui.microchart.InteractiveDonutChart. I want to render it in a custom control. When I try to render a simple control like sap.m.Text, it works just fine. However, it doesn't with the donut chart. Generating the donut chart like this in a controller works just fine, though. Any ideas as to why this doesn't work? It doesn't give me any errors...

aggregations

aggregations: {
                content: {
                    type: "sap.ui.core.Control",
                    multiple: true,
                    singluarName: "content"
                }
            }

renderer

        //start of content
        oRM.write("
");
        oRM.renderControl(oControl.getChosenControl());
        oRM.renderControl(oControl.getChosenControl2());
        oRM.write("
"); // close div 3
        //end of content

functions

getChosenControl: function() {
        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var textField = new sap.m.Text({
            text: "Dynamically created textfield"
        });

        flexBox.addItem(textField);
        return flexBox;
    },

    getChosenControl2: function() {

        var flexBox = new sap.m.FlexBox({
            width: "90%",
            alignItems: "Center"
        });

        var donutChart = new sap.suite.ui.microchart.InteractiveDonutChart();

        for (var i = 0; i < 3; i++) {
            var segment = new sap.suite.ui.microchart.InteractiveDonutChartSegment();
            segment.setLabel("Parter");
            segment.setValue(50);
            segment.setDisplayedValue("50 %");

            donutChart.addSegment(segment);
        }

        flexBox.addItem(donutChart);
        return flexBox;
    }

Body:
I actually found a solution myself. I first added it to my aggregation 'content' with the 'AddContent' method. The next step is to get the content with the 'getContent' method. The last step is to render the returned content.

            //start of content
                oRM.write("<div ");
                oRM.addClass("cardContent");
                oRM.writeClasses();
                oRM.write(">");

                //add content
                oControl.addContent(oControl.getChosenControl2());

                //get content
                var items = oControl.getContent();

                //render items
                for (var i = 0; i < items.length; i++) {
                    oRM.renderControl(oControl.getContent()[i]);
                }

                oRM.write("</div>"); // close div 3
                //end of content


问:
How to add an item to a listview on a button click event?
I am coding in Android Studio and having some trouble. I have a button and a listview. When the button is clicked it should add a hardcoded String to the arraylist.</p>

```<code>List participants;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initParticipants();

    ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, participants);
    ListView participantList = findViewById(R.id.participantList);
    participantList.setAdapter(listAdapter);

}

public void changeJoinState(View view) {

    boolean checked = ((ToggleButton) view).isChecked();

    if(checked) {

        participants.add("example");

        Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
                .show();

    } else {

        Toast.makeText(MainActivity.this, "Left event", Toast.LENGTH_SHORT)
                .show();

    }

}

void initParticipants() {
    participants = new ArrayList<String>();
    participants.add("Creator");
}
</code>```

答:
After updating the list you should call notifyDataSetChanged to see the updated UI. Make the ListView variable at class level. Also call notifyDataSetChanged after adding string to list.</p>

```<code>participants.add("example");
listAdapter.notifyDataSetChanged();
</code>```

Body:
I am coding in Android Studio and having some trouble. I have a button and a listview. When the button is clicked it should add a hardcoded String to the arraylist.

List participants;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initParticipants();

    ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, participants);
    ListView participantList = findViewById(R.id.participantList);
    participantList.setAdapter(listAdapter);

}

public void changeJoinState(View view) {

    boolean checked = ((ToggleButton) view).isChecked();

    if(checked) {

        participants.add("example");

        Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
                .show();

    } else {

        Toast.makeText(MainActivity.this, "Left event", Toast.LENGTH_SHORT)
                .show();

    }

}

void initParticipants() {
    participants = new ArrayList<String>();
    participants.add("Creator");
}

Body:
After updating the list you should call notifyDataSetChanged to see the updated UI. Make the ListView variable at class level. Also call notifyDataSetChanged after adding string to list.

participants.add("example");
listAdapter.notifyDataSetChanged();


问:
Latex Column chart
Trying to create a latex column chart with single values in 3 different columns having 3 colors.</p>

```<code>\begin{tikzpicture}
\begin{axis}[
x tick label style={
    /pgf/number format/1000 sep=},
ylabel=Accuracy,
enlargelimits=0.05,
legend style={at={(0.5,-0.15)},
    anchor=north,legend columns=-1},
ybar interval=0.7,]
\addplot
 coordinates {(1930,80)};
\addplot
  coordinates {(1930,80)};
\addplot
coordinates {(1930,80)};
\legend{Far,Near,Here}
\end{axis}
\end{tikzpicture}
</code>```

答:
You need to add a ybar size (e.g., ybar=5pt) and remove the ybar interval parameter, which looks bogus:

```<code>\begin{tikzpicture}
    \begin{axis}[
        ybar=5pt,
        ylabel=Accuracy,
        xtick=data,
        legend style={at={(0.5,-0.15)}, anchor=north,legend columns=-1},
        x tick label style={/pgf/number format/1000 sep=},
        enlargelimits=0.05,
    ]
        \addplot coordinates {(1930,80)};
        \addplot coordinates {(1930,80)};
        \addplot coordinates {(1930,80)};
        \legend{Far,Near,Here}
    \end{axis}
\end{tikzpicture}
</code>```

Title: Latex Column chart

Body:
Trying to create a latex column chart with single values in 3 different columns having 3 colors.

\begin{tikzpicture}
\begin{axis}[
x tick label style={
    /pgf/number format/1000 sep=},
ylabel=Accuracy,
enlargelimits=0.05,
legend style={at={(0.5,-0.15)},
    anchor=north,legend columns=-1},
ybar interval=0.7,]
\addplot
 coordinates {(1930,80)};
\addplot
  coordinates {(1930,80)};
\addplot
coordinates {(1930,80)};
\legend{Far,Near,Here}
\end{axis}
\end{tikzpicture}

Body:
You need to add a ybar size (e.g., ybar=5pt) and remove the ybar interval parameter, which looks bogus:

\begin{tikzpicture}
    \begin{axis}[
        ybar=5pt,
        ylabel=Accuracy,
        xtick=data,
        legend style={at={(0.5,-0.15)}, anchor=north,legend columns=-1},
        x tick label style={/pgf/number format/1000 sep=},
        enlargelimits=0.05,
    ]
        \addplot coordinates {(1930,80)};
        \addplot coordinates {(1930,80)};
        \addplot coordinates {(1930,80)};
        \legend{Far,Near,Here}
    \end{axis}
\end{tikzpicture}


问:
Firebase, react and redux wait for store to update
I have a React app connected to Firebase, i want to check if user is logged in at every page refresh, dispatching IS_SIGNED_IN action, here's the action creator:

```<code>export function checkAuth() {
return dispatch => {
    firebaseAuth().onAuthStateChanged((user) => {
        if (user) {
            dispatch(signedInAction())
        } else {
            dispatch(signedOutAction())
        }
    })
  }
}
</code>```

Inside the reducer i just make boolean isAuthenticated to true/false:

```<code>case ActionTypes.isSignedIn: {
    return Object.assign({}, state, {
        isAuthenticated: true
    })
}
case ActionTypes.isSignedOut: {
    return Object.assign({}, state, {
        isAuthenticated: false
    })
}
</code>```

Because i want to check if user is signed in when app loads i dispatch the action at componentDidMount (which is wrong i guess):

```<code>class Main extends Component {

constructor(props) {
    super(props);
}

componentDidMount() {
    store.dispatch(checkAuth());
}

render() {
    return (
        <Provider store={store}>
            <Router>
                <Theme>
                    <Routes />
                </Theme>
            </Router>
        </Provider>
    );
  }
}
</code>```

This makes my code where i check for isAuthenticated fail, because it's not yet set in the store, this is in Routes component for example. What would be the best way to solve this? To add up, i know i can use conditional rendering and check to see when isAuthenticated is defined, but i don't like that solution. Thoughts? Thanks

答:
I have done what you are trying to do with a live application and used in it Firebase Auth. You need to use the Actions as a login and logout only then use componentWillMount() and componentWillReceiveProps() to check if the user is logged in:

Actions:

```<code>import { auth } from '../fire';
export const GET_USER = 'get_user';

export function getUser(){
    return dispatch => {
        auth.onAuthStateChanged(user=>{
            dispatch({
                type: GET_USER,
                payload: user
            });
        });
    };
}

export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}
</code>```

your Reducer should have this:

```<code>import {GET_USER} from '../Actions/UserActions';

export default function( state = {loading:true}, action){
    switch (action.type){
        case GET_USER:
            return { loading: false, ...action.payload };
        default:
        return state;
    }
}
</code>```

in your App.js for example, just in the start of it use this:

```<code> componentWillMount(){
   this.props.getUser();
   if(this.props.user.loading === false && this.props.user.email === undefined){
     this.props.history.replace('/Login');
   }
 }

 componentWillReceiveProps(nextProps){
  if(nextProps.user.loading === false && nextProps.user.email === undefined){
    this.props.history.replace('/Login');
  }
 }
</code>```

this is because you have your Auth credentials in your props already.

I hope this works for you..

Body:
I have a React app connected to Firebase, i want to check if user is logged in at every page refresh, dispatching IS_SIGNED_IN action, here's the action creator:

export function checkAuth() {
return dispatch => {
    firebaseAuth().onAuthStateChanged((user) => {
        if (user) {
            dispatch(signedInAction())
        } else {
            dispatch(signedOutAction())
        }
    })
  }
}

Inside the reducer i just make boolean isAuthenticated to true/false:

case ActionTypes.isSignedIn: {
    return Object.assign({}, state, {
        isAuthenticated: true
    })
}
case ActionTypes.isSignedOut: {
    return Object.assign({}, state, {
        isAuthenticated: false
    })
}

Because i want to check if user is signed in when app loads i dispatch the action at componentDidMount (which is wrong i guess):

class Main extends Component {

constructor(props) {
    super(props);
}

componentDidMount() {
    store.dispatch(checkAuth());
}

render() {
    return (
        <Provider store={store}>
            <Router>
                <Theme>
                    <Routes />
                </Theme>
            </Router>
        </Provider>
    );
  }
}

This makes my code where i check for isAuthenticated fail, because it's not yet set in the store, this is in Routes component for example. What would be the best way to solve this? To add up, i know i can use conditional rendering and check to see when isAuthenticated is defined, but i don't like that solution. Thoughts? Thanks

Body:
I have done what you are trying to do with a live application and used in it Firebase Auth. You need to use the Actions as a login and logout only then use componentWillMount() and componentWillReceiveProps() to check if the user is logged in:

Actions:

import { auth } from '../fire';
export const GET_USER = 'get_user';

export function getUser(){
    return dispatch => {
        auth.onAuthStateChanged(user=>{
            dispatch({
                type: GET_USER,
                payload: user
            });
        });
    };
}

export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}

your Reducer should have this:

import {GET_USER} from '../Actions/UserActions';

export default function( state = {loading:true}, action){
    switch (action.type){
        case GET_USER:
            return { loading: false, ...action.payload };
        default:
        return state;
    }
}

in your App.js for example, just in the start of it use this:

 componentWillMount(){
   this.props.getUser();
   if(this.props.user.loading === false && this.props.user.email === undefined){
     this.props.history.replace('/Login');
   }
 }

 componentWillReceiveProps(nextProps){
  if(nextProps.user.loading === false && nextProps.user.email === undefined){
    this.props.history.replace('/Login');
  }
 }

this is because you have your Auth credentials in your props already.

I hope this works for you..


问:
Rails 3, updated_at is 1 day ahead?
For some reason when updating a record, updated_at is getting updated as 2011-01-23, even though Date.today is returning 2011-01-22. Why are these different? Is there a way to set them to be the same?

Thanks!

答:
By default, Rails uses UTC as the timezone for all created_at and updated_at fields. You can override this by setting a custom timezone in config/application.rb:

```<code>config.time_zone = 'Central Time (US & Canada)'
</code>```

You can run rake time:zones:all from your application directory to get a list of all valid time zones.

Title: Rails 3, updated_at is 1 day ahead?

Body:
By default, Rails uses UTC as the timezone for all created_at and updated_at fields. You can override this by setting a custom timezone in config/application.rb:

config.time_zone = 'Central Time (US & Canada)'

You can run rake time:zones:all from your application directory to get a list of all valid time zones.


问:
How to re-write  tag on platforms that don't allow it?
I'm on a platform that meets the requirements of Google AMP except for one in particular; I can't rename the  tag. It seems like an arbitrary requirement compared to everything else, so I'm hoping there's some way of indicating to Google it is an AMP page without modifying it.

Has anyone successfully worked around re-writing the opening  tag?

答:
Unfortunately, the opening html tag must contain either the ⚡ or amp attribute in order to become a valid AMP page.

Unless the AMP HTML Specification changes, I doubt what you're trying to achieve is possible, unless the page is pre-processed where you could manipulate the opening  tag with preg_replace (or similar), though this is by no means an elegant solution.

Resources

Required Mark-Up

AMP HTML Specification

PHP :: preg_replace

Title: How to re-write <html> tag on platforms that don't allow it?

Body:
Unfortunately, the opening html tag must contain either the ⚡ or amp attribute in order to become a valid AMP page.

Unless the AMP HTML Specification changes, I doubt what you're trying to achieve is possible, unless the page is pre-processed where you could manipulate the opening <html> tag with preg_replace (or similar), though this is by no means an elegant solution.

Resources

Required Mark-Up

AMP HTML Specification

PHP :: preg_replace


问:
How to make EF code first work under `IIS AppPool\MySiteName`?
I am learning MVC 3 from asp.net site.

My MVC 3 application already has been tested under IIS AppPool\MySiteName and it works well.

Using Sql Server Management Studio, I created a new account for IIS AppPool\MySiteName.

I followed this tutorial "creating db on the fly" and I got an error as follows:

```<code>Server Error in '/' Application.
--------------------------------------------------------------------------------

Cannot open database "Movies" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\Getting Started'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
</code>```

答: Well that error is saying that the user IIS APPPOOL\Getting Started doesn't have the proper login credentials, either your username or password is incorrect. Why not show us what the connection string looks like in your web.config file</p>

Body:
I am learning MVC 3 from asp.net site.

My MVC 3 application already has been tested under IIS AppPool\MySiteName and it works well.

Using Sql Server Management Studio, I created a new account for IIS AppPool\MySiteName.

I followed this tutorial "creating db on the fly" and I got an error as follows:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Cannot open database "Movies" requested by the login. The login failed.
Login failed for user 'IIS APPPOOL\Getting Started'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.


问:
Highcharts Sunburst chart - What is the range of colorVariation.to values?
Highcharts API reference explains that colorVariation.to is the ending value of color variation that is applied to the last sibling.
Demo example : http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/sunburst/

```<code>levels: [{
        level: 2,
        colorByPoint: true,
        dataLabels: {
            rotationMode: 'parallel'
        }
    },
    {
        level: 3,
        colorVariation: {
            key: 'brightness',
            to: -0.5
        }
    }, {
        level: 4,
        colorVariation: {
            key: 'brightness',
            to: 0.5
        }
    }]
</code>```

When i set colorVariation.To = 0 for level 3, all the siblings at this level are shown in same color. Refer: http://jsfiddle.net/hqkk8ut5/

```<code>levels: [{
        level: 2,
        colorByPoint: true,
        dataLabels: {
            rotationMode: 'parallel'
        }
    },
    {
        level: 3,
        colorVariation: {
            key: 'brightness',
            to: 0
        }
    }, {
        level: 4,
        colorVariation: {
            key: 'brightness',
            to: 0.5
        }
    }]
</code>```

In my application, I want to configure the colorVariation.to value.
I would like to know that what range of values should i allow?

答:
I think that the key to understand how colorVariation.to works is by analyzing two core functions:

1. variation from sunburst.src.js

```<code>        function variation(color) {
            var colorVariation = level && level.colorVariation;
            if (colorVariation) {
                if (colorVariation.key === 'brightness') {
                    return H.color(color).brighten(
                        colorVariation.to * (index / siblings)
                    ).get();
                }
            }

            return color;
        }
</code>```

2. brighten from highcharts.src.js

```<code>        brighten: function(alpha) {
            var i,
                rgba = this.rgba;

            if (this.stops) {
                each(this.stops, function(stop) {
                    stop.brighten(alpha);
                });

            } else if (isNumber(alpha) && alpha !== 0) {
                for (i = 0; i < 3; i++) {
                    rgba[i] += pInt(alpha * 255);

                    if (rgba[i] < 0) {
                        rgba[i] = 0;
                    }
                    if (rgba[i] > 255) {
                        rgba[i] = 255;
                    }
                }
            }
            return this;
        },
</code>```

Example:

Les't assume that we have two siblings on the same level and their colorVariation.to is 0,5. The base color for this level is rgba(255,0,0,1) (red). For the first sibling the index equals to 0 in variation function. So the value passed to the brighten function is 0 (0.5 * (0 / 2)). The next step is multiplying this value by 255 (maximum level of brightness) and adding it to each color component except a: r, g and b. So for the first sibling this value remains the same as colorVariation.to.

For the second sibling the value of alfa is 0.25 (0.5 * (1 /2)). pInt(alpha * 255) will return 63 (pInt works just like Math.floor in this case). So the final value will be rgba(255, 63, 63). The values higher than 255 and 0 are corrected by two if statements.

In this case Math.min(r,g,b) is 0, so the if we want to get maximum brightness for the last leaf the alpha should equal to 1 (all components (r,b,g) must have value of 255).

If we solve the equation from variation function: colorVariation.to * (1 / 2) = 1
we will get 2 - the maximum value for colorVariation in this case. All values higher than this will work the same as if they were 2.

The value of colorVariation can be a negative number - it will make colors darker instead of brighter.

Body:
Highcharts API reference explains that colorVariation.to is the ending value of color variation that is applied to the last sibling.
Demo example : http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/sunburst/

levels: [{
        level: 2,
        colorByPoint: true,
        dataLabels: {
            rotationMode: 'parallel'
        }
    },
    {
        level: 3,
        colorVariation: {
            key: 'brightness',
            to: -0.5
        }
    }, {
        level: 4,
        colorVariation: {
            key: 'brightness',
            to: 0.5
        }
    }]

When i set colorVariation.To = 0 for level 3, all the siblings at this level are shown in same color. Refer: http://jsfiddle.net/hqkk8ut5/

levels: [{
        level: 2,
        colorByPoint: true,
        dataLabels: {
            rotationMode: 'parallel'
        }
    },
    {
        level: 3,
        colorVariation: {
            key: 'brightness',
            to: 0
        }
    }, {
        level: 4,
        colorVariation: {
            key: 'brightness',
            to: 0.5
        }
    }]

In my application, I want to configure the colorVariation.to value.
I would like to know that what range of values should i allow?

Body:
I think that the key to understand how colorVariation.to works is by analyzing two core functions:

1. variation from sunburst.src.js

        function variation(color) {
            var colorVariation = level && level.colorVariation;
            if (colorVariation) {
                if (colorVariation.key === 'brightness') {
                    return H.color(color).brighten(
                        colorVariation.to * (index / siblings)
                    ).get();
                }
            }

            return color;
        }

2. brighten from highcharts.src.js

        brighten: function(alpha) {
            var i,
                rgba = this.rgba;

            if (this.stops) {
                each(this.stops, function(stop) {
                    stop.brighten(alpha);
                });

            } else if (isNumber(alpha) && alpha !== 0) {
                for (i = 0; i < 3; i++) {
                    rgba[i] += pInt(alpha * 255);

                    if (rgba[i] < 0) {
                        rgba[i] = 0;
                    }
                    if (rgba[i] > 255) {
                        rgba[i] = 255;
                    }
                }
            }
            return this;
        },

Example:

Les't assume that we have two siblings on the same level and their colorVariation.to is 0,5. The base color for this level is rgba(255,0,0,1) (red). For the first sibling the index equals to 0 in variation function. So the value passed to the brighten function is 0 (0.5 * (0 / 2)). The next step is multiplying this value by 255 (maximum level of brightness) and adding it to each color component except a: r, g and b. So for the first sibling this value remains the same as colorVariation.to.

For the second sibling the value of alfa is 0.25 (0.5 * (1 /2)). pInt(alpha * 255) will return 63 (pInt works just like Math.floor in this case). So the final value will be rgba(255, 63, 63). The values higher than 255 and 0 are corrected by two if statements.

In this case Math.min(r,g,b) is 0, so the if we want to get maximum brightness for the last leaf the alpha should equal to 1 (all components (r,b,g) must have value of 255).

If we solve the equation from variation function: colorVariation.to * (1 / 2) = 1
we will get 2 - the maximum value for colorVariation in this case. All values higher than this will work the same as if they were 2.

The value of colorVariation can be a negative number - it will make colors darker instead of brighter.


问:
Python list | How to remove parenthesis,quotes and commas in my list?
From my database, I'm returning a list to be displayed into my HTML page but my list has this unwanted symbols. I tried using split() function but it wont work. How can I remove those parenthesis,commas and quotes. Thanks for you help

The output is :

```<code>[('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
</code>```

I want:

```<code> [cenomar, cedula, Birth Certificate, Clearance]
</code>```

Here is my python function:

```<code> @app.route('/')
    def search():
        conn=psycopg2.connect("dbname='forms' user='postgres' password='everboy'
       host='localhost' port='5432'")
       cur=conn.cursor()
       cur.execute("SELECT name from form")
       rows=cur.fetchall()
       print(rows)
       return render_template("form.html",rows=rows)
</code>```

答:
Try this one</p>

```<code>l = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
b = []
for i in l:
    b.append(i[0])
print(b)
</code>```

Body:
From my database, I'm returning a list to be displayed into my HTML page but my list has this unwanted symbols. I tried using split() function but it wont work. How can I remove those parenthesis,commas and quotes. Thanks for you help

The output is :

[('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]

I want:

 [cenomar, cedula, Birth Certificate, Clearance]

Here is my python function:

 @app.route('/')
    def search():
        conn=psycopg2.connect("dbname='forms' user='postgres' password='everboy'
       host='localhost' port='5432'")
       cur=conn.cursor()
       cur.execute("SELECT name from form")
       rows=cur.fetchall()
       print(rows)
       return render_template("form.html",rows=rows)

Body:
Try this one

l = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
b = []
for i in l:
    b.append(i[0])
print(b)


问:
Get index of object in python using value without looping
So basically I have this:

```<code>data = [
    {
        "id" : "hello",
        ...
    },
    {
        "id" : "world",
         ...
    }
]
</code>```

and I want to get the result:

```<code>"1"
</code>```

if I enter something like:

```<code>get_index(id="world")
</code>```

And the main thing is that I don't want to loop through the array since there is a lot of data in it. If I were to loop it would be easy and I would end up with some code like:

```<code>for obj in data:
    if obj['id'] == 'hello':
        print(obj['id'])
</code>```

But is there a direct way of doing this without looping?

答: It is not possible to do this more efficiently than the looping you described as long as you can't exploit the specific structure of the data in some way.</p>

Body:
So basically I have this:

data = [
    {
        "id" : "hello",
        ...
    },
    {
        "id" : "world",
         ...
    }
]

and I want to get the result:

"1"

if I enter something like:

get_index(id="world")

And the main thing is that I don't want to loop through the array since there is a lot of data in it. If I were to loop it would be easy and I would end up with some code like:

for obj in data:
    if obj['id'] == 'hello':
        print(obj['id'])

But is there a direct way of doing this without looping?


问:
I need to input 20 numbers and to output only double location
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.</p>

```<code>#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;

for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}

for(i=0;i<n;i++)
{
    if (i%2==0 && i!=1 && i!=0)
    {
        printf("%d\n",num[i]);
    }
}
}
</code>```

答:
If you mean you want the numbers from array that are present at even position than you can do like this:

```<code>for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
{
    printf("%d\n",arr[i]);
}
</code>```

I above code i is initialized to 2 and the increment in each iteration is 2 so it will access elements only at even position (2,4,6...).

Body:
try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.

#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;

for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}

for(i=0;i<n;i++)
{
    if (i%2==0 && i!=1 && i!=0)
    {
        printf("%d\n",num[i]);
    }
}
}

Body:
If you mean you want the numbers from array that are present at even position than you can do like this:

for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
{
    printf("%d\n",arr[i]);
}

I above code i is initialized to 2 and the increment in each iteration is 2 so it will access elements only at even position (2,4,6...).


问:
Node.js serve as microservice service
I want to access my node.js server as service in microservice infrastructure. This means that if locally I can access node server services /root-path-to-service. But after deploying to infrastructure in AWS it is accessed as /microservice-path/root-path-to-service and app.use('/root-path-to-service', ...) does not work anymore. How can I configure to work in both cases?

答:
Provide the path as an environment variable. Then read it from there in Node using:

```<code>process.env.ENV_VARIABLE_NAME
</code>```

This is standard microservice practice.

Title: Node.js serve as microservice service

Body:
Provide the path as an environment variable. Then read it from there in Node using:

process.env.ENV_VARIABLE_NAME

This is standard microservice practice.


答:
Use notifyDataSetChanged()</p>

```<code>void initParticipants() {
   participants = new ArrayList<String>();
   participants.add("Creator");
   participants.notifyDataSetChanged();
}
</code>```

Title: How to add an item to a listview on a button click event?

Body:
I am coding in Android Studio and having some trouble. I have a button and a listview. When the button is clicked it should add a hardcoded String to the arraylist.

List participants;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initParticipants();

    ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, participants);
    ListView participantList = findViewById(R.id.participantList);
    participantList.setAdapter(listAdapter);

}

public void changeJoinState(View view) {

    boolean checked = ((ToggleButton) view).isChecked();

    if(checked) {

        participants.add("example");

        Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
                .show();

    } else {

        Toast.makeText(MainActivity.this, "Left event", Toast.LENGTH_SHORT)
                .show();

    }

}

void initParticipants() {
    participants = new ArrayList<String>();
    participants.add("Creator");
}

Body:
Use notifyDataSetChanged()

void initParticipants() {
   participants = new ArrayList<String>();
   participants.add("Creator");
   participants.notifyDataSetChanged();
}


问:
Is there "transaction log" on datastore?
I want to check history of datastore operation.
But, I cannot found it on logging/datastore console/stackdriver.

Is there "transaction log" about datastore?
Should I insert log manually to webapp?

答:
Indeed, datastore transactions are not logged.

If you so desire you'd have to create such logs yourself. See Using Stackdriver logging in App Engine apps.


问:
SpringBoot: how to pass argument (request id) from controller through all program?
I use SpringBoot app. Every request has ID. And I has to use this ID when log errors in some services and more lowlevel places of the program. How can I  implement it? Thank you!</p>

答:
You can use ThreadLocal to store that ID for a specific Thread.

Then, in your services you can get that ID throghtout the method ThreadLocal#get.

For example (This is just an approach):

```<code>class AppProvider {
    public static final ThreadLocal<String> APP_CONTEXT = new ThreadLocal<String>();
}

class Controller {
    public void users(@RequestParam String id) {
        AppProvider.APP_CONTEXT.set(id);
        .......
    }
}

class Service {
    try {
    } catch (Exception e) {
        log.error(String.format("Id: %s", AppProvider.APP_CONTEXT.get()));
    }
}
</code>```

This is just an approach using ThreadLocal.

Look a this for Memory leak handling: https://stackoverflow.com/a/17975255/1715121

Body:
You can use ThreadLocal to store that ID for a specific Thread.

Then, in your services you can get that ID throghtout the method ThreadLocal#get.

For example (This is just an approach):

class AppProvider {
    public static final ThreadLocal<String> APP_CONTEXT = new ThreadLocal<String>();
}

class Controller {
    public void users(@RequestParam String id) {
        AppProvider.APP_CONTEXT.set(id);
        .......
    }
}

class Service {
    try {
    } catch (Exception e) {
        log.error(String.format("Id: %s", AppProvider.APP_CONTEXT.get()));
    }
}

This is just an approach using ThreadLocal.

Look a this for Memory leak handling: https://stackoverflow.com/a/17975255/1715121


问:
Critical Error Occurs when Booting Up R ...."jvm.dll" is missing! Can't use libraries any more
I have a critical problem which has effectively halted my R programming environment. I need the Java integration and rJava library  as I use the R program in many other packages, and they specify this library as a prerequisite ( Rapidminer, SAP Predictive analytics etc). It used to work, I don't know what happened!. Please assist.

When I boot up R it comes up with:

. The message says " its Header is: rsession.exe- System error  , the body says:

"the program can't start because jvm.dll is missing from your computer. Try re-installing the program to fix this problem".

What program (referred to in the message)  must I re-install  and where must I install it to?

I have installed and reinstalled r ( version3.2.1)[2] ..see second image ( I am using R studio ( Version 0.99893))

![enter image description here][2]

I also deleted and re-installed the java library rJava , and it installs  but wont load i.e. library(rJava)..results in the same error message as in 1 above and when I press OK to continue the console brings up the following text :

ERROR MESSAGE IN R CONSOLE WHEN USING "library(rJava)"

```<code>"library("rJava", lib.loc="~/R/win-library/3.2")
 Error : .onLoad failed in loadNamespace() for 'rJava', details:
 call: inDL(x, as.logical(local), as.logical(now), ...)
 error: unable to load shared object 'C:/Users/grbortz/
 Documents/R/win-library/3.2/rJava/libs/x64/rJava.dll':
  LoadLibrary failure:  The specified module could not be found.
</code>```

In addition: Warning message:

package ‘rJava’ was built under R version 3.2.5

  Error: package or namespace load failed for ‘rJava’

However when I Look in my directory as it mentioned above i.e.
the  rJava.dll path mentioned above, i.e.
~  " Users\  grbortz\ Documents /R/ winlibrary /3.2/rJava/libs / x64 / rJava.dll

The rJava.dll file is there!

Please help. If any more actons are needed from my side  I am happy to oblige.

答:
R-studio is looking for the 'jvm.dll' file in a location where it does not exist. You probably might have a 64bit R studio installed and it's looking in the 32bit java folder. Try to find where the 64bit version of java is and inside there you will have the jvm.dll. on my machine this jvm.dll file is in

"C:\Program Files\Java\jre7\bin\server".

Once found, all you have to do is point to where the java "jre7" folder resides and RStudio would automatically look inside it for jvm.dll. You can point it with the following command

Sys.setenv(JAVA_HOME='C:\\Program Files\\Java\\jre7').

Body:
I have a critical problem which has effectively halted my R programming environment. I need the Java integration and rJava library  as I use the R program in many other packages, and they specify this library as a prerequisite ( Rapidminer, SAP Predictive analytics etc). It used to work, I don't know what happened!. Please assist.

When I boot up R it comes up with:

. The message says " its Header is: rsession.exe- System error  , the body says:

"the program can't start because jvm.dll is missing from your computer. Try re-installing the program to fix this problem".

What program (referred to in the message)  must I re-install  and where must I install it to?

I have installed and reinstalled r ( version3.2.1)[2] ..see second image ( I am using R studio ( Version 0.99893))

![enter image description here][2]

I also deleted and re-installed the java library rJava , and it installs  but wont load i.e. library(rJava)..results in the same error message as in 1 above and when I press OK to continue the console brings up the following text :

ERROR MESSAGE IN R CONSOLE WHEN USING "library(rJava)"

"library("rJava", lib.loc="~/R/win-library/3.2")
 Error : .onLoad failed in loadNamespace() for 'rJava', details:
 call: inDL(x, as.logical(local), as.logical(now), ...)
 error: unable to load shared object 'C:/Users/grbortz/
 Documents/R/win-library/3.2/rJava/libs/x64/rJava.dll':
  LoadLibrary failure:  The specified module could not be found.

In addition: Warning message:

package ‘rJava’ was built under R version 3.2.5

  Error: package or namespace load failed for ‘rJava’

However when I Look in my directory as it mentioned above i.e.
the  rJava.dll path mentioned above, i.e.
~  " Users\  grbortz\ Documents /R/ winlibrary /3.2/rJava/libs / x64 / rJava.dll

The rJava.dll file is there!

Please help. If any more actons are needed from my side  I am happy to oblige.


问:
where to put modal login in html5
i am entirely new to web development. i have an index page and a login page. i want to incorporate the login in the index page as a modal login page. please how would i do it.

here are the codes

```<code><!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Ascend — be loved</title>
</head>

<body>

<div id="mypage">
<header id="myheader" role="banner">
    <div class="container">
        <div class="header-inner">
            <h1><a href="#">Ascend<span>.</span></a></h1>
            <nav role="navigation">
                <ul>
                    <li><a href="products.html">Products</a></li>
                    <li><a href="services.html">Services</a></li>
                    <li><a href="pricing.html">Pricing</a></li>
                    <li><a href="about.html">About</a></li>
                    <li><a href="contact.html">Contact</a></li>

                    <!-- i want to inert the modal login button here-->

                </ul>
            </nav>
        </div>
    </div>
</header>
<div>
</code>```

Here is the sample form i want to convert to modal form. the button to call the form should be placed on the header eg "login here"
and this form should be placed within the html5 codes such that when i click the "login here" button the modal form below will appear.

```<code><a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
<div>
    <a href="#close" title="Close" class="close">X</a>
    <h2>Modal Box</h2>
    <p>This is a sample modal box that can be created using the powers of
CSS3.</p>
    <p>You could do a lot of things here like have a pop-up ad that shows
when your website loads, or create a login/register form for users.</p>
</div>
</div>
</code>```

thanks

答:
You can put modal wherever you want. You can write it's code just below header closing tag and give it an unique id which will have z-index property of negative value. It will make you modal appear in front of everything.

You can read more about z-index here.

Title: where to put modal login in html5

Body:
i am entirely new to web development. i have an index page and a login page. i want to incorporate the login in the index page as a modal login page. please how would i do it.

here are the codes

<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Ascend — be loved</title>

Ascend.

Products

Services

Pricing

About

Contact

Here is the sample form i want to convert to modal form. the button to call the form should be placed on the header eg "login here"
and this form should be placed within the html5 codes such that when i click the "login here" button the modal form below will appear.

Open Modal

    X

Modal Box

This is a sample modal box that can be created using the powers of
CSS3.

You could do a lot of things here like have a pop-up ad that shows
when your website loads, or create a login/register form for users.

thanks


问:
How to use nested routes with several parameters in ember 2.17

I am trying to build an smarthome app and I am stuck with calling nested routes with serveral parameters. I want to show an information which user is logged in and below that template which is in my parent route i want to render child pages for showing households. After a specific household is chosen, i want to show the rooms in the household and then devices. This is my router.js

```<code>    Router.map(function() {
      this.route('about');
      this.route('users', function() {
      });
      this.route('households', { path: '/:user_id' }, function() {
        this.route('index', { path: '/:user_id' })
        this.route('rooms',{ path: '/:household_id' });
        this.route('devices', { path: '/:room_id' });
      });
    });

export default Router;
</code>```

I link to households like this

```<code>  <h3>{{#link-to "households" user.id}}{{user.surname}}{{/link-to}}</h3>
</code>```

and now I want to declare a model in the route of households.js which returns an user from the ember data store and render the parent template. Afterwards the model should redirect to households.index with the user.id too and the households.index.hbs should render all households below the parent template.
 My households.js route looks like this:

```<code>export default Route.extend({
  model(params){
    {
      return this.get('store').findRecord('user', params.user_id);
    }
  }
});
</code>```

and my household.index route like this

```<code>export default Route.extend({
    model(params) {
       return this.get('store').findAll('household').then(results => results.filter((site) => {
           return site.get('member').filter(x => x == params.user_id).length > 0;
       }));
      }
});
</code>```

Actually the following error occurs:

Error: Assertion Failed: You
  attempted to define a {{link-to "households.rooms"}} but did not
  pass the parameters required for generating its dynamic segments. You
  must provide param user_id to generate.

In general I need serveral parameters in all nested routes/subroutes, because I need the user_id for example in the route devices for checking if the calling user is a admin. If he is an admin he would be able to add and edit devices. And i need the room_id to show only devices which are in the chosen room.

Is there any way to pass serveral parameters or using the controllers in a way, I can handle my purpose?

答:
In my understanding, you haven't set up the routing hierarchy well.

Assuming that you have multiple users, and every user has multiple households, and every household has multiple rooms, I suggest you make your router.js like this:

```<code>Router.map(function() {
  this.route('about');
  this.route('users', function() {
    this.route('index'); // Lists all the users, URL looks like /users
    this.route('single', { path: '/:user_id' }, function() {
      this.route('index'); // Shows a single user, URL looks like /users/123
      this.route('households', function() {
        this.route('index'); // Shows all households a user with user_id has, URL looks like /users/123/households
        this.route('single',{ path: '/:household_id' }, function() {
          this.route('index'); // Shows a single household, URL looks like /users/123/households/456
          this.route('rooms', function() {
            this.route('index'); // Shows all rooms a household with household_id has, URL looks like /users/123/households/456/rooms
            this.route('single', { path: '/:room_id' }); // Shows a single room, URL looks like /users/123/households/456/rooms/789
          });
        });
      });
    });
  });
});
</code>```

Feel free to omit this.route('index'); lines in the router if you want, but make sure you make a route to handle this. Your templates should look something like this.

```<code>// templates/users.hbs

{{outlet}}

// templates/users/index.hbs

<h1>This shows all the users</h1>

<ul>
{{#each model as |user|}}
  <li>{{user.name}}</li>
{{/each}}
</ul>

// templates/users/single.hbs

{{outlet}}

// templates/users/single/index.hbs

<h1>This shows a single user with id {{model.id}}</h1>

<p>This is the user named {{model.name}}.</p>

// templates/users/single/households.hbs

{{outlet}}

// ... And so on
</code>```

You should implement model() hooks in such a way that they fetch only what you really need. For the lists, you fetch them in the index route.js of the type you want to display (i.e. the model() of routes/users/index.js for users), and for the single record not in the index, but in the single route.js (i.e. for a single household in the model() of routes/users/single/households/single.js) to make that model accessible to both the index route and the child routes.

So, with this configuration, your links should look something like this:

```<code>// All users
{{#link-to 'users'}}All users{{/link-to}}

// Single user
{{#link-to 'users.single' user.id}}{{user.name}}{{/link-to}}

// Households of a single user
{{#link-to 'users.single.households' user.id}}All households of {{user.name}}{{/link-to}}

// Specific household of a single user
{{#link-to 'users.single.households.single' user.id household.id}}Household {{household.name}} of {{user.name}}{{/link-to}}

// Rooms within a specific household
{{#link-to 'users.single.households.single.rooms' user.id household.id}}All rooms within household {{household.name}} of {{user.name}}{{/link-to}}
</code>```

Note: Make sure to specify models and their relationships properly to make your life easier from the very beginning. So, for the configuration assumed at the beginning of this answer, you should make your models something like this:

```<code>// models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    households: DS.hasMany('household')
});

// models/household.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    user: DS.belongsTo('user'),
    rooms: DS.hasMany('room')
});

// models/room.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    household: DS.belongsTo('household')
});
</code>```

If you organize your models like this, then Ember will let you link from a rooms page (route) to the user's page like this:

```<code>{{#link-to 'users.single' model.household.user}}Go to user{{/link-to}}
</code>```

Body:
I am trying to build an smarthome app and I am stuck with calling nested routes with serveral parameters. I want to show an information which user is logged in and below that template which is in my parent route i want to render child pages for showing households. After a specific household is chosen, i want to show the rooms in the household and then devices. This is my router.js

    Router.map(function() {
      this.route('about');
      this.route('users', function() {
      });
      this.route('households', { path: '/:user_id' }, function() {
        this.route('index', { path: '/:user_id' })
        this.route('rooms',{ path: '/:household_id' });
        this.route('devices', { path: '/:room_id' });
      });
    });

export default Router;

I link to households like this

{{#link-to "households" user.id}}{{user.surname}}{{/link-to}}

and now I want to declare a model in the route of households.js which returns an user from the ember data store and render the parent template. Afterwards the model should redirect to households.index with the user.id too and the households.index.hbs should render all households below the parent template.
 My households.js route looks like this:

export default Route.extend({
  model(params){
    {
      return this.get('store').findRecord('user', params.user_id);
    }
  }
});

and my household.index route like this

export default Route.extend({
    model(params) {
       return this.get('store').findAll('household').then(results => results.filter((site) => {
           return site.get('member').filter(x => x == params.user_id).length > 0;
       }));
      }
});

Actually the following error occurs:

Error: Assertion Failed: You
  attempted to define a {{link-to "households.rooms"}} but did not
  pass the parameters required for generating its dynamic segments. You
  must provide param user_id to generate.

In general I need serveral parameters in all nested routes/subroutes, because I need the user_id for example in the route devices for checking if the calling user is a admin. If he is an admin he would be able to add and edit devices. And i need the room_id to show only devices which are in the chosen room.

Is there any way to pass serveral parameters or using the controllers in a way, I can handle my purpose?

Body:
In my understanding, you haven't set up the routing hierarchy well.

Assuming that you have multiple users, and every user has multiple households, and every household has multiple rooms, I suggest you make your router.js like this:

Router.map(function() {
  this.route('about');
  this.route('users', function() {
    this.route('index'); // Lists all the users, URL looks like /users
    this.route('single', { path: '/:user_id' }, function() {
      this.route('index'); // Shows a single user, URL looks like /users/123
      this.route('households', function() {
        this.route('index'); // Shows all households a user with user_id has, URL looks like /users/123/households
        this.route('single',{ path: '/:household_id' }, function() {
          this.route('index'); // Shows a single household, URL looks like /users/123/households/456
          this.route('rooms', function() {
            this.route('index'); // Shows all rooms a household with household_id has, URL looks like /users/123/households/456/rooms
            this.route('single', { path: '/:room_id' }); // Shows a single room, URL looks like /users/123/households/456/rooms/789
          });
        });
      });
    });
  });
});

Feel free to omit this.route('index'); lines in the router if you want, but make sure you make a route to handle this. Your templates should look something like this.

// templates/users.hbs

{{outlet}}

// templates/users/index.hbs

<h1>This shows all the users</h1>

<ul>
{{#each model as |user|}}
  <li>{{user.name}}</li>
{{/each}}
</ul>

// templates/users/single.hbs

{{outlet}}

// templates/users/single/index.hbs

<h1>This shows a single user with id {{model.id}}</h1>

<p>This is the user named {{model.name}}.</p>

// templates/users/single/households.hbs

{{outlet}}

// ... And so on

You should implement model() hooks in such a way that they fetch only what you really need. For the lists, you fetch them in the index route.js of the type you want to display (i.e. the model() of routes/users/index.js for users), and for the single record not in the index, but in the single route.js (i.e. for a single household in the model() of routes/users/single/households/single.js) to make that model accessible to both the index route and the child routes.

So, with this configuration, your links should look something like this:

// All users
{{#link-to 'users'}}All users{{/link-to}}

// Single user
{{#link-to 'users.single' user.id}}{{user.name}}{{/link-to}}

// Households of a single user
{{#link-to 'users.single.households' user.id}}All households of {{user.name}}{{/link-to}}

// Specific household of a single user
{{#link-to 'users.single.households.single' user.id household.id}}Household {{household.name}} of {{user.name}}{{/link-to}}

// Rooms within a specific household
{{#link-to 'users.single.households.single.rooms' user.id household.id}}All rooms within household {{household.name}} of {{user.name}}{{/link-to}}

Note: Make sure to specify models and their relationships properly to make your life easier from the very beginning. So, for the configuration assumed at the beginning of this answer, you should make your models something like this:

// models/user.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    households: DS.hasMany('household')
});

// models/household.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    user: DS.belongsTo('user'),
    rooms: DS.hasMany('room')
});

// models/room.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),

    household: DS.belongsTo('household')
});

If you organize your models like this, then Ember will let you link from a rooms page (route) to the user's page like this:

{{#link-to 'users.single' model.household.user}}Go to user{{/link-to}}


答:
You need to change if conditional block code with below code

```<code> if(checked) {

    participants.add("example");
     participantList.notifyDataSetChanged();
    Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
            .show();

}
</code>```

Whenever there is a change in a list, adapter needs to be notified via notifyDataSetChanged() method

Body:
You need to change if conditional block code with below code

 if(checked) {

    participants.add("example");
     participantList.notifyDataSetChanged();
    Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
            .show();

}

Whenever there is a change in a list, adapter needs to be notified via notifyDataSetChanged() method


问:
I am using `max()` to get the highest value from n digits?
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

```<code>def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)
</code>```

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

```<code>def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)
</code>```

答:
You don't quite say what your question is, but if you want another way to solve the problem,

```<code>def is_divisable(n):
    return int(max(str(n))) % 3 == 0
</code>```

This code converts the number to its decimal string representation, finds the largest digit (as a character), changes that digit to an integer, checks if that is divisible by 3, then returns that answer.

If your question is why you are getting that error, your parameter n is an integer, and you try to apply the max() function to that integer. However, max() is supposed to be used on iterable objects such as strings, lists, tuples, generators, and so on. My code changes the integer to a string before using max() so it does not have that problem, and it iterates over the digits in the string.

Body:
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:

def is_divisable(n):
    a = str(n)
    b = 0
    for i in a:
        if int(i)>b:
            b = int(i)

    if b % 3 == 0:
        return "True"
print is_divisable(67479)

I have thought of it in another way but my code is not working and
I am getting an error says:

"TypeError: 'int' object is not iterable"

def is_dvo(n):

    if max(n) % 3 == 0:
        return True

print is_dvo(67479)

Body:
You don't quite say what your question is, but if you want another way to solve the problem,

def is_divisable(n):
    return int(max(str(n))) % 3 == 0

This code converts the number to its decimal string representation, finds the largest digit (as a character), changes that digit to an integer, checks if that is divisible by 3, then returns that answer.

If your question is why you are getting that error, your parameter n is an integer, and you try to apply the max() function to that integer. However, max() is supposed to be used on iterable objects such as strings, lists, tuples, generators, and so on. My code changes the integer to a string before using max() so it does not have that problem, and it iterates over the digits in the string.


问:
Using $http or $timeout with $stateProvider in AngularJS
I come here from this question Is it possible to load a template via AJAX request for UI-Router in Angular?

I wish to load a template for a given state using $http.

ui.router docs shows examples where both $timeout and $http are used within $stateProvider config, e.g.

Or you can use a template provider function which can be injected, has
  access to locals, and must return template HTML, like this:

```<code>$stateProvider.state('contacts', {   templateProvider: function
 ($timeout, $stateParams) {
   return $timeout(function () {
    return '<h1>' + $stateParams.contactId + '</h1>'
   }, 100);
 }
})
</code>```

However, as I understand it, $stateProvider has to be configured during module.config phase, and $timeout is not available then. I cannot find any example which shows how to access $timeout (or $http) for $stateProvider exactly per the example provided by the docs.

Is there a way to access either $timeout or $http as defined in the docs? Do I configure state at another point? Is there an alternative way to do this which I'm overlooking?

答:
The templateProvider function itself is injected with the dependencies using injector service, and it has nothing to do with the config phase.

So you should be able to use $http simply by injecting it in the function. If you see the example, $timeout or $stateParams are also not available at the config phase, but they work fine in the templateProvider function.

For example, the below snippet returns the content of HTTPBin:

```<code>templateProvider: function($http) {
  return $http.get('https://httpbin.org/get')
    .then(function(response) {
      return JSON.stringify(response.data);
    });
  }
</code>```

For more details, refer to this fiddle.

Body:
I come here from this question Is it possible to load a template via AJAX request for UI-Router in Angular?

I wish to load a template for a given state using $http.

ui.router docs shows examples where both $timeout and $http are used within $stateProvider config, e.g.

Or you can use a template provider function which can be injected, has
  access to locals, and must return template HTML, like this:

$stateProvider.state('contacts', {   templateProvider: function
 ($timeout, $stateParams) {
   return $timeout(function () {
    return '
' + $stateParams.contactId + '
'
   }, 100);
 }
})

However, as I understand it, $stateProvider has to be configured during module.config phase, and $timeout is not available then. I cannot find any example which shows how to access $timeout (or $http) for $stateProvider exactly per the example provided by the docs.

Is there a way to access either $timeout or $http as defined in the docs? Do I configure state at another point? Is there an alternative way to do this which I'm overlooking?

Body:
The templateProvider function itself is injected with the dependencies using injector service, and it has nothing to do with the config phase.

So you should be able to use $http simply by injecting it in the function. If you see the example, $timeout or $stateParams are also not available at the config phase, but they work fine in the templateProvider function.

For example, the below snippet returns the content of HTTPBin:

templateProvider: function($http) {
  return $http.get('https://httpbin.org/get')
    .then(function(response) {
      return JSON.stringify(response.data);
    });
  }

For more details, refer to this fiddle.


问:
How good is GATE for NLP?
I am trying to build a NLP app which essentially has to do Named Entity Recognition (NER). I came across GATE. From what i understand it is a framework to build NLP apps. I tested ANNIE, the IE system distributed with GATE but the NER results for my domain is not up-to the expectation. As a matter of fact any NER, like Stanford CoreNLP or NLTK, is not giving me required results. So i decide to tweak the existing systems to get desired result.

Regarding GATE i liked few things:

1. The modularity of components: For example in ANNIE, components like Tokenizer, Gaztteer, Sentence splitter, POS tagger etc can be used independently of each other.

2. Its rule language called JAPE which has a very nice way of writing rules or patterns.

But few things i want to know about GATE are:

1. What are the other major advantages of GATE particularly for NER?

2. How flexible is GATE for adding new components? For example some day if i want to use NLTK's POS tagger inside GATE?

3. If i want to use custom machine learning models with GATE?

4. I am aware that NLP group at University of Sheffield is involved in GATE, but i want to know how active is GATE's community and how active is the support for GATE?

5. Can GATE be used for commercial software?

Keen to here suggestions from people who have actually used GATE

答:
Though late, might be useful for someone.

As you already mentioned,  JAPE grammars will be very useful if effectively written. Also the GATE embedded is another big advantage i consider as we can tweak the way we wanted in JAVA.

Again, GATE embedded can be used for adding new components where you can build your own plugins. However, if you want to use Stanford tools, these are already readily available in GATE. You can just plug and play.

There are already many algorithms available in GATE and i guess they(University of Sheffield) are building it continuously.

The GATE support team is very active, you can subscribe to their mailing list and ask questions if you have any, and they will reply asap.

I guess so. However, if you contact GATE team directly, they will answer you better.

Title: How good is GATE for NLP?


问:
Visual studio can't find a controller even though I have added a reference to it and made sure it is public
I have a Unit Test solution that references the main solution for the controller.

Reference: using Solution.Controllers;

Unit Test class:

```<code>namespace solution.UnitTests.SolutionTests.ControllersTests
{
    [TestClass]
    public class BrandCategoryControllerTests
    {
        private BrandCategoryController _brandCategoryController;
        [TestInitialize]
        public void Init()
        {
            _brandCategoryController = new BrandCategoryController();
        }
    }
}
</code>```

The controller it is referencing is in Solution/Controllers folder.

The file begins with:

```<code>namespace Solution.Controllers
{
    public class BrandCategoryController : Controller
</code>```

So I don't see why it can't find it. I've tried the intellisense and it doesn't recognize it. I've tried Cleaning and rebuilding the solution and closing and reopening visual studio. The annoying part is I have another controller and another controller test class both of which share the same folder structures and they work fine.

The error I am getting is "The type or namespace "BrandCategoryController" could not be found (are you missing a using directive or an assembly reference?)" I have added a using Directive and have tried using the full reference on the private variable.

答: I've managed to get this working. The way it was fixed was I added a new controller to that folder to see if the intellisense would pick it up and when I did and checked the intellisense it picked up all three of the controllers in there. The original, the one I wanted and the new one. So I deleted the new one I created and it works fine now. Not Sure what caused this.</p>

Body:
I have a Unit Test solution that references the main solution for the controller.

Reference: using Solution.Controllers;

Unit Test class:

namespace solution.UnitTests.SolutionTests.ControllersTests
{
    [TestClass]
    public class BrandCategoryControllerTests
    {
        private BrandCategoryController _brandCategoryController;
        [TestInitialize]
        public void Init()
        {
            _brandCategoryController = new BrandCategoryController();
        }
    }
}

The controller it is referencing is in Solution/Controllers folder.

The file begins with:

namespace Solution.Controllers
{
    public class BrandCategoryController : Controller

So I don't see why it can't find it. I've tried the intellisense and it doesn't recognize it. I've tried Cleaning and rebuilding the solution and closing and reopening visual studio. The annoying part is I have another controller and another controller test class both of which share the same folder structures and they work fine.

The error I am getting is "The type or namespace "BrandCategoryController" could not be found (are you missing a using directive or an assembly reference?)" I have added a using Directive and have tried using the full reference on the private variable.


答:
First of all there is no way that your code is printing the 0-th location of the array. That's impossible given the condition of the if statement.

Secondly n- you don;t need to use macro expansion for that name.

```<code>/* This program takes 20 integer number from input.
 * Prints the numbers entered in odd positions.(First,Third,..etc).
 */
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
    int numArr[NUM];
    for(size_t i = 0; i < NUM; i++) {
        printf("please enter %zu number\n",i+1);
        if( scanf("%d",&numArr[i]) != 1){
            fprintf(stderr, "%s\n","Error in input" );
            exit(1);
        }
    }

    for(size_t i = 0; i < n; i++)
    {
        if( i%2 == 0 )// if you want to omit the first number put the
                      // the condition (i%2 == 0 && i)
        {
            printf("%d\n",numArr[i]);
        }
    }
    return 0;
}
</code>```

What you did wrong that your code skipped 0th element?

```<code>if (i%2==0 && i!=1 && i!=0)
                      ^^^^
</code>```

i when 0 makes this condition false - and you never get to print it.

i!=1 ?

If i=1 then i%2 will be 1, so you will not even check the second conditions, the whole conditional expression will become false. So you can safely omit this logic.

Is there a better way?

Sure,

```<code>for(size_t i = 0; i < n; i += 2){
    printf("%d\n",num[i]);
}
</code>```

Explanation

If you consider that every time you check the modular arithmetic of 2 the elements which results to 0 remained are

```<code> 0,2,4,6,8,10,...18
</code>```

See the pattern? Starts with 0 and increments by 2 each time and when does it stop? Yes before reaching 20 coding it we get

```<code>for(size_t i = 0; i < n; i += 2){
/*   Initialize with i=0 as first number is 0 (i=0)
 *   Increments by 2 (i+=2)
 *   Runs when less than 20 (i<n)
 */
    printf("%d\n",num[i]);
}
</code>```

If you want to omit the 0-th index do initialize properly

```<code>for(size_t i = 2; i < n; i += 2){
</code>```

Title: I need to input 20 numbers and to output only double location

Body:
First of all there is no way that your code is printing the 0-th location of the array. That's impossible given the condition of the if statement.

Secondly n- you don;t need to use macro expansion for that name.

/* This program takes 20 integer number from input.
 * Prints the numbers entered in odd positions.(First,Third,..etc).
 */
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
    int numArr[NUM];
    for(size_t i = 0; i < NUM; i++) {
        printf("please enter %zu number\n",i+1);
        if( scanf("%d",&numArr[i]) != 1){
            fprintf(stderr, "%s\n","Error in input" );
            exit(1);
        }
    }

    for(size_t i = 0; i < n; i++)
    {
        if( i%2 == 0 )// if you want to omit the first number put the
                      // the condition (i%2 == 0 && i)
        {
            printf("%d\n",numArr[i]);
        }
    }
    return 0;
}

What you did wrong that your code skipped 0th element?

if (i%2==0 && i!=1 && i!=0)
                      ^^^^

i when 0 makes this condition false - and you never get to print it.

i!=1 ?

If i=1 then i%2 will be 1, so you will not even check the second conditions, the whole conditional expression will become false. So you can safely omit this logic.

Is there a better way?

Sure,

for(size_t i = 0; i < n; i += 2){
    printf("%d\n",num[i]);
}

Explanation

If you consider that every time you check the modular arithmetic of 2 the elements which results to 0 remained are

 0,2,4,6,8,10,...18

See the pattern? Starts with 0 and increments by 2 each time and when does it stop? Yes before reaching 20 coding it we get

for(size_t i = 0; i < n; i += 2){
/*   Initialize with i=0 as first number is 0 (i=0)
 *   Increments by 2 (i+=2)
 *   Runs when less than 20 (i<n)
 */
    printf("%d\n",num[i]);
}

If you want to omit the 0-th index do initialize properly

for(size_t i = 2; i < n; i += 2){


问:
User name in .bazelrc
I would like to add this to my .bazelrc, but the $(whoami) doesn't expand like if it was in a shell.

```<code>startup --output_user_root=/tmp/bazel/out/$(whoami)
</code>```

It produces the literal result:

```<code>/tmp/bazel/out/$(whoami)/faedb999bdce730c9c495251de1ca1a4/execroot/__main__/bazel-out/
</code>```

Is there any way to do what I want: adding a name/hash to the option in the .bashrc file?

Edit: what I really want is to set the outputRoot to /tmp/bazel/out without using an environment variable and to let bazel create it's user and workspace hash directories there.

答:
/usr/bin/bazel is a script which looks for //tools/bazel, and if it exists, calls it.  Otherwise, it calls bazel-real.  This lets you check Bazel into your repo, or otherwise modify how it gets called.  We use that to download a specific version of bazel, extract it, and then call it.

I would recommend creating //tools/bazel, and having that do your modification.  It can then either call a versioned version of bazel, or call bazel-real.  That keeps your modifications local to your repo rather than global.

Title: User name in .bazelrc

Body:
I would like to add this to my .bazelrc, but the $(whoami) doesn't expand like if it was in a shell.

startup --output_user_root=/tmp/bazel/out/$(whoami)

It produces the literal result:

/tmp/bazel/out/$(whoami)/faedb999bdce730c9c495251de1ca1a4/execroot/__main__/bazel-out/

Is there any way to do what I want: adding a name/hash to the option in the .bashrc file?

Edit: what I really want is to set the outputRoot to /tmp/bazel/out without using an environment variable and to let bazel create it's user and workspace hash directories there.