问:
Ionic2, how to import custom plugin (appsee or uxcam) into Ionic App
I am trying to use Appsee or UXcam

I tried import like below, but no luck
// import { Appsee } from '@ionic-native/appsee';

Else where i saw that you have to declare the variable in question for typescript to recognize the variable, I did that like below

declare var cordova:any;

```<code>// import { Appsee } from '@ionic-native/appsee';

declare var cordova:any;

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  rootPage:any = LoginPage;       // FOR TESTING

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
    cordova.plugins.Appsee.start("my key");

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}
</code>```

I've also tried adding public appsee: Appsee to the constructor but still no luck.

Any guidance is appreciated. I'm getting ReferenceError: cordova is not defined.

How do I import a custom plugin, appsee

edit adding suggested code
declare var Appsee:any;

```<code>@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = LoginPage;       // FOR TESTING

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
    Appsee.start("my key");

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}
</code>```

答:
You just need to put it under the imports as shown below.

```<code>//your other imports here

declare var Appsee:any;

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;
</code>```

Body:
I am trying to use Appsee or UXcam

I tried import like below, but no luck
// import { Appsee } from '@ionic-native/appsee';

Else where i saw that you have to declare the variable in question for typescript to recognize the variable, I did that like below

declare var cordova:any;

// import { Appsee } from '@ionic-native/appsee';

declare var cordova:any;

@Component({
  templateUrl: 'app.html'
})
export class MyApp {

  rootPage:any = LoginPage;       // FOR TESTING

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
    cordova.plugins.Appsee.start("my key");

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

I've also tried adding public appsee: Appsee to the constructor but still no luck.

Any guidance is appreciated. I'm getting ReferenceError: cordova is not defined.

How do I import a custom plugin, appsee

edit adding suggested code
declare var Appsee:any;

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = LoginPage;       // FOR TESTING

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
    platform.ready().then(() => {
    Appsee.start("my key");

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

Body:
You just need to put it under the imports as shown below.

//your other imports here

declare var Appsee:any;

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;


来源: stackexchange

问:
Rounded divs/buttons on iOS only??? jQuery, ajax, css
I've been working on a client that consumes an API and dynamically creates buttons. Everything works great on every platform, chrome dev tools show nothing out of the ordinary on every "device." I threw it up on AWS to test it on actual devices. Works/looks as expected on everything except on iOS (iphone and ipad) the divs/buttons are being rounded. Has anyone else seen this problem? Better yet know how to fix it? Here's the link:

https://s3.us-east-2.amazonaws.com/rpjr/GitHubAPI/index.html

答:
iOS is applying default browser styles to your <button> elements (not div).

Add this CSS rule to fix it:

```<code>.tapMe {
  -webkit-appearance: none;
}
</code>```

If this still doesn't fix the rounded edges, add border-radius: 0 to that element.

ContentLicense: CC BY-SA 3.0

Body:
iOS is applying default browser styles to your <button> elements (not div).

Add this CSS rule to fix it:

.tapMe {
  -webkit-appearance: none;
}

If this still doesn't fix the rounded edges, add border-radius: 0 to that element.


问:
How to import an saved Tensorflow model train using tf.estimator and predict on input data
I have save the model using tf.estimator .method export_savedmodel as follows:

```<code>export_dir="exportModel/"

feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)

input_receiver_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)

classifier.export_savedmodel(export_dir, input_receiver_fn, as_text=False, checkpoint_path="Model/model.ckpt-400")
</code>```

How can I import this saved model and use for predictions?

答:
You need to export the saved model using  tf.contrib.export_savedmodel and you need to define input receiver function to pass input to.
  Later you can load the saved model ( generally saved.model.pb) from the disk and serve it.

TensorFlow: How to predict from a SavedModel?

Body:
I have save the model using tf.estimator .method export_savedmodel as follows:

export_dir="exportModel/"

feature_spec = tf.feature_column.make_parse_example_spec(feature_columns)

input_receiver_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)

classifier.export_savedmodel(export_dir, input_receiver_fn, as_text=False, checkpoint_path="Model/model.ckpt-400")

How can I import this saved model and use for predictions?


问:
In Java, can the this/super keywords represent anything other than classes/enums?
I've noticed that:

```<code>class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}
</code>```

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

答:
Your anonymous class always extends another class.  Even if you explicitly implement an interface, you are extending java.lang.Object and you can only call methods of java.lang.Object via super calls.

```<code>Runnable r = new Runnable() {
    public void run() {
        super.run(); // Error: run() is not a method of java.lang.Object
        super.toString(); // OK: toString() is inherited from java.lang.Object
    }
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I've noticed that:

class A {
    ClassB b = new ClassB() { // anonymous class
        /* some expression using this */
    }
}

Whenever I use the this keyword inside an anonymous class, the this refers to the enclosing outer class/enum and not to the anonymous class.

Does this mean this can never represent an anonymous class? Just "normal" classes and enums?

Also, can this or super represent an interface?

Body:
Your anonymous class always extends another class.  Even if you explicitly implement an interface, you are extending java.lang.Object and you can only call methods of java.lang.Object via super calls.

Runnable r = new Runnable() {
    public void run() {
        super.run(); // Error: run() is not a method of java.lang.Object
        super.toString(); // OK: toString() is inherited from java.lang.Object
    }
};


问:
Pandas to get multiple column values when a variable matches another column value that is repeated
I have a dataframe :

```<code>A   |  B
1     123
2     321
1     456
2     999
1     888
3     333
2     422
</code>```

I have a variable x that contains (1,2,3) so when i match it to column A with variable x being 1 it should give me:

```<code>123
456
888
</code>```

the code i am using right now is:

```<code>df.loc(df[A] == x, 'B').iloc[0]
</code>```

This gives me only 123.

P.S : I would like to add these values in a list.

Body:
I have a dataframe :

A   |  B
1     123
2     321
1     456
2     999
1     888
3     333
2     422

I have a variable x that contains (1,2,3) so when i match it to column A with variable x being 1 it should give me:

123
456
888

the code i am using right now is:

df.loc(df[A] == x, 'B').iloc[0]

This gives me only 123.

P.S : I would like to add these values in a list.

Body:
df.loc[df['A'] == x, 'B']

or

df[df['A'] == x]['B']


问:
Creating an Array with multiple arrays within the array
I was wondering how you create an array with multiple arrays inside as I already have the created arrays which you can see bellow in the code. But I want to put those array in side of an array called "Patients". while more so all the index of 1 in the following array Name, age, Etc can be seen under index 1 of Patients. Thank you

Public Class DataEntry

```<code>Dim Patients()

Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)
</code>```

答:
```<code>    BIM = FormatNumber(Val(txtWeight.Text) / Val((txtHeight.Text / 1000) ^ 2))

    If BIM < 18.5 Then
        Health = "Underweigth"
    ElseIf BIM > 18.5 And BIM < 24.9 Then
        Health = "Healthy Weight"
    ElseIf BIM > 24.9 And BIM < 29.9 Then
        Health = "Overweight"
    ElseIf BIM > 29.9 And BIM < 39.9 Then
        BIM = "Obese"
    ElseIf BIM > 40 Then
        Health = "Morbidly Obese"
    End If

    Dim p As Patient = New Patient()
    p.FirstName = txtFirst.Text
    p.SurName = txtSur.Text
    p.Age = txtAge.Text
    p.Height = txtHeight.Text
    p.Weight = txtWeight.Text

    Dim textAppend As String

    textAppend = "  " & p.SurName & ", " + p.FirstName & ", " + "Age: " & p.Age & ",  " + "Height: " & p.Height & "mm" & ",  " + "Weight: " & p.Weight & "kg" & "  ," + BIM & " = " & Health & "."

    Try
        File.AppendAllText(filepath, textAppend)
        MsgBox("Patient Added Successfully")
    Catch ex As Exception
        MsgBox("Error Adding Patient")
    End Try
</code>```

Body:
I was wondering how you create an array with multiple arrays inside as I already have the created arrays which you can see bellow in the code. But I want to put those array in side of an array called "Patients". while more so all the index of 1 in the following array Name, age, Etc can be seen under index 1 of Patients. Thank you

Public Class DataEntry

Dim Patients()

Dim Surname(200)
Dim Firstname(200)
Dim Age(200) As String
Dim HeightA(200) As String
Dim Weight(200)


问:
Trigger automation if certain merge fields are completed?
I'm looking to trigger an automation if the user enters additional information about themselves (i.e. Date of Birth and State).

Is it possible to trigger an automation if the user adds these details and updates in the Preference Centre?

Mailchimp only allows a trigger on a specific merge field value whereas I want to trigger an automation for Merge Field Value = NOT EMPTY.

答:
This is not an ideal solution but just a trick that I used to get around it.

You can add an additional field called 'StateAvailable' or 'DOBAvailable' or something else on those lines and then set up your list import such that this field is set to TRUE/FALSE after updating. You can then use this as a trigger for your campaign.


问:
how to get text outside in HTML JS
```<code><ul class="select2-selection__rendered">
  <li class="select2-selection__choice" title="List"><span class="select2-selection__choice__remove" role="presentation">×</span>**List**</li>
  <li class="select2-search select2-search--inline">
    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">
  </li>
</ul>
</code>```

Thats the code ..

I want to get text "List" which I bold .

```<code>alert( $("ul > li > .select2-selection__choice").text() );
</code>```

still can't get the text .
Thanks

答:
Fix

```<code>alert( $("ul > li > .select2-selection__choice").text() );
</code>```

to

```<code>$("ul > li.select2-selection__choice")[0].childNodes[1].textContent // **List**
</code>```

If you just want List, then it should be:

```<code>$("ul > li.select2-selection__choice")[0].childNodes[1].textContent.match(/List/g)[0]; // List
</code>```

Title: how to get text outside in HTML JS

Body:
×**List**

    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">

Thats the code ..

I want to get text "List" which I bold .

alert( $("ul > li > .select2-selection__choice").text() );

still can't get the text .
Thanks

Body:
Fix

alert( $("ul > li > .select2-selection__choice").text() );

to

$("ul > li.select2-selection__choice")[0].childNodes[1].textContent // **List**

If you just want List, then it should be:

$("ul > li.select2-selection__choice")[0].childNodes[1].textContent.match(/List/g)[0]; // List


问:
Arguments passed into for loop in bash script
I am trying to pass the argument as max limit for the for loop like this:

```<code>#!/bin/bash

for i in {1..$1}
do
    echo $i
done
</code>```

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

```<code>1
2
</code>```

答:
As well as John Kugelman's solution, you can use eval like this:

```<code>x=10; for i in $(eval echo {1..$x}); do echo $i; done
</code>```

Or, if $1 is 10, then:

```<code>set -- 10
for i in $(eval echo {1..$1})
do
    echo $i
done
</code>```

You could also use some variants on:

```<code>set -- 1000
eval echo {1..$1} |
while read i
do
    echo $i
done
</code>```

Or:

```<code>set -- 1000
while read i
do
     echo $i
done <(eval echo {1..$1})
</code>```

That uses process substitution.

Body:
I am trying to pass the argument as max limit for the for loop like this:

#!/bin/bash

for i in {1..$1}
do
    echo $i
done

This however returns {1..2} when called with argument 2, instead of executing the script and giving me

1
2

Body:
As well as John Kugelman's solution, you can use eval like this:

x=10; for i in $(eval echo {1..$x}); do echo $i; done

Or, if $1 is 10, then:

set -- 10
for i in $(eval echo {1..$1})
do
    echo $i
done

You could also use some variants on:

set -- 1000
eval echo {1..$1} |
while read i
do
    echo $i
done

Or:

set -- 1000
while read i
do
     echo $i
done <(eval echo {1..$1})

That uses process substitution.


问:
Oracle sql - Selecting the difference between two sums from two different tables?
Say I have two tables, which I want to calculate their sum differences:

```<code>company1(
id INTEGER,
salary INTEGER
)

company2(
id INTEGER,
salary INTEGER
)
</code>```

How can I select the difference between their SUM(salary) from each of their employees using only one select query?

For example:

```<code>SELECT
(SELECT SUM(company1.salary) FROM company1 GROUP BY id) - (SELECT SUM(company2.salary) FROM company2 GROUP BY id) as diff_between_pay
</code>```

The end results would be like:

```<code>company1
id   salary
1    40000
2    20000
3    50000

company2
id   salary
1    30000
2    15000
3    25000

end result differences:
id
1    10000
2    5000
3    25000
</code>```

答:
You can do this in a select:

```<code>select (select sum(salary) from company1) - (select sum(salary) from company2) as diff_between_pay
from dual;
</code>```

For your revised question, use a full join:

```<code>select ( coalesce(c1.sums, 0) - coalesce(c2.sums, 0) ) as diff_between_pay
from (select id, sum(salary) as sums
      from company1
      group by id
     ) c1 full join
     (select id, sum(salary) as sums
      from company2
      group by id
     ) c2
     on c1.id = c2.id;
</code>```

Body:
Say I have two tables, which I want to calculate their sum differences:

company1(
id INTEGER,
salary INTEGER
)

company2(
id INTEGER,
salary INTEGER
)

How can I select the difference between their SUM(salary) from each of their employees using only one select query?

For example:

SELECT
(SELECT SUM(company1.salary) FROM company1 GROUP BY id) - (SELECT SUM(company2.salary) FROM company2 GROUP BY id) as diff_between_pay

The end results would be like:

company1
id   salary
1    40000
2    20000
3    50000

company2
id   salary
1    30000
2    15000
3    25000

end result differences:
id
1    10000
2    5000
3    25000

Body:
You can do this in a select:

select (select sum(salary) from company1) - (select sum(salary) from company2) as diff_between_pay
from dual;

For your revised question, use a full join:

select ( coalesce(c1.sums, 0) - coalesce(c2.sums, 0) ) as diff_between_pay
from (select id, sum(salary) as sums
      from company1
      group by id
     ) c1 full join
     (select id, sum(salary) as sums
      from company2
      group by id
     ) c2
     on c1.id = c2.id;


问:
How to style images and side bar
The layout I'm trying to create: Layout

Current fiddle of what I have: full page

As you can see the page is responsive and works the way its suppose to for now.

I would like some insight on how to style this page the way it is drawn in the image.

Current image container css (which is basically repeated with either 6 images or 3 images. When it comes to the 3 image display, one image takes up 50% of the container, while the other two takes up 25% each.)

```<code>.aestheticsDisplay {
margin: 0 auto;
}

.imageGrid {
margin: 20px 0 0 0;
padding: 0;
list-style: ;
display: inline;
text-align: center;
float:none;
}

.imageGrid:after {
    clear: both;
}

.imageGrid:after, .aestheticsBox:before {
    display: table;
}

.imageGrid li {
    width: 400px;
    height: 400px;
    display: inline-grid;
    margin: 20px;
  float: none;

}

.aestheticsBox {
    width: 100%;
    height: 100%;
     position: inherit;
     cursor: pointer;
border-radius: 10px;
-webkit-transition: 0.3s ease-in-out,
-webkit-transform 0.3s ease-in-out;
-moz-transition:  0.3s ease-in-out,
-moz-transform 0.3s ease-in-out;
transition: all 0.3s ease-in-out,
transform 0.3s ease-in-out;
}

.aestheticsBox:hover {
transform: scale(1.05);
}

.displayImg-1 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-2 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-3 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-4 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-5 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}
.displayImg-6 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}
</code>```

As for the Navigator

```<code>.nav-container {
/* flex-basis: 30%; */
padding-top: 500px;

}

.navigation {
   width: 150px;
   }

.mainmenu, .submenu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.mainmenu a {
  display: block;
  background-color: #fff;
  text-decoration: none;
  padding: 10px;
  color: #000;
}

.mainmenu a:hover {
    background-color: #rainbow;
}

.mainmenu li:hover .submenu {
  display: block;
  max-height: 200px;
}

.submenu a {
  background-color: #fff;
}

.submenu a:hover {
  background-color: #fff;
}

.submenu {
  overflow: hidden;
  max-height: 0;
  -webkit-transition: all 0.5s ease-out;
}
</code>```

All help is very much appreciated.

答: Don't use  auto in margin it will solve your problem</p>

Title: How to style images and side bar

Body:
The layout I'm trying to create: Layout

Current fiddle of what I have: full page

As you can see the page is responsive and works the way its suppose to for now.

I would like some insight on how to style this page the way it is drawn in the image.

Current image container css (which is basically repeated with either 6 images or 3 images. When it comes to the 3 image display, one image takes up 50% of the container, while the other two takes up 25% each.)

.aestheticsDisplay {
margin: 0 auto;
}

.imageGrid {
margin: 20px 0 0 0;
padding: 0;
list-style: ;
display: inline;
text-align: center;
float:none;
}

.imageGrid:after {
    clear: both;
}

.imageGrid:after, .aestheticsBox:before {
    display: table;
}

.imageGrid li {
    width: 400px;
    height: 400px;
    display: inline-grid;
    margin: 20px;
  float: none;

}

.aestheticsBox {
    width: 100%;
    height: 100%;
     position: inherit;
     cursor: pointer;
border-radius: 10px;
-webkit-transition: 0.3s ease-in-out,
-webkit-transform 0.3s ease-in-out;
-moz-transition:  0.3s ease-in-out,
-moz-transform 0.3s ease-in-out;
transition: all 0.3s ease-in-out,
transform 0.3s ease-in-out;
}

.aestheticsBox:hover {
transform: scale(1.05);
}

.displayImg-1 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-2 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-3 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-4 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

.displayImg-5 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}
.displayImg-6 {
background: linear-gradient( rgba(0, 0, 0, 0.50), rgba(0, 0, 0, 0.10)),
url("../imgs/nick_1.jpg");
}

As for the Navigator

.nav-container {
/* flex-basis: 30%; */
padding-top: 500px;

}

.navigation {
   width: 150px;
   }

.mainmenu, .submenu {
  list-style: none;
  padding: 0;
  margin: 0;
}

.mainmenu a {
  display: block;
  background-color: #fff;
  text-decoration: none;
  padding: 10px;
  color: #000;
}

.mainmenu a:hover {
    background-color: #rainbow;
}

.mainmenu li:hover .submenu {
  display: block;
  max-height: 200px;
}

.submenu a {
  background-color: #fff;
}

.submenu a:hover {
  background-color: #fff;
}

.submenu {
  overflow: hidden;
  max-height: 0;
  -webkit-transition: all 0.5s ease-out;
}

All help is very much appreciated.


问:
Can iterators be reset in Python?
Can I reset an iterator / generator in Python?  I am using DictReader and would like to reset it to the beginning of the file.</p>

答:
For small files, you may consider using more_itertools.seekable - a third-party tool that offers resetting iterables.

Demo

```<code>import csv

import more_itertools as mit

filename = "data/iris.csv"
with open(filename, "r") as f:
    reader = csv.DictReader(f)
    iterable = mit.seekable(reader)                    # 1
    print(next(iterable))                              # 2
    print(next(iterable))
    print(next(iterable))

    print("\nReset iterable\n--------------")
    iterable.seek(0)                                   # 3
    print(next(iterable))
    print(next(iterable))
    print(next(iterable))
</code>```

Output

```<code>{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}

Reset iterable
--------------
{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}
</code>```

Here a DictReader is wrapped in a seekable object (1) and advanced (2).  The seek() method is used to reset/rewind the iterator to the 0th position (3).

Note: memory consumption grows with iteration, so be wary applying this tool to  large files, as indicated in the docs.

ContentLicense: CC BY-SA 4.0

Title: Can iterators be reset in Python?

Body:
For small files, you may consider using more_itertools.seekable - a third-party tool that offers resetting iterables.

Demo

import csv

import more_itertools as mit

filename = "data/iris.csv"
with open(filename, "r") as f:
    reader = csv.DictReader(f)
    iterable = mit.seekable(reader)                    # 1
    print(next(iterable))                              # 2
    print(next(iterable))
    print(next(iterable))

    print("\nReset iterable\n--------------")
    iterable.seek(0)                                   # 3
    print(next(iterable))
    print(next(iterable))
    print(next(iterable))

Output

{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}

Reset iterable
--------------
{'Sepal width': '3.5', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '5.1', 'Species': 'Iris-setosa'}
{'Sepal width': '3', 'Petal width': '0.2', 'Petal length': '1.4', 'Sepal length': '4.9', 'Species': 'Iris-setosa'}
{'Sepal width': '3.2', 'Petal width': '0.2', 'Petal length': '1.3', 'Sepal length': '4.7', 'Species': 'Iris-setosa'}

Here a DictReader is wrapped in a seekable object (1) and advanced (2).  The seek() method is used to reset/rewind the iterator to the 0th position (3).

Note: memory consumption grows with iteration, so be wary applying this tool to  large files, as indicated in the docs.


问:
Updating values of dynamically created nested UI elements C#
I am new to UWP and C# but I have been tasked with creating a UI that is created dynamically based on an XML file that is read in.

I am having trouble updating values that are nested inside an ObservableCollection.

The current structure uses StackPanels as a container to add UI elements to. The heirarchy looks like this when the elements are created.

```<code>StackPanel = Outermost container panel
-StackPanel = Section Stack panel :implements ObservableCollection
--StackPanel = Entry container panel :implements INotifyPropertyChanged
---StackPanel = Entry inner Wrapper panel :implements INotifyPropertyChanged
---- This is where the UI elements like textboxes live
---- TextBox
---- TextBox
</code>```

I need extract the values of the TextBoxes but they don't ever update from their original value.
I am having trouble finding documentation that points to a good way of doing this kind of thing (usually means it shouldn't really be done haaa) any input would be much appreciated.

答:
You need to do the following:

Read the data from your xml to your ObservableCollection to build a data as base data structure.

Use binding to bind it to your UI elements from your ObservableCollection. By the way, as Peter mentioned, make sure you've already made it twoway binding, in that way the changes from your UI will reflect the data store in memory

Use some ways(for example use a button) to save changes from your UI and then update and save the data in memory to your original xml file.

Some documention can be found from the following:

https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-quickstart

Code Sample:https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XmlDocument

Body:
I am new to UWP and C# but I have been tasked with creating a UI that is created dynamically based on an XML file that is read in.

I am having trouble updating values that are nested inside an ObservableCollection.

The current structure uses StackPanels as a container to add UI elements to. The heirarchy looks like this when the elements are created.

StackPanel = Outermost container panel
-StackPanel = Section Stack panel :implements ObservableCollection
--StackPanel = Entry container panel :implements INotifyPropertyChanged
---StackPanel = Entry inner Wrapper panel :implements INotifyPropertyChanged
---- This is where the UI elements like textboxes live
---- TextBox
---- TextBox

I need extract the values of the TextBoxes but they don't ever update from their original value.
I am having trouble finding documentation that points to a good way of doing this kind of thing (usually means it shouldn't really be done haaa) any input would be much appreciated.


问:
AKNodeOutputPlot increase speed?
I am using AudioKit for an iOS app. Right now everything is working well for me. However I am having trouble customizing the AKNodeOutputPlot animation. When using AKNodeOutputPlot how do you increase its speed? Basically it takes x seconds to fill its view. How can I get it do it in x/2 seconds with a view of the same size?</p>

答:
Sounds like you're using a rolling plot, in which case do:</p>

```<code>plot.setRollingHistoryLength(<#T##historyLength: Int32##Int32#>)
</code>```

Title: AKNodeOutputPlot increase speed?

Body:
Sounds like you're using a rolling plot, in which case do:

plot.setRollingHistoryLength(<#T##historyLength: Int32##Int32#>)


问:
long term session storage (php shopping cart)
this is more of a 'can you point me in the right direction' type of question.

Basically I would like to offer customers a way to 'save' their shopping cart, perhaps to view later with a relative (it's a 'photo basket' for a photographers clients).

When my 'photo basket' is used, it creates a single basket array that is then filled with item arrays.

My idea was --- create a table for each user and then implode each array in the $_SESSION['basket'] to a string and then add this string to a row in the DB. When the user logs back in, their saved basket can then be exploded from the database to form a new basket...

That's my chain of thought (not started this section yet). Just wondered if anyone could spot any obvious flaws and errors I might encounter.

Thanks for any input.

Shane

答: Don't create a table for each user. You can create a single table with a userid and datavalue columns, and save all users' baskets in the one table. Nor do you want to implode... use serialize on the $_SESSION['basket'] before storing it on the database, and unserialize when reading it back from the database</p>


问:
Creating a singly linked list out of an array of integers
I'm having trouble with taking an array of integers and creating a singly linked list with JavaScript. It sounds easy enough, but there's something I'm just not seeing with the function I have an I'd appreciate any help you can provide.

This is the constructor function I use to make nodes:

```<code> function ListNode(val) {
     this.val = val;
     this.next = null;
 }
</code>```

And this is the function I'm writing that is supposed to take an array and create a linked list out of it. The basic idea is just a while loop that shifts off the first value until there's nothing left to shift:

```<code>var createLinkedList = function(array) {
    var head = new ListNode(parseInt(array[0]));
    array.shift();
    while(array.length) {
        var prev = new ListNode(parseInt(array[0]));
        head.next = head;
        prev = head;
        array.shift();
    }
    return head;
}
</code>```

I've tried running this with a couple basic arrays and it always just returns the last value in the array instead of a linked list. Is there something simple I'm just not seeing here? Thanks in advance.

答:
The problem is not with array.shift, but how you link the nodes together inside the while loop.

To chain the nodes together, essentially you need to do:

```<code>var new_node = new ListNode(parseInt(array[0]));
head.next = new_node;
new_node = new ListNode(parseInt(array[1]));
head.next.next = new_node;
new_node = new ListNode(parseInt(array[2]));
head.next.next.next = new_node;
.
.
.
</code>```

I think you get the idea. So what you want to do is rework your while loop, store a reference of the tailNode so instead of calling head.next.next.next.next.next = newNode, you can call tailNode.next = newNode, and tailNode = newNode inside the while loop.

Body:
I'm having trouble with taking an array of integers and creating a singly linked list with JavaScript. It sounds easy enough, but there's something I'm just not seeing with the function I have an I'd appreciate any help you can provide.

This is the constructor function I use to make nodes:

 function ListNode(val) {
     this.val = val;
     this.next = null;
 }

And this is the function I'm writing that is supposed to take an array and create a linked list out of it. The basic idea is just a while loop that shifts off the first value until there's nothing left to shift:

var createLinkedList = function(array) {
    var head = new ListNode(parseInt(array[0]));
    array.shift();
    while(array.length) {
        var prev = new ListNode(parseInt(array[0]));
        head.next = head;
        prev = head;
        array.shift();
    }
    return head;
}

I've tried running this with a couple basic arrays and it always just returns the last value in the array instead of a linked list. Is there something simple I'm just not seeing here? Thanks in advance.

Body:
The problem is not with array.shift, but how you link the nodes together inside the while loop.

To chain the nodes together, essentially you need to do:

var new_node = new ListNode(parseInt(array[0]));
head.next = new_node;
new_node = new ListNode(parseInt(array[1]));
head.next.next = new_node;
new_node = new ListNode(parseInt(array[2]));
head.next.next.next = new_node;
.
.
.

I think you get the idea. So what you want to do is rework your while loop, store a reference of the tailNode so instead of calling head.next.next.next.next.next = newNode, you can call tailNode.next = newNode, and tailNode = newNode inside the while loop.


问:
Unwind Segue with Image
I'm trying to use a unwind Segue with an ImageView. In my main VC I created this function for the unwind segue:

```<code>@IBAction func didUnwindFromSelectIcon(_ sender: UIStoryboardSegue){
    guard let imageSelectionImage = sender.source as? SelectIconViewController else {return}
    addEatImageViewEat.image = imageSelectionImage.img
}
</code>```

Then I use this in my second VC

```<code>var img: UIImage?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let selectedImage = collectionView.cellForItem(at: indexPath) as! SelectIconCollectionViewCell
    img = selectedImage.selectIconImageView.image

}
</code>```

I selected the didUnwindFromSelectIcon at the CollectionViewCell on the Storyboard. I get no error or something and I'm not sure what my mistake is. My addEatImageViewEat won't show my selected Image... Hope someone see what's my mistake - Thanks in advance

Update:

MainVC:

```<code>@IBAction func didUnwindFromSelectIcon(_ sender: UIStoryboardSegue){
    guard let imageSelectionImage = sender.source as? SelectIconViewController else {return}
    addEatImageViewEat.image = imageSelectionImage.img
}
</code>```

SecondVC:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "unwindSegue" {
        if let cell = sender as? SelectIconCollectionViewCell {
            img = cell.selectIconImageView.image
        }
    }
}
</code>```

答:
The problem is that the segue happens before func collectionView(_:didSelectItemAt:) is called.

Instead of using that function, use prepare(for:sender:) to set the image:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "unwindSegue" {
        if let cell = sender as? SelectIconCollectionViewCell {
            img = cell.selectIconImageView.image
        }
    }
}
</code>```

Make sure to set the identifier for your segue and use that in place of "unwindSegue" above.  To set the segue identifier, find the unwind segue in the Document Outline view and select it.  Then in the Attributes Inspector on the right, set the Storyboard Segue Identifier to your identifier.

Title: Unwind Segue with Image

Body:
I'm trying to use a unwind Segue with an ImageView. In my main VC I created this function for the unwind segue:

@IBAction func didUnwindFromSelectIcon(_ sender: UIStoryboardSegue){
    guard let imageSelectionImage = sender.source as? SelectIconViewController else {return}
    addEatImageViewEat.image = imageSelectionImage.img
}

Then I use this in my second VC

var img: UIImage?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let selectedImage = collectionView.cellForItem(at: indexPath) as! SelectIconCollectionViewCell
    img = selectedImage.selectIconImageView.image

}

I selected the didUnwindFromSelectIcon at the CollectionViewCell on the Storyboard. I get no error or something and I'm not sure what my mistake is. My addEatImageViewEat won't show my selected Image... Hope someone see what's my mistake - Thanks in advance

Update:

MainVC:

@IBAction func didUnwindFromSelectIcon(_ sender: UIStoryboardSegue){
    guard let imageSelectionImage = sender.source as? SelectIconViewController else {return}
    addEatImageViewEat.image = imageSelectionImage.img
}

SecondVC:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "unwindSegue" {
        if let cell = sender as? SelectIconCollectionViewCell {
            img = cell.selectIconImageView.image
        }
    }
}

Body:
The problem is that the segue happens before func collectionView(_:didSelectItemAt:) is called.

Instead of using that function, use prepare(for:sender:) to set the image:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "unwindSegue" {
        if let cell = sender as? SelectIconCollectionViewCell {
            img = cell.selectIconImageView.image
        }
    }
}

Make sure to set the identifier for your segue and use that in place of "unwindSegue" above.  To set the segue identifier, find the unwind segue in the Document Outline view and select it.  Then in the Attributes Inspector on the right, set the Storyboard Segue Identifier to your identifier.


问:
Python 2.7 attribute error on custom module
I'm running Debian Jessie with Python 2.7 installed. I tried to create this tiny module called linalg.py which only contains a few helper functions. I added the folder with the module into the PYTHONPATH hoping that it would allow me to simply import it from any python project.
The problem is that when I import it and call any of the functions, I get

```<code>AttributeError: 'module' object has no attribute '<xyz>'
</code>```

I have added an __init__.py into the directory with my module. The tree looks like this:

```<code>custom-packages/
  python2.7/
    linalg/
      linalg.py
      __init__.py
</code>```

PYTHONPATH contains the python2.7 directory from above.
The file in question (linalg.py)

```<code>import sympy
import numpy as np

from numpy import dot

def vector(*lst):
  return np.array(lst)

def _projection(a, b):
  return sympy.Rational(dot(a, b), dot(b, b)) * b

def projection(a, *b):
  result = np.zeros(len(a))
  for vec in b:
    result += _projection(a, vec)
  return result

def perpendicular(a, *vecs):
  a_hat = projection(a, *vecs)
  return a - a_hat
</code>```

if I run the following on the python shell I get the attribute error:

```<code>>>> import linalg
>>> linalg.vector(1,2,3,4)
AttributeError: 'module' object has no attribute 'vector'
</code>```

Using from linalg import * doesn't help.

答:
You seem to want your linalg.py to be the linalg module, but you've actually made it the linalg submodule of a linalg package. With how you have things set up now, you'd have to access vector as something like

```<code>import linalg.linalg

linalg.linalg.vector(1, 2, 3, 4)
</code>```

but you probably shouldn't do that. Instead, you should pull linalg.py up a directory and delete the linalg folder, so your directory structure looks like

```<code>custom-packages/
  python2.7/
    linalg.py
</code>```

and then

```<code>import linalg

linalg.vector(1, 2, 3, 4)
</code>```

will work.

Body:
I'm running Debian Jessie with Python 2.7 installed. I tried to create this tiny module called linalg.py which only contains a few helper functions. I added the folder with the module into the PYTHONPATH hoping that it would allow me to simply import it from any python project.
The problem is that when I import it and call any of the functions, I get

AttributeError: 'module' object has no attribute '<xyz>'

I have added an __init__.py into the directory with my module. The tree looks like this:

custom-packages/
  python2.7/
    linalg/
      linalg.py
      __init__.py

PYTHONPATH contains the python2.7 directory from above.
The file in question (linalg.py)

import sympy
import numpy as np

from numpy import dot

def vector(*lst):
  return np.array(lst)

def _projection(a, b):
  return sympy.Rational(dot(a, b), dot(b, b)) * b

def projection(a, *b):
  result = np.zeros(len(a))
  for vec in b:
    result += _projection(a, vec)
  return result

def perpendicular(a, *vecs):
  a_hat = projection(a, *vecs)
  return a - a_hat

if I run the following on the python shell I get the attribute error:

>>> import linalg
>>> linalg.vector(1,2,3,4)
AttributeError: 'module' object has no attribute 'vector'

Using from linalg import * doesn't help.

Body:
You seem to want your linalg.py to be the linalg module, but you've actually made it the linalg submodule of a linalg package. With how you have things set up now, you'd have to access vector as something like

import linalg.linalg

linalg.linalg.vector(1, 2, 3, 4)

but you probably shouldn't do that. Instead, you should pull linalg.py up a directory and delete the linalg folder, so your directory structure looks like

custom-packages/
  python2.7/
    linalg.py

and then

import linalg

linalg.vector(1, 2, 3, 4)

will work.


问:
Call function only once if bool value changed in update() method
I need help. I have an update() method which called every tick. This method has a lot of functions, just like this one:

```<code>if (myBoolValue)
    some stuff
else
    another stuff
</code>```

But how to call this "some stuff" and "another stuff" only once if myBoolValue will be changed without calling it on every tick?

答:
If you need to call both why not do this?</p>

```<code>If(myboolvalue)
    Somestuff;
If(anotherboolvalue)
    Someotherstuff
</code>```

Body:
I need help. I have an update() method which called every tick. This method has a lot of functions, just like this one:

if (myBoolValue)
    some stuff
else
    another stuff

But how to call this "some stuff" and "another stuff" only once if myBoolValue will be changed without calling it on every tick?

Body:
If you need to call both why not do this?

If(myboolvalue)
    Somestuff;
If(anotherboolvalue)
    Someotherstuff


问:
How order searchkick search by distance?
```<code>@professional_services =
  Professional::Service.search @keywords, where: {
    location: {
      near: { lat: @cordinate[0], lon: @cordinate[1] },
      within: "100km"
    }
  }
</code>```

How order this search by distance?

答:
I sort results by distance with the query:  </p>

```<code>@professional_services =
Professional::Service.search "*", where: {
  location: {
    near: {lat: @cordinate[0], lon: @cordinate[1]}, within: "10000km"
  }
},
order: [{
  _score: :desc}, {_geo_distance: {location: "#{@cordinate[0]},
  #{@cordinate[1]}", order: "asc",unit: "km"}
}]
</code>```

Body:
@professional_services =
  Professional::Service.search @keywords, where: {
    location: {
      near: { lat: @cordinate[0], lon: @cordinate[1] },
      within: "100km"
    }
  }

How order this search by distance?

Body:
I sort results by distance with the query:

@professional_services =
Professional::Service.search "*", where: {
  location: {
    near: {lat: @cordinate[0], lon: @cordinate[1]}, within: "10000km"
  }
},
order: [{
  _score: :desc}, {_geo_distance: {location: "#{@cordinate[0]},
  #{@cordinate[1]}", order: "asc",unit: "km"}
}]


问:
Coverage.py does not discover tests without init.py file in sub directories
When I run coverage for python, I always need an empty __init__.py file in the tests sub-directory to get coverage to run the tests. This is a requirement for python2 packages, but not for python3. To reproduce, I did the following (pre-requisites are python3, pip3 and brew):

Run the following terminal command:

```<code>pip3 install coverage
</code>```

Create the following directory structure:

```<code>example\
    example.py
tests\
    test_example.py
</code>```

example.py:

```<code>#!/usr/bin/env python3
class Example:
    value = 3

    def update(self):
        self.value = 4
</code>```

test_example.py:

```<code>#!/usr/bin/env python3

import unittest
from example.example import Example

class TestExample(unittest.TestCase):
    def test_example(self):
        example_object = Example()
        self.assertEqual(3, example_object.value)
        example_object.update()
        self.assertEqual(4, example_object.value)
</code>```

Run the following terminal command:

```<code>coverage run --branch -m unittest discover -s . && coverage report
</code>```

I should get: Ran 1 test in x.yz seconds, but I always get Ran 0 tests in x.yz seconds, and to fix this, I have to add __init__.py files to both directories. How can I run coverage without needing the init files?

Please let me know if you need anything else from me regarding this question. I would appreciate any help!

答:
Although Python 3 doesn't need __init__.py files, omitting them creates namespace packages, which are not a good idea if you don't need them.  For example, they are read last, so even directories later in the PYTHONPATH can shadow your files.

You should create the __init__.py files anyway.

Body:
When I run coverage for python, I always need an empty __init__.py file in the tests sub-directory to get coverage to run the tests. This is a requirement for python2 packages, but not for python3. To reproduce, I did the following (pre-requisites are python3, pip3 and brew):

Run the following terminal command:

pip3 install coverage

Create the following directory structure:

example\
    example.py
tests\
    test_example.py

example.py:

#!/usr/bin/env python3
class Example:
    value = 3

    def update(self):
        self.value = 4

test_example.py:

#!/usr/bin/env python3

import unittest
from example.example import Example

class TestExample(unittest.TestCase):
    def test_example(self):
        example_object = Example()
        self.assertEqual(3, example_object.value)
        example_object.update()
        self.assertEqual(4, example_object.value)

Run the following terminal command:

coverage run --branch -m unittest discover -s . && coverage report

I should get: Ran 1 test in x.yz seconds, but I always get Ran 0 tests in x.yz seconds, and to fix this, I have to add __init__.py files to both directories. How can I run coverage without needing the init files?

Please let me know if you need anything else from me regarding this question. I would appreciate any help!


问:
External File Chrome Extension
I am trying to reference an image in my content script for my extension. I have declared it in my web accessible resources. I am using chrome.extension.getURL(). Not sure what is wrong here. Image is not displaying only alt is.

Here is my manifest file:

```<code>{
"manifest_version": 2,
"name": "Test Image",
"description": "",
"version": "1.0",
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "js": ["script.js"],
  "web_accessible_resources":["images/Image.png"]
}
]
}
</code>```

and here is my javascript

```<code>window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '<img alt="image" src="">';
div.src = chrome.extension.getURL("images/image.png");
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "20000";
div.className = "jack";
div.id = "jack";
document.body.appendChild(div);
</code>```

答:
1: web accessible resources is not a subset of content scripts:

```<code>{
  "manifest_version": 2,
  "name": "Test Image",
  "description": "",
  "version": "1.0",
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["script.js"]
  }],
  "web_accessible_resources":["images/Image.png"]
}
</code>```

2a: you should set img.src, not div.src. fast solution:

```<code>div.firstElementChild.src = chrome.extension...
</code>```

2b: better way to manipulate HTML DOM:

```<code>var img = div.appendChild( document.createElement("img") );
img.setAttribute("alt", "image");
img.setAttribute("src", chrome.extension.getUrl("images/Image.png") );
</code>```

Title: External File Chrome Extension

Body:
I am trying to reference an image in my content script for my extension. I have declared it in my web accessible resources. I am using chrome.extension.getURL(). Not sure what is wrong here. Image is not displaying only alt is.

Here is my manifest file:

{
"manifest_version": 2,
"name": "Test Image",
"description": "",
"version": "1.0",
"content_scripts": [
{
  "matches": ["<all_urls>"],
  "js": ["script.js"],
  "web_accessible_resources":["images/Image.png"]
}
]
}

and here is my javascript

window.onload = function() {
var div = document.createElement("div");
div.innerHTML = '';
div.src = chrome.extension.getURL("images/image.png");
div.style.visibility = "visible";
div.style.position = "absolute";
div.style.zIndex = "20000";
div.className = "jack";
div.id = "jack";
document.body.appendChild(div);

Body:
1: web accessible resources is not a subset of content scripts:

{
  "manifest_version": 2,
  "name": "Test Image",
  "description": "",
  "version": "1.0",
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["script.js"]
  }],
  "web_accessible_resources":["images/Image.png"]
}

2a: you should set img.src, not div.src. fast solution:

div.firstElementChild.src = chrome.extension...

2b: better way to manipulate HTML DOM:

var img = div.appendChild( document.createElement("img") );
img.setAttribute("alt", "image");
img.setAttribute("src", chrome.extension.getUrl("images/Image.png") );


问:
Win32: Bring a window to top
I have a Windows program which has two 2 windows in it:

```<code>hwnd (main interface)

hwnd2 (toplevel window, no parent, created by hwnd)
</code>```

When I double click on hwnd, I need hwnd2 to pop up and show some data, so I use this function to bring hwnd2 to top:

```<code>BringWindowToTop(hwnd2);
</code>```

hwnd2 is brought to top, but there is one thing odd. When I click on hwnd2 again, hwnd (main interface) pops itself up again automatically.
I tried to use the following function to solve this problem, but non of them works.

```<code>SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                                                  //doesn't work

BringWindowToTop(hwnd2);    //This is the function brings hwnd2 to top

SetForegroundWindow(hwnd2); //doesn't work

SetWindowPos(hwnd2, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                                                  //doesn't work

SetWindowPos(hwnd2, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                       // hwnd2 "always" on top, not what I want

SetActiveWindow(hwnd2); // doesn't work too (for replying to Magnus Skog, thanks)

SwitchToThisWindow(hwnd2, TRUE);// got the same problem with BringWindowToTop function
SwitchToThisWindow(hwnd2, FALSE);
</code>```

How could I solve this problem?
Thanks in advance.

(for replying to aJ, hwnd2 doesn't have parent because it needs to be a toplevel window so it can be in front/back of other windows)

(hwnd2 is a media player which is composed of several windows, one of the windows is for video dispaly, two other trackbar controls for progress bar and volume bar, one Toolbar control for control panel.)

(There is one this might help, no matter which window I click on hwnd2, hwnd pops up automatically as loong as "the mouse is on top of hwnd in Z-order", including menu bar and  non-client area, etc.)

(This media player is writen in Direct Show. I use IVideoWindow::put_Owner to put video window as the video owner, Direct Show internally creates a sub-video window as a child of the video window. Except for this sub-video window which I can't see the source code, I don't see any thing suspicious in hwnd2.)

I found the reason, which is because of Direct Show. I use multithread to execute it, and then the problem's solved. But...why??

This problem can be resolved by using PostMessage (rather than SendMessage).

答:
After many tries and errors.I found following solution to this problem:

```<code>SendMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); // restore the minimize window
SetForegroundWindow(hwnd);
SetActiveWindow(hwnd);
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE  | SWP_NOSIZE);
//redraw to prevent the window blank.
RedrawWindow(hwnd, NULL, 0, RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN );
</code>```

The hwnd is your windows HWND . Please do not just copy and paste. You also need use GetLastError to check api error after every api call.

I have confirm following result on my win7:

Can restore minimize window and no error return.

If the window already top, the window title will blink and no error return.

If the window has closed, it will return the error "0x578 Invalid window handle."

It can bring the window to the top on all not top-most window and no error return.(For example it will behind the top-most taskmanager)

It do not make the window top-most. The user can make other window on top of it.

OwnerDisplayName: KenC

LastEditorDisplayName: KenC

Title: Win32: Bring a window to top

Body:
I have a Windows program which has two 2 windows in it:

hwnd (main interface)

hwnd2 (toplevel window, no parent, created by hwnd)

When I double click on hwnd, I need hwnd2 to pop up and show some data, so I use this function to bring hwnd2 to top:

BringWindowToTop(hwnd2);

hwnd2 is brought to top, but there is one thing odd. When I click on hwnd2 again, hwnd (main interface) pops itself up again automatically.
I tried to use the following function to solve this problem, but non of them works.

SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                                                  //doesn't work

BringWindowToTop(hwnd2);    //This is the function brings hwnd2 to top

SetForegroundWindow(hwnd2); //doesn't work

SetWindowPos(hwnd2, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                                                  //doesn't work

SetWindowPos(hwnd2, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
                                       // hwnd2 "always" on top, not what I want

SetActiveWindow(hwnd2); // doesn't work too (for replying to Magnus Skog, thanks)

SwitchToThisWindow(hwnd2, TRUE);// got the same problem with BringWindowToTop function
SwitchToThisWindow(hwnd2, FALSE);

How could I solve this problem?
Thanks in advance.

(for replying to aJ, hwnd2 doesn't have parent because it needs to be a toplevel window so it can be in front/back of other windows)

(hwnd2 is a media player which is composed of several windows, one of the windows is for video dispaly, two other trackbar controls for progress bar and volume bar, one Toolbar control for control panel.)

(There is one this might help, no matter which window I click on hwnd2, hwnd pops up automatically as loong as "the mouse is on top of hwnd in Z-order", including menu bar and  non-client area, etc.)

(This media player is writen in Direct Show. I use IVideoWindow::put_Owner to put video window as the video owner, Direct Show internally creates a sub-video window as a child of the video window. Except for this sub-video window which I can't see the source code, I don't see any thing suspicious in hwnd2.)

I found the reason, which is because of Direct Show. I use multithread to execute it, and then the problem's solved. But...why??

This problem can be resolved by using PostMessage (rather than SendMessage).

Body:
After many tries and errors.I found following solution to this problem:

SendMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); // restore the minimize window
SetForegroundWindow(hwnd);
SetActiveWindow(hwnd);
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE  | SWP_NOSIZE);
//redraw to prevent the window blank.
RedrawWindow(hwnd, NULL, 0, RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN );

The hwnd is your windows HWND . Please do not just copy and paste. You also need use GetLastError to check api error after every api call.

I have confirm following result on my win7:

Can restore minimize window and no error return.

If the window already top, the window title will blink and no error return.

If the window has closed, it will return the error "0x578 Invalid window handle."

It can bring the window to the top on all not top-most window and no error return.(For example it will behind the top-most taskmanager)

It do not make the window top-most. The user can make other window on top of it.


问:
Ionic 3 - how use cordova plugin Network interface with ionic?
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

```<code> "cordova plugin add cordova-plugin-networkinterface"
</code>```

2. Declare the variable in global scope to access the object

```<code>declare var NetworkInterface: any;
export class TestClass{}
</code>```

3. Call the object using the global variable inside a component

```<code>NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});
</code>```

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

答:
You need to use below CLI:

```<code>ionic plugin add cordova-plugin-networkinterface --save
</code>```

You need to declare it as global.And also you need to test this on either device or emulator since this is a plugin.

```<code> declare var NetworkInterface: any;
</code>```

Old Answer:

You can easily do it using native Network plugin.

```<code>ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network
</code>```

From the doc:

```<code>import { Network } from '@ionic-native/network';

constructor(private network: Network) { }

...

// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection but we need to wait briefly
   // before we determine the connection type. Might need to wait.
  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});
</code>```

Body:
My problem:
I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

 "cordova plugin add cordova-plugin-networkinterface"

2. Declare the variable in global scope to access the object

declare var NetworkInterface: any;
export class TestClass{}

3. Call the object using the global variable inside a component

NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise):  ReferenceError: NetworkInterface
  is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

Body:
You need to use below CLI:

ionic plugin add cordova-plugin-networkinterface --save

You need to declare it as global.And also you need to test this on either device or emulator since this is a plugin.

 declare var NetworkInterface: any;

Old Answer:

You can easily do it using native Network plugin.

ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

From the doc:

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }

...

// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection but we need to wait briefly
   // before we determine the connection type. Might need to wait.
  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});


问:
Fork project into group for a new contributor (API)
For the possibility that there is a better approach that I'm thinking about I would like to explain my requirement first (the question starts after the divider line).

Given I have the following GitLab group structure:

```<code>- main-group
  - sub-group-project-templates
    - project-template-1
  - sub-group-projects
</code>```

In main-group/sub-group-project-templates there are multiple projects that function as starter project for a task.
If there is someone who wants to do such a task I want to have a fork of the corresponding project template (e.g. project-template-1) in the group sub-group-projects with the name of the person as project name.

Given the name of the person is John Doe who wants to start the task of project-template-1 there should be a new project main-group/sub-group-projects/john_doe_project-template-1.

John Doe should only be able to see (read / write) the repository john_doe_project-template-1 and NOT the rest of the project (other forks, ...).

My solution would be to fork the template project to the sub group and then add a new contributor.

But I already fail at the first step (forking the project into the sub group with a new name).

My first shot at it was looking at:

```<code>POST http://gitlab.com/api/v4/projects/project_id/fork
</code>```

But I don't know how to define the target directory and set the name of the new fork.
The following isn't working:

```<code>POST http://gitlab.com/api/v4/projects/project_id/fork?namespace=main-group%2Fsub-group-projects%2Fjohn_doe_project-template-1
</code>```

"message": "404 Target Namespace Not Found"

Is something like this even possible or how can I achieve this?

答:
Supposing you have the following configuration with project project-template-1 in subgroup sub-group-project-templates :

It can be done in multiple API requests but there are some work-in-progress for the following features:

(1) forking a project with namespace in a subgroup doesn't work

(2) choosing a custom name when forking is not implemented

But these 2 issues have workarounds eg just perform an additionnal request to get the namespace id (1) and perform an edit project request (2) after forking

The steps are the following :

get namespace id for the subgroup sub-group-projects

fork project main-group/sub-group-project-templates/project-template-1 to namespace with id $namespace_id & get the project id of the created project

rename project with id $project_id from project-template-1 to : johndoe_project-template-1

get user id for user johndoe

add project member for project johndoe_project-template-1 : add user with id $user_id

Note that to add a member, you need the user id which I assume you want to search in the 4th step but you may not need this step if you already have it

Here is a bash script performing all these step, it uses curl & jq :

#!/bin/bash
set -e

gitlab_host=gitlab.your.host
access_token=YOUR_ACCESS_TOKEN

username=johndoe
project=project-template-1
user_access=30

group=main-group
namespace_src=sub-group-project-templates
namespace_dest=sub-group-projects
new_project_name=${username}_${project}

project_src=$group/$namespace_src/$project

encoded_project=$(echo $project_src | sed 's/\//%2F/g')

echo "1 - get namespace id for $namespace_dest"
#https://docs.gitlab.com/ce/api/namespaces.html
namespace_id=$(curl -s "https://$gitlab_host/api/v4/namespaces?search=$namespace_dest" \
    -H "Private-Token: $access_token" | jq -r '.[0].id')

echo "2 - fork project $project_src to namespace with id $namespace_id"
#https://docs.gitlab.com/ce/api/projects.html#fork-project
project_id=$(curl -s -X POST "https://$gitlab_host/api/v4/projects/$encoded_project/fork?namespace=$namespace_id" \
    -H "Private-Token: $access_token" | jq '.id')

if [ -z $project_id ]; then
    echo "fork failed"
    exit 1
fi

echo "3 - rename project with id $project_id from $project to : $new_project_name"
#https://docs.gitlab.com/ce/api/projects.html#edit-project
curl -s -X PUT "https://$gitlab_host/api/v4/projects/$project_id" \
    -H "Content-Type: application/json" \
    -d "{\"path\": \"$new_project_name\",\"name\": \"$new_project_name\" }" \
    -H "Private-Token: $access_token" > /dev/null

echo "4 - get user id for : $username"
#https://docs.gitlab.com/ce/api/users.html
user_id=$(curl -s "https://$gitlab_host/api/v4/users?username=johndoe" \
    -H "Private-Token: $access_token" | \
    jq -r '.[] | select(.name == "johndoe") | .id')

echo "5 - edit project member : add user with id $user_id"
#https://docs.gitlab.com/ce/api/members.html#add-a-member-to-a-group-or-project
curl -s "https://$gitlab_host/api/v4/projects/$project_id/members" \
    -H "Private-Token: $access_token" \
    -d "user_id=$user_id&access_level=$user_access" > /dev/null
```

In the 2nd step (fork project), project source namespace is URL encoded so you may want to use a proper manner to encode it (in this case we only have to replace / with %2F)

Body:
For the possibility that there is a better approach that I'm thinking about I would like to explain my requirement first (the question starts after the divider line).

Given I have the following GitLab group structure:

- main-group
  - sub-group-project-templates
    - project-template-1
  - sub-group-projects

In main-group/sub-group-project-templates there are multiple projects that function as starter project for a task.
If there is someone who wants to do such a task I want to have a fork of the corresponding project template (e.g. project-template-1) in the group sub-group-projects with the name of the person as project name.

Given the name of the person is John Doe who wants to start the task of project-template-1 there should be a new project main-group/sub-group-projects/john_doe_project-template-1.

John Doe should only be able to see (read / write) the repository john_doe_project-template-1 and NOT the rest of the project (other forks, ...).

My solution would be to fork the template project to the sub group and then add a new contributor.

But I already fail at the first step (forking the project into the sub group with a new name).

My first shot at it was looking at:

POST http://gitlab.com/api/v4/projects/project_id/fork

But I don't know how to define the target directory and set the name of the new fork.
The following isn't working:

POST http://gitlab.com/api/v4/projects/project_id/fork?namespace=main-group%2Fsub-group-projects%2Fjohn_doe_project-template-1

"message": "404 Target Namespace Not Found"

Is something like this even possible or how can I achieve this?

Body:
Supposing you have the following configuration with project project-template-1 in subgroup sub-group-project-templates :

It can be done in multiple API requests but there are some work-in-progress for the following features:

(1) forking a project with namespace in a subgroup doesn't work

(2) choosing a custom name when forking is not implemented

But these 2 issues have workarounds eg just perform an additionnal request to get the namespace id (1) and perform an edit project request (2) after forking

The steps are the following :

get namespace id for the subgroup sub-group-projects

fork project main-group/sub-group-project-templates/project-template-1 to namespace with id $namespace_id & get the project id of the created project

rename project with id $project_id from project-template-1 to : johndoe_project-template-1

get user id for user johndoe

add project member for project johndoe_project-template-1 : add user with id $user_id

Note that to add a member, you need the user id which I assume you want to search in the 4th step but you may not need this step if you already have it

Here is a bash script performing all these step, it uses curl & jq :

#!/bin/bash
set -e

gitlab_host=gitlab.your.host
access_token=YOUR_ACCESS_TOKEN

username=johndoe
project=project-template-1
user_access=30

group=main-group
namespace_src=sub-group-project-templates
namespace_dest=sub-group-projects
new_project_name=${username}_${project}

project_src=$group/$namespace_src/$project

encoded_project=$(echo $project_src | sed 's/\//%2F/g')

echo "1 - get namespace id for $namespace_dest"
#https://docs.gitlab.com/ce/api/namespaces.html
namespace_id=$(curl -s "https://$gitlab_host/api/v4/namespaces?search=$namespace_dest" \
    -H "Private-Token: $access_token" | jq -r '.[0].id')

echo "2 - fork project $project_src to namespace with id $namespace_id"
#https://docs.gitlab.com/ce/api/projects.html#fork-project
project_id=$(curl -s -X POST "https://$gitlab_host/api/v4/projects/$encoded_project/fork?namespace=$namespace_id" \
    -H "Private-Token: $access_token" | jq '.id')

if [ -z $project_id ]; then
    echo "fork failed"
    exit 1
fi

echo "3 - rename project with id $project_id from $project to : $new_project_name"
#https://docs.gitlab.com/ce/api/projects.html#edit-project
curl -s -X PUT "https://$gitlab_host/api/v4/projects/$project_id" \
    -H "Content-Type: application/json" \
    -d "{\"path\": \"$new_project_name\",\"name\": \"$new_project_name\" }" \
    -H "Private-Token: $access_token" > /dev/null

echo "4 - get user id for : $username"
#https://docs.gitlab.com/ce/api/users.html
user_id=$(curl -s "https://$gitlab_host/api/v4/users?username=johndoe" \
    -H "Private-Token: $access_token" | \
    jq -r '.[] | select(.name == "johndoe") | .id')

echo "5 - edit project member : add user with id $user_id"
#https://docs.gitlab.com/ce/api/members.html#add-a-member-to-a-group-or-project
curl -s "https://$gitlab_host/api/v4/projects/$project_id/members" \
    -H "Private-Token: $access_token" \
    -d "user_id=$user_id&access_level=$user_access" > /dev/null

In the 2nd step (fork project), project source namespace is URL encoded so you may want to use a proper manner to encode it (in this case we only have to replace / with %2F)


问:
How to dynamically set the argument to $_GET or $_POST?
I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.

Unfortunately I get this error:

Notice: Undefined variable: _POST

The code running is the following:

```<code># check for the right arguments
function checkArguments($type, $arg_array) {
    # $type is either 'GET' or 'POST'
    # $arg_array is an array with all the arguments names

    foreach($arg_array as $arg) {
        print(${"_" . $type}["name"]);
        $type = "_" . $type;
        if(!isset($$type[$arg])) {
            $missing[] = $arg;
        }
    }
}
</code>```

答:
HI I will assume you wanted a variable variable, I try to avoid them as they are very hard to read in code. It also breaks ( or doesn't work in ) most IDE editors.

One thing I just saw that is relevant.

http://php.net/manual/en/language.variables.variable.php

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

The $_POST would be counted among the "Superglobal" as is $_GET

Body:
I'm writing a function in php to check, if all arguments are set. This is for preventing the program to crash when a argument isn't set.

Unfortunately I get this error:

Notice: Undefined variable: _POST

The code running is the following:

# check for the right arguments
function checkArguments($type, $arg_array) {
    # $type is either 'GET' or 'POST'
    # $arg_array is an array with all the arguments names

    foreach($arg_array as $arg) {
        print(${"_" . $type}["name"]);
        $type = "_" . $type;
        if(!isset($$type[$arg])) {
            $missing[] = $arg;
        }
    }
}


问:
iOS Development: How can I shorten a URL from my code?
I'm building an iPhone app and I'd like to include functionality that allows users to login to twitter and tweet a link to my app. In order to do this, however, the tweet will need to shorten the URL to my app on the App Store.  How can I write code to shorten a URL for a tweet?

I've done a search for this and found a tutorial on iCodeBlog, as well as some questions posted on SO, however, they're all either more work than I think is needed or they're using http://api.tr.im, which is no longer available.  I'm hoping there's a newer approach to this that is as simple as the iCodeBlog solution.

Thanks for your wisdom!

答:
You simple do a HTTP Request to an Service of your choice. I have choosen l.pr in this example. Many other Services have such an easy API. The magic here is in a method that is a part of NSString. This method is called stringWithContentsOfURL. It will easily allow you to grab the text of any remote source.

As an example:

```<code>NSString *url    = @"http://woodleader.org";
NSString *apiEndpoint = [NSString stringWithFormat:@"http:/api.l.pr/shorten?apikey=axbymc46859i685jfk9fk&longurl=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
         encoding:NSASCIIStringEncoding
         error:nil];
NSLog(@"Long: %@ - Short: %@",url,shortURL);
</code>```

Body:
You simple do a HTTP Request to an Service of your choice. I have choosen l.pr in this example. Many other Services have such an easy API. The magic here is in a method that is a part of NSString. This method is called stringWithContentsOfURL. It will easily allow you to grab the text of any remote source.

As an example:

NSString *url    = @"http://woodleader.org";
NSString *apiEndpoint = [NSString stringWithFormat:@"http:/api.l.pr/shorten?apikey=axbymc46859i685jfk9fk&longurl=%@",url];
NSString *shortURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:apiEndpoint]
         encoding:NSASCIIStringEncoding
         error:nil];
NSLog(@"Long: %@ - Short: %@",url,shortURL);


问:
Why does this date parsing fail?
I'm trying to convert a string into a LocalDateTime object.

```<code>@Test
public void testDateFormat() {
   String date = "20171205014657111";
   DateTimeFormatter formatter =
       DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
   LocalDateTime dt = LocalDateTime.parse(date, formatter);
}
</code>```

I would expect this test to pass.

I get the following error:

java.time.format.DateTimeParseException: Text '20171205014657111' could not be parsed at index 0

答:
Looks like I may have run across this bug: https://bugs.openjdk.java.net/browse/JDK-8031085 as it corresponds to the JVM version I'm using. The workaround in the comments fixes the issue for me:</p>

```<code>@Test
public void testDateFormat() {
    String date = "20171205014657111";
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
       .appendPattern("yyyyMMddHHmmss")
       .appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter();
    LocalDateTime dt = LocalDateTime.parse(date, dtf);
}
</code>```

Title: Why does this date parsing fail?

Body:
I'm trying to convert a string into a LocalDateTime object.

@Test
public void testDateFormat() {
   String date = "20171205014657111";
   DateTimeFormatter formatter =
       DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
   LocalDateTime dt = LocalDateTime.parse(date, formatter);
}

I would expect this test to pass.

I get the following error:

java.time.format.DateTimeParseException: Text '20171205014657111' could not be parsed at index 0

Body:
Looks like I may have run across this bug: https://bugs.openjdk.java.net/browse/JDK-8031085 as it corresponds to the JVM version I'm using. The workaround in the comments fixes the issue for me:

@Test
public void testDateFormat() {
    String date = "20171205014657111";
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
       .appendPattern("yyyyMMddHHmmss")
       .appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter();
    LocalDateTime dt = LocalDateTime.parse(date, dtf);
}


问:
How To Avoid Repair With Keycache?
I have had some experience with optimizing the my.cnf file but my database has around 4 million records (MyISAM).  I am trying to restore from a mysqldump but every time I do I eventually get the dreaded "Repair With Keycache", that may take days. Is there any way to get past this and let it roll as "Repair By Sorting"?

I have 2GB RAM, Dual Cores, lots of extra hard-drive space.

Snip out of my.cnf:

```<code>set-variable = max_connections=650
set-variable = key_buffer=256M
set-variable = myisam_sort_buffer_size=64M
set-variable = join_buffer=1M
set-variable = record_buffer=1M
set-variable = sort_buffer_size=2M
set-variable = read_buffer_size=2M
set-variable = query_cache_size=32M
set-variable = table_cache=1024
set-variable = thread_cache_size=256
set-variable = wait_timeout=7200
set-variable = connect_timeout=10
set-variable = max_allowed_packet=16M
set-variable = max_connect_errors=10
set-variable = thread_concurrency=8
</code>```

答:
None of the solutions here worked for me: no matter how much I increased the myisam_sort_buffer_size variable or where I made the tmpdir variable point to, the table always got repaired with keycache.

What worked was to use the commandline utility myisamchk:

```<code>myisamchk --sort-recover --sort_buffer_size=14G /path/to/table
</code>```

where:

/path/to/table is the path of the database file without its extension (so, without the .MYI at the end). It is by default located in directory /var/lib/mysql/your_database.

Change the buffer size from 14G to whatever free space available you have.

As an added bonus, it also displays the on-going progress as it churns the data.

Title: How To Avoid Repair With Keycache?

Body:
I have had some experience with optimizing the my.cnf file but my database has around 4 million records (MyISAM).  I am trying to restore from a mysqldump but every time I do I eventually get the dreaded "Repair With Keycache", that may take days. Is there any way to get past this and let it roll as "Repair By Sorting"?

I have 2GB RAM, Dual Cores, lots of extra hard-drive space.

Snip out of my.cnf:

set-variable = max_connections=650
set-variable = key_buffer=256M
set-variable = myisam_sort_buffer_size=64M
set-variable = join_buffer=1M
set-variable = record_buffer=1M
set-variable = sort_buffer_size=2M
set-variable = read_buffer_size=2M
set-variable = query_cache_size=32M
set-variable = table_cache=1024
set-variable = thread_cache_size=256
set-variable = wait_timeout=7200
set-variable = connect_timeout=10
set-variable = max_allowed_packet=16M
set-variable = max_connect_errors=10
set-variable = thread_concurrency=8

Body:
None of the solutions here worked for me: no matter how much I increased the myisam_sort_buffer_size variable or where I made the tmpdir variable point to, the table always got repaired with keycache.

What worked was to use the commandline utility myisamchk:

myisamchk --sort-recover --sort_buffer_size=14G /path/to/table

where:

/path/to/table is the path of the database file without its extension (so, without the .MYI at the end). It is by default located in directory /var/lib/mysql/your_database.

Change the buffer size from 14G to whatever free space available you have.

As an added bonus, it also displays the on-going progress as it churns the data.


问:
Hide menu bar in Firefox 57
I'd like to give a presentation in Firefox 57, but I cannot find a way of hiding the menubar/address bar/tab bar when I'm in full screen. I feel like it would be distracting to see that during a slideshow.

Is there a way to hide the menu bar?

I am using Firefox Quantum 57.0b3 (64-bit).

Edit: on OSX.

答:
This is not so easy anymore since the new webextensions add-ons system can no longer modify the UI in that way. Follow below instructions:

Type about:profiles into Firefox. Click the show in finder button next to root directory. This will open your Firefox profile folder.

Create a new folder inside your profile folder called chrome. Create a file called userChrome.css so your path looks like /chrome/userChrome.css

Add this CSS code to your file. Save it. Restart Firefox. Remove the code or comment it out to enable the toolbars again.

```<code>@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

#nav-bar { display: none;}

#TabsToolbar {
    visibility: collapse;
}

#main-window[sizemode="maximized"] #titlebar {
    margin-bottom: -34px !important;
}
</code>```

Note: there is a small stripe at the top in fullscreen I couldn't figure out how to fix. If someone figures it out please add to this solution instead of making a new one.

Title: Hide menu bar in Firefox 57

Body:
This is not so easy anymore since the new webextensions add-ons system can no longer modify the UI in that way. Follow below instructions:

Type about:profiles into Firefox. Click the show in finder button next to root directory. This will open your Firefox profile folder.

Create a new folder inside your profile folder called chrome. Create a file called userChrome.css so your path looks like /chrome/userChrome.css

Add this CSS code to your file. Save it. Restart Firefox. Remove the code or comment it out to enable the toolbars again.

@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");

#nav-bar { display: none;}

#TabsToolbar {
    visibility: collapse;
}

#main-window[sizemode="maximized"] #titlebar {
    margin-bottom: -34px !important;
}

Note: there is a small stripe at the top in fullscreen I couldn't figure out how to fix. If someone figures it out please add to this solution instead of making a new one.


问:
Relative links in Jekyll on Github Pages and localhost are not working correctly
I use Gulp to run Jekyll. My setup works fine on localhost, but when I introduce Github Pages relative links stop working. I use gulp-gh-pages npm package to push _site contents to gh-pages branch.

Contents of gulpfile.js related to Jekyll and Github Pages:

```<code>var browserSync  = require('browser-sync').create();
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var ghPages      = require('gulp-gh-pages');
var gutil        = require('gulp-util');
var run          = require('gulp-run');
var del          = require('del');

gulp.task('build:jekyll', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('clean', function() {
    return del(['_site', 'assets']);
});

// [`build:scripts`, `build:styles`, `build:images`] is removed from the runSequence example for MVP
gulp.task('build:prod', function(callback) {
    return runSequence('clean', 'build:jekyll', callback)
    browserSync.reload();
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});
</code>```

Contents of config.yml:

```<code>baseurl: /

collections:
  pages:
    output: true
    permalink: /:title/

exclude: ["_assets", "gulpfile.js", "node_modules", "package.json", "package-lock.json", ".jekyll-metadata"]
</code>```

Reference to assets:

```<code><link rel="stylesheet" href="{{ site.baseurl }}assets/styles/main.min.css">
</code>```

Front matter on every page inside _pages directory:

```<code>---
layout: page
title: Title
description: Awesome description
image: https://source.unsplash.com/random/?water
---
</code>```

Here is the link to my Github repository with full source code: https://github.com/alljamin/portfolio

How can I configure Gulp and Jekyll so all the relative links work both locally and on Github Pages?

答:
Elaborating on the @david-jacquel answer I was able to find a way to successfully run localhost and Github Pages environments via separate Gulp tasks.

Contents of gulpfile.js:

```<code>gulp.task('build:jekyll:dev', function(callback) {
    var shellCommand = 'jekyll build --incremental --baseurl "" ';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('build:jekyll:prod', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

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

The build:jekyll:dev task will overwrite the _config.yml baseurl to "". So I can do something like this:

```<code>gulp.task('build:dev', function(callback) {
    return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:dev', callback)
    browserSync.reload();
});

gulp.task('build:prod', function(callback) {
    return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:prod', callback)
    browserSync.reload();
});

gulp.task('serve', ['build:dev'], function() {
    browserSync.init({
        server: {
            baseDir: "_site"
        },
        ghostMode: false,
        logFileChanges: true,
        logLevel: 'debug',
        open: true
    });
    gulp.watch(...);
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});
</code>```

Body:
I use Gulp to run Jekyll. My setup works fine on localhost, but when I introduce Github Pages relative links stop working. I use gulp-gh-pages npm package to push _site contents to gh-pages branch.

Contents of gulpfile.js related to Jekyll and Github Pages:

var browserSync  = require('browser-sync').create();
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var ghPages      = require('gulp-gh-pages');
var gutil        = require('gulp-util');
var run          = require('gulp-run');
var del          = require('del');

gulp.task('build:jekyll', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('clean', function() {
    return del(['_site', 'assets']);
});

// [`build:scripts`, `build:styles`, `build:images`] is removed from the runSequence example for MVP
gulp.task('build:prod', function(callback) {
    return runSequence('clean', 'build:jekyll', callback)
    browserSync.reload();
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});

Contents of config.yml:

baseurl: /

collections:
  pages:
    output: true
    permalink: /:title/

exclude: ["_assets", "gulpfile.js", "node_modules", "package.json", "package-lock.json", ".jekyll-metadata"]

Reference to assets:

<link rel="stylesheet" href="{{ site.baseurl }}assets/styles/main.min.css">

Front matter on every page inside _pages directory:

---
layout: page
title: Title
description: Awesome description
image: https://source.unsplash.com/random/?water
---

Here is the link to my Github repository with full source code: https://github.com/alljamin/portfolio

How can I configure Gulp and Jekyll so all the relative links work both locally and on Github Pages?

Body:
Elaborating on the @david-jacquel answer I was able to find a way to successfully run localhost and Github Pages environments via separate Gulp tasks.

Contents of gulpfile.js:

gulp.task('build:jekyll:dev', function(callback) {
    var shellCommand = 'jekyll build --incremental --baseurl "" ';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

gulp.task('build:jekyll:prod', function(callback) {
    var shellCommand = 'jekyll build --incremental';

    return gulp.src('')
        .pipe(run(shellCommand))
        .on('error', gutil.log);

    callback();
});

The build:jekyll:dev task will overwrite the _config.yml baseurl to "". So I can do something like this:

gulp.task('build:dev', function(callback) {
    return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:dev', callback)
    browserSync.reload();
});

gulp.task('build:prod', function(callback) {
    return runSequence('clean', ['build:scripts', 'build:styles', 'build:images'], 'build:jekyll:prod', callback)
    browserSync.reload();
});

gulp.task('serve', ['build:dev'], function() {
    browserSync.init({
        server: {
            baseDir: "_site"
        },
        ghostMode: false,
        logFileChanges: true,
        logLevel: 'debug',
        open: true
    });
    gulp.watch(...);
});

gulp.task('deploy',['build:prod'], function(){
    return gulp.src('./_site/**/*')
        .pipe(ghPages());
});