问:
sorting lists of python 3.6.3 with custom def
I'm Trying to sort a list in python with my own def

this is my code :

```<code>def mysort(a):

    for i in range(len(a)):
        if (a[i]<a[(i+1)]):
            a[i],a[i+1] = a[i+1],a[i]
            i=0
    return a

a = [2,3,4]

print(mysort(a))
</code>```

The First Error I faced was List Is Out Of Range
and when I looked at the list in live programming mode I saw that only the first item was replaced with the second one and the third that was the biggest number in the list did not come first

my list in live programming mode before the error:

```<code>[3,4,2]
</code>```

how can i fix this?

答:
You are missing a few components to your sort:

1- you are sorting in reverse order.

2- you must limit your sort to len(a)-1

3- when the swap contition is not met, you must increment the index.

4- you are changing the index in a for loop... you must use a while loop here.

```<code>def mysort(a):
    idx = 0
    while idx < len(a)-1:
        if a[idx] < a[(idx+1)]:
            a[idx] ,a[idx+1] = a[idx+1], a[idx]
            idx = 0
        else:
            idx += 1
    return a

a = [2,3,4]

print(mysort(a))
</code>```

tests:

```<code>a = [2,3,4]
print(mysort(a))

a = [0, 1, 4, 3, 6, 2]
print(mysort(a))

a = [6, 4, 2]
print(mysort(a))

a = [-1, -1, -1, 1]
print(mysort(a))
</code>```

output:

```<code>[4, 3, 2]
[6, 4, 3, 2, 1, 0]
[6, 4, 2]
[1, -1, -1, -1]
</code>```

IDK what sort it is, but it looks like a bubble sort where you start again and again at the very beginning of the list

Body:
I'm Trying to sort a list in python with my own def

this is my code :

def mysort(a):

    for i in range(len(a)):
        if (a[i]<a[(i+1)]):
            a[i],a[i+1] = a[i+1],a[i]
            i=0
    return a

a = [2,3,4]

print(mysort(a))

The First Error I faced was List Is Out Of Range
and when I looked at the list in live programming mode I saw that only the first item was replaced with the second one and the third that was the biggest number in the list did not come first

my list in live programming mode before the error:

[3,4,2]

how can i fix this?

Body:
You are missing a few components to your sort:

1- you are sorting in reverse order.

2- you must limit your sort to len(a)-1

3- when the swap contition is not met, you must increment the index.

4- you are changing the index in a for loop... you must use a while loop here.

def mysort(a):
    idx = 0
    while idx < len(a)-1:
        if a[idx] < a[(idx+1)]:
            a[idx] ,a[idx+1] = a[idx+1], a[idx]
            idx = 0
        else:
            idx += 1
    return a

a = [2,3,4]

print(mysort(a))

tests:

a = [2,3,4]
print(mysort(a))

a = [0, 1, 4, 3, 6, 2]
print(mysort(a))

a = [6, 4, 2]
print(mysort(a))

a = [-1, -1, -1, 1]
print(mysort(a))

output:

[4, 3, 2]
[6, 4, 3, 2, 1, 0]
[6, 4, 2]
[1, -1, -1, -1]

IDK what sort it is, but it looks like a bubble sort where you start again and again at the very beginning of the list


来源: stackexchange

问:
How to screen record iOS-real device with command?
I need to screen record iOS from iMAC for the purpose of test automation.
I found commands for Android and iOS-Simulator which are:

adb screenrecord /sdcard/123.mp4

xcrun simctl io  recordVideo --type=mp4

However, I need a command for iOS-real device.

The purpose of this is for taking video of device during each of test automation sessions.

答:
iOS 11 has built-in Screen Recording for real devices, you need to check if its possible to do run/stop/getFile from device via command line tools or whatever using in terminal.

In addition, its possible to use QuickTime + Applescript for screen recording, check here for details.

ContentLicense: CC BY-SA 3.0


问:
Hibernate : More than one table found: table_name
I am using Hibernate 5.x in my project. when the application is starting up i get the following message continuously and my app does not start.
the human readable part is "More than one table found: t_agent" sentence.

org.hibernate.dialect.Dialect.@156:   HHH000400: Using dialect:
  org.hibernate.dialect.Oracle12cDialect
  org.hibernate.type.BasicTypeRegistry.register@138:  HHH000270: Type
  registration [byte[]] overrides previous :
  org.hibernate.type.BinaryType@149b53fa
  org.hibernate.type.BasicTypeRegistry.register@138:  HHH000270: Type
  registration [[B] overrides previous :
  org.hibernate.type.BinaryType@149b53fa
  org.hibernate.type.BasicTypeRegistry.register@138:  HHH000270: Type
  registration [Byte[]] overrides previous :
  org.hibernate.type.WrapperBinaryType@638977e0
  org.hibernate.type.BasicTypeRegistry.register@138:  HHH000270: Type
  registration [[Ljava.lang.Byte;] overrides previous :
  org.hibernate.type.WrapperBinaryType@638977e0
  o.h.t.s.e.i.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults@377:
  HHH000263: More than one table found: t_agent
  o.hibernate.jpa.internal.util.LogHelper.logPersistenceUnitInformation@31:
  HHH000204: Processing PersistenceUnitInfo [
          name: defaultPersistenceUnit

答:
Adding

```<code><property name="hibernate.default_schema" value="myuser"/>
</code>```

in persitence.xml solved the problem.

Body:
Adding

<property name="hibernate.default_schema" value="myuser"/>

in persitence.xml solved the problem.


问:
Horizontal recycler view on top of vertical recycler veiw
```<code>        This is the individual item's layout file

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#DDE6EC"
        tools:context="com.example.personal.newsfeeder.MainActivity">

        <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/section_recycler_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/tools"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_marginTop="16dp"

            android:id="@+id/card_view"
            android:layout_gravity="center"
            card_view:cardCornerRadius="8dp"
            card_view:cardElevation="10dp"
            >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/avatar_section"
                    android:layout_width="match_parent"
                    android:layout_height="72dp"
                    android:padding="16dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:background="@drawable/circular_image"
                        android:id="@+id/avatar_image"
                        />
                    <TextView
                        android:id="@+id/avatar_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@id/avatar_image"
                        android:layout_marginLeft="4dp"
                        tools:text="Title"
                        android:textStyle="bold"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="#616161"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/avatar_name"
                        android:layout_toRightOf="@id/avatar_image"
                        android:layout_marginLeft="4dp"
                        tools:text="Subhead"
                        android:id="@+id/avatar_subhead"
                        android:textAppearance="?android:textAppearanceSmall"
                        android:textColor="#616161"/>

                </RelativeLayout>

                    <ImageView
                        android:layout_height="wrap_content"
                        android:layout_width="match_parent"
                        tools:src="@drawable/placeholder"
                        android:id="@+id/image_view"
                        android:scaleType="centerCrop"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingTop="16dp"
                        android:text="Keep Moving"
                        android:paddingLeft="16dp"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textAllCaps="true"
                        android:textStyle="bold"
                        android:id="@+id/the_title"
                        />f

                <TextView
                    android:id="@+id/the_three_lines"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="3"
                    android:padding="16dp"
                    tools:text="@string/description"
                    android:ellipsize="end"
                    android:lineSpacingMultiplier="1.2"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    >
                    <ImageView
                        android:id="@+id/heart_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/heart"
                        android:padding="8dp"
                        />
                    <ImageView
                        android:id="@+id/bookmark_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/bookmark"
                        android:padding="8dp"
                        />

                </LinearLayout>

            </LinearLayout>

        enter code here
        </android.support.v7.widget.CardView>

    </LinearLayout>

This is the recycler's Adapter code
  @Override
    public void onBindViewHolder(ArticleViewHolder holder, int position) {
        holder.mAvatarView.setText(mArticles.get(position).getmAvatarInitial());
        holder.mAvatarNameView.setText(mArticles.get(position).getmAvatarName());
        holder.mAvatarSubView.setText(mArticles.get(position).getmAvatarSub());
        mRowIndex++;
        if (position == 0) {

            holder.horizontalList.setLayoutManager(new LinearLayoutManager(holder.context, LinearLayoutManager.HORIZONTAL, false));
            holder.horizontalAdapter = new SectionRVAdapter(holder.context);
            holder.horizontalList.setAdapter(holder.horizontalAdapter);
            holder.horizontalAdapter.setDataset(holder.sections);

        }

        String imageUrl = mArticles.get(position).getmImageURL();

        Picasso.with(mContext)
                .load(imageUrl)
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.error_img)
                .into(holder.mImageView);
        holder.mTheTitleView.setText(mArticles.get(position).getmTheTitle());

        holder.mTheThreeLinesView.setText(mArticles.get(position).getmTheThreeLines());

    }
</code>```

Now i want a horizontal recycler view over the vertical recycler view. But at present the horizontal recycler view is repeated after every 5 cardviews.

I am checking if position is equal to 0 in my onBindViewHolder method but still why is it created multiple times?

I hope i made my question clear.

答:
holder.setIsRecyclable(false);

Add this line in   public void onBindViewHolder(ArticleViewHolder holder, int position) {}

I hope this will help you

Body:
        This is the individual item's layout file

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#DDE6EC"
        tools:context="com.example.personal.newsfeeder.MainActivity">

        <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/section_recycler_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/tools"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_marginTop="16dp"

            android:id="@+id/card_view"
            android:layout_gravity="center"
            card_view:cardCornerRadius="8dp"
            card_view:cardElevation="10dp"
            >

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/avatar_section"
                    android:layout_width="match_parent"
                    android:layout_height="72dp"
                    android:padding="16dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:background="@drawable/circular_image"
                        android:id="@+id/avatar_image"
                        />
                    <TextView
                        android:id="@+id/avatar_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@id/avatar_image"
                        android:layout_marginLeft="4dp"
                        tools:text="Title"
                        android:textStyle="bold"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textColor="#616161"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@id/avatar_name"
                        android:layout_toRightOf="@id/avatar_image"
                        android:layout_marginLeft="4dp"
                        tools:text="Subhead"
                        android:id="@+id/avatar_subhead"
                        android:textAppearance="?android:textAppearanceSmall"
                        android:textColor="#616161"/>

                </RelativeLayout>

                    <ImageView
                        android:layout_height="wrap_content"
                        android:layout_width="match_parent"
                        tools:src="@drawable/placeholder"
                        android:id="@+id/image_view"
                        android:scaleType="centerCrop"/>

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingTop="16dp"
                        android:text="Keep Moving"
                        android:paddingLeft="16dp"
                        android:textAppearance="?android:textAppearanceMedium"
                        android:textAllCaps="true"
                        android:textStyle="bold"
                        android:id="@+id/the_title"
                        />f

                <TextView
                    android:id="@+id/the_three_lines"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="3"
                    android:padding="16dp"
                    tools:text="@string/description"
                    android:ellipsize="end"
                    android:lineSpacingMultiplier="1.2"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    >
                    <ImageView
                        android:id="@+id/heart_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/heart"
                        android:padding="8dp"
                        />
                    <ImageView
                        android:id="@+id/bookmark_image"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:src="@drawable/bookmark"
                        android:padding="8dp"
                        />

                </LinearLayout>

            </LinearLayout>

        enter code here
        </android.support.v7.widget.CardView>

    </LinearLayout>

This is the recycler's Adapter code
  @Override
    public void onBindViewHolder(ArticleViewHolder holder, int position) {
        holder.mAvatarView.setText(mArticles.get(position).getmAvatarInitial());
        holder.mAvatarNameView.setText(mArticles.get(position).getmAvatarName());
        holder.mAvatarSubView.setText(mArticles.get(position).getmAvatarSub());
        mRowIndex++;
        if (position == 0) {

            holder.horizontalList.setLayoutManager(new LinearLayoutManager(holder.context, LinearLayoutManager.HORIZONTAL, false));
            holder.horizontalAdapter = new SectionRVAdapter(holder.context);
            holder.horizontalList.setAdapter(holder.horizontalAdapter);
            holder.horizontalAdapter.setDataset(holder.sections);

        }

        String imageUrl = mArticles.get(position).getmImageURL();

        Picasso.with(mContext)
                .load(imageUrl)
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.error_img)
                .into(holder.mImageView);
        holder.mTheTitleView.setText(mArticles.get(position).getmTheTitle());

        holder.mTheThreeLinesView.setText(mArticles.get(position).getmTheThreeLines());

    }

Now i want a horizontal recycler view over the vertical recycler view. But at present the horizontal recycler view is repeated after every 5 cardviews.

I am checking if position is equal to 0 in my onBindViewHolder method but still why is it created multiple times?

I hope i made my question clear.


问:
How to figure out what is running on my (NVIDIA) GPU?
I am using my GPU (Tesla K80) to train neural networks using tensorflow, and something has gone wrong. When I type nvidia-smi I see that 11239MiB / 11439MiB of the memory is being used, but no processes are listed for the GPU.
Normally when this happens I can type ps aux | grep python and find the process that is using up the GPU, but this time nothing is coming up.

How do I figure out what is running on my GPU, and how do I kill it?

答:
See all processes being run by the user who used the GPU. Kill all processes that may have used the GPU.

```<code>ps -ef | grep <username>
</code>```

You could also try

```<code>sudo nvidia-smi --gpu-reset
</code>```

If nothing works then consider rebooting.

Body:
See all processes being run by the user who used the GPU. Kill all processes that may have used the GPU.

ps -ef | grep <username>

You could also try

sudo nvidia-smi --gpu-reset

If nothing works then consider rebooting.


问:
Are multiple MX/CNAME TXT records for the same domain ok?
We use Gmail for business and Amazon SES for sending email.

Just wondering if it ok in our CloudFlare DNS to have several CNAME, TXT and MX records?

答:
It depends. There can not be a CNAME for the root(naked) domain, although some DNS providers detect that it is for the root domain and convert it to ALIAS (or some other type, in the back-end). Also a CNAME can not co-exist with other records for the same hostname (that is why there can not be for the root domain, it always has SOA and NS records and they can not be removed).

It is recommended to have more MX records for a given hostname for backup purposes, also there is no problem to have them for multiple hosts.

The TXT records also can be multiple for the same host, but not with the same values, for example there can not be 2 or more SPF records (SPF records are created as TXT RR, not as SPF RR (RR type 99)) for the same host.

ContentLicense: CC BY-SA 4.0


问:
Bootstrap align navbar items to the right
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

```<code><div id="app" class="container">
  <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricingg</a>
      </li>
    </ul>
    <ul class="navbar-nav " >
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/login') }}">Login</a>
      </li>
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/register') }}">Register</a>
      </li>
    </ul>
  </nav>
  @yield('content')
</div>
</code>```

答:
The working example for BS v4.0.0-beta.2:

```<code><body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Features</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Pricingg</a>
          </li>
        </ul>
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="#">Login</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Register</a>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
      container content
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
    <script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
  </body>
</code>```

Body:
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>
    Navbar

        Home (current)

        Features

        Pricingg

        Login

        Register

  @yield('content')

Body:
The working example for BS v4.0.0-beta.2:

<body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Features</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Pricingg</a>
          </li>
        </ul>
        <ul class="navbar-nav">
          <li class="nav-item">
            <a class="nav-link" href="#">Login</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Register</a>
          </li>
        </ul>
      </div>
    </nav>

    <div class="container-fluid">
      container content
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="node_modules/jquery/dist/jquery.slim.min.js"></script>
    <script src="node_modules/popper.js/dist/umd/popper.min.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
  </body>


问:
Thrown off by functor syntax in Effective C++
In Item 15 of Effective C++ 3rd edition an RAII class Font contains as its resource a FontHandle.
The item shows how the Font class can offer an implicit conversion function to its FontHandle thus:

```<code>operator FontHandle() const
    {return f;}
</code>```

What is the difference between this code and:

```<code>FontHandle operator()() const
    {return f;}
</code>```

If there is no difference, is it an unusual and not commonly used syntax?

答:
The first provides an implicit conversion, so that you can write

```<code>FontHandle h = myFont;
</code>```

and also (to be explicit about what's going on)

```<code>FontHandle h = (FontHandle)myFont;
</code>```

The seconds overloads the function call operator (), so that you can write

```<code>FontHandle h = myFont();
</code>```

Why you'd want the second, I'm not sure. I only have More Effective C++ handy, so I can't check what Meyers says about it.

ContentLicense: CC BY-SA 2.5

Body:
In Item 15 of Effective C++ 3rd edition an RAII class Font contains as its resource a FontHandle.
The item shows how the Font class can offer an implicit conversion function to its FontHandle thus:

operator FontHandle() const
    {return f;}

What is the difference between this code and:

FontHandle operator()() const
    {return f;}

If there is no difference, is it an unusual and not commonly used syntax?

Body:
The first provides an implicit conversion, so that you can write

FontHandle h = myFont;

and also (to be explicit about what's going on)

FontHandle h = (FontHandle)myFont;

The seconds overloads the function call operator (), so that you can write

FontHandle h = myFont();

Why you'd want the second, I'm not sure. I only have More Effective C++ handy, so I can't check what Meyers says about it.


问:
Two nested for with several statements under each in python
I am new in python. I want to write two "for" where each of the has many statements under it. I cannot find how I should differentiate these statement from each other? I need a code like this in python. I appreciate if any one can help.</p>

```<code> for(i=1,i<10,i++){
      statement 1;
      statement 2;
      for(j=1,j<5,j++){
           statement 1;
           statement 1;
      }
      statement 3;
      statement 4;
    }
</code>```

答:
This is how you do it in python:

```<code>for i in range(1, 11):
    print("statement 1 example")
    print("statement 2 example")
    for j in range(1, 6):
        print("statement 1 example")
        print("statement 2 example")
    print("statement 3 example")
    print("statement 4 example")
</code>```

There are no curly braces, semi-colons

Line indentation is what determines if it's nested or not. Also you need a colon after your for loop.
This will help Python For Loop Wiki

Body:
I am new in python. I want to write two "for" where each of the has many statements under it. I cannot find how I should differentiate these statement from each other? I need a code like this in python. I appreciate if any one can help.

 for(i=1,i<10,i++){
      statement 1;
      statement 2;
      for(j=1,j<5,j++){
           statement 1;
           statement 1;
      }
      statement 3;
      statement 4;
    }

Body:
This is how you do it in python:

for i in range(1, 11):
    print("statement 1 example")
    print("statement 2 example")
    for j in range(1, 6):
        print("statement 1 example")
        print("statement 2 example")
    print("statement 3 example")
    print("statement 4 example")

There are no curly braces, semi-colons

Line indentation is what determines if it's nested or not. Also you need a colon after your for loop.
This will help Python For Loop Wiki


问:
How to make Logback complete compression before my short-lived application exits?
I'm using the rollingPolicy in Logback to gzip the logs. However, as my application is short-lived (run and quit immediately), it randomly can't finish compressing the log file, resulting in some .tmp files. Is there any way to have Logback prevent my application from exiting until compression completes? I've tried to simply switch to AsyncAppender but no luck.

答:
Since Logback v1.1.3 you can add a ShutdownHook into your configuration. This will instruct Logback to shut itself down gracefully, including completing any in-flight work such as compressing files on rollover.

In XML configuration you add a ShutdownHook by including the following in your logback.xml:

```<code><shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>
</code>```

Alternatively, you can be explicit about your desired delay period (in milliseconds) as follows:

```<code><shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook">
    <delay>100</delay>
</shutdownHook>
</code>```

More details in the docs. Note: the docs incorrectly imply that you do not need to supply a shutdown hook classname. However, you do have to supply a class name (there's an open issue to get the docs fixed).

Body:
Since Logback v1.1.3 you can add a ShutdownHook into your configuration. This will instruct Logback to shut itself down gracefully, including completing any in-flight work such as compressing files on rollover.

In XML configuration you add a ShutdownHook by including the following in your logback.xml:

<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook"/>

Alternatively, you can be explicit about your desired delay period (in milliseconds) as follows:

<shutdownHook class="ch.qos.logback.core.hook.DelayingShutdownHook">
    <delay>100</delay>
</shutdownHook>

More details in the docs. Note: the docs incorrectly imply that you do not need to supply a shutdown hook classname. However, you do have to supply a class name (there's an open issue to get the docs fixed).


问:
How do I make the UI in IE 8 update as lines of JavaScript are executed in a function, rather than at the end of of the function?
I'm trying to display a progress bar while ajax calls populate a form. I have a function called LOADFORM(). It launches a jquery dialog box, displays a progress bar, calles a few other non-async ajax calls to get data. With each data call complete it advances the progress bar and at the end it hides the progressbar and displays the form. This works perfecly in Firfox, but in IE, it just shows the completed form. I doesn't update the UI until the function is done running and by that time everything is complete, but the user has to sit at a uneventful screen for several seconds. How do I make the UI in IE 8 update as lines of JavaScript are executed in a function?

Example:

```<code>ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    this.ShowError(false, "");

    //SHOW PROGRESS BAR
    this.ShowProgress(true, 30, "loading...");

    this.ShowDialogBox();

    //POPULATE FIELDS
    this.GetAccountName(constId);
    this.ShowProgress(true, 60, "loading...proposals");
    this.GetProposlas(constId);
    this.ShowProgress(true, 90, "loading...action types");
    this.GetActionTypes();
    this.ShowProgress(true, 100, "loading...complete");
    this.ConstituentID = constId;
    $("#" + this.CONSTITUENTID_ID + ":input").val("");
    $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + this.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (formType != "") {
        ToggleForms(formType);
    }

    //HIDE PROGRESS BAR
    this.ShowProgress(false, 0, "");

}
</code>```

Thanks,
T

答:
You could chain the different stages together with window.setTimout(). This gives the browser a little time to redraw the page. In this example I set the timeout to 1ms. I am not shure if that will do the trick. Note that I start the chain at the end of the outer function.</p>

```<code>ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    var hideErrors = function()
    {
        this.ShowError(false, "");
        window.setTimeout(showProgessBar, 1);
    };

    //SHOW PROGRESS BAR
    var showProgressBar = function()
    {
        this.ShowProgress(true, 30, "loading...");
        this.ShowDialogBox();
        window.setTimeout(populateFields, 1);
    };

    //POPULATE FIELDS
    var populateFields = function()
    {
        this.GetAccountName(constId);
        this.ShowProgress(true, 60, "loading...proposals");
        window.setTimeout(loadProposals, 1);
    };

    var loadProposals = function()
    {
        this.GetProposlas(constId);
        this.ShowProgress(true, 90, "loading...action types");
        window.setTimeout(loadActionTypes, 1);
    };

    var loadActionTypes = function()
    {
        this.GetActionTypes();
        this.ShowProgress(true, 100, "loading...complete");
        this.ConstituentID = constId;
        $("#" + this.CONSTITUENTID_ID + ":input").val("");
        $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

        //HIDE
        $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
        $('#' + this.CRDATEFIELD_ID).datepicker("hide");

        //TOGGLE FORM
        if (formType != "") {
            ToggleForms(formType);
        }

        //HIDE PROGRESS BAR
        this.ShowProgress(false, 0, "");
    };

    // Start with hide errors.
    hideErrors();
};
</code>```

Body:
I'm trying to display a progress bar while ajax calls populate a form. I have a function called LOADFORM(). It launches a jquery dialog box, displays a progress bar, calles a few other non-async ajax calls to get data. With each data call complete it advances the progress bar and at the end it hides the progressbar and displays the form. This works perfecly in Firfox, but in IE, it just shows the completed form. I doesn't update the UI until the function is done running and by that time everything is complete, but the user has to sit at a uneventful screen for several seconds. How do I make the UI in IE 8 update as lines of JavaScript are executed in a function?

Example:

ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    this.ShowError(false, "");

    //SHOW PROGRESS BAR
    this.ShowProgress(true, 30, "loading...");

    this.ShowDialogBox();

    //POPULATE FIELDS
    this.GetAccountName(constId);
    this.ShowProgress(true, 60, "loading...proposals");
    this.GetProposlas(constId);
    this.ShowProgress(true, 90, "loading...action types");
    this.GetActionTypes();
    this.ShowProgress(true, 100, "loading...complete");
    this.ConstituentID = constId;
    $("#" + this.CONSTITUENTID_ID + ":input").val("");
    $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + this.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (formType != "") {
        ToggleForms(formType);
    }

    //HIDE PROGRESS BAR
    this.ShowProgress(false, 0, "");

}

Thanks,
T

Body:
You could chain the different stages together with window.setTimout(). This gives the browser a little time to redraw the page. In this example I set the timeout to 1ms. I am not shure if that will do the trick. Note that I start the chain at the end of the outer function.

ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    var hideErrors = function()
    {
        this.ShowError(false, "");
        window.setTimeout(showProgessBar, 1);
    };

    //SHOW PROGRESS BAR
    var showProgressBar = function()
    {
        this.ShowProgress(true, 30, "loading...");
        this.ShowDialogBox();
        window.setTimeout(populateFields, 1);
    };

    //POPULATE FIELDS
    var populateFields = function()
    {
        this.GetAccountName(constId);
        this.ShowProgress(true, 60, "loading...proposals");
        window.setTimeout(loadProposals, 1);
    };

    var loadProposals = function()
    {
        this.GetProposlas(constId);
        this.ShowProgress(true, 90, "loading...action types");
        window.setTimeout(loadActionTypes, 1);
    };

    var loadActionTypes = function()
    {
        this.GetActionTypes();
        this.ShowProgress(true, 100, "loading...complete");
        this.ConstituentID = constId;
        $("#" + this.CONSTITUENTID_ID + ":input").val("");
        $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

        //HIDE
        $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
        $('#' + this.CRDATEFIELD_ID).datepicker("hide");

        //TOGGLE FORM
        if (formType != "") {
            ToggleForms(formType);
        }

        //HIDE PROGRESS BAR
        this.ShowProgress(false, 0, "");
    };

    // Start with hide errors.
    hideErrors();
};


问:
React Native styling SectionList: header and item in same row
I am new to React and React Native and I am exploring its Components.

Is it possible to style SectionList so that you have the section title and the content on the same row?

I tried styling the SectionList with flexDirection: row, but it seems useless:
https://snack.expo.io/H1ZiFXDJM

Thanks!

答:
I don't think this is the proper functioning of the SectionList.

I think you could achieve this with a FlatList and pass it an object like this:

```<code><View style={{ flexDirection: 'row' }}>
   <View>
     <Text>Section Header</Text>
   </View>
   <View>
     <Text>Section Item</Text>
   </View>
</View>
</code>```

Obviously the array must be united and not split as in the SectionList

Body:
I don't think this is the proper functioning of the SectionList.

I think you could achieve this with a FlatList and pass it an object like this:

<View style={{ flexDirection: 'row' }}>
   <View>
     <Text>Section Header</Text>
   </View>
   <View>
     <Text>Section Item</Text>
   </View>
</View>

Obviously the array must be united and not split as in the SectionList


问:
Cant add PCL project's Reference into Xunit project
I have one PCL project, in this project I made Xunit project, which I want to reference my PCL project to test it.

When I'm trying to add a reference, I cant check it, because of I have an error like this:

```<code>Incompatible target framework: .NETPortable,Version=v.4.5,profile=Profile111)
</code>```

I'm using Visual studio Mac, I've also updated everything from Check Updates
Also updated all Nuget packages.

答:
I am assuming this is a .NET Core xUnit project which is trying to reference the PCL project.

Currently this is prevented in Visual Studio for Mac 7.2 and earlier versions. In Visual Studio for Mac 7.3 and later, currently available on the alpha channel, it is possible to reference a PCL project from a .NET Core project.

For Visual Studio for Mac 7.2 the only workaround would be to add the project reference manually by editing the .csproj in the text editor. For example:

```<code><ItemGroup>
  <ProjectReference Include="..\PclProject\PclProject.csproj" />
</ItemGroup>
</code>```

Body:
I have one PCL project, in this project I made Xunit project, which I want to reference my PCL project to test it.

When I'm trying to add a reference, I cant check it, because of I have an error like this:

Incompatible target framework: .NETPortable,Version=v.4.5,profile=Profile111)

I'm using Visual studio Mac, I've also updated everything from Check Updates
Also updated all Nuget packages.

Body:
I am assuming this is a .NET Core xUnit project which is trying to reference the PCL project.

Currently this is prevented in Visual Studio for Mac 7.2 and earlier versions. In Visual Studio for Mac 7.3 and later, currently available on the alpha channel, it is possible to reference a PCL project from a .NET Core project.

For Visual Studio for Mac 7.2 the only workaround would be to add the project reference manually by editing the .csproj in the text editor. For example:

<ItemGroup>
  <ProjectReference Include="..\PclProject\PclProject.csproj" />
</ItemGroup>


问:
Matlab: bar No public property CData exists
The Matlab example code cannot run in Matlab 2017a (Linux 64bits):
https://cn.mathworks.com/help/matlab/ref/bar.html

```<code>b = bar(rand(10,1));
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];
</code>```

It can not color the specific bar and warns as:

No public property CData exists for class matlab.graphics.chart.primitive.Bar.

I don't know it is a specific feature merely for Matlab 2017b?

This code is only to color the specific bar. In Matlab 2012a, it can be easily done by:

```<code>bh=bar(MyStem); h=get(bh, 'children');
shading flat;  set(h,'FaceVertexCData',MyColor);
</code>```

I cannot understand why Matlab 2017 removes this feature.

答:
You can achieve what you are looking for like this:

```<code>b = bar([rand(1,3);nan(1,3)],'b');
b(2).FaceColor = 'r';
</code>```

You can also achieve this by calling the bar function multiple times with different values (which is a practice that you may need to use sometimes):

```<code>A = [1,2,3,4,1,3,2];

bar([1],A(1),'FaceColor','r');
bar([2:4],A(2:4),'FaceColor','g');
bar([5:7],A(5:7),'FaceColor','b');
</code>```

Body:
The Matlab example code cannot run in Matlab 2017a (Linux 64bits):
https://cn.mathworks.com/help/matlab/ref/bar.html

b = bar(rand(10,1));
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];

It can not color the specific bar and warns as:

No public property CData exists for class matlab.graphics.chart.primitive.Bar.

I don't know it is a specific feature merely for Matlab 2017b?

This code is only to color the specific bar. In Matlab 2012a, it can be easily done by:

bh=bar(MyStem); h=get(bh, 'children');
shading flat;  set(h,'FaceVertexCData',MyColor);

I cannot understand why Matlab 2017 removes this feature.

Body:
You can achieve what you are looking for like this:

b = bar([rand(1,3);nan(1,3)],'b');
b(2).FaceColor = 'r';

You can also achieve this by calling the bar function multiple times with different values (which is a practice that you may need to use sometimes):

A = [1,2,3,4,1,3,2];

bar([1],A(1),'FaceColor','r');
bar([2:4],A(2:4),'FaceColor','g');
bar([5:7],A(5:7),'FaceColor','b');


问:
How to have different gradle.properties files for release/debug builds?
We need to have gradle.properties files with different configs for release and debug builds, because some of the features we use are experimental and they break some things. Is that possible?

Example of our gradle.properties file

```<code>org.gradle.daemon=true
org.gradle.jvmargs=-Xmx1500m -XX:MaxPermSize=512m
org.gradle.parallel=true
kotlin.incremental=true
android.enableD8=true
</code>```

答:
As per official document:

You can create and configure build types in the module-level build.gradle file inside the android block. When you create a new module, Android Studio automatically creates the debug and release build types for you. Although the debug build type doesn't appear in the build configuration file, Android Studio configures it with debuggable true. This allows you to debug the app on secure Android devices and configures APK signing with a generic debug keystore.

You can add the debug build type to your configuration if you want to add or change certain settings. The following sample specifies an applicationIdSuffix for the debug build type, and configures a "staging" build type that is initialized using settings from the debug build type.

You can use same build.gradle for release and debug modes like:

```<code>buildTypes {
        release {
// Do whatever you want to do in release mode
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
// Do whatever you want to do in debug mode
            applicationIdSuffix ".debug"
            debuggable true
        }

        /**
         * The `initWith` property allows you to copy configurations from other build types,
         * then configure just the settings you want to change. This one copies the debug build
         * type, and then changes the manifest placeholder and application ID.
         */
        staging {
            initWith debug
            manifestPlaceholders = [hostName:"internal.example.com"]
            applicationIdSuffix ".debugStaging"
        }
    }
</code>```

Ref: Source

Body:
We need to have gradle.properties files with different configs for release and debug builds, because some of the features we use are experimental and they break some things. Is that possible?

Example of our gradle.properties file

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx1500m -XX:MaxPermSize=512m
org.gradle.parallel=true
kotlin.incremental=true
android.enableD8=true

Body:
As per official document:

You can create and configure build types in the module-level build.gradle file inside the android block. When you create a new module, Android Studio automatically creates the debug and release build types for you. Although the debug build type doesn't appear in the build configuration file, Android Studio configures it with debuggable true. This allows you to debug the app on secure Android devices and configures APK signing with a generic debug keystore.

You can add the debug build type to your configuration if you want to add or change certain settings. The following sample specifies an applicationIdSuffix for the debug build type, and configures a "staging" build type that is initialized using settings from the debug build type.

You can use same build.gradle for release and debug modes like:

buildTypes {
        release {
// Do whatever you want to do in release mode
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
// Do whatever you want to do in debug mode
            applicationIdSuffix ".debug"
            debuggable true
        }

        /**
         * The `initWith` property allows you to copy configurations from other build types,
         * then configure just the settings you want to change. This one copies the debug build
         * type, and then changes the manifest placeholder and application ID.
         */
        staging {
            initWith debug
            manifestPlaceholders = [hostName:"internal.example.com"]
            applicationIdSuffix ".debugStaging"
        }
    }

Ref: Source


问:
Web Crawler For Competive Pricing
I am thinking of writing an application that will pseudo-track competing websites to ensure that our prices stay competitive, etc. I looked at possibly using the Google Shopping Search API, but I felt that it could possibly be lacking in flexibility and not all of our competitors are fully listed or updated regularly.

My question, is where is a good place to start with a PHP based webcrawler? I obviously want a crawler that is respectful (even to our competitors), so it will hopefully obey the robots.txt and throttling. (To be fair, I think I am even going to host this on a third party server and have it crawl our websites to show no biases.) I looked around via google and I couldn't find any mature packages -- only some poorly written sourceforge scripts that haven't been maintained in over a year, despite being labeled as beta or alpha.

Looking for ideas or suggestions.
Thanks

答:
A crawler in itself isn't that complicated.  You just load up the site then evaluate and follow the links you find.

What you might do in order to be "friendly" is to purpose build a crawler for each site you plan on trawling.  In other words pick one site and see how they are structured.  Code your get requests and html parsing around that structure.  Rinse and repeat for the other sites.

If they are using a common shopping cart software (anything is possible here) then obviously you have a bit of reuse.

When crawling, you might want to hit their sites during off peak hours (this is going to be a guess).  Also, don't execute 500/requests a second.  Throttle it down quite a bit.

One optional thing you might even consider would be to contact these other sites and see if they want to participate in some direct data sharing.  The ideal would be for everyone to have an RSS feed for their products.

Of course, depending on who you are selling to this might be considered price fixing...  So, proceed with caution.

Title: Web Crawler For Competive Pricing


问:
Firebase Auth & Firebase Auth With Facebook not working
Hello i'm trying to implement an firebase auth to my app. but i does not seem to work. When i Submit the Form or click the Facebook Login it does nothing. I get this error:

Uncaught Error: The error you provided does not contain a stack trace.

Thank you in advance for helping me.

import firebase from 'firebase'

```<code>const loginStyles = {
  width: "90%",
  maxWidth: "380px",
  margin: "20px auto",
  border: "1px solid #ddd",
  borderRadius: "5px",
  padding: "10px"
}

const provider = new firebase.auth.FacebookAuthProvider();

class Login extends Component {

  constructor(props){
    super(props);
    this.authWithFacebook= this.authWithFacebook.bind(this);
    this.authWithEmailPassword= this.authWithEmailPassword.bind(this);
    this.state = {
      redirect: false
    }
  }
  authWithFacebook(){
    firebase.auth().signInWithPopup(provider)
      .then((result, error) => {
        if(error){
          console.log(error);
          this.toaster.show({intend: Intent.DANGER, message: "kann nicht mit Facebook einloggen"})
;
      }else{
          this.setState({
            redirect: true
          })
      }
    })
  };

  authWithEmailPassword(event){
    event.preventDefault();
    const email = this.emailInput.value;
    const password = this.passwordInput.value;
    firebase.auth().fetchProvidersForEmail(email)
      .then((providers)=>{
        if(providers.length === 0){
          //Benutzer Account erstellen
          return firebase.auth.createUserWithEmailAndPassword(email, password)

        } else if (providers.indexOf("password") === -1 ){
          //Facebook wird schon benutzt
          this.loginForm.reset()
          this.toaster.show({intend: Intent.WARNING, message: "versuche es mit einem abderen Login"})
        } else {
          // den Benutzer Einloggen
          return firebase.auth().signInWithEmailAndPassword(email, password)
        }
      })
      .then((user => {
        if(user && user.email){
        this.loginForm.reset();
        this.setState({
          redirect: true
        })
      }}))
      .catch((error) => {
        this.toaster.show({intend: Intent.DANGER, message: error.message})
      })
  }

    render(){
      if (this.state.redirect === true){
        return <Redirect to='/' />
      }
      return (

      <div style={loginStyles}>
        <Toaster ref={(element) => {this.toaster = element}} />
          <div >
            <Col  xs={12} md={12}>
              <Button style={{width: "100%", marginTop: "10px"}} bsStyle="primary" onClick={()=> {this.authWithFacebook() }}>
                Log-In mit Facebook
              </Button>
            </Col>
          </div>
          <Col xs={12} md={12}>
            <hr/>
          </Col>
          <Form onSubmit={(event)=> {this.authWithEmailPassword(event)}} ref={(form) =>{this.loginForm = form}}>
            <FormGroup style={{marginBottom: "20px"}} controlId="formHorizontalEmail">
                <Col  xs={12} md={12}>
                  <FormControl name="email" inputRef={(ref) => { this.emailInput = ref; }} type="email" placeholder="Email" />
                </Col>
              </FormGroup>

              <FormGroup controlId="formHorizontalPassword">
                <Col  xs={12} md={12}>
                  <FormControl name="password" inputRef={(ref) => { this.passwordInput = ref; }} type="password" placeholder="Password" />
                </Col>
              </FormGroup>

              <FormGroup style={{marginTop  : "20px"}} >
                <Col  sm={12}>
                  <Checkbox>Remember me</Checkbox>
                </Col>
              </FormGroup>

              <FormGroup >
                <Col  sm={12}>
                  <Button type="submit">
                    Einloggen
                  </Button>
                </Col>
              </FormGroup>
          </Form>
      </div>
    )
  }
}
;

export default Login;
</code>```

答:
This is incorrect:

```<code>firebase.auth().signInWithPopup(provider)
  .then((result, error) => {
</code>```

It should be:

```<code>firebase.auth().signInWithPopup(provider)
  .then((result) => {
    // Success.
  }, (error) => {
    // Error.
  });
</code>```

Body:
Hello i'm trying to implement an firebase auth to my app. but i does not seem to work. When i Submit the Form or click the Facebook Login it does nothing. I get this error:

Uncaught Error: The error you provided does not contain a stack trace.

Thank you in advance for helping me.

import firebase from 'firebase'

const loginStyles = {
  width: "90%",
  maxWidth: "380px",
  margin: "20px auto",
  border: "1px solid #ddd",
  borderRadius: "5px",
  padding: "10px"
}

const provider = new firebase.auth.FacebookAuthProvider();

class Login extends Component {

  constructor(props){
    super(props);
    this.authWithFacebook= this.authWithFacebook.bind(this);
    this.authWithEmailPassword= this.authWithEmailPassword.bind(this);
    this.state = {
      redirect: false
    }
  }
  authWithFacebook(){
    firebase.auth().signInWithPopup(provider)
      .then((result, error) => {
        if(error){
          console.log(error);
          this.toaster.show({intend: Intent.DANGER, message: "kann nicht mit Facebook einloggen"})
;
      }else{
          this.setState({
            redirect: true
          })
      }
    })
  };

  authWithEmailPassword(event){
    event.preventDefault();
    const email = this.emailInput.value;
    const password = this.passwordInput.value;
    firebase.auth().fetchProvidersForEmail(email)
      .then((providers)=>{
        if(providers.length === 0){
          //Benutzer Account erstellen
          return firebase.auth.createUserWithEmailAndPassword(email, password)

        } else if (providers.indexOf("password") === -1 ){
          //Facebook wird schon benutzt
          this.loginForm.reset()
          this.toaster.show({intend: Intent.WARNING, message: "versuche es mit einem abderen Login"})
        } else {
          // den Benutzer Einloggen
          return firebase.auth().signInWithEmailAndPassword(email, password)
        }
      })
      .then((user => {
        if(user && user.email){
        this.loginForm.reset();
        this.setState({
          redirect: true
        })
      }}))
      .catch((error) => {
        this.toaster.show({intend: Intent.DANGER, message: error.message})
      })
  }

    render(){
      if (this.state.redirect === true){
        return <Redirect to='/' />
      }
      return (

        <Toaster ref={(element) => {this.toaster = element}} />

            <Col  xs={12} md={12}>
              <Button style={{width: "100%", marginTop: "10px"}} bsStyle="primary" onClick={()=> {this.authWithFacebook() }}>
                Log-In mit Facebook
              </Button>
            </Col>

          <Col xs={12} md={12}>

          </Col>
          <Form onSubmit={(event)=> {this.authWithEmailPassword(event)}} ref={(form) =>{this.loginForm = form}}>
            <FormGroup style={{marginBottom: "20px"}} controlId="formHorizontalEmail">
                <Col  xs={12} md={12}>
                  <FormControl name="email" inputRef={(ref) => { this.emailInput = ref; }} type="email" placeholder="Email" />
                </Col>
              </FormGroup>

              <FormGroup controlId="formHorizontalPassword">
                <Col  xs={12} md={12}>
                  <FormControl name="password" inputRef={(ref) => { this.passwordInput = ref; }} type="password" placeholder="Password" />
                </Col>
              </FormGroup>

              <FormGroup style={{marginTop  : "20px"}} >
                <Col  sm={12}>
                  <Checkbox>Remember me</Checkbox>
                </Col>
              </FormGroup>

              <FormGroup >
                <Col  sm={12}>
                  <Button type="submit">
                    Einloggen
                  </Button>
                </Col>
              </FormGroup>
          </Form>

    )
  }
}
;

export default Login;

Body:
This is incorrect:

firebase.auth().signInWithPopup(provider)
  .then((result, error) => {

It should be:

firebase.auth().signInWithPopup(provider)
  .then((result) => {
    // Success.
  }, (error) => {
    // Error.
  });


问:
Spring - creating @Bean based on @Service with @Autowired field causes NullPointerException on @Autowired field
I have following Context:

```<code>@Configuration
@ComponentScan
public class MyContext {

    @Bean
    public Logger getLogger() {
        return LoggerFactory.getLogger(MyContext.class);
    }

    @Bean
    @Autowired
    public RequestSpecification getRequestSpecification(RestServiceImpl restService) {
        return restService.getService();
    }
}
</code>```

My inside my service I have @Autowired field (Logger):

```<code>@Service
public class RestServiceImpl {

      @Autowired
      Logger logger;
}
</code>```

And now the problem comes. When I am trying to reuse my RequestSpecification in other service:

```<code>@Service
public class RequestWrapperForMyEndpoint {
    @Value("${rest.service.url}")
    private String SERVICE_URL;

    @Autowired
    private RequestSpecification restService;
}
</code>```

I am running into NullPointerException. Because Logger is not injected into RestServiceImpl class.

What is the reason?

答:
My very simple answer to your specific problem would be: Do NOT inject a logger.

```<code>@Service
public class RestServiceImpl {
      private static Logger logger = LoggerFactory.getLogger(RestServiceImpl.class);
}
</code>```

Argument #1: Whatever you log inside a class, should be done with a logger of that class. You should NOT log from within RestServiceImpl with a logger which was initialized from MyContext. There is no point in reducing the number of loggers. There should be one logger per class and it would not affect your performance, since creating loggers is very cheap.

Argument #2: What's not quite as cheap as instantiating a logger is autowiring a bean. Autowiring / and maybe having an auto-generated proxy bean in between is quite expensive.

Argument #3: One might argue that it is good design to autowire EVERYTHING. Then you could still argue - YES, everything but objects which do not depend on anything else. And a logger is one of those exceptions. It does not depend on anything else by definition.

Sorry - but I don't have any good idea for your actual autowiring problem.

Body:
I have following Context:

@Configuration
@ComponentScan
public class MyContext {

    @Bean
    public Logger getLogger() {
        return LoggerFactory.getLogger(MyContext.class);
    }

    @Bean
    @Autowired
    public RequestSpecification getRequestSpecification(RestServiceImpl restService) {
        return restService.getService();
    }
}

My inside my service I have @Autowired field (Logger):

@Service
public class RestServiceImpl {

      @Autowired
      Logger logger;
}

And now the problem comes. When I am trying to reuse my RequestSpecification in other service:

@Service
public class RequestWrapperForMyEndpoint {
    @Value("${rest.service.url}")
    private String SERVICE_URL;

    @Autowired
    private RequestSpecification restService;
}

I am running into NullPointerException. Because Logger is not injected into RestServiceImpl class.

What is the reason?

Body:
My very simple answer to your specific problem would be: Do NOT inject a logger.

@Service
public class RestServiceImpl {
      private static Logger logger = LoggerFactory.getLogger(RestServiceImpl.class);
}

Argument #1: Whatever you log inside a class, should be done with a logger of that class. You should NOT log from within RestServiceImpl with a logger which was initialized from MyContext. There is no point in reducing the number of loggers. There should be one logger per class and it would not affect your performance, since creating loggers is very cheap.

Argument #2: What's not quite as cheap as instantiating a logger is autowiring a bean. Autowiring / and maybe having an auto-generated proxy bean in between is quite expensive.

Argument #3: One might argue that it is good design to autowire EVERYTHING. Then you could still argue - YES, everything but objects which do not depend on anything else. And a logger is one of those exceptions. It does not depend on anything else by definition.

Sorry - but I don't have any good idea for your actual autowiring problem.


问:
playing with java Operators (XOR and AND/OR)
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

```<code> // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }
</code>```

2.

```<code>  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }
</code>```

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

答:
simply:</p>

```<code>  if (isCorrect(a) == isCorrect(b))
  {
       // a AND b are both correct or incorrect
  } else {
      // a OR b is incorrect

  }
</code>```

Body:
In a program I am trying to check two boolean values (returned from a function); the condition that needs to be checked is:

- only if any one of the returned value is true and the other is false then I have a problem;

- else if both are true or false I am good to go to next step.

Which of the following two examples would be the efficient way to check the condition, or is there a better solution?

a and b are integer values on which I am checking a condition for correctness in isCorrect function and it return true or false.

1.

 // checking for the correctness of both a and b
 if ((isCorrect(a) && !isCorrect(b)) ||
     (!isCorrect(a) && isCorrect(b)))
 {
   // a OR b is incorrect
 }
 else
 {
   // a AND b are both correct or incorrect
 }

2.

  // checking for the correctness of both a and b
  if (! (isCorrect(a) ^ isCorrect(b)))
  {
    // a OR b is incorrect
  }
  else
  {
    // a AND b are correct or incorrect
  }

Thanks,

Ivar

P.S: code readability is not an issue.
EDIT: I meant to have an XOR in the second option.
Also, I agree with the == and != options, but what if I had to use boolean operators?

Body:
simply:

  if (isCorrect(a) == isCorrect(b))
  {
       // a AND b are both correct or incorrect
  } else {
      // a OR b is incorrect

  }


问:
Drools XStream in a spring service
I'm starting to work with drools , I wanted to use it in spring-boot service, but even for a simple example I 've got a no such method error on Xstream. What did I miss?</p>

```<code>  Caused by: java.lang.NoSuchMethodError: com.thoughtworks.xstream.XStream.setupDefaultSecurity(Lcom/thoughtworks/xstream/XStream;)V
        at org.kie.internal.xstream.XStreamUtils.internalCreateXStream(XStreamUtils.java:58)
        at org.kie.internal.xstream.XStreamUtils.createXStream(XStreamUtils.java:38)
        at org.drools.compiler.kproject.models.KieModuleModelImpl$kModuleMarshaller.<init>(KieModuleModelImpl.java:170)
        at org.drools.compiler.kproject.models.KieModuleModelImpl$kModuleMarshaller.<init>(KieModuleModelImpl.java:169)
        at org.drools.compiler.kproject.models.KieModuleModelImpl.<clinit>(KieModuleModelImpl.java:167)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.fetchKModule(ClasspathKieProject.java:179)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.fetchKModule(ClasspathKieProject.java:141)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.discoverKieModules(ClasspathKieProject.java:112)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.init(ClasspathKieProject.java:84)
        at org.drools.compiler.kie.builder.impl.KieContainerImpl.<init>(KieContainerImpl.java:142)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.newKieClasspathContainer(KieServicesImpl.java:135)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:101)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:79)
</code>```

答:
```<code>|  \- org.drools:drools-decisiontables:jar:7.4.1.Final:compile
[INFO] |     +- (org.drools:drools-core:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     +- org.drools:drools-compiler:jar:7.4.1.Final:compile
[INFO] |     |  +- (org.drools:drools-core:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.kie:kie-api:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.kie:kie-internal:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.uberfire:uberfire-maven-support:jar:1.4.0.Final:compile - omitted for duplicate)
[INFO] |     |  +- org.antlr:antlr-runtime:jar:3.5.2:compile
[INFO] |     |  +- org.eclipse.jdt.core.compiler:ecj:jar:4.4.2:compile
[INFO] |     |  +- (org.mvel:mvel2:jar:2.3.2.Final:compile - omitted for duplicate)
[INFO] |     |  +- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for duplicate)
</code>```

drools need the 1.4.10 version but my maven keep the 1.4.9 version using by eureka ( a netflix solution)

```<code>|  +- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for duplicate)
</code>```

If I force the version 1.4.10, I've got this message

```<code>+- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for conflict with 1.4.10)
</code>```

but it's working....

Title: Drools XStream in a spring service

Body:
I'm starting to work with drools , I wanted to use it in spring-boot service, but even for a simple example I 've got a no such method error on Xstream. What did I miss?

  Caused by: java.lang.NoSuchMethodError: com.thoughtworks.xstream.XStream.setupDefaultSecurity(Lcom/thoughtworks/xstream/XStream;)V
        at org.kie.internal.xstream.XStreamUtils.internalCreateXStream(XStreamUtils.java:58)
        at org.kie.internal.xstream.XStreamUtils.createXStream(XStreamUtils.java:38)
        at org.drools.compiler.kproject.models.KieModuleModelImpl$kModuleMarshaller.<init>(KieModuleModelImpl.java:170)
        at org.drools.compiler.kproject.models.KieModuleModelImpl$kModuleMarshaller.<init>(KieModuleModelImpl.java:169)
        at org.drools.compiler.kproject.models.KieModuleModelImpl.<clinit>(KieModuleModelImpl.java:167)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.fetchKModule(ClasspathKieProject.java:179)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.fetchKModule(ClasspathKieProject.java:141)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.discoverKieModules(ClasspathKieProject.java:112)
        at org.drools.compiler.kie.builder.impl.ClasspathKieProject.init(ClasspathKieProject.java:84)
        at org.drools.compiler.kie.builder.impl.KieContainerImpl.<init>(KieContainerImpl.java:142)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.newKieClasspathContainer(KieServicesImpl.java:135)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:101)
        at org.drools.compiler.kie.builder.impl.KieServicesImpl.getKieClasspathContainer(KieServicesImpl.java:79)

Body:
|  \- org.drools:drools-decisiontables:jar:7.4.1.Final:compile
[INFO] |     +- (org.drools:drools-core:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     +- org.drools:drools-compiler:jar:7.4.1.Final:compile
[INFO] |     |  +- (org.drools:drools-core:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.kie:kie-api:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.kie:kie-internal:jar:7.4.1.Final:compile - omitted for duplicate)
[INFO] |     |  +- (org.uberfire:uberfire-maven-support:jar:1.4.0.Final:compile - omitted for duplicate)
[INFO] |     |  +- org.antlr:antlr-runtime:jar:3.5.2:compile
[INFO] |     |  +- org.eclipse.jdt.core.compiler:ecj:jar:4.4.2:compile
[INFO] |     |  +- (org.mvel:mvel2:jar:2.3.2.Final:compile - omitted for duplicate)
[INFO] |     |  +- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for duplicate)

drools need the 1.4.10 version but my maven keep the 1.4.9 version using by eureka ( a netflix solution)

|  +- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for duplicate)

If I force the version 1.4.10, I've got this message

+- (com.thoughtworks.xstream:xstream:jar:1.4.9:compile - version managed from 1.4.10; omitted for conflict with 1.4.10)

but it's working....


问:
MySQL Variables in Eloquent Query
I have a question about Eloquent Builder in Laravel

```<code>$query = EntryUserVote::query()
                      ->join('users', 'challenge_entry.user_id', '=', 'users.id')
                      ->groupBy(['user_id'])
                      ->select([
                          'users.id as user_id',
                          'users.name as username',
                          DB::raw('count(*) AS amount'),
                          DB::raw("@row := @row + 1 as position")
                      ])
                      ->orderBy('amount', 'desc');
</code>```

I have that Query in my repo and I need to basically add a "rank" which is what that position variable refers to, but I need to know how to initialize the variable in Eloquent. Doesn't make sense to do a from call since I'm already defining the table through the Eloquent Model...

How would you guys do this? A seperate SET statement?

答:
You can intialize the variable using the set keyword in a raw statement :

```<code>DB::statement(DB::raw('set @row=0'));
$query = EntryUserVote::query()
                      ->join('users', 'challenge_entry.user_id', '=', 'users.id')
                      ->groupBy(['user_id'])
                      ->select([
                          'users.id as user_id',
                          'users.name as username',
                          DB::raw('count(*) AS amount'),
                          DB::raw("@row := @row + 1 as position")
                      ])
                      ->orderBy('amount', 'desc');
</code>```

Title: MySQL Variables in Eloquent Query

Body:
I have a question about Eloquent Builder in Laravel

$query = EntryUserVote::query()
                      ->join('users', 'challenge_entry.user_id', '=', 'users.id')
                      ->groupBy(['user_id'])
                      ->select([
                          'users.id as user_id',
                          'users.name as username',
                          DB::raw('count(*) AS amount'),
                          DB::raw("@row := @row + 1 as position")
                      ])
                      ->orderBy('amount', 'desc');

I have that Query in my repo and I need to basically add a "rank" which is what that position variable refers to, but I need to know how to initialize the variable in Eloquent. Doesn't make sense to do a from call since I'm already defining the table through the Eloquent Model...

How would you guys do this? A seperate SET statement?

Body:
You can intialize the variable using the set keyword in a raw statement :

DB::statement(DB::raw('set @row=0'));
$query = EntryUserVote::query()
                      ->join('users', 'challenge_entry.user_id', '=', 'users.id')
                      ->groupBy(['user_id'])
                      ->select([
                          'users.id as user_id',
                          'users.name as username',
                          DB::raw('count(*) AS amount'),
                          DB::raw("@row := @row + 1 as position")
                      ])
                      ->orderBy('amount', 'desc');


问:
Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic
I always get this error message when I run "Ionic start project name":

Error message

```<code>Running command - failed![ERROR] An error occurred while running npm install (exit code 1):

    module.js:471
        throw err;
        ^

    Error: Cannot find module '../lib/utils/unsupported.js'
        at Function.Module._resolveFilename (module.js:469:15)
        at Function.Module._load (module.js:417:25)
        at Module.require (module.js:497:17)
        at require (internal/module.js:20:19)
        at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
        at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:79:3)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
</code>```

答:
In my case it was $NODE_PATH missing:

```<code>NODE="/home/ubuntu/local/node" #here your user account after home
NODE_PATH="/usr/local/lib/node_modules"
PATH="$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$NODE/bin:$NODE/lib/node_modules"
</code>```

To check just echo $NODE_PATH empty means it is not set. Add them to .bashrc is recommended.

Body:
I always get this error message when I run "Ionic start project name":

Error message

Running command - failed![ERROR] An error occurred while running npm install (exit code 1):

    module.js:471
        throw err;
        ^

    Error: Cannot find module '../lib/utils/unsupported.js'
        at Function.Module._resolveFilename (module.js:469:15)
        at Function.Module._load (module.js:417:25)
        at Module.require (module.js:497:17)
        at require (internal/module.js:20:19)
        at /usr/local/lib/node_modules/npm/bin/npm-cli.js:19:21
        at Object.<anonymous> (/usr/local/lib/node_modules/npm/bin/npm-cli.js:79:3)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)

Body:
In my case it was $NODE_PATH missing:

NODE="/home/ubuntu/local/node" #here your user account after home
NODE_PATH="/usr/local/lib/node_modules"
PATH="$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:$NODE/bin:$NODE/lib/node_modules"

To check just echo $NODE_PATH empty means it is not set. Add them to .bashrc is recommended.


问:
How to import the pickle file if sacred failed to connect to MongoDB
The experiment software sacred was run without MongoDB in the background with a configured mongo-observer. When it tried to write the settings to MongoDB, this failed, creating the file /tmp/sacred_mongo_fail__eErwU.pickle, with the message

```<code>Warning: saving to MongoDB failed! Stored experiment entry in /tmp/sacred_mongo_fail__eErwU.pickle
Traceback (most recent calls WITHOUT Sacred internals):
  File "/usr/local/lib/python2.7/dist-packages/sacred/observers/mongo.py", line 127, in started_event
    self.run_entry[experiment][sources] = self.save_sources(ex_info)
  File "/usr/local/lib/python2.7/dist-packages/sacred/observers/mongo.py", line 239, in save_sources
    file = self.fs.find_one({filename: abs_path, md5: md5})
  File "/usr/local/lib/python2.7/dist-packages/gridfs/__init__.py", line 261, in find_one
    for f in self.find(filter, *args, **kwargs):
  File "/usr/local/lib/python2.7/dist-packages/gridfs/grid_file.py", line 658, in next
    next_file = super(GridOutCursor, self).next()
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 888, in _send_message_with_response
    server = topology.select_server(selector)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 214, in select_server
    address))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))
ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused
</code>```

How can this pickle file be imported into MongoDB manually?

答:
Load the pickle file,

set the _id,

insert

```<code>db = pymongo.MongoClient().sacred
entry = pickle.load(open('/tmp/sacred_mongo_fail__eErwU.pickle'))
entry['_id'] = list(db.runs.find({}, {"_id": 1}))[-1]['_id']
db.runs.insert_one(entry)
</code>```

This is quick and dirty, depends on the find to list objects in order, and could use Cleanest way to get last item from Python iterator instead of list(...)[-1], but it should work.

Body:
The experiment software sacred was run without MongoDB in the background with a configured mongo-observer. When it tried to write the settings to MongoDB, this failed, creating the file /tmp/sacred_mongo_fail__eErwU.pickle, with the message

Warning: saving to MongoDB failed! Stored experiment entry in /tmp/sacred_mongo_fail__eErwU.pickle
Traceback (most recent calls WITHOUT Sacred internals):
  File "/usr/local/lib/python2.7/dist-packages/sacred/observers/mongo.py", line 127, in started_event
    self.run_entry[experiment][sources] = self.save_sources(ex_info)
  File "/usr/local/lib/python2.7/dist-packages/sacred/observers/mongo.py", line 239, in save_sources
    file = self.fs.find_one({filename: abs_path, md5: md5})
  File "/usr/local/lib/python2.7/dist-packages/gridfs/__init__.py", line 261, in find_one
    for f in self.find(filter, *args, **kwargs):
  File "/usr/local/lib/python2.7/dist-packages/gridfs/grid_file.py", line 658, in next
    next_file = super(GridOutCursor, self).next()
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 888, in _send_message_with_response
    server = topology.select_server(selector)
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 214, in select_server
    address))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))
ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

How can this pickle file be imported into MongoDB manually?

Body:
Load the pickle file,

set the _id,

insert

db = pymongo.MongoClient().sacred
entry = pickle.load(open('/tmp/sacred_mongo_fail__eErwU.pickle'))
entry['_id'] = list(db.runs.find({}, {"_id": 1}))[-1]['_id']
db.runs.insert_one(entry)

This is quick and dirty, depends on the find to list objects in order, and could use Cleanest way to get last item from Python iterator instead of list(...)[-1], but it should work.


问:
Facebook messenger bot callback url curl error 35
I am trying to create a facebook messenger bot. every thing work woth heroku. then i transfer it to my own server. then i got the error "curl errno =35" i tried it with ngrok work fine on the server but not work with my server.

using debian with nginx x and letsencrypt.

the url is preetombot.bddevwork.net

my setting

```<code>server {
    listen 80;
    server_name preetombot.bddevwork.net www.preetombot.bddevwork.net;
    #root /usr/share/nginx/www/preetombot.bddevwork.net;
    #return 301 https://$server_name$request_uri;
    }
server {
    listen 443 default_server ssl http2;
    server_name preetombot.bddevwork.net
www.preetombot.bddevwork.net;
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_certificate /etc/letsencrypt/live/preetombot.bddevwork.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/preetombot.bddevwork.net/privkey.pem;
    ssl_trusted_certificate /test/ca-certs.pem;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM$
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_dhparam /test/dhparam.pem;
    root /usr/share/nginx/www/preetombot.bddevwork.net;
    index index.php index.html index.htm;
    location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_pass http://localhost:5000$request_uri;
            proxy_redirect off;
            proxy_http_version 1.1;
    }
     location ~ /.well-known{
                allow all;
                    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/www;
    }
location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name;
            include fastcgi_params;
            }
}
</code>```

答:
I have multiple secure ports listening within a single server, in this case for FB bot I'm using port 8083.

```<code>upstream botd {
        server application_1:8083 max_fails=3 fail_timeout=30s;
        keepalive 64;
}

server {
    listen 443 default_server;
    listen [::]:443 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    rewrite_log on;
    ssl on;
    server_name _;
    access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log debug;

    ssl_certificate /etc/ssl/techie8.io/api.techie8.io.bundle;
    ssl_certificate_key /etc/ssl/techie8.io/api.techie8.io.key;

    # Botd skill.
        location /botd {

                proxy_redirect off;
                if (!-f $request_filename) {
                        proxy_pass http://botd;
                        break;
                }

        }

    # Techie8 API.
    location / {
            proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;

        #Timeout after 8 hours
        proxy_read_timeout 43200000;
        proxy_connect_timeout 43200000;

            proxy_redirect off;
            if (!-f $request_filename) {
                    proxy_pass http://application;
                    break;
            }
        }

}
</code>```

In Flask App:

```<code>@app.route('/botd', methods=['GET'])
def handle_verification():
    """Handle Token verification."""

    print "Handling Verification."
    if request.args.get('hub.verify_token') == VERIFY_TOKEN:
        print "Verification successful!"
        return request.args.get('hub.challenge')
    else:
        print "Verification failed!"
        return 'Error, wrong validation token'

@app.route('/botd', methods=['POST'])
def handle_messages():
    print "Handling Incoming Messages\n"
    payload = request.get_data()
    print payload
    for sender, message in messaging_events(payload):
        print "Incoming Message from %s: %s" % (sender, message)
        print ("Access Token: %s" % ACCESS_TOKEN)
        send_message(ACCESS_TOKEN, sender, message)
    return "ok"
</code>```

In Facebook WebHook Callback URL I have my host configured:
 https://api.mycompany.io/botd

Body:
I am trying to create a facebook messenger bot. every thing work woth heroku. then i transfer it to my own server. then i got the error "curl errno =35" i tried it with ngrok work fine on the server but not work with my server.

using debian with nginx x and letsencrypt.

the url is preetombot.bddevwork.net

my setting

server {
    listen 80;
    server_name preetombot.bddevwork.net www.preetombot.bddevwork.net;
    #root /usr/share/nginx/www/preetombot.bddevwork.net;
    #return 301 https://$server_name$request_uri;
    }
server {
    listen 443 default_server ssl http2;
    server_name preetombot.bddevwork.net
www.preetombot.bddevwork.net;
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_certificate /etc/letsencrypt/live/preetombot.bddevwork.net/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/preetombot.bddevwork.net/privkey.pem;
    ssl_trusted_certificate /test/ca-certs.pem;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:ECDHE-RSA-AES128-GCM-SHA256:AES256+EECDH:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM$
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_dhparam /test/dhparam.pem;
    root /usr/share/nginx/www/preetombot.bddevwork.net;
    index index.php index.html index.htm;
    location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For
$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_pass http://localhost:5000$request_uri;
            proxy_redirect off;
            proxy_http_version 1.1;
    }
     location ~ /.well-known{
                allow all;
                    }

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/www;
    }
location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name;
            include fastcgi_params;
            }
}

Body:
I have multiple secure ports listening within a single server, in this case for FB bot I'm using port 8083.

upstream botd {
        server application_1:8083 max_fails=3 fail_timeout=30s;
        keepalive 64;
}

server {
    listen 443 default_server;
    listen [::]:443 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    rewrite_log on;
    ssl on;
    server_name _;
    access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log debug;

    ssl_certificate /etc/ssl/techie8.io/api.techie8.io.bundle;
    ssl_certificate_key /etc/ssl/techie8.io/api.techie8.io.key;

    # Botd skill.
        location /botd {

                proxy_redirect off;
                if (!-f $request_filename) {
                        proxy_pass http://botd;
                        break;
                }

        }

    # Techie8 API.
    location / {
            proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;

        #Timeout after 8 hours
        proxy_read_timeout 43200000;
        proxy_connect_timeout 43200000;

            proxy_redirect off;
            if (!-f $request_filename) {
                    proxy_pass http://application;
                    break;
            }
        }

}

In Flask App:

@app.route('/botd', methods=['GET'])
def handle_verification():
    """Handle Token verification."""

    print "Handling Verification."
    if request.args.get('hub.verify_token') == VERIFY_TOKEN:
        print "Verification successful!"
        return request.args.get('hub.challenge')
    else:
        print "Verification failed!"
        return 'Error, wrong validation token'

@app.route('/botd', methods=['POST'])
def handle_messages():
    print "Handling Incoming Messages\n"
    payload = request.get_data()
    print payload
    for sender, message in messaging_events(payload):
        print "Incoming Message from %s: %s" % (sender, message)
        print ("Access Token: %s" % ACCESS_TOKEN)
        send_message(ACCESS_TOKEN, sender, message)
    return "ok"

In Facebook WebHook Callback URL I have my host configured:
 https://api.mycompany.io/botd


问:
Appium Python sun/misc/BASE64Encoder
i try to test my mobile application with Appium.
I wrote a function test in python.
When i run the test i have this error.

in setup at line :  self.driver = webdriver.Remote(xxxx)
  selenium.common.exceptions.WebDriverException: Message: A new session could not be created
  Exception in thread "main" java.lang.NoClassDefFoundError: sun/misc/BASE64Encoder

the size of the apk past xxK0 to 0ko ???

答: Without code sample there is no much help you can get. Take a look at official code samples in python and make sure you run setup server and capabilities in a proper way

Title: Appium Python sun/misc/BASE64Encoder


问:
How to remove the blank space at the top of a grouped UITableView?
When you create a UITableView with the UITableViewStyleGrouped style, it adds quite a lot of space in between the actual tableviewcells and the borders of the table's frame.  This space is above, below, to the left, and to the right of the tableviewcells.

You can change the space between tableviewcells themselves by:

```<code>[myTableView setSectionHeaderHeight:0];
[myTableView setSectionFooterHeight:25];
</code>```

However, even by doing that, there's still this annoying space between the top of the frame and the first tableviewcell.  Furthermore, there's a ton of space still in between the left of the frame and the tableviewcell, as well as the right side of the frame and the tableviewcell.

-=-=-=-=-=-=-

Is there a way to manipulate that space (resize it)?  My only solution thus far is to make the size of the frame larger than the screen to fake out the program into having that "blank space" outside of the screen, thus removing it.  However, this is obviously not optimal and a clear hack.

答:
You need to set footer too</p>

```<code>-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
  return [[UIView alloc] initWithFrame:CGRectZero];
}
</code>```

Body:
When you create a UITableView with the UITableViewStyleGrouped style, it adds quite a lot of space in between the actual tableviewcells and the borders of the table's frame.  This space is above, below, to the left, and to the right of the tableviewcells.

You can change the space between tableviewcells themselves by:

[myTableView setSectionHeaderHeight:0];
[myTableView setSectionFooterHeight:25];

However, even by doing that, there's still this annoying space between the top of the frame and the first tableviewcell.  Furthermore, there's a ton of space still in between the left of the frame and the tableviewcell, as well as the right side of the frame and the tableviewcell.

-=-=-=-=-=-=-

Is there a way to manipulate that space (resize it)?  My only solution thus far is to make the size of the frame larger than the screen to fake out the program into having that "blank space" outside of the screen, thus removing it.  However, this is obviously not optimal and a clear hack.

Body:
You need to set footer too

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
  return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
  return [[UIView alloc] initWithFrame:CGRectZero];
}