问:
Why does this happen IEnumerable versus List
I have the following BL method

```<code>public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

```<code>public void Save()
{
   group.SomeProp = true;
}
</code>```

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

```<code>public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}
</code>```

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

答:
Your problem is occurring because of deferred execution. In your first example, groupWithFalse doesn't represent a list of objects where SomeProp is false, it refers to a query that can evaluate to said list.

If you want your list to stay put during your entire function, simply add .ToList() on the end of your LINQ query like so:

```<code>IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                        where gr.SomeProp == false
                                        select gr).ToList();
//                                                ^^^^^^^^^
</code>```

This will cause the query to execute immediately and return its results into a List<SomeClass> whose contents won't change if you modify the objects within it.

Body:
I have the following BL method

public static void SomeMethod (List<SomeClass> group)
{
    IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                            where gr.SomeProp== false
                                            select gr);
    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

The mock implementation for dl saving (which cannot be changed as it used in a lot of unit tests) is:

public void Save()
{
   group.SomeProp = true;
}

If I try to unit test the last statement of the flow e.g if (groupWithFalse.Any()) the statement fails, as apparently there are no more elements with that property set to false.
If I change the code in business logic to :

public static void SomeMethod (List<SomeClass> group)
{
    List<SomeClass> groupWithFalse = new List<SomeClass>();
    foreach (var g in group)
    {
      if (g.SomeProp == false)
          groupWithFalse.Add(g);
    }

    foreach (SomeClass grFalse in groupWithFalse)
    {
      grFalse.Save();
    }

    if (groupWithFalse.Any())
    {
      // do some stuff
    }
}

the conditional statement if (groupWithFalse.Any()) does not fail in unit tests. Why does this happen? Thanks

Body:
Your problem is occurring because of deferred execution. In your first example, groupWithFalse doesn't represent a list of objects where SomeProp is false, it refers to a query that can evaluate to said list.

If you want your list to stay put during your entire function, simply add .ToList() on the end of your LINQ query like so:

IEnumerable<SomeClass> groupWithFalse =(from SomeClass gr in group
                                        where gr.SomeProp == false
                                        select gr).ToList();
//                                                ^^^^^^^^^

This will cause the query to execute immediately and return its results into a List<SomeClass> whose contents won't change if you modify the objects within it.


来源: stackexchange

问:
A way to accomplish @ConditionalOn*ANY*Class?
I am using Spring Boot autoconfiguration to load a bean in the context in case there is at least one of 3 beans present.

I need something like:

```<code>@Bean
@ConditionalOnANYClass({ CreateHandler.class, UpdateHandler.class, DeleteHandler.class})
</code>```

Any smart solution or out-of-the-box annotation for the logical OR?

答: You can use AnyNestedCondition with one nested condition per class that you want to match.

ContentLicense: CC BY-SA 3.0

Body:
I am using Spring Boot autoconfiguration to load a bean in the context in case there is at least one of 3 beans present.

I need something like:

@Bean
@ConditionalOnANYClass({ CreateHandler.class, UpdateHandler.class, DeleteHandler.class})

Any smart solution or out-of-the-box annotation for the logical OR?


问:
How i can SELECT with multiple WHERE in one table
i have table in database with rows:

id, kills, deaths, week

How i can select kills where week=1 AND deaths where week=2 in ONE TABLE?

答:
You can use two seperate select statements:

```<code>SELECT(
    (SELECT kills FROM tablename WHERE week = 1),
    (SELECT deaths FROM tablename WHERE week = 2)
)
</code>```

This will create a column for kills where week = 1, and another column for deaths where week = 2.

You can use the UNION keyword to combine them together:

```<code>SELECT 'week 1 - kills' as source, kills FROM tablename WHERE week = 1
UNION
SELECT 'week 2 - deaths' as source, deaths FROM tablename WHERE week = 2
</code>```

These two approaches require double scanning the tables.

An alternate approach is to use a condition clause @Juan Carlos Oropeza's solution if you need an aggregate function. However, as pointed out, it may not be the best idea to combine these two statements into one.

Body:
You can use two seperate select statements:

SELECT(
    (SELECT kills FROM tablename WHERE week = 1),
    (SELECT deaths FROM tablename WHERE week = 2)
)

This will create a column for kills where week = 1, and another column for deaths where week = 2.

You can use the UNION keyword to combine them together:

SELECT 'week 1 - kills' as source, kills FROM tablename WHERE week = 1
UNION
SELECT 'week 2 - deaths' as source, deaths FROM tablename WHERE week = 2

These two approaches require double scanning the tables.

An alternate approach is to use a condition clause @Juan Carlos Oropeza's solution if you need an aggregate function. However, as pointed out, it may not be the best idea to combine these two statements into one.


问:
Error When creating dummies for a range of time period, Pandas
I have a pandas data frame that has the time column from 00:00:00 to 23:00:00 with type timedelta64[ns]. I want to get create a new column df['m_hours'] with 1 and 0 based on time range. For example, when the time range is 01:00:00 to 04:00:00, it should be 1 and the rest should be 0. I tried the following code,

```<code>df['m_hours'] = np.where(df['hour']>= '01:00:00'& df['hour']<= '04:00:00', '1', '0')
</code>```

I get an error saying,
TypeError: cannot compare a dtyped [timedelta64[ns]] array with a scalar of type [bool] and then I tried,

```<code>df['m_hours'] = np.where(df[(df['hour']>= '01:00:00')& (df['hour']<= '04:00:00'), '1', '0']
</code>```

an then I got an error,
SyntaxError: unexpected EOF while parsing

This post looks promising, but does not help much in my situation. Are there any other ways to create dummies for a certain range of time? I will appreciate any help.

Thank you!

As requested, the following edit is a sample df and data types

```<code>    date   hour                   avg_price
2016-05-01 00:00:00                  69.5
2016-05-01 01:00:00                  67.0
2016-05-01 02:00:00                  66.0
2016-05-01 03:00:00                  66.0
2016-05-01 04:00:00                  65.0
2016-05-01 05:00:00                  65.0
2016-05-01 06:00:00                  65.5
2016-05-01 07:00:00                  69.0
2016-05-01 08:00:00                  72.0
2016-05-01 09:00:00                  77.0
2016-05-01 10:00:00                  80.0
2016-05-01 11:00:00                  81.0
2016-05-01 12:00:00                  82.0
2016-05-01 13:00:00                  85.0
2016-05-01 14:00:00                  85.0
2016-05-01 15:00:00                  85.0
2016-05-01 16:00:00                  88.0
2016-05-01 17:00:00                  87.0
2016-05-01 18:00:00                  86.0
2016-05-01 19:00:00                  81.0
2016-05-01 20:00:00                  79.0
2016-05-01 21:00:00                  78.0
2016-05-01 22:00:00                  76.0
2016-05-01 23:00:00                  74.0
2016-05-02 00:00:00                  73.0
2016-05-02 01:00:00                  68.0
2016-05-02 02:00:00                  66.0
2016-05-02 03:00:00                  66.0
2016-05-02 04:00:00                  64.0
2016-05-02 05:00:00                  67.0
</code>```

and the data types are:

```<code>date                    datetime64[ns]
hour                    timedelta64[ns]
avg_price               float64
</code>```

答:
I thought of posting an answer to my own question after doing a little more research and hope this might help other if anyone come across this issue.
I tried the following code without changing the type of my object,

```<code>df['m_hour'] = np.where((df['hour'] >= '01:00:00') & (df['hour'] <= '04:00:00'),'1','0')
</code>```

I was missing a parenthesis after np.where clause.

Body:
I have a pandas data frame that has the time column from 00:00:00 to 23:00:00 with type timedelta64[ns]. I want to get create a new column df['m_hours'] with 1 and 0 based on time range. For example, when the time range is 01:00:00 to 04:00:00, it should be 1 and the rest should be 0. I tried the following code,

df['m_hours'] = np.where(df['hour']>= '01:00:00'& df['hour']<= '04:00:00', '1', '0')

I get an error saying,
TypeError: cannot compare a dtyped [timedelta64[ns]] array with a scalar of type [bool] and then I tried,

df['m_hours'] = np.where(df[(df['hour']>= '01:00:00')& (df['hour']<= '04:00:00'), '1', '0']

an then I got an error,
SyntaxError: unexpected EOF while parsing

This post looks promising, but does not help much in my situation. Are there any other ways to create dummies for a certain range of time? I will appreciate any help.

Thank you!

As requested, the following edit is a sample df and data types

    date   hour                   avg_price
2016-05-01 00:00:00                  69.5
2016-05-01 01:00:00                  67.0
2016-05-01 02:00:00                  66.0
2016-05-01 03:00:00                  66.0
2016-05-01 04:00:00                  65.0
2016-05-01 05:00:00                  65.0
2016-05-01 06:00:00                  65.5
2016-05-01 07:00:00                  69.0
2016-05-01 08:00:00                  72.0
2016-05-01 09:00:00                  77.0
2016-05-01 10:00:00                  80.0
2016-05-01 11:00:00                  81.0
2016-05-01 12:00:00                  82.0
2016-05-01 13:00:00                  85.0
2016-05-01 14:00:00                  85.0
2016-05-01 15:00:00                  85.0
2016-05-01 16:00:00                  88.0
2016-05-01 17:00:00                  87.0
2016-05-01 18:00:00                  86.0
2016-05-01 19:00:00                  81.0
2016-05-01 20:00:00                  79.0
2016-05-01 21:00:00                  78.0
2016-05-01 22:00:00                  76.0
2016-05-01 23:00:00                  74.0
2016-05-02 00:00:00                  73.0
2016-05-02 01:00:00                  68.0
2016-05-02 02:00:00                  66.0
2016-05-02 03:00:00                  66.0
2016-05-02 04:00:00                  64.0
2016-05-02 05:00:00                  67.0

and the data types are:

date                    datetime64[ns]
hour                    timedelta64[ns]
avg_price               float64

Body:
I thought of posting an answer to my own question after doing a little more research and hope this might help other if anyone come across this issue.
I tried the following code without changing the type of my object,

df['m_hour'] = np.where((df['hour'] >= '01:00:00') & (df['hour'] <= '04:00:00'),'1','0')

I was missing a parenthesis after np.where clause.


问:
Remove 3D plot's white spaces in mixed 2D/3D subplots
I am having trouble removing the excessive white spaces when mixing 2D and 3D subplots. For pure 3D subplots, I can adjust the region being plotted with fig.subplots_adjust() to remove the white spaces, see here.

However, the same trick doesn't work if this 3D image is inside a 2D subplots.
I created the mixed subplots like the following:

```<code>import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d

fig,axes = plt.subplots(2,2)
ax = axes.flat

for a in range(3):
    ax[a].plot(range(10),range(10))

ax[3].remove()
ax[3] = fig.add_subplot(224,projection='3d')

X, Y, Z = axes3d.get_test_data(0.03)
ax[3].plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.8,cmap=cm.coolwarm)

ax[3].set_xticklabels('')
ax[3].set_yticklabels('')
ax[3].set_zticklabels('')

fig.subplots_adjust(hspace=0,wspace=0)
</code>```

Now the trick eg. fig.subplots_adjust(left=-0.01) will act on the 2D subplot's left edge, and the 3D subplots is not modified. Is there a way to completely remove the white spaces surrounding the 3D subplot? I also tried smaller ax.dist and it is not good if the 3D plot is longer in say z-direction.

答:
There is no whitespace around the axes, it even overlaps the other subplots (their spines are hidden by the 3D axes).

What you want is to adjust the size of gray cube inside the axes. This can be done by changing the viewing distance to that cube.

E.g. ax[3].dist = 7

ax[3].dist = 9

The optimal distance depends of course on the viewing angle.

ContentLicense: CC BY-SA 4.0

Body:
I am having trouble removing the excessive white spaces when mixing 2D and 3D subplots. For pure 3D subplots, I can adjust the region being plotted with fig.subplots_adjust() to remove the white spaces, see here.

However, the same trick doesn't work if this 3D image is inside a 2D subplots.
I created the mixed subplots like the following:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import axes3d

fig,axes = plt.subplots(2,2)
ax = axes.flat

for a in range(3):
    ax[a].plot(range(10),range(10))

ax[3].remove()
ax[3] = fig.add_subplot(224,projection='3d')

X, Y, Z = axes3d.get_test_data(0.03)
ax[3].plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.8,cmap=cm.coolwarm)

ax[3].set_xticklabels('')
ax[3].set_yticklabels('')
ax[3].set_zticklabels('')

fig.subplots_adjust(hspace=0,wspace=0)

Now the trick eg. fig.subplots_adjust(left=-0.01) will act on the 2D subplot's left edge, and the 3D subplots is not modified. Is there a way to completely remove the white spaces surrounding the 3D subplot? I also tried smaller ax.dist and it is not good if the 3D plot is longer in say z-direction.


问:
relations with 2 rows and user id
So what I'm trying to do is this, basically I have a table called games which has

creator_id
and
guest_id

now what i want to do is when i want to list all games i want to join two tables and get for example if creator_id is John and guest_id is Mary

i want to list all the "games" with their names

ID: 322   |     Creator Name: John   |     Guest Name: Mary

and so on, this is what i got so far:

Controller:

```<code>class AdminController extends Controller
{
    public function index()
    {
        return view('admin.home');
    }

    public function listGames()
    {
        $games = Game::get();
        return view('admin.games.list', compact('games'));
    }
}
</code>```

View:

```<code>@extends('admin.content')

@section('title', 'List games')

@section('content')

<table class="table table-hover">

@foreach($games as $game)

// now i want to list that here

@endforeach
</table>

@endsection
</code>```

Later on I added this to games model

```<code>public function creator() {
    return $this->hasOne(User::class, 'creator_id');
}

public function guest() {
    return $this->hasOne(User::class, 'guest_id');
}
</code>```

this to controller

```<code>public function index() {
    $games = Game::with('creator', 'guest')->get();
    return view('admin.games.list', compact('games'));
}
</code>```

and looped like this

```<code>@foreach($games as $game)
    Creator: {{ $game->creator->name }}
    Guest: {{ $game->guest->name }}
@endforeach
</code>```

but then this occured

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.creator_id' in 'where clause' (SQL: select * from users where users.creator_id in (14, 15, 16) and users.deleted_at is null), I dont know why but i dont have creator_id and guest_id in users table, its in games table

答:
Try to change the relation of the Game model to:</p>

```<code>public function creator() {
    return $this->belongsTo(User::class, 'creator_id');
}

public function guest() {
    return $this->belongsTo(User::class, 'guest_id');
}
</code>```

Title: relations with 2 rows and user id

Body:
So what I'm trying to do is this, basically I have a table called games which has

creator_id
and
guest_id

now what i want to do is when i want to list all games i want to join two tables and get for example if creator_id is John and guest_id is Mary

i want to list all the "games" with their names

ID: 322   |     Creator Name: John   |     Guest Name: Mary

and so on, this is what i got so far:

Controller:

class AdminController extends Controller
{
    public function index()
    {
        return view('admin.home');
    }

    public function listGames()
    {
        $games = Game::get();
        return view('admin.games.list', compact('games'));
    }
}

View:

@extends('admin.content')

@section('title', 'List games')

@section('content')

@foreach($games as $game)

// now i want to list that here

@endforeach

@endsection

Later on I added this to games model

public function creator() {
    return $this->hasOne(User::class, 'creator_id');
}

public function guest() {
    return $this->hasOne(User::class, 'guest_id');
}

this to controller

public function index() {
    $games = Game::with('creator', 'guest')->get();
    return view('admin.games.list', compact('games'));
}

and looped like this

@foreach($games as $game)
    Creator: {{ $game->creator->name }}
    Guest: {{ $game->guest->name }}
@endforeach

but then this occured

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.creator_id' in 'where clause' (SQL: select * from users where users.creator_id in (14, 15, 16) and users.deleted_at is null), I dont know why but i dont have creator_id and guest_id in users table, its in games table

Body:
Try to change the relation of the Game model to:

public function creator() {
    return $this->belongsTo(User::class, 'creator_id');
}

public function guest() {
    return $this->belongsTo(User::class, 'guest_id');
}


问:
Split the My Account WooCommerce tabbed menu
How to split the "My Account" WooCommerce tabbed menu in three different sections.

Here is the current code that I got:

```<code><nav class="woocommerce-MyAccount-navigation">
    <ul>
        <?php foreach ( wc_get_account_menu_items() as $endpoint => $label ) : ?>
            <li class="<?php echo wc_get_account_menu_item_classes( $endpoint ); ?>">
                <a href="<?php echo esc_url( wc_get_account_endpoint_url( $endpoint ) ); ?>"><?php echo esc_html( $label ); ?></a>
            </li>
        <?php endforeach; ?>
    </ul>
</nav>
</code>```

What I need: I have a total 15 menu items to split this way:

I want to wrap first 5 items in first

then 4 items in second

and rest in third

Please help me how to fix this.

Thanks

答:
This is very easy adding a counter that will add

 after the 5th and the 9th menu items. See below:

```<code><nav class="woocommerce-MyAccount-navigation">
    <ul>
        <?php
            $count = 0; // Initializing the count variable
            foreach ( wc_get_account_menu_items() as $endpoint => $label ) :
        ?>
            <li class="<?php echo wc_get_account_menu_item_classes( $endpoint ); ?>">
                <a href="<?php echo esc_url( wc_get_account_endpoint_url( $endpoint ) ); ?>"><?php echo esc_html( $label ); ?></a>
            </li>
        <?php
            $count++; // increasing count
            if($count == 5 || $count == 9 ) echo '</ul><ul>'; // Adding <ul>
            endforeach;
        ?>
    </ul>
</nav>
</code>```

Body:
How to split the "My Account" WooCommerce tabbed menu in three different sections.

Here is the current code that I got:

        <?php foreach ( wc_get_account_menu_items() as $endpoint => $label ) : ?>
            <li class="<?php echo wc_get_account_menu_item_classes( $endpoint ); ?>">
                <a href="<?php echo esc_url( wc_get_account_endpoint_url( $endpoint ) ); ?>"><?php echo esc_html( $label ); ?>

        <?php endforeach; ?>

What I need: I have a total 15 menu items to split this way:

I want to wrap first 5 items in first

then 4 items in second

and rest in third

Please help me how to fix this.

Thanks

Body:
This is very easy adding a counter that will add </ul><ul> after the 5th and the 9th menu items. See below:

<nav class="woocommerce-MyAccount-navigation">
    <ul>
        <?php
            $count = 0; // Initializing the count variable
            foreach ( wc_get_account_menu_items() as $endpoint => $label ) :
        ?>
            <li class="<?php echo wc_get_account_menu_item_classes( $endpoint ); ?>">
                <a href="<?php echo esc_url( wc_get_account_endpoint_url( $endpoint ) ); ?>"><?php echo esc_html( $label ); ?></a>
            </li>
        <?php
            $count++; // increasing count
            if($count == 5 || $count == 9 ) echo '</ul><ul>'; // Adding <ul>
            endforeach;
        ?>
    </ul>
</nav>


问:
Override ember component template with template from addon (in-repo)
I want to create an in-repo addon to make certain modifications (styles, templates, etc.) to an existing ember app in an encapsulated way, but I'm having troubles overriding the templates.

Right now, I'm trying to override an existing component template with the template from a component with the same name in the in-repo addon. My code looks something like this:

// my-app/app/templates/components/foo.hbs

Some headline

// my-app/app/lib/my-addon/app/templates/components/foo.hbs

A different headline
 // -> this never shows up```

I've tried a lot of switching around the template structure (like putting it in /addons or /app and linking to the template in different ways, but without success. My problem is that ember never uses the template from the addon.

If the component within the addon has a different name, like foobar.hbs, I can call it without a problem.

I'm currently looking through the source code and docs, trying to make sense of this. Is this even accomplishable the way I imagine it?

Thanks a lot!

答:
You'd have to create the component in your ember app which, initially, will mean the component renders as nothing as it's a brand new, empty component. Then you'd dig into your node_modules, find the component file and template and copy over what you'd need to work with.

Here's an example. While working with ember-cli-jsonapi-pagination, I need to customize the paginate-collection component:

I created the component in my application.

I looked at the source: https://github.com/BookingSync/ember-cli-jsonapi-pagination/tree/master/app

In components/paginate-collection/component.js I copied over the component code, but you should be able to import it as well.

In components/paginate-collection/template.hbs I modified the template as needed.

Body:
I want to create an in-repo addon to make certain modifications (styles, templates, etc.) to an existing ember app in an encapsulated way, but I'm having troubles overriding the templates.

Right now, I'm trying to override an existing component template with the template from a component with the same name in the in-repo addon. My code looks something like this:

// my-app/app/templates/components/foo.hbs

Some headline

// my-app/app/lib/my-addon/app/templates/components/foo.hbs

A different headline
 // -> this never shows up

I've tried a lot of switching around the template structure (like putting it in /addons or /app and linking to the template in different ways, but without success. My problem is that ember never uses the template from the addon.

If the component within the addon has a different name, like foobar.hbs, I can call it without a problem.

I'm currently looking through the source code and docs, trying to make sense of this. Is this even accomplishable the way I imagine it?

Thanks a lot!


问:
Java command line using classpath for Libraries and Manifest file for MainClass
I am able to achieve the following two things already.

Use ManifestFile to define classpath libraries and Main class as below.

manifest-Version: 1.0

Class-Path: lib/log4j-1.2.17.jar

Main-Class: FQNofMainClass

Pass the ClassPath libraries folder and MainClass from Command Line as below.

(java -cp my.jar;lib_folder/* FQNofMainClass)

But now my scenario is to run the .jar file with Classpath libraries in command line and MainClass details inside Manifest File. How do I achieve this?

答:
Since you setup your jar to know that FQNofMainClass is the main class, you can run it using the -jar command-line option.  But for this to work, you should also jar up all of the dependencies that your program relies on into the jar.  This way you don't have any external dependencies and the jar can be delivered to users without any extra funny instructions or additional files to install.

java -jar my.jar

By "jarring up" the dependencies, I mean repackaging all of the .class files from the other jars you need into my.jar when you create it.


问:
Enable and disable onkeydown event?
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

```<code>var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};
</code>```

Kind Regards

答:
Click on the close div and assign keydown function Click on the open deletes the keydown function from document.onkeydown.

function moveFunc(e) {
            alert(e.keyCode);
    };

$(".open-project").click(function(){
    document.onkeydown = null;
});

$("#project_close").click(function(){
    document.onkeydown = moveFunc;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.open-project{
  background-color: red;
  width: 150px;
  height: 150px;
  }

 #project_close{
  background-color: green;
  width: 150px;
  height: 150px;
  }</code>```

open project

project close
```

Title: Enable and disable onkeydown event?

Body:
Hi I am trying to start off with the keys enable and then once a button is clicked to disable the event this so far works fine, then once the close button is pressed I want to enable the event again this part doesn't work I'd like to solve this using javascript if possible my close button is in another html (project1.html) file and is loaded via Ajax here is my code:

var enable_keydown = document.onkeydown;

$(".open-project").click(function(){
document.onkeydown = null;
});

$("#project_close").click(function(){
document.onkeydown = enable_keydown;
});

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
             $.fn.fullpage.moveSectionUp();
            break;
        case 38:
             $.fn.fullpage.moveSectionUp();
            break;
        case 39:
             $.fn.fullpage.moveSectionDown();
            break;
        case 40:
             $.fn.fullpage.moveSectionDown();
            break;
    }
};

Kind Regards

Body:
Click on the close div and assign keydown function Click on the open deletes the keydown function from document.onkeydown.

function moveFunc(e) {
            alert(e.keyCode);
    };

$(".open-project").click(function(){
    document.onkeydown = null;
});

$("#project_close").click(function(){
    document.onkeydown = moveFunc;
});

.open-project{
  background-color: red;
  width: 150px;
  height: 150px;
  }

 #project_close{
  background-color: green;
  width: 150px;
  height: 150px;
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="open-project" >open project</div>
<div id="project_close" >project close</div>


答:
You're confusing the child and the parent model. The games don't have users - they belongTo() them, since the games table contain the ids of the parents.

And for the inverse, unless each user can only create or play one game, you should use hasMany() rather than hasOne().

Title: relations with 2 rows and user id


问:
Is it possible to attach an uploaded file to http request?
I have a form that submits a file to an endpoint. In theory that endpoint takes the file and attaches it to another post request that goes to the API.

I was trying to figure out how to do it with Laravel and read a few things that suggest it's not possible? That the only solution would be save it in a public place and submit the link to the API. Anyone able to shed some light on this? Below is the code that I thought would work but does not send the file.

```<code>$this->client->post('/api/endpoint', ['form_params' => ['file' => $request->file('file')->getRealPath()]])
</code>```

Client being the Guzzle client.

答:
Yes it is. Guzzle Docs</p>

```<code>$client->request('POST', '/post', [
    'multipart' => [
        [
            'name'     => 'foo',
            'contents' => 'data',
            'headers'  => ['X-Baz' => 'bar']
        ],
        [
            'name'     => 'baz',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'qux',
            'contents' => fopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.txt'
        ],
    ]
]);
</code>```

Body:
I have a form that submits a file to an endpoint. In theory that endpoint takes the file and attaches it to another post request that goes to the API.

I was trying to figure out how to do it with Laravel and read a few things that suggest it's not possible? That the only solution would be save it in a public place and submit the link to the API. Anyone able to shed some light on this? Below is the code that I thought would work but does not send the file.

$this->client->post('/api/endpoint', ['form_params' => ['file' => $request->file('file')->getRealPath()]])

Client being the Guzzle client.

Body:
Yes it is. Guzzle Docs

$client->request('POST', '/post', [
    'multipart' => [
        [
            'name'     => 'foo',
            'contents' => 'data',
            'headers'  => ['X-Baz' => 'bar']
        ],
        [
            'name'     => 'baz',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'qux',
            'contents' => fopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.txt'
        ],
    ]
]);


答:
It seems fairly uncommon for APIs to handle file uploads as this is generally something a person does. If i were to do something like this I would first read the contents of the file and base64 encode it. Then send the normal Http POST request with the base64 encoded file content as a string. On the API, you could then decode it and do whatever you need to o with the file.

Dealing with base64 in PHP is fairly simple http://php.net/manual/en/function.base64-encode.php

Title: Is it possible to attach an uploaded file to http request?


问:
Resizing Div vertically when view port is resized
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class='container'>
    <div class='content'>
      <div class='page-header'> System Dashboard </div>

      <div class='wrapper'>
        <div class='col-md-4 override'>
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
        </div>
      </div>

      <div class='footer'> Copyright here </div>
    </div>
  </div>
</body></code>```

答: You can use height: 100vh; where VH is Viewport Height

Body:
I am trying to resize a Div(with content) vertically when changing the view port. I want to change the div(with content) size based on vertically increasing or decreasing the size of window.

Currently I am making this work by providing a fix size to my wrapper div and providing overflow to auto , so when screen is resized Vertically it will give me scroll for Div.

Is there a way such that my div(with content) auto shrink to height as screen size is vertically decreased

HTML Fragement

* {
  box-sizing:border-box;
}

body, html {
  height:100%;
}

.container {
  height:100%;
  border:1px solid #bbb;
}

.footer {
  position:fixed;
  bottom:0px;
  text-align:center;
  height:25px;
}

.override {
  border:1px solid blue;
}

.content {
  height:100%
}

.wrapper {
  height:calc(100%-100px);
  overflow:auto;
}

 System Dashboard

          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper
          First wrapperFirst wrapperFirst wrapperFirst wrapperFirst wrapper

 Copyright here


问:
Are string literals const?
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

```<code>char *foo = "bar";
</code>```

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?

答: String literals have formal type char [] but semantic type const char []. The purists hate it but this is generally useful and harmless, except for bringing lots of newbies to SO with "WHY IS MY PROGRAM CRASHING?!?!" questions.

ContentLicense: CC BY-SA 2.5

Title: Are string literals const?

Body:
Both GCC and Clang do not complain if I assign a string literal to a char*, even when using lots of pedantic options (-Wall -W -pedantic -std=c99):

char *foo = "bar";

while they (of course) do complain if I assign a const char* to a char*.

Does this mean that string literals are considered to be of char* type? Shouldn't they be const char*? It's not defined behavior if they get modified!

And (an uncorrelated question) what about command line parameters (ie: argv): is it considered to be an array of string literals?


问:
How to create grails project only for domain classes?
I'm starting to create a new project and I need to have a separate project only for the domains, which will be packed into a jar file to be used on another files.
I'm wondering the best way to do that with Grails.
Is there a way to create a grails project only with the domain classes?</p>

答:
Without more info (grails version especially!), it's hard to say for sure but you could certainly put all of your domain classes in a plugin.  If you're using Grails 3+, plugins are released as jar files anyway, so that might work pretty well for you too.

grails create-plugin (your plugin name)

And then just use your plugin in your build.gradle, like any other plugin.  It's a bit different in grails 2, but the documentation could help you out there too.


问:
How do I return the response from an asynchronous call?
How do I return the response/result from a function foo that makes an asynchronous request?

I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response — they all return undefined or whatever the initial value of the variable result is.

Example of an asynchronous function that accepts a callback (using jQuery's ajax function):

```<code>function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result; // It always returns `undefined`
}
</code>```

Example using Node.js:

```<code>function foo() {
    var result;

    fs.readFile("path/to/file", function(err, data) {
        result = data;
        // return data; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}
</code>```

Example using the then block of a promise:

```<code>function foo() {
    var result;

    fetch(url).then(function(response) {
        result = response;
        // return response; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}
</code>```

答:
Of course there are many approaches like synchronous request, promise, but from my experience I think you should use the callback approach. It's natural to asynchronous behavior of JavaScript.

So, your code snippet can be rewritten to be a little different:

```<code>function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            myCallback(response);
        }
    });

    return result;
}

function myCallback(response) {
    // Does something.
}
</code>```

Body:
How do I return the response/result from a function foo that makes an asynchronous request?

I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response — they all return undefined or whatever the initial value of the variable result is.

Example of an asynchronous function that accepts a callback (using jQuery's ajax function):

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            result = response;
            // return response; // <- I tried that one as well
        }
    });

    return result; // It always returns `undefined`
}

Example using Node.js:

function foo() {
    var result;

    fs.readFile("path/to/file", function(err, data) {
        result = data;
        // return data; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}

Example using the then block of a promise:

function foo() {
    var result;

    fetch(url).then(function(response) {
        result = response;
        // return response; // <- I tried that one as well
    });

    return result; // It always returns `undefined`
}

Body:
Of course there are many approaches like synchronous request, promise, but from my experience I think you should use the callback approach. It's natural to asynchronous behavior of JavaScript.

So, your code snippet can be rewritten to be a little different:

function foo() {
    var result;

    $.ajax({
        url: '...',
        success: function(response) {
            myCallback(response);
        }
    });

    return result;
}

function myCallback(response) {
    // Does something.
}


问:
How do I test my NativeScript application on the device and am I in Windows?
I'm using a translator because I speak Spanish. I hope they understand me. I'm starting in Nativescript and I have a test application running on an Android emulator, so I want to test that application on my ios device. I have read that to run the command tns run ios it is necessary to do it in mac but I have Windows Any way to do it? , I have also read about Telerik but I still do not know what it is about</p>

答:
in windows is imposible to test IOS, you need to do it on a MAC OS because you need XCode to compile to IOS, even in MAC you need an IOS developer account because of the profiles.

Best regards!


问:
C# - How can i get the count of child elements using LINQ to XML
This is an extract of the XML i'm using

```<code>    <AccountNumber>
      <RecordID>A9</RecordID>
      <SegmentLength>14</SegmentLength>
      <Number>6770307103</Number>
    </AccountNumber>
    <PaymentCounter>
      <RecordID>B2</RecordID>
      <SegmentLength>14</SegmentLength>
      <History>99</History>
      <Delinq30Day>00</Delinq30Day>
      <Delinq60Day>00</Delinq60Day>
      <Delinq90PlusDay>00</Delinq90PlusDay>
      <DerogCnt>00</DerogCnt>
    </PaymentCounter>
</code>```

Here I'm trying to identify the number of child elements under AccountNumber and PaymentCounter.

I'm looking for this answer
AccountNumber count = 3
PaymentCounter count = 7

After I get the count, I will use the data to dynamically populate a table.

I tried this :
int count1 = xmlDocument.Descendants("AccountNumber").Count();

The count() in LINQ to XML will give me the number of times element "AccountNumber" is repeated in the XML, but doesnot give me the number of child elements.

Is there a way to do this?

答:
Descendants("AccountNumber") returns the children, grandchildren, etc. with the name AccountNumber. You actually want the children of the AccountNumber element.

See MSDN

In your sample there is exactly one AccountNumber, assuming this XML fragment is true of the actual document you are processing and the AccountNumber element is a child of the root element you probably want to do this:

```<code>xmlDocument.Element("AccountNumber").Elements().Count()
</code>```

Body:
This is an extract of the XML i'm using

    <AccountNumber>
      <RecordID>A9</RecordID>
      <SegmentLength>14</SegmentLength>
      <Number>6770307103</Number>
    </AccountNumber>
    <PaymentCounter>
      <RecordID>B2</RecordID>
      <SegmentLength>14</SegmentLength>
      <History>99</History>
      <Delinq30Day>00</Delinq30Day>
      <Delinq60Day>00</Delinq60Day>
      <Delinq90PlusDay>00</Delinq90PlusDay>
      <DerogCnt>00</DerogCnt>
    </PaymentCounter>

Here I'm trying to identify the number of child elements under AccountNumber and PaymentCounter.

I'm looking for this answer
AccountNumber count = 3
PaymentCounter count = 7

After I get the count, I will use the data to dynamically populate a table.

I tried this :
int count1 = xmlDocument.Descendants("AccountNumber").Count();

The count() in LINQ to XML will give me the number of times element "AccountNumber" is repeated in the XML, but doesnot give me the number of child elements.

Is there a way to do this?

Body:
Descendants("AccountNumber") returns the children, grandchildren, etc. with the name AccountNumber. You actually want the children of the AccountNumber element.

See MSDN

In your sample there is exactly one AccountNumber, assuming this XML fragment is true of the actual document you are processing and the AccountNumber element is a child of the root element you probably want to do this:

xmlDocument.Element("AccountNumber").Elements().Count()


问:
Loading text with animation
I want to display a buffering text like Buffering..

And I need the dots to NOT be static i.e. every 2 seconds change the number of dots so it goes 'one dot, two dots, 3 dots, one dot and so on.
I was wondering what is the best way to do this. Should the dots be in an image view? Should I have three images each with a specific number of dots? Or is there a different way to animate this?

I have similar thing using handler long back. But in that case i know the end time.

Below is my previous code also:

```<code>/**
     *  Use to show Loading... text while splash screen is loading. Here after each 350 milliseconds, i am adding
     *  a single dot(.) using thread and showing in the text view. And after reaching 3 dots, procedure is iterating itself again.
     *  This code will run till 3500 milliseconds.
     */
    for (int i = 350; i <= SPLASHTIME; i = i + 350) {
        final int j = i;
        handler.postDelayed(new Runnable() {
            public void run() {
                if (j / 350 == 1 || j / 350 == 4 || j / 350 == 7
                        || j / 350 == 10) {
                    tvLoadingdots.setText(".");
                } else if (j / 350 == 2 || j / 350 == 5 || j / 350 == 8) {
                    tvLoadingdots.setText("..");
                } else if (j / 350 == 3 || j / 350 == 6 || j / 350 == 9) {
                    tvLoadingdots.setText("...");
                }
            }
        }, i);
    }
</code>```

Can anyone tell me the best way for this.

Thanks in Advance.

答:
I used a Text Switcher and a runnable to solve this problem</p>

```<code>private void setupTextSwitcher() {
    mLoadingChatBotTextSwitcher = (TextSwitcher)findViewById(R.id.chat_bot_loading_text_switcher);
    mLoadingChatBotTextSwitcher.setInAnimation(this, android.R.anim.fade_in);
    mLoadingChatBotTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);
    mLoadingChatBotTextSwitcher.addView(getTextSwitcherTextView());
    mLoadingChatBotTextSwitcher.addView(getTextSwitcherTextView());
}

private TextView getTextSwitcherTextView() {
    TextView textView = new TextView(this);
    textView.setTextColor(getResources().getColor(R.color.birthday_white, null));
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    return textView;
}

private void kickOffLoadingTextAnimation() {
    if(mTextSwitchingHandler == null) {
        mTextSwitchingHandler = new Handler(Looper.getMainLooper());
        mTextSwitchingRunnable = new Runnable() {
            int loadingIndex = 0;
            @Override
            public void run() {
                switch(loadingIndex % 5) {
                    case 0:
                        changeLoadingMessage("Loading.    ");
                        break;
                    case 1:
                        changeLoadingMessage("Loading..   ");
                        break;
                    case 2:
                        changeLoadingMessage("Loading...  ");
                        break;
                    case 3:
                        changeLoadingMessage("Loading.... ");
                        break;
                    case 4:
                        changeLoadingMessage("Loading.....");
                        break;
                }
                loadingIndex++;
                mTextSwitchingHandler.postDelayed(this, 500);
            }
        };
        mTextSwitchingHandler.post(mTextSwitchingRunnable);
    }
}
</code>```

Title: Loading text with animation

Body:
I want to display a buffering text like Buffering..

And I need the dots to NOT be static i.e. every 2 seconds change the number of dots so it goes 'one dot, two dots, 3 dots, one dot and so on.
I was wondering what is the best way to do this. Should the dots be in an image view? Should I have three images each with a specific number of dots? Or is there a different way to animate this?

I have similar thing using handler long back. But in that case i know the end time.

Below is my previous code also:

/**
     *  Use to show Loading... text while splash screen is loading. Here after each 350 milliseconds, i am adding
     *  a single dot(.) using thread and showing in the text view. And after reaching 3 dots, procedure is iterating itself again.
     *  This code will run till 3500 milliseconds.
     */
    for (int i = 350; i <= SPLASHTIME; i = i + 350) {
        final int j = i;
        handler.postDelayed(new Runnable() {
            public void run() {
                if (j / 350 == 1 || j / 350 == 4 || j / 350 == 7
                        || j / 350 == 10) {
                    tvLoadingdots.setText(".");
                } else if (j / 350 == 2 || j / 350 == 5 || j / 350 == 8) {
                    tvLoadingdots.setText("..");
                } else if (j / 350 == 3 || j / 350 == 6 || j / 350 == 9) {
                    tvLoadingdots.setText("...");
                }
            }
        }, i);
    }

Can anyone tell me the best way for this.

Thanks in Advance.

Body:
I used a Text Switcher and a runnable to solve this problem

private void setupTextSwitcher() {
    mLoadingChatBotTextSwitcher = (TextSwitcher)findViewById(R.id.chat_bot_loading_text_switcher);
    mLoadingChatBotTextSwitcher.setInAnimation(this, android.R.anim.fade_in);
    mLoadingChatBotTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);
    mLoadingChatBotTextSwitcher.addView(getTextSwitcherTextView());
    mLoadingChatBotTextSwitcher.addView(getTextSwitcherTextView());
}

private TextView getTextSwitcherTextView() {
    TextView textView = new TextView(this);
    textView.setTextColor(getResources().getColor(R.color.birthday_white, null));
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    return textView;
}

private void kickOffLoadingTextAnimation() {
    if(mTextSwitchingHandler == null) {
        mTextSwitchingHandler = new Handler(Looper.getMainLooper());
        mTextSwitchingRunnable = new Runnable() {
            int loadingIndex = 0;
            @Override
            public void run() {
                switch(loadingIndex % 5) {
                    case 0:
                        changeLoadingMessage("Loading.    ");
                        break;
                    case 1:
                        changeLoadingMessage("Loading..   ");
                        break;
                    case 2:
                        changeLoadingMessage("Loading...  ");
                        break;
                    case 3:
                        changeLoadingMessage("Loading.... ");
                        break;
                    case 4:
                        changeLoadingMessage("Loading.....");
                        break;
                }
                loadingIndex++;
                mTextSwitchingHandler.postDelayed(this, 500);
            }
        };
        mTextSwitchingHandler.post(mTextSwitchingRunnable);
    }
}


问:
Programmatically Set Browser Proxy Settings in C#
I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry:

```<code>RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "127.0.0.1:8080");
</code>```

Is going into the registry the best way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution.

答:
from: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a

Add these lines at the beginning of your code:

using System.Runtime.InteropServices;
using Microsoft.Win32;

```<code>    [DllImport("wininet.dll")]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
    public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
    public const int INTERNET_OPTION_REFRESH = 37;
    bool settingsReturn, refreshReturn;
</code>```

And imply the code:

```<code>        RegKey.SetValue("ProxyServer", YOURPROXY);
        RegKey.SetValue("ProxyEnable", 1);

        // These lines implement the Interface in the beginning of program
        // They cause the OS to refresh the settings, causing IP to realy update
        settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
        refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
</code>```

OwnerDisplayName: John Miller

Body:
I'm writing an winforms app that needs to set internet explorer's proxy settings and then open a new browser window. At the moment, I'm applying the proxy settings by going into the registry:

RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
registry.SetValue("ProxyEnable", 1);
registry.SetValue("ProxyServer", "127.0.0.1:8080");

Is going into the registry the best way to do this, or is there a more recommended approach? I'd like to avoid registry changes if there's an alternative solution.

Body:
from: http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/19517edf-8348-438a-a3da-5fbe7a46b61a

Add these lines at the beginning of your code:

using System.Runtime.InteropServices;
using Microsoft.Win32;

    [DllImport("wininet.dll")]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
    public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
    public const int INTERNET_OPTION_REFRESH = 37;
    bool settingsReturn, refreshReturn;

And imply the code:

        RegKey.SetValue("ProxyServer", YOURPROXY);
        RegKey.SetValue("ProxyEnable", 1);

        // These lines implement the Interface in the beginning of program
        // They cause the OS to refresh the settings, causing IP to realy update
        settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
        refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);


问:
How do I remove an item from the Intellij default changelist?
Somehow or other a file in the .idea folder has landed on the default changelist and every time I make a commit Intellij is asking me if if I want to include the file in the commit.

I can't figure out why Intellij insists on trying to version control this file or how I can change its mind.

答: You should create a .gitignore file that tells git and intellij to ignore the  .idea folder</p>


问:
Get pytest to look within the base directory of the testing script
In pytest, my testing script compares the calculated results with baseline results which are loaded via

```<code>SCRIPTLOC = os.path.dirname(__file__)
TESTBASELINE = os.path.join(SCRIPTLOC, 'baseline', 'baseline.csv')
baseline = pandas.DataFrame.from_csv(TESTBASELINE)
</code>```

Is there a non-boilerplate way to tell pytest to start looking from the root directory of the script rather than get the absolute location through SCRIPTLOC?

答:
If you are simply looking for the pytest equivalent of using __file__, you can add the request fixture to your test and use request.fspath

From the docs:

```<code>class FixtureRequest
  ...
  fspath
      the file system path of the test module which collected this test.
</code>```

So an example might look like:

```<code>def test_script_loc(request):
    baseline = os.path.join(request.fspath.dirname, 'baseline', 'baseline.cvs')
    print(baseline)
</code>```

If you're wanting to avoid boilerplate though, you're not going to gain much from doing this (assuming I understand what you mean by 'non-boilerplate')

Personally, I think using the fixture is more explicit (within pytest idioms), but I prefer to wrap the request manipulation in another fixture so I know that I'm specifically grabbing sample test data just by looking at the method signature of a test.

Here's a snippet I use (modified to match your question, I use a subdirectory hierarchy):

```<code># in conftest.py
import pytest

@pytest.fixture(scope="module")
def script_loc(request):
    '''Return the directory of the currently running test script'''

    # uses .join instead of .dirname so we get a LocalPath object instead of
    # a string. LocalPath.join calls normpath for us when joining the path
    return request.fspath.join('..')
</code>```

And sample usage

```<code>def test_script_loc(script_loc):
    baseline = script_loc.join('baseline/baseline.cvs')
    print(baseline)
</code>```

Update: pathlib

Given that I've long since stopped supporting legacy Python and instead use pathlib, I no longer return LocalPath objects nor depend on their API.
The pytest team is also planning to eventually deprecate py.path and port their internals to the standard library pathlib. This started as early as pytest 3.9.0 with the introduction of tmp_path, though the actual removal of LocalPath attributes may not happen for some time.

Though the pytest team will likely add an alternative attribute (e.g. request.fs_path) that returns a Path object, it's easy enough to convert the LocalPath to a Path ourselves for now.

Here's a variant of the above example using a Path object, tweak as it suits you:

```<code># in conftest.py
import pytest

from pathlib import Path

@pytest.fixture(scope="module")
def script_loc(request):
    '''Return the directory of the currently running test script'''

    return Path(request.fspath).parent
</code>```

And sample usage

```<code>def test_script_loc(script_loc):
    baseline = script_loc.joinpath('baseline/baseline.cvs')
    print(baseline)
</code>```

Body:
In pytest, my testing script compares the calculated results with baseline results which are loaded via

SCRIPTLOC = os.path.dirname(__file__)
TESTBASELINE = os.path.join(SCRIPTLOC, 'baseline', 'baseline.csv')
baseline = pandas.DataFrame.from_csv(TESTBASELINE)

Is there a non-boilerplate way to tell pytest to start looking from the root directory of the script rather than get the absolute location through SCRIPTLOC?

Body:
If you are simply looking for the pytest equivalent of using __file__, you can add the request fixture to your test and use request.fspath

From the docs:

class FixtureRequest
  ...
  fspath
      the file system path of the test module which collected this test.

So an example might look like:

def test_script_loc(request):
    baseline = os.path.join(request.fspath.dirname, 'baseline', 'baseline.cvs')
    print(baseline)

If you're wanting to avoid boilerplate though, you're not going to gain much from doing this (assuming I understand what you mean by 'non-boilerplate')

Personally, I think using the fixture is more explicit (within pytest idioms), but I prefer to wrap the request manipulation in another fixture so I know that I'm specifically grabbing sample test data just by looking at the method signature of a test.

Here's a snippet I use (modified to match your question, I use a subdirectory hierarchy):

# in conftest.py
import pytest

@pytest.fixture(scope="module")
def script_loc(request):
    '''Return the directory of the currently running test script'''

    # uses .join instead of .dirname so we get a LocalPath object instead of
    # a string. LocalPath.join calls normpath for us when joining the path
    return request.fspath.join('..')

And sample usage

def test_script_loc(script_loc):
    baseline = script_loc.join('baseline/baseline.cvs')
    print(baseline)

Update: pathlib

Given that I've long since stopped supporting legacy Python and instead use pathlib, I no longer return LocalPath objects nor depend on their API.
The pytest team is also planning to eventually deprecate py.path and port their internals to the standard library pathlib. This started as early as pytest 3.9.0 with the introduction of tmp_path, though the actual removal of LocalPath attributes may not happen for some time.

Though the pytest team will likely add an alternative attribute (e.g. request.fs_path) that returns a Path object, it's easy enough to convert the LocalPath to a Path ourselves for now.

Here's a variant of the above example using a Path object, tweak as it suits you:

# in conftest.py
import pytest

from pathlib import Path

@pytest.fixture(scope="module")
def script_loc(request):
    '''Return the directory of the currently running test script'''

    return Path(request.fspath).parent

And sample usage

def test_script_loc(script_loc):
    baseline = script_loc.joinpath('baseline/baseline.cvs')
    print(baseline)


问:
Selecting data from three MySQL tables in PHP
I have had a look and I am really struggling to see how I can overcome this. I have looked at UNION/UNION ALL and JOIN but I cant get it to work.

Basically, I have data from three MySQL tables. The three tables have form data from it and are named Fleet, Facilities, HAS. The data have similar headers but different information. They all share the same 4 headers:

ticket | agentname | dept | resolved.

I have the below PHP code to display this in an HTML table but I can not get it to display from all three tables. (I can only post two images)

```<code>$mysqli=mysqli_connect("example","root","toor","site");
include('config.php');    //include of db config file
include ('paginate.php'); //include of paginat page

$per_page = 25;         // number of results to show per page
$result = mysqli_query("SELECT * FROM fleet
                        UNION ALL
                        SELECT * FROM has
                        ORDER resolved BY ASC;");
</code>```

I am not a web programmer. I have learned what I know from youtube and google. Please explain where possible your answer.

答:
You have syntax error: ORDER resolved BY ASC, that should be : ORDER BY resolved ASC

Have you try to specify columns in your selects? Try something like this:

```<code>    SELECT ticket, agentname, dept, resolved FROM fleet
    UNION ALL
    SELECT ticket, agentname, dept, resolved FROM has
    ORDER BY resolved ASC;
</code>```

Body:
I have had a look and I am really struggling to see how I can overcome this. I have looked at UNION/UNION ALL and JOIN but I cant get it to work.

Basically, I have data from three MySQL tables. The three tables have form data from it and are named Fleet, Facilities, HAS. The data have similar headers but different information. They all share the same 4 headers:

ticket | agentname | dept | resolved.

I have the below PHP code to display this in an HTML table but I can not get it to display from all three tables. (I can only post two images)

$mysqli=mysqli_connect("example","root","toor","site");
include('config.php');    //include of db config file
include ('paginate.php'); //include of paginat page

$per_page = 25;         // number of results to show per page
$result = mysqli_query("SELECT * FROM fleet
                        UNION ALL
                        SELECT * FROM has
                        ORDER resolved BY ASC;");

I am not a web programmer. I have learned what I know from youtube and google. Please explain where possible your answer.

Body:
You have syntax error: ORDER resolved BY ASC, that should be : ORDER BY resolved ASC

Have you try to specify columns in your selects? Try something like this:

    SELECT ticket, agentname, dept, resolved FROM fleet
    UNION ALL
    SELECT ticket, agentname, dept, resolved FROM has
    ORDER BY resolved ASC;


问:
Creating a variable that is restricted to certain values
Relatively new to Typescript - I am looking for a way to create a variable type that is restricted to certain values.

For example, I have an element that I want to change the width of based on some "zoom" variable.

I am looking to be able to create some variable type "Zoom", that works like a number but can only be the values 1, 2, 5, 10, 20, 50, or 100 (restricting the scales at which the element can be zoomed in on)

I also want to be able to increment my zoom variable and have it iterate through these values like so:

```<code>let zoom : Zoom = 1;

zoom++
// Here, zoom should equal 2

zoom++
// Here, zoom should equal 5

zoom++
// Here, zoom should equal 10

zoom--
// Here, zoom should equal 5
</code>```

And so on, etc. Is there a way to easily do this in Typescript?

答:
Globaly said. It is imposible. In could be done using helping variable and array containing right values.</p>

```<code>var zoomLevels = [1, 2, 5, 10, 20, 50, 100]

var zoom = 0;
// zoomLevels[zoom] is now 1

zoom++;
// zoomLevels[zoom] is now 2

zoom++;
// zoomLevels[zoom] is now 5

zoom++;
// zoomLevels[zoom] is now 10

zoom--;
// zoomLevels[zoom] is now 5
</code>```

Body:
Relatively new to Typescript - I am looking for a way to create a variable type that is restricted to certain values.

For example, I have an element that I want to change the width of based on some "zoom" variable.

I am looking to be able to create some variable type "Zoom", that works like a number but can only be the values 1, 2, 5, 10, 20, 50, or 100 (restricting the scales at which the element can be zoomed in on)

I also want to be able to increment my zoom variable and have it iterate through these values like so:

let zoom : Zoom = 1;

zoom++
// Here, zoom should equal 2

zoom++
// Here, zoom should equal 5

zoom++
// Here, zoom should equal 10

zoom--
// Here, zoom should equal 5

And so on, etc. Is there a way to easily do this in Typescript?

Body:
Globaly said. It is imposible. In could be done using helping variable and array containing right values.

var zoomLevels = [1, 2, 5, 10, 20, 50, 100]

var zoom = 0;
// zoomLevels[zoom] is now 1

zoom++;
// zoomLevels[zoom] is now 2

zoom++;
// zoomLevels[zoom] is now 5

zoom++;
// zoomLevels[zoom] is now 10

zoom--;
// zoomLevels[zoom] is now 5


问:
Dynamic selection of dataframe fields by value comparison
I can get the sum of all values in a dataframe meeting specified conditions by typing

```<code>df.loc[(df[column_1] == value_1) & (df[column_2] == value_2), columnWithValues].sum()
</code>```

I am looking for an easy solution which uses a set with columns and values specified.
Is there something like the following?

```<code>set_columns = set([column_1, column_2])
set_values = set([value_1, value_2])
df.loc[set_col == set_val, columnWithValues].sum()
</code>```

This way, the input could have any number of arguments.

答:
You can put the columns' names to query on in a list, and the target values in a tuple; Set the columns as index on the data frame and then query with values:

```<code>columns = ['column_1', 'column_2']
values = ('value_1', 'value_2')

df.set_index(columns).loc[values, columnWithValues].sum()
</code>```

Example:

```<code>df = pd.DataFrame({
        "A": [1,1,1,1,2,2,2,2],
        "B": [1,1,2,2,3,3,4,4],
        "C": [2,1,2,3,4,3,5,6],
        "D": [5,3,2,1,6,7,8,9]
    })

columns = ['A', 'B']
values = (2,4)
df.set_index(columns).loc[values, ['C','D']].sum()

#C    11
#D    17
#dtype: int64
</code>```

Body:
I can get the sum of all values in a dataframe meeting specified conditions by typing

df.loc[(df[column_1] == value_1) & (df[column_2] == value_2), columnWithValues].sum()

I am looking for an easy solution which uses a set with columns and values specified.
Is there something like the following?

set_columns = set([column_1, column_2])
set_values = set([value_1, value_2])
df.loc[set_col == set_val, columnWithValues].sum()

This way, the input could have any number of arguments.

Body:
You can put the columns' names to query on in a list, and the target values in a tuple; Set the columns as index on the data frame and then query with values:

columns = ['column_1', 'column_2']
values = ('value_1', 'value_2')

df.set_index(columns).loc[values, columnWithValues].sum()

Example:

df = pd.DataFrame({
        "A": [1,1,1,1,2,2,2,2],
        "B": [1,1,2,2,3,3,4,4],
        "C": [2,1,2,3,4,3,5,6],
        "D": [5,3,2,1,6,7,8,9]
    })

columns = ['A', 'B']
values = (2,4)
df.set_index(columns).loc[values, ['C','D']].sum()

#C    11
#D    17
#dtype: int64


问:
Vue JS Error when using v-for to get JSON key values from an object array
I am trying to parse a list of objects in a JSON payload into a table using Vue.js.

I want to take the keys from the first object in the array to create the table headings, the code below works and provides the correct values, but the problem is I keep getting this error message

The Error message

```<code>[Vue warn]: Error in render function: "TypeError: objectArray is null"

(found in <Root>)
</code>```

The Html element

```<code><thead>
    <tr>
        <th v-for="(value, key) in objectArray[0]">
            {{ key }}
        </th>
    </tr>
</thead>
</code>```

The JSON payload

```<code>[
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" }
]
</code>```

The Vue code to populate the object

```<code>var link = 'api/array';

new Vue ({
    el: '#app',
    data: {
        objectArray: null
    },
    methods:{
        getObjectArray: function(){
            this.$http.get(link).then(function(response){
                this.objectArray = response.data;
            }, function(error){
                console.log(error.statusText);
            });
        }
    },
    mounted: function () {
        this.getObjectArray();
    }
});
</code>```

答:
The error is because the objectArray is null the first time and isn't a Array. Try this code to prevent the error until your request is loaded:</p>

```<code><thead v-if='objectArray'>
    <tr>
        <th v-for="(value, key) in objectArray[0]">
            {{ key }}
        </th>
    </tr>
</thead>
</code>```

Body:
I am trying to parse a list of objects in a JSON payload into a table using Vue.js.

I want to take the keys from the first object in the array to create the table headings, the code below works and provides the correct values, but the problem is I keep getting this error message

The Error message

[Vue warn]: Error in render function: "TypeError: objectArray is null"

(found in <Root>)

The Html element

            {{ key }}

The JSON payload

[
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" },
{ "field1": "value", "field2": "value", "field3": "value", "field4": "value", "field5": "value", "field6": "value", "field7": "value" }
]

The Vue code to populate the object

var link = 'api/array';

new Vue ({
    el: '#app',
    data: {
        objectArray: null
    },
    methods:{
        getObjectArray: function(){
            this.$http.get(link).then(function(response){
                this.objectArray = response.data;
            }, function(error){
                console.log(error.statusText);
            });
        }
    },
    mounted: function () {
        this.getObjectArray();
    }
});

Body:
The error is because the objectArray is null the first time and isn't a Array. Try this code to prevent the error until your request is loaded:

<thead v-if='objectArray'>
    <tr>
        <th v-for="(value, key) in objectArray[0]">
            {{ key }}
        </th>
    </tr>
</thead>


问:
Modal works, until duplicated
I have a javascript modal that I created, which works fine, unless there are 2 on the page. When 2 of them exist on the page, the first one will work, but the next ones do now.

Here is the JS that controls it:

```<code>// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};
</code>```

and here is a working example. I've tried messing around with using var instead of let, but not 100% sure on how to scope them to their specific html structures programtically.

答:
Change your javascript:</p>

```<code>    // Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];

let trigger1 = document.getElementsByClassName("js-modal")[1];

trigger.onclick = function() {
  modal.style.display = "block";
};

trigger1.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};
</code>```

Title: Modal works, until duplicated

Body:
I have a javascript modal that I created, which works fine, unless there are 2 on the page. When 2 of them exist on the page, the first one will work, but the next ones do now.

Here is the JS that controls it:

// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};

and here is a working example. I've tried messing around with using var instead of let, but not 100% sure on how to scope them to their specific html structures programtically.

Body:
Change your javascript:

    // Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];

let trigger1 = document.getElementsByClassName("js-modal")[1];

trigger.onclick = function() {
  modal.style.display = "block";
};

trigger1.onclick = function() {
  modal.style.display = "block";
};

// Get the modal linked with with trigger element
let modal = document.getElementById(
  trigger.href.substring(trigger.href.indexOf("#") + 1)
);

// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
  allClose[i].onclick = function() {
    modal.style.display = "none";
  };
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
  if (e.target == modal) {
     modal.style.display = "none";
  }
};


问:
Why must accessor functions be const? Where is the vulnerability?
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

```<code>#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}
</code>```

答:
where is the vulnerability?

The answer is that function names can lie, but interfaces containing references to const cannot.

example:

```<code>#include <iostream>
#include <string>

// this function name lies
void i_wont_touch_your_cheese(std::string& s)
{
    // uh-oh - I lied!
    s = "lol, I touched your cheese!";
}

// this one cannot. The compiler won't allow it
void i_really_wont_touch_your_cheese(const std::string& s)
{
    // compiler error here!
    // cheese is safe
    s = "lol, I touched your cheese!";
}

int main() {
    auto cheese = std::string("untouched cheese");
    i_wont_touch_your_cheese(cheese);
    std::cout << cheese << std::endl;

    cheese = "more untouched cheese";
    i_really_wont_touch_your_cheese(cheese);
    std::cout << cheese << std::endl;

    return 0;
}
</code>```

Body:
Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: "accessor" (aka "selector" or "getter") methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;
    return 0;
}

Body:
where is the vulnerability?

The answer is that function names can lie, but interfaces containing references to const cannot.

example:

#include <iostream>
#include <string>

// this function name lies
void i_wont_touch_your_cheese(std::string& s)
{
    // uh-oh - I lied!
    s = "lol, I touched your cheese!";
}

// this one cannot. The compiler won't allow it
void i_really_wont_touch_your_cheese(const std::string& s)
{
    // compiler error here!
    // cheese is safe
    s = "lol, I touched your cheese!";
}

int main() {
    auto cheese = std::string("untouched cheese");
    i_wont_touch_your_cheese(cheese);
    std::cout << cheese << std::endl;

    cheese = "more untouched cheese";
    i_really_wont_touch_your_cheese(cheese);
    std::cout << cheese << std::endl;

    return 0;
}


问:
Copy Asana Project to Google Sheets
I already have Zapier copying new tasks in Asana to a Google Sheets, but what I really need is a dump of ALL tasks (and due dates, etc.) from a given Asana project to a Google Sheets. From there, my Zap would be able to maintain the Sheets, especially if I had a second Zap to find and sync state-change.

In any case, I need a way to make printable/sharable "lists" of all Asana tasks within a given project; Asana's print an export options are simply LACKING.

答: Have you tried to sync a project to Google Sheets:

Title: Copy Asana Project to Google Sheets


问:
use response write to make a link
I have a urlcolumn and a title column and i want the link to be automatically made in asp</p>

```<code> <td><%response.write(<a href="rs.fields.item("urlcolumn")target=_"blank">rs.fields.item("titlecolumn")</a>)%></td>
</code>```

答:
You could do what you are trying by string concatenation:

<%= Response.Write("" + rs.fields.item("titlecolumn") + "") %>

However, you might be better served using an asp:HyperLink control.

Title: use response write to make a link

Body:
I have a urlcolumn and a title column and i want the link to be automatically made in asp

 <%response.write(rs.fields.item("titlecolumn"))%>

Body:
You could do what you are trying by string concatenation:

<%= Response.Write("<a href=\"" + rs.fields.item("urlcolumn") + "\" target=\"_blank\">" + rs.fields.item("titlecolumn") + "</a>") %>

However, you might be better served using an asp:HyperLink control.


问:
Swift 3 pass data from one ViewController to another ViewController
I am new to IOS programming and don't really know what I'm asking but I will try and explain

I am using Firebase to auth and then I want to take the UID and pass it to a different VC the problem I am getting I cant get the var userID to print out side of the IBAction here is where I am so far, any pointer would get good cheers guys

```<code>@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text,
        let password = passwordTextField.text,
        let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
            }
            let userID            = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String  = self.nameTextField.text!
            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])
            self.userID1          = user!.uid as! String
        })
        print(self.userID1)
        presentLoggedInScreen()
    }
}

func presentLoggedInScreen() {
    let stroyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let loggedInVC: LoggedInVCViewController = stroyboard.instantiateViewController(withIdentifier: "loggedInVC") as! LoggedInVCViewController
    self.present(loggedInVC, animated: true, completion: nil)
}
</code>```

答:
Put

```<code>print(self.userID1)

presentLoggedInScreen()
</code>```

inside the completion block. Currently those lines are almost certain to happen before the completion block is done as the block is executed after the required network calls return.

Be sure to wrap presentLoggedInScreen() in a block that dispatches it to the main thread as it touches the UI and all UI calls must be made from the main thread.

```<code>DispatchQueue.main.async {
  presentLoggedInScreen()
}
</code>```

This will make it so that presentLoggedInScreen() executes after the value as been assigned to userID1 allowing you to pass the value over to the incoming view controller (assuming, of course, that the incoming VC has an appropriate variable to pass userID1 into).

Something like:

```<code>loggedInVC.userID = self.userID1
</code>```

before you present the VC.

Body:
I am new to IOS programming and don't really know what I'm asking but I will try and explain

I am using Firebase to auth and then I want to take the UID and pass it to a different VC the problem I am getting I cant get the var userID to print out side of the IBAction here is where I am so far, any pointer would get good cheers guys

@IBAction func creatAccountPressed(_ sender: Any) {
    if let email = emailTextField.text,
        let password = passwordTextField.text,
        let name = nameTextField.text {
        Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
            if let firebaseError = error {
                print(firebaseError.localizedDescription)
            }
            let userID            = user!.uid
            let userEmail: String = self.emailTextField.text!
            let fullName: String  = self.nameTextField.text!
            self.ref.child("users").child(userID).setValue(["Email": userEmail, "Name": fullName])
            self.userID1          = user!.uid as! String
        })
        print(self.userID1)
        presentLoggedInScreen()
    }
}

func presentLoggedInScreen() {
    let stroyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let loggedInVC: LoggedInVCViewController = stroyboard.instantiateViewController(withIdentifier: "loggedInVC") as! LoggedInVCViewController
    self.present(loggedInVC, animated: true, completion: nil)
}

Body:
Put

print(self.userID1)

presentLoggedInScreen()

inside the completion block. Currently those lines are almost certain to happen before the completion block is done as the block is executed after the required network calls return.

Be sure to wrap presentLoggedInScreen() in a block that dispatches it to the main thread as it touches the UI and all UI calls must be made from the main thread.

DispatchQueue.main.async {
  presentLoggedInScreen()
}

This will make it so that presentLoggedInScreen() executes after the value as been assigned to userID1 allowing you to pass the value over to the incoming view controller (assuming, of course, that the incoming VC has an appropriate variable to pass userID1 into).

Something like:

loggedInVC.userID = self.userID1

before you present the VC.


问:
Centering Bootstrap columns when they are aligned vertically
I am having a bit of trouble with bootstrap columns centering when it is collapsed to mobile view;

Some Text

more text here

```

I am using code similar to this and when I go into chrome inspect element and click the mobile button and collapse the view the first column will go on top of the second column but will not center in the middle of the page which is what I want. Do you have any ideas how I would fix this?

答:
You can use Bootstrap' offset classes so it requires no change in markup and no extra CSS. The key is to set an offset equal to half of the remaining size of the row. You are using even column widths, so this could work. Here is a link to Bootstrap offsets: http://getbootstrap.com/css/#grid-offsetting

Specifically for mobile, you can change the column widths for different size devices. You are only specifying md in your example. See: http://getbootstrap.com/css/#grid-example-mixed-complete. A combination of offsetting columns and device size will give you what you want.

Body:
I am having a bit of trouble with bootstrap columns centering when it is collapsed to mobile view;

Some Text

more text here

I am using code similar to this and when I go into chrome inspect element and click the mobile button and collapse the view the first column will go on top of the second column but will not center in the middle of the page which is what I want. Do you have any ideas how I would fix this?


问:
How to iterate over a DataSnapshot?
I'm trying to iterate over the children of the contacts node. .

However my ListArray contacts only partially populates. The first two entries populate the array as expected (output from Logcat) but the 3rd entry fails to populate the array. Here is the MainActivity.java:

```<code>public class MainActivity extends AppCompatActivity {
TextView stringTextView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    stringTextView = (TextView)findViewById(R.id.textView2);

    FirebaseDatabase firebaseDatabase= FirebaseDatabase.getInstance().getInstance();
    DatabaseReference dbRef= firebaseDatabase.getReference("County/Dublin");

    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            DataSnapshot contactSnapshot = dataSnapshot.child("contacts");
            Iterable<DataSnapshot> contactChildren = contactSnapshot.getChildren();
            ArrayList<Contact> contacts= new ArrayList<>();

            for (DataSnapshot contact : contactChildren) {
                Contact c = contact.getValue(Contact.class);
                Log.d("contact:: ", c.name + " " + c.number);
                contacts.add(c);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
}
</code>```

And the model class Contact.java:

```<code>public class Contact {
public String name;
public String number;

public Contact() {
}

public Contact(String name, String number) {
    this.name = name;
    this.number = number;
}
}
</code>```

Why is my ListArray not completely populating?

UPDATE

Here is what I've done with the suggested code example:

```<code>@Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<String> names= new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.child("name").getValue(String.class);
                names.add(name);
                String number = ds.child("number").getValue(String.class);
                Log.d("TAG", name);
            }
            for(int i=0; i < names.size(); i++){

                stringTextView.setText(stringTextView.getText() + names
                        .get(i) + " , ");
            }
        }
</code>```

Array still not populating and no display to the screen.

答:
Please use this code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("County").child("Dublin").child("contacts");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<String> names= new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            names.add(name);
            String number = ds.child("number").getValue(String.class);
            Log.d("TAG", name + " / " + number);
        }
        for(String name : names) {
            TextView stringTextView = (TextView) findViewById(R.id.string_text_view);
            stringTextView.setText(stringTextView.getText().toString() + name + " , ");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>ger / 0213
paddy / 3345556
jeff / 55555
</code>```

So, having this data, you can add it to an ArrayList, display it, do what you want with it.

Title: How to iterate over a DataSnapshot?

Body:
I'm trying to iterate over the children of the contacts node. .

However my ListArray contacts only partially populates. The first two entries populate the array as expected (output from Logcat) but the 3rd entry fails to populate the array. Here is the MainActivity.java:

public class MainActivity extends AppCompatActivity {
TextView stringTextView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    stringTextView = (TextView)findViewById(R.id.textView2);

    FirebaseDatabase firebaseDatabase= FirebaseDatabase.getInstance().getInstance();
    DatabaseReference dbRef= firebaseDatabase.getReference("County/Dublin");

    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            DataSnapshot contactSnapshot = dataSnapshot.child("contacts");
            Iterable<DataSnapshot> contactChildren = contactSnapshot.getChildren();
            ArrayList<Contact> contacts= new ArrayList<>();

            for (DataSnapshot contact : contactChildren) {
                Contact c = contact.getValue(Contact.class);
                Log.d("contact:: ", c.name + " " + c.number);
                contacts.add(c);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}
}

And the model class Contact.java:

public class Contact {
public String name;
public String number;

public Contact() {
}

public Contact(String name, String number) {
    this.name = name;
    this.number = number;
}
}

Why is my ListArray not completely populating?

UPDATE

Here is what I've done with the suggested code example:

@Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<String> names= new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = ds.child("name").getValue(String.class);
                names.add(name);
                String number = ds.child("number").getValue(String.class);
                Log.d("TAG", name);
            }
            for(int i=0; i < names.size(); i++){

                stringTextView.setText(stringTextView.getText() + names
                        .get(i) + " , ");
            }
        }

Array still not populating and no display to the screen.

Body:
Please use this code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("County").child("Dublin").child("contacts");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        ArrayList<String> names= new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            names.add(name);
            String number = ds.child("number").getValue(String.class);
            Log.d("TAG", name + " / " + number);
        }
        for(String name : names) {
            TextView stringTextView = (TextView) findViewById(R.id.string_text_view);
            stringTextView.setText(stringTextView.getText().toString() + name + " , ");
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);

Your output will be:

ger / 0213
paddy / 3345556
jeff / 55555

So, having this data, you can add it to an ArrayList, display it, do what you want with it.