问:
Detect if python pip subpackage is installed by name
Airflow module comes with a main pip package apache-airflow and multiple subpackages to install only what we need (check doc https://airflow.incubator.apache.org/installation.html#extra-packages)

I would like to test if a subpackage is installed or not (and for example get a bash command to know if apache-airflow[mysql] is installed).

To know if apache-airflow is installed, I can do pip show apache-airflow and get 0 as exit code if installed, 1 otherwise. If I do pip show apache-airflow['mysql'], I always get 1 as exit code, the subpackage being installed or not.

And I could not find any option for that. Any idea?

答:
The "subpackage" you're referring to here is called a "setuptools extra".  pip does not record these anywhere in the filesystem.  You can however detect whether they are installed by iterating the installation metadata and testing whether each dependent package is installed.

Fortunately, there's a method in pkg_resources which does this for you

I tested with jsonschema[format] as it was easy for me to install / uninstall.

with jsonschema[format] installed

```<code>$ python -c 'import pkg_resources; pkg_resources.require("jsonschema[format]")'
$ echo $?
0
</code>```

without the dependencies of the [format] extra

```<code>$ python -c 'import pkg_resources; pkg_resources.require("jsonschema[format]")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 967, in require
    needed = self.resolve(parse_requirements(requirements))
  File "venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 853, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'webcolors; extra == "format"' distribution was not found and is required by jsonschema

$ echo $?
1
</code>```

Body:
The "subpackage" you're referring to here is called a "setuptools extra".  pip does not record these anywhere in the filesystem.  You can however detect whether they are installed by iterating the installation metadata and testing whether each dependent package is installed.

Fortunately, there's a method in pkg_resources which does this for you

I tested with jsonschema[format] as it was easy for me to install / uninstall.

with jsonschema[format] installed

$ python -c 'import pkg_resources; pkg_resources.require("jsonschema[format]")'
$ echo $?
0

without the dependencies of the [format] extra

$ python -c 'import pkg_resources; pkg_resources.require("jsonschema[format]")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 967, in require
    needed = self.resolve(parse_requirements(requirements))
  File "venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 853, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'webcolors; extra == "format"' distribution was not found and is required by jsonschema

$ echo $?
1


来源: stackexchange

问:
while loop does not break out
Doing an exercise and I can't figure out why my while loop isn't escaping, it keeps saying that the values aren't valid even when only digits are entered. Any ideas?

// 31. Karvonen Heart Rate
var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

    valid = false;
    numCheckAge = /^\d+$/.test(age);
    numCheckPulse = /^\d+$/.test(restingPulse);

    while(valid === false) {
      age = parseFloat(prompt("Enter your age:"));
      restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
      if(numCheckAge === true && numCheckPulse === true) {
        valid = true;
      } else {
        alert("Sorry. That's not a valid input, please enter numbers.");
      }
    }

    for (var i = 0.55; i < 1; i+=0.05){
      targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
      document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
    }```

答:
You were on the right track you just forgot to initialize the variable.

var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

age = 0;
restingPulse = 0;

valid = false;
numCheckAge = /^\d+$/.test(age);
numCheckPulse = /^\d+$/.test(restingPulse);

while(valid !== true) {
    age = parseFloat(prompt("Enter your age:"));
    restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
    if(numCheckAge === true && numCheckPulse === true) {
        valid = true;
    } else {
        alert("Sorry. That's not a valid input, please enter numbers.");
    }
}

for (var i = 0.55; i < 1; i+=0.05){
    targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
    document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "
");
}```

ContentLicense: CC BY-SA 4.0

Title: while loop does not break out

Body:
You were on the right track you just forgot to initialize the variable.

var age, restingPulse, targetRate, numCheckAge, numCheckPulse, valid;

age = 0;
restingPulse = 0;

valid = false;
numCheckAge = /^\d+$/.test(age);
numCheckPulse = /^\d+$/.test(restingPulse);

while(valid !== true) {
    age = parseFloat(prompt("Enter your age:"));
    restingPulse = parseFloat(prompt("Enter your resting heart rate:"));
    if(numCheckAge === true && numCheckPulse === true) {
        valid = true;
    } else {
        alert("Sorry. That's not a valid input, please enter numbers.");
    }
}

for (var i = 0.55; i < 1; i+=0.05){
    targetRate = (((220 - age) - restingPulse) * i) + restingPulse;
    document.write("Intensity: " + Math.round((i * 100)) + "% | Rate: " + Math.round(targetRate) + "<br>");
}

ContentLicense: CC BY-SA 3.0


问:
What unit should I use for HTML?
I like to use em, and tend to stay away from % because it tends to screw up the design easily, and pt, px, cm... Because they aren't that friendly to all devices. Am I right in doing so?</p>

答: Yes. It scales, its easy to remember, and even easy to convert into other measurements for comparison :)</p>

ContentLicense: CC BY-SA 2.5

Title: What unit should I use for HTML?


问:
AWS CLI: Pass arguments to --user-data(shell-script) in aws ec2 run-instances
I am trying to launch an aws ec2 instance via cli.

```<code>aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 \
 --instance-type t2.medium --key-name myKey \
 --security-group-ids sg-yyyyyyyy --subnet-id subnet-mysubnet \
 --region us-east-1 --user-data file://myscript
</code>```

While launching I call a shell script that runs some basic commands.
I was wondering if there is a way to pass arguments to this

```<code>--user-data file://myscript
</code>```

sample shell script:

```<code>echo $1
echo $2
</code>```

答:
You could either create the myscript file with parameters, and then call run-instances, or you could pass parameters on the command-line:

```<code>aws ec2 run-instances ... --user-data "#!\naws ec2 describe-instances --instance-id $INSTANCE\n"
</code>```

The above inserts shell variables into the command, but this can get a bit messy. It's probably better to have a script that creates the myscript file and passes it into the command.

Body:
I am trying to launch an aws ec2 instance via cli.

aws ec2 run-instances --image-id ami-xxxxxxxx --count 1 \
 --instance-type t2.medium --key-name myKey \
 --security-group-ids sg-yyyyyyyy --subnet-id subnet-mysubnet \
 --region us-east-1 --user-data file://myscript

While launching I call a shell script that runs some basic commands.
I was wondering if there is a way to pass arguments to this

--user-data file://myscript

sample shell script:

echo $1
echo $2

Body:
You could either create the myscript file with parameters, and then call run-instances, or you could pass parameters on the command-line:

aws ec2 run-instances ... --user-data "#!\naws ec2 describe-instances --instance-id $INSTANCE\n"

The above inserts shell variables into the command, but this can get a bit messy. It's probably better to have a script that creates the myscript file and passes it into the command.


问:
How can I remove the jQuery .css() when clicking other button?
In this jQuery switch, I'm trying to make the button that is currently clicked go back to its original state when the other button is clicked. Also id like the off button to be clicked first automatically when the page is loaded. I've tried many codes but cant seem to get it to work.

HTML:

```<code><!DOCTYPE HTML>
<html>

<head>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src='script.js' type='text/javascript'></script>

</head>
<body>

<div class="switchcontainer">
    <button id="darkmodeon">ON</button>
    <button id="darkmodeoff">OFF</button>
</div>

</body>
</html>
</code>```

CSS:

```<code>body{
    background-color: black;
}

.switchcontainer{
    background-color: white;
    display: flex;
    justify-content: space-between;
    border-radius: 50px;
    width: 125px;
    padding: 5px;

}

button{
    width:50px;
    height: 50px;
    border: none;
    border-radius: 50px;
    background-color: #d8d8d8;
    color: #777777;
    font-family: 'calibri light';
    font-size: 17px;
    font-weight: bold;

}
</code>```

jQuery:

```<code>$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });

        $(this).off('click',darkon);

    });

});
</code>```

答:
If you want to turn of the event, then you will have to pass in the handler as  the argument to the click event.

Instead of adding CSS on the fly, use a class to target the state, which is cleaner.

To invoke the handler, on page load, trigger the click event after the handler is bound.

var darkon = '#darkmodeon';
var darkoff = '#darkmodeoff';

// This is how you should be binding your click handler
// to the button if you are planning to turn of the event
// at a later stage. Since, the `off` method expects the same
// function to be passed when you attach the event
$(darkon).click(addActiveClass);

$(darkoff).click(function(e) {
  addActiveClass(e);

  $(darkon).removeClass('on');

  $(darkon).off('click', addActiveClass);

});

function addActiveClass(e) {
   var $target = $(e.target);

   $target.addClass('on');
}

$(darkon).click();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
}

.on {
  background-color: #85c452;
  transition: all 0.2s ease;
}</code>```

  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>

```

Body:
In this jQuery switch, I'm trying to make the button that is currently clicked go back to its original state when the other button is clicked. Also id like the off button to be clicked first automatically when the page is loaded. I've tried many codes but cant seem to get it to work.

HTML:

<!DOCTYPE HTML>

    <title>Toggleswitch</title>
    <link rel="stylesheet" type="text/css" href="main.css">

    <button id="darkmodeon">ON</button>
    <button id="darkmodeoff">OFF</button>

CSS:

body{
    background-color: black;
}

.switchcontainer{
    background-color: white;
    display: flex;
    justify-content: space-between;
    border-radius: 50px;
    width: 125px;
    padding: 5px;

}

button{
    width:50px;
    height: 50px;
    border: none;
    border-radius: 50px;
    background-color: #d8d8d8;
    color: #777777;
    font-family: 'calibri light';
    font-size: 17px;
    font-weight: bold;

}

jQuery:

$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });
    });

    $(darkoff).click(function(){
        $(this).css({
            "background-color": "#85c452",
            "color": "white",
            "transition": "all 0.2s ease"
        });

        $(this).off('click',darkon);

    });

});

Body:
If you want to turn of the event, then you will have to pass in the handler as  the argument to the click event.

Instead of adding CSS on the fly, use a class to target the state, which is cleaner.

To invoke the handler, on page load, trigger the click event after the handler is bound.

var darkon = '#darkmodeon';
var darkoff = '#darkmodeoff';

// This is how you should be binding your click handler
// to the button if you are planning to turn of the event
// at a later stage. Since, the `off` method expects the same
// function to be passed when you attach the event
$(darkon).click(addActiveClass);

$(darkoff).click(function(e) {
  addActiveClass(e);

  $(darkon).removeClass('on');

  $(darkon).off('click', addActiveClass);

});

function addActiveClass(e) {
   var $target = $(e.target);

   $target.addClass('on');
}

$(darkon).click();

body {
  background-color: black;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border-radius: 50px;
  width: 125px;
  padding: 5px;
}

button {
  width: 50px;
  height: 50px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
}

.on {
  background-color: #85c452;
  transition: all 0.2s ease;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switchcontainer">
  <button id="darkmodeon">ON</button>
  <button id="darkmodeoff">OFF</button>
</div>


问:
Logic on a Pandas Dataframe with a string
This should be a really easy one, but I can't figure it out::
I have a dataframe, df, and it has two string values, "normal" and "odd".
I'd like to find out how many are in either catagory::

```<code>type(bro_df)
pandas.core.frame.DataFrame

print(len(bro_df))
2000000

type(bro_df['label'])
pandas.core.series.Series

print(len(bro_df['label'] == 'normal'))
2000000

print(len(bro_df['label'] == 'odd'))
2000000
</code>```

What's going on??!?!

Thanks,
Nic

答:
len(bro_df['label'] == 'odd') is the length of the boolean series of True and False. If you want the number of rows with those values:

```<code>(bro_df['label'] == 'odd').sum()
</code>```

Or better yet

```<code>bro_df.label.value_counts()
</code>```

Body:
This should be a really easy one, but I can't figure it out::
I have a dataframe, df, and it has two string values, "normal" and "odd".
I'd like to find out how many are in either catagory::

type(bro_df)
pandas.core.frame.DataFrame

print(len(bro_df))
2000000

type(bro_df['label'])
pandas.core.series.Series

print(len(bro_df['label'] == 'normal'))
2000000

print(len(bro_df['label'] == 'odd'))
2000000

What's going on??!?!

Thanks,
Nic

Body:
len(bro_df['label'] == 'odd') is the length of the boolean series of True and False. If you want the number of rows with those values:

(bro_df['label'] == 'odd').sum()

Or better yet

bro_df.label.value_counts()


问:
Return value from temporary express server
I'm writing an app that needs to authenticate externally with a service. To do this, I'm using express to listen to the redirect and get the data I need. However, I would like to return that data to the main scope. Here's what I have so far:

```<code>const authorize = () => {
    app.get('/', (req, res) => {
        res.status(200).send('<script>window.close()</script>')
        return req.query.code;
    });

    app.listen(3000, () => {
        console.log('listening');
    });
}

const code = authorize();
</code>```

req.query.code is the data I need, and I would like to return it from authorize(). Instead I get undefined. What is the best practice to accomplish what I want?

答:
Fixed it by returning a Promise.

```<code>const authorize = () => {

    return new Promise((resolve, reject) => {
        app.get('/', (req, res) => {
            res.status(200).send('<script>window.close()</script>')
            resolve(req.query.code);
        });

        app.listen(3000, () => {
            console.log('listening');
        });
    })
}
</code>```

Body:
I'm writing an app that needs to authenticate externally with a service. To do this, I'm using express to listen to the redirect and get the data I need. However, I would like to return that data to the main scope. Here's what I have so far:

const authorize = () => {
    app.get('/', (req, res) => {
        res.status(200).send('')
        return req.query.code;
    });

    app.listen(3000, () => {
        console.log('listening');
    });
}

const code = authorize();

req.query.code is the data I need, and I would like to return it from authorize(). Instead I get undefined. What is the best practice to accomplish what I want?

Body:
Fixed it by returning a Promise.

const authorize = () => {

    return new Promise((resolve, reject) => {
        app.get('/', (req, res) => {
            res.status(200).send('<script>window.close()</script>')
            resolve(req.query.code);
        });

        app.listen(3000, () => {
            console.log('listening');
        });
    })
}


答:
You can do it easily using classes and Jquery.

Create a new class for your "on" state.

```<code>.on {
     background-color: #85c452;
     color: white;
     transition: all 0.2s ease;
 }
</code>```

Then change your click handlers to toggle this class on and off instead of setting the specific CSS styles.

```<code>$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).addClass("on");
        $(darkoff).removeClass("on");
    });

    $(darkoff).click(function(){
        $(this).addClass("on");
        $(darkon).removeClass("on");
    });
});
</code>```

Title: How can I remove the jQuery .css() when clicking other button?

Body:
You can do it easily using classes and Jquery.

Create a new class for your "on" state.

.on {
     background-color: #85c452;
     color: white;
     transition: all 0.2s ease;
 }

Then change your click handlers to toggle this class on and off instead of setting the specific CSS styles.

$(document).ready(function(){
    var darkon = '#darkmodeon';
    var darkoff = '#darkmodeoff';

    $(darkon).click(function(){
        $(this).addClass("on");
        $(darkoff).removeClass("on");
    });

    $(darkoff).click(function(){
        $(this).addClass("on");
        $(darkon).removeClass("on");
    });
});


问:
convert sqlite database to .db file
I was working on SQLite database and need to convert it to a .db extension instead of having data.sqlite. My client needs the data in data.db extension. So is there any way to convert the data.sqlite file into data.db file?</p>

答:
The name of your file is completely irrelevant to the data inside of it. Assuming the data structure is properly setup, simply renaming the file will suffice.

Note: If you're running windows, you will need to enable file extension visibility.

Title: convert sqlite database to .db file


问:
simple Kivy DropDown errors with 'NoneType' object has no attribute 'bind'
I have been using kivy 1.7.2 on Ubuntu 14.04 for some time; very easy to use and kv language makes design a breeze....

...except the DropDown has proven near impossible to setup without running it with kv and even has issues when initiated with more python code.

Here is what I start with....

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown

kv_text = """#:kivy 1.7.2
<MyWidget>
    DropDown:
        id: menupanel
        on_parent: self.dismiss()
        on_select: lambda: None
        Button:
            id: button_a
            size_hint_y: None
            text: "A"
        Button:
            id: button_b
            size_hint_y: None
            text: "B"
    Button:
        id: button_opendd
        pos_hint: {"top":1, "right":1}
        on_release: root.ids.menupanel.open(self)
        text: "open"
"""

class MyWidget(FloatLayout):
    def __init__(self, **kwargs):
        super(FloatLayout, self).__init__(**kwargs)

class MyWidgetApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyWidgetApp()
    app.run()

if __name__ == '__main__':
    main()
</code>```

...
....which produces this error....
...

```<code> Traceback (most recent call last):
   File "wtfkivy.py", line 60, in <module>
     main()
   File "wtfkivy.py", line 57, in main
     app.run()
   File "/usr/lib/python2.7/dist-packages/kivy/app.py", line 577, in run
     root = self.build()
   File "wtfkivy.py", line 52, in build
     return MyWidget()
   File "wtfkivy.py", line 48, in __init__
     super(FloatLayout, self).__init__(**kwargs)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/layout.py", line 61, in __init__
     super(Layout, self).__init__(**kwargs)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/widget.py", line 163, in __init__
     Builder.apply(self)
   File "/usr/lib/python2.7/dist-packages/kivy/lang.py", line 1429, in apply
     self._apply_rule(widget, rule, rule)
   File "/usr/lib/python2.7/dist-packages/kivy/lang.py", line 1531, in _apply_rule
     child = cls(__no_builder=True)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/dropdown.py", line 160, in __init__
     self.container.bind(minimum_size=self._container_minimum_size)
 AttributeError: 'NoneType' object has no attribute 'bind'
</code>```

The DropDown's self.container is supposed to default to a GridLayout but somehow that doesn't happen when set up via kv file.

I have gotten around this error by changing DropDown: in the kv to MyDropDown: and putting the <MyDropDown>: definition below everything. Then, in the python, I had to add the class with a super(MyDropDown,self).__init__() However! It just put a duplicate set of widgets into the dropdown. Woops? (If I change that init to __init__(**kwargs), I end up with the same bind error. Huh?)

I have honestly scoured the internet numerous times for good examples of DropDown set up mostly via kv, but nothing that really hit the mark.

Even if the implementation in python worked out (with super(), it would not be preferred. I need the DropDown's widgets to be able to access attributes of the main app widget.

So the question: is there either a way to implement a DropDown almost entirely in kv (which makes design so clean and accessible) or something else that still makes the main app widget accessible?

EDIT
As indicated by FJSevilla and verified by testing, DropDown is broken in version 1.7.2. I added an answer to elaborate, since many others may be using the version supplied from their distro.

答:
DropDown (and maybe other widgets) are broken in Kivy 1.7. DropDown specifically does not initiate properly from kv code.

If anyone needs to use a version this old, implement dropdowns using python alone and not kv (and expect trouble):

```<code>dd = DropDown()
b1 = Button(text="a")
b2 = Button(text="b")
dd.add_widget(b1)
dd.add_widget(b2)
</code>```

Or try getting the kivy you wanted by upgrading to at least 1.9.x. (I did not test 1.8.)
First off, if you use an older distro, you will probably have to upgrade kivy beyond what your distro provides.

On Ubuntu 14.04:

```<code>sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A863D2D6
sudo add-apt-repository ppa:kivy-team/kivy-daily
sudo apt-get update
sudo apt-get install python-kivy python3-kivy
</code>```

Note that this upgrade seems to change certain behaviors (read: new errors)...

First change...

For DropDown, on_parent:self.dismiss() was a bound attribute on the DropDown itself. After upgrading, this caused the DropDown to immediately dismiss itself on open. (You see it flicker for only a split-second.)

If you now encounter this error, moving menupanel.dismiss() (substituting your id in place of menupanel) to the root widget alleviated that problem.

Second change...

Somehow, having the menupanel.dismiss() OR self.ids.menupanel.dismiss() on the root widget was breaking the refs to the dropdown (essentially deleting the strong refs / getting garbage-collected) and causing this:

```<code>     on_release: menupanel.open(self)
File "weakproxy.pyx", line 30, in kivy.weakproxy.WeakProxy.__getattr__ (kivy/weakproxy.c:1145)
File "weakproxy.pyx", line 26, in kivy.weakproxy.WeakProxy.__ref__ (kivy/weakproxy.c:1069)
ReferenceError: weakly-referenced object no longer exists
</code>```

(NOTE: The only time I see this error on the interwebs are for named classes (i.e. class MyButton(Button) that are instantiated by kv code. This is just a normal generic DropDown, so why cause an issue here?)

The solution, if you receive that error, is to add a reference to your DropDown instance...anywhere, to any object, when instantiated or in the function where the DropDown is opened. It just has to happen before the other reference is removed. (In my case, getting removed while switching to new Screen and back.)

```<code>class ...
    def ...
        self.backup_reference = self.ids.menupanel
</code>```

Why? I have no idea.

....Or, if your DropDown was going to be very simple, try using 1 Spinner instead.

Body:
I have been using kivy 1.7.2 on Ubuntu 14.04 for some time; very easy to use and kv language makes design a breeze....

...except the DropDown has proven near impossible to setup without running it with kv and even has issues when initiated with more python code.

Here is what I start with....

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown

kv_text = """#:kivy 1.7.2
<MyWidget>
    DropDown:
        id: menupanel
        on_parent: self.dismiss()
        on_select: lambda: None
        Button:
            id: button_a
            size_hint_y: None
            text: "A"
        Button:
            id: button_b
            size_hint_y: None
            text: "B"
    Button:
        id: button_opendd
        pos_hint: {"top":1, "right":1}
        on_release: root.ids.menupanel.open(self)
        text: "open"
"""

class MyWidget(FloatLayout):
    def __init__(self, **kwargs):
        super(FloatLayout, self).__init__(**kwargs)

class MyWidgetApp(App):
    def build(self):
        return MyWidget()

def main():
    Builder.load_string(kv_text)
    app = MyWidgetApp()
    app.run()

if __name__ == '__main__':
    main()

...
....which produces this error....
...

 Traceback (most recent call last):
   File "wtfkivy.py", line 60, in <module>
     main()
   File "wtfkivy.py", line 57, in main
     app.run()
   File "/usr/lib/python2.7/dist-packages/kivy/app.py", line 577, in run
     root = self.build()
   File "wtfkivy.py", line 52, in build
     return MyWidget()
   File "wtfkivy.py", line 48, in __init__
     super(FloatLayout, self).__init__(**kwargs)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/layout.py", line 61, in __init__
     super(Layout, self).__init__(**kwargs)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/widget.py", line 163, in __init__
     Builder.apply(self)
   File "/usr/lib/python2.7/dist-packages/kivy/lang.py", line 1429, in apply
     self._apply_rule(widget, rule, rule)
   File "/usr/lib/python2.7/dist-packages/kivy/lang.py", line 1531, in _apply_rule
     child = cls(__no_builder=True)
   File "/usr/lib/python2.7/dist-packages/kivy/uix/dropdown.py", line 160, in __init__
     self.container.bind(minimum_size=self._container_minimum_size)
 AttributeError: 'NoneType' object has no attribute 'bind'

The DropDown's self.container is supposed to default to a GridLayout but somehow that doesn't happen when set up via kv file.

I have gotten around this error by changing DropDown: in the kv to MyDropDown: and putting the <MyDropDown>: definition below everything. Then, in the python, I had to add the class with a super(MyDropDown,self).__init__() However! It just put a duplicate set of widgets into the dropdown. Woops? (If I change that init to __init__(**kwargs), I end up with the same bind error. Huh?)

I have honestly scoured the internet numerous times for good examples of DropDown set up mostly via kv, but nothing that really hit the mark.

Even if the implementation in python worked out (with super(), it would not be preferred. I need the DropDown's widgets to be able to access attributes of the main app widget.

So the question: is there either a way to implement a DropDown almost entirely in kv (which makes design so clean and accessible) or something else that still makes the main app widget accessible?

EDIT
As indicated by FJSevilla and verified by testing, DropDown is broken in version 1.7.2. I added an answer to elaborate, since many others may be using the version supplied from their distro.

Body:
DropDown (and maybe other widgets) are broken in Kivy 1.7. DropDown specifically does not initiate properly from kv code.

If anyone needs to use a version this old, implement dropdowns using python alone and not kv (and expect trouble):

dd = DropDown()
b1 = Button(text="a")
b2 = Button(text="b")
dd.add_widget(b1)
dd.add_widget(b2)

Or try getting the kivy you wanted by upgrading to at least 1.9.x. (I did not test 1.8.)
First off, if you use an older distro, you will probably have to upgrade kivy beyond what your distro provides.

On Ubuntu 14.04:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys A863D2D6
sudo add-apt-repository ppa:kivy-team/kivy-daily
sudo apt-get update
sudo apt-get install python-kivy python3-kivy

Note that this upgrade seems to change certain behaviors (read: new errors)...

First change...

For DropDown, on_parent:self.dismiss() was a bound attribute on the DropDown itself. After upgrading, this caused the DropDown to immediately dismiss itself on open. (You see it flicker for only a split-second.)

If you now encounter this error, moving menupanel.dismiss() (substituting your id in place of menupanel) to the root widget alleviated that problem.

Second change...

Somehow, having the menupanel.dismiss() OR self.ids.menupanel.dismiss() on the root widget was breaking the refs to the dropdown (essentially deleting the strong refs / getting garbage-collected) and causing this:

     on_release: menupanel.open(self)
File "weakproxy.pyx", line 30, in kivy.weakproxy.WeakProxy.__getattr__ (kivy/weakproxy.c:1145)
File "weakproxy.pyx", line 26, in kivy.weakproxy.WeakProxy.__ref__ (kivy/weakproxy.c:1069)
ReferenceError: weakly-referenced object no longer exists

(NOTE: The only time I see this error on the interwebs are for named classes (i.e. class MyButton(Button) that are instantiated by kv code. This is just a normal generic DropDown, so why cause an issue here?)

The solution, if you receive that error, is to add a reference to your DropDown instance...anywhere, to any object, when instantiated or in the function where the DropDown is opened. It just has to happen before the other reference is removed. (In my case, getting removed while switching to new Screen and back.)

class ...
    def ...
        self.backup_reference = self.ids.menupanel

Why? I have no idea.

....Or, if your DropDown was going to be very simple, try using 1 Spinner instead.


问:
Having trouble with the output/structure of a nested Array in PHP and MySQL
Im trying to make a neat, structured list of, in this case, films and showdates.

```<code>$shows = array(
    array(
        "Thursday" => array(
            "17:00",
            "19:00")),
    array(
        "Friday" => array(
            "16:30",
            "18:45"
            "20:10")),
    array(
        "Saturday" => array(
            "18:30",
            "21:00"))
);
</code>```

The problem is that I cant seem to be able to print the things out in a reasonable way.
The days are supposed to be dynamic, not hard corded as of this case.

```<code>for ($row = 0; $row < $shows.length(); $row++) //Haven't got a clue about the 'length()'
{
    print $shows[$row] . "<br>"; //Print the day.

    for (

   $col = 0; $col < $shows[$row].length(); $col++) //Loop through each day.
    {
        print (">" . $shows[$row][$col] . "<br>"); //Print each time of the day.
    }

}
</code>```

And what im trying to do is to print out each day with the corresponding times.
Should come out as something like this.

```<code>Thursday - 17:00
           19:00

Friday   - 16:30
           18:45
           20:10
</code>```

答:
In PHP to get the number of elements in the array you use the count function.

```<code>for ($row = 0; $row < count($shows); $row++) {
        foreach($shows[$row] as $key => $vals) {
                echo "$key - ";
                $first = true;
                foreach($vals as $val) {
                        if($first) {
                                echo "\t$val\n";
                                $first = false;
                        } else {
                                echo "\t\t$val\n";
                        }
                }
        }
}
</code>```

Ideone Link

Body:
Im trying to make a neat, structured list of, in this case, films and showdates.

$shows = array(
    array(
        "Thursday" => array(
            "17:00",
            "19:00")),
    array(
        "Friday" => array(
            "16:30",
            "18:45"
            "20:10")),
    array(
        "Saturday" => array(
            "18:30",
            "21:00"))
);

The problem is that I cant seem to be able to print the things out in a reasonable way.
The days are supposed to be dynamic, not hard corded as of this case.

for ($row = 0; $row < $shows.length(); $row++) //Haven't got a clue about the 'length()'
{
    print $shows[$row] . "
"; //Print the day.

    for (

   $col = 0; $col < $shows[$row].length(); $col++) //Loop through each day.
    {
        print (">" . $shows[$row][$col] . "
"); //Print each time of the day.
    }

}

And what im trying to do is to print out each day with the corresponding times.
Should come out as something like this.

Thursday - 17:00
           19:00

Friday   - 16:30
           18:45
           20:10

Body:
In PHP to get the number of elements in the array you use the count function.

for ($row = 0; $row < count($shows); $row++) {
        foreach($shows[$row] as $key => $vals) {
                echo "$key - ";
                $first = true;
                foreach($vals as $val) {
                        if($first) {
                                echo "\t$val\n";
                                $first = false;
                        } else {
                                echo "\t\t$val\n";
                        }
                }
        }
}

Ideone Link


问:
Script stops working when I insert into another script
I have a problem that is killing me right now because I can't see why it isn't working. I have made a script in one file that works, but when I copy/paste it into the file that I want it to work in, it doesn't work.
Here's the script I just made:

```<code><html>
<body>
<p id="myElement"></p>
    <script>
        if (window.location.hash == "#hello") {
            document.getElementById("myElement").innerHTML = 'Vi har Hello';
        } else {
            document.getElementById("myElement").innerHTML = '';
        }
    </script>
</body>
</html>
</code>```

Here it works, but when I insert it into the file that it was meant for it won't work. Here it is:

```<code><html>
<head>
    <title>...</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
    <link rel="shortcut icon" href="images/favicon.ico">
</head>
<body id="top">
    <div id="forside"></div>
    <div class="bgded overlay" style="background-image:url('images/stor_1.png');">
        <div id="pageintro" class="hoc clear">
            <li>
                <p></p><h2>Log ind</h2>
                <p id="myElement"></p>
                <script>
                    if (window.location.hash == "#hello") {
                    document.getElementById("myElement").innerHTML = 'Vi har Hello';
                    } else {
                    document.getElementById("myElement").innerHTML = '';
                    }
                </script>
                <div id="comments">
                    <font color="black">
                        <form action="proces.php" method="post">
                            <input class="form-control" type="text" id="name" size="22" name="username" placeholder="Brugernavn" required><br>
                            <input class="form-control" type="password" id="name" size="22" name="pass" placeholder="Kodeord" required><br>
                            <input type="submit" name="submit" value="Log Ind!">
                        </form>
                    </font><br>
                    <a href="index.php"><i class="fa fa-chevron-left" aria-hidden="true"> Tilbage til forsiden</i></a>
                </div>
            </li>
        </div>
    </div>
<?php include_once "footer.php"; ?>
<a id="backtotop" href="#top"><i class="fa fa-chevron-up"></i></a>
    <script src="layout/scripts/jquery.min.js"></script>
    <script src="layout/scripts/jquery.mobilemenu.js"></script>
</body>
</html>
</code>```

What the script, I am inserting, does is to detect if #Hello is in the URL and if it is, it has to display some text... But it won't work.

Anybody who has an idea about what I could be doing wrong?

答:
your code will only run once when your page document first time load, if you do want to check the hash every time its changed, it is better to put in a change callback.
please also be sure you jQuery relative path is right.

```<code>$(function() { // ensure you will execute script after document loaded

    $(window).on('hashchange', function() {   // put you code in side change callback.
        if (window.location.hash == "#hello") {
            document.getElementById("myElement").innerHTML = 'Vi har Hello';
        } else {
            document.getElementById("myElement").innerHTML = '';
        }
    });
});
</code>```

    <title>...</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
    <link rel="shortcut icon" href="images/favicon.ico">

Log ind

                        <form action="proces.php" method="post">
                            <input class="form-control" type="text" id="name" size="22" name="username" placeholder="Brugernavn" required>

                            <input class="form-control" type="password" id="name" size="22" name="pass" placeholder="Kodeord" required>

                            <input type="submit" name="submit" value="Log Ind!">
                        </form>

                     Tilbage til forsiden

```

Body:
I have a problem that is killing me right now because I can't see why it isn't working. I have made a script in one file that works, but when I copy/paste it into the file that I want it to work in, it doesn't work.
Here's the script I just made:

Here it works, but when I insert it into the file that it was meant for it won't work. Here it is:

    <title>...</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
    <link rel="shortcut icon" href="images/favicon.ico">

Log ind

                        <form action="proces.php" method="post">
                            <input class="form-control" type="text" id="name" size="22" name="username" placeholder="Brugernavn" required>

                            <input class="form-control" type="password" id="name" size="22" name="pass" placeholder="Kodeord" required>

                            <input type="submit" name="submit" value="Log Ind!">
                        </form>

                     Tilbage til forsiden

<?php include_once "footer.php"; ?>

What the script, I am inserting, does is to detect if #Hello is in the URL and if it is, it has to display some text... But it won't work.

Anybody who has an idea about what I could be doing wrong?

Body:
your code will only run once when your page document first time load, if you do want to check the hash every time its changed, it is better to put in a change callback.
please also be sure you jQuery relative path is right.

$(function() { // ensure you will execute script after document loaded

    $(window).on('hashchange', function() {   // put you code in side change callback.
        if (window.location.hash == "#hello") {
            document.getElementById("myElement").innerHTML = 'Vi har Hello';
        } else {
            document.getElementById("myElement").innerHTML = '';
        }
    });
});

<html>

<head>
    <title>...</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
    <link rel="shortcut icon" href="images/favicon.ico">
</head>

<body id="top">
    <div id="forside"></div>
    <div class="bgded overlay" style="background-image:url('images/stor_1.png');">
        <div id="pageintro" class="hoc clear">
            <li>
                <p></p>
                <h2>Log ind</h2>
                <p id="myElement"></p>
                <script>
                </script>
                <div id="comments">
                    <font color="black">
                        <form action="proces.php" method="post">
                            <input class="form-control" type="text" id="name" size="22" name="username" placeholder="Brugernavn" required>
                            <br>
                            <input class="form-control" type="password" id="name" size="22" name="pass" placeholder="Kodeord" required>
                            <br>
                            <input type="submit" name="submit" value="Log Ind!">
                        </form>
                    </font>
                    <br>
                    <a href="index.php"><i class="fa fa-chevron-left" aria-hidden="true"> Tilbage til forsiden</i></a>
                </div>
            </li>
        </div>
    </div>
    <a id="backtotop" href="#top"><i class="fa fa-chevron-up"></i></a>
    <script src="layout/scripts/jquery.min.js"></script>
    <script src="layout/scripts/jquery.mobilemenu.js"></script>
    <script type="text/javascript">
    $(function() {
        $(window).on('hashchange', function() {
            if (window.location.hash == "#hello") {
                document.getElementById("myElement").innerHTML = 'Vi har Hello';
            } else {
                document.getElementById("myElement").innerHTML = '';
            }
        });
    });
    </script>
</body>

</html>


问:
How to conform an array from another array that comes from a REST Service?
I’m trying to create a TableView with elements that comes from a REST Service, It’s a list of coupons that has description, title, category and images. So I deserialize the data first, put it in an array and then convert it into an specific array per each section, but my loop is not working, can anyone help me please?

This is my code:

```<code>    var couponsTitle : [String] = []

    var couponsDesc : [String] = []

    var couponsCat : [String] = []

    func getCoupons(){

        let miURL = URL(string: RequestConstants.requestUrlBase)

        let request =  NSMutableURLRequest(url: miURL!)

        request.httpMethod = "GET"

        if let data = try? Data(contentsOf: miURL! as URL) {

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary

                let parseJSON = json

                let object = parseJSON?["object"] as! NSDictionary

                let mainCoupon = object["mainCoupon"] as! NSArray

                let coupons = object["coupons"] as! NSArray

                for i in mainCoupon {
                    self.couponsCat.append((mainCoupon[i as! Int] as AnyObject).value(forKey: "category"))
                }

                for i in coupons {
                    self.couponsCat.append((coupons[i as! Int] as AnyObject).value(forKey: "category"))
                }

                for i in mainCoupon {

                    self.couponsDesc.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “description"))

                }

                for i in coupons {

                    self.couponsDesc.append((coupons[i as! Int] as AnyObject).value(forKey: “description"))

                }

                for i in mainCoupon {

                    self.couponsTitle.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “name"))

                }

                for i in coupons {

                    self.couponsTitle.append((coupons[i as! Int] as AnyObject).value(forKey: “name"))

                }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell

        cell.couponTitle.text = couponsTitle[indexPath.row]
        cell.couponDescription.text = couponsDesc[indexPath.row].
        cell.couponCategory.text = couponsCat[indexPath.row]
        return cell

}
</code>```

My biggest issue is that I don’t know how to put in a loop the array but with the specification of each section (I mean, the title, description, category, etc.) Any idea?

答:
Rather than having three arrays (one for each property), why not have a custom class for Coupon that has three properties?

```<code>class Coupon: AnyObject {

    var description: String
    var title: String
    var category: String

    init(description: String, title: String, category: String) {
        self.description = description
        self.title = title
        self.category = category
    }
}
</code>```

If you do it that way, you can avoid so many loops by doing something like this

```<code>for coupon in mainCoupon {

            let description = mainCoupon["description"]
            let title = mainCoupon["name"]
            let category = mainCoupon["category"]

            let newCoupon = Coupon(description: description, title: title, category: category)

            couponsArray.append(newCoupon)
        }
</code>```

Body:
I’m trying to create a TableView with elements that comes from a REST Service, It’s a list of coupons that has description, title, category and images. So I deserialize the data first, put it in an array and then convert it into an specific array per each section, but my loop is not working, can anyone help me please?

This is my code:

    var couponsTitle : [String] = []

    var couponsDesc : [String] = []

    var couponsCat : [String] = []

    func getCoupons(){

        let miURL = URL(string: RequestConstants.requestUrlBase)

        let request =  NSMutableURLRequest(url: miURL!)

        request.httpMethod = "GET"

        if let data = try? Data(contentsOf: miURL! as URL) {

            do {

                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary

                let parseJSON = json

                let object = parseJSON?["object"] as! NSDictionary

                let mainCoupon = object["mainCoupon"] as! NSArray

                let coupons = object["coupons"] as! NSArray

                for i in mainCoupon {
                    self.couponsCat.append((mainCoupon[i as! Int] as AnyObject).value(forKey: "category"))
                }

                for i in coupons {
                    self.couponsCat.append((coupons[i as! Int] as AnyObject).value(forKey: "category"))
                }

                for i in mainCoupon {

                    self.couponsDesc.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “description"))

                }

                for i in coupons {

                    self.couponsDesc.append((coupons[i as! Int] as AnyObject).value(forKey: “description"))

                }

                for i in mainCoupon {

                    self.couponsTitle.append((mainCoupon[i as! Int] as AnyObject).value(forKey: “name"))

                }

                for i in coupons {

                    self.couponsTitle.append((coupons[i as! Int] as AnyObject).value(forKey: “name"))

                }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeTableViewCell

        cell.couponTitle.text = couponsTitle[indexPath.row]
        cell.couponDescription.text = couponsDesc[indexPath.row].
        cell.couponCategory.text = couponsCat[indexPath.row]
        return cell

}

My biggest issue is that I don’t know how to put in a loop the array but with the specification of each section (I mean, the title, description, category, etc.) Any idea?

Body:
Rather than having three arrays (one for each property), why not have a custom class for Coupon that has three properties?

class Coupon: AnyObject {

    var description: String
    var title: String
    var category: String

    init(description: String, title: String, category: String) {
        self.description = description
        self.title = title
        self.category = category
    }
}

If you do it that way, you can avoid so many loops by doing something like this

for coupon in mainCoupon {

            let description = mainCoupon["description"]
            let title = mainCoupon["name"]
            let category = mainCoupon["category"]

            let newCoupon = Coupon(description: description, title: title, category: category)

            couponsArray.append(newCoupon)
        }


问:
Rails after_save and after_commit callbacks
I went through difference in after_save and after_commit callbacks in rails and major difference I found is after_commit calls both on create and update,is there a way to call after_commit only on create?? </p>

答: The other big difference is that after_save takes place in the same transaction as the create/save.  This means that if there is an error the object is not created/saved.  It also means that the row or table that the create/save is taking place on will be locked until the after_save completes.  This can cause db performance issues or deadlocks.  Particularly when you have several after_save call backs.  In general, I default to using after_commit unless I have a good reason to do otherwise. </p>


问:
Importing Certificates - Access denied (while run as administrator)
I'm working on automating the add of a certificate I created from Cert:\CurrentUser\My to Cert:\CurrentUser\TrustedPublisher so that I can use the AllSigned ExecutionPolicy.  When I use the Import-PfxCertificate cmdlet (after exporting, obviously), I'm getting Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

The weird thing about all of this, I can go into the certificates MMC and import the certificate myself, but when trying to run it through PowerShell (as administrator), it's giving me the errors.

答:
I found I was able to import the cert to the LocalMachine, but not CurrentUser.</p>

```<code>Import-PfxCertificate -FilePath 'Path\Cert.pfx' -Password (Get-Credential).Password -CertStoreLocation Cert:\LocalMachine\Root
Import-PfxCertificate -FilePath 'Path\Cert.pfx' -Password (Get-Credential).Password -CertStoreLocation Cert:\LocalMachine\TrustedPublisher
</code>```

Body:
I found I was able to import the cert to the LocalMachine, but not CurrentUser.

Import-PfxCertificate -FilePath 'Path\Cert.pfx' -Password (Get-Credential).Password -CertStoreLocation Cert:\LocalMachine\Root
Import-PfxCertificate -FilePath 'Path\Cert.pfx' -Password (Get-Credential).Password -CertStoreLocation Cert:\LocalMachine\TrustedPublisher


问:
PROC NLIN from SAS to R
I have been currently assigned a work where I need to translate a SAS code to R. I have been able to successfully do 80% of it and now I am stuck at the part where PROC NLIN is used. From what I read, PROC NLIN is used to fit Non-Linear Models andI am not sure if the code is actually is doing that and hence, stuck at how to do it in R. The code is as follows -

```<code>proc nlin data=ds1 outest=estout;
 parms ET= 0 f= 10.68;
  E= f- R*(1-ET*M);
  L   = E*E;
  model.like = sqrt(E*E);
  by Name ;
run;
</code>```

The sample data is as follows -

```<code>Name    M           R
Anna    0.5456231   4.118197
Anna    0.5359164   4.240243
Anna    0.541881    3.943975
Anna    0.5436047   3.822222
Anna    0.5522962   3.58813
Anna    0.5561487   3.513195
Anna    0.5423374   3.666507
Anna    0.525836    3.715371
Anna    0.5209941   3.805572
Anna    0.5304675   3.750689
Anna    0.5232541   3.788292
</code>```

When I went through the pages on PROC NLIN in SAS help, the argument 'MODEL' is used to specify the equation but the code here doesn't have a model equation. Model.like is to specify the likelihood function (page 4316 - https://support.sas.com/documentation/cdl/en/statugnlin/61811/PDF/default/statugnlin.pdf) So what is this code doing? I am totally confused. I, initially felt that this can be done in R using nls() and I tried the following -

```<code>fit = nls(E~ f - R*(1-eta*M),sample, start=list(eta=0,phi=10.86)
      ,trace=T)
</code>```

But I quickly realised this is wrong because the model didn't converge even after 5000 iterations. This is because, I don't have a column 'E' in my dataset. So, how is SAS doing it?
Any help is appreciated!

答:
A tidyverse approach</p>

```<code>library(tidyverse)
library(broom)

sample <- read.table(textConnection(
  "Name    M           R
  Anna    0.5456231   4.118197
  Anna    0.5359164   4.240243
  Anna    0.541881    3.943975
  Anna    0.5436047   3.822222
  Anna    0.5522962   3.58813
  Anna    0.5561487   3.513195
  Anna    0.5423374   3.666507
  Anna    0.525836    3.715371
  Anna    0.5209941   3.805572
  Anna    0.5304675   3.750689
  Anna    0.5232541   3.788292"), header=TRUE)

x <- sample %>%
  group_by(Name) %>%
  nest() %>%
  mutate(
    model = data %>% map(~nls(0 ~ f - R*(1-eta*M), data= . , start=list(eta=0,f=10.86), trace=T)),
    coef = map(model, tidy),
    quali = map(model, glance),
    resid = map(model, augment)
  )

unnest(select(x, coef))
# A tibble: 2 x 6
    Name  term  estimate std.error statistic      p.value
  <fctr> <chr>     <dbl>     <dbl>     <dbl>        <dbl>
1   Anna   eta 1.7259120 0.2260999 7.6334045 3.213398e-05
2   Anna     f 0.2731282 0.4645288 0.5879683 5.710103e-01

unnest(select(x, quali))
# A tibble: 1 x 8
       sigma isConv       finTol   logLik       AIC       BIC   deviance df.residual
       <dbl>  <lgl>        <dbl>    <dbl>     <dbl>     <dbl>      <dbl>       <int>
1 0.08348998   TRUE 4.345363e-07 12.80868 -19.61736 -18.42368 0.06273518           9
</code>```

Title: PROC NLIN from SAS to R

Body:
I have been currently assigned a work where I need to translate a SAS code to R. I have been able to successfully do 80% of it and now I am stuck at the part where PROC NLIN is used. From what I read, PROC NLIN is used to fit Non-Linear Models andI am not sure if the code is actually is doing that and hence, stuck at how to do it in R. The code is as follows -

proc nlin data=ds1 outest=estout;
 parms ET= 0 f= 10.68;
  E= f- R*(1-ET*M);
  L   = E*E;
  model.like = sqrt(E*E);
  by Name ;
run;

The sample data is as follows -

Name    M           R
Anna    0.5456231   4.118197
Anna    0.5359164   4.240243
Anna    0.541881    3.943975
Anna    0.5436047   3.822222
Anna    0.5522962   3.58813
Anna    0.5561487   3.513195
Anna    0.5423374   3.666507
Anna    0.525836    3.715371
Anna    0.5209941   3.805572
Anna    0.5304675   3.750689
Anna    0.5232541   3.788292

When I went through the pages on PROC NLIN in SAS help, the argument 'MODEL' is used to specify the equation but the code here doesn't have a model equation. Model.like is to specify the likelihood function (page 4316 - https://support.sas.com/documentation/cdl/en/statugnlin/61811/PDF/default/statugnlin.pdf) So what is this code doing? I am totally confused. I, initially felt that this can be done in R using nls() and I tried the following -

fit = nls(E~ f - R*(1-eta*M),sample, start=list(eta=0,phi=10.86)
      ,trace=T)

But I quickly realised this is wrong because the model didn't converge even after 5000 iterations. This is because, I don't have a column 'E' in my dataset. So, how is SAS doing it?
Any help is appreciated!

Body:
A tidyverse approach

library(tidyverse)
library(broom)

sample <- read.table(textConnection(
  "Name    M           R
  Anna    0.5456231   4.118197
  Anna    0.5359164   4.240243
  Anna    0.541881    3.943975
  Anna    0.5436047   3.822222
  Anna    0.5522962   3.58813
  Anna    0.5561487   3.513195
  Anna    0.5423374   3.666507
  Anna    0.525836    3.715371
  Anna    0.5209941   3.805572
  Anna    0.5304675   3.750689
  Anna    0.5232541   3.788292"), header=TRUE)

x <- sample %>%
  group_by(Name) %>%
  nest() %>%
  mutate(
    model = data %>% map(~nls(0 ~ f - R*(1-eta*M), data= . , start=list(eta=0,f=10.86), trace=T)),
    coef = map(model, tidy),
    quali = map(model, glance),
    resid = map(model, augment)
  )

unnest(select(x, coef))
# A tibble: 2 x 6
    Name  term  estimate std.error statistic      p.value
  <fctr> <chr>     <dbl>     <dbl>     <dbl>        <dbl>
1   Anna   eta 1.7259120 0.2260999 7.6334045 3.213398e-05
2   Anna     f 0.2731282 0.4645288 0.5879683 5.710103e-01

unnest(select(x, quali))
# A tibble: 1 x 8
       sigma isConv       finTol   logLik       AIC       BIC   deviance df.residual
       <dbl>  <lgl>        <dbl>    <dbl>     <dbl>     <dbl>      <dbl>       <int>
1 0.08348998   TRUE 4.345363e-07 12.80868 -19.61736 -18.42368 0.06273518           9


问:
How can I best parse this comma delimited text file?
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

```<code>bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...
</code>```

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

```<code>string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();
</code>```

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

答:
Use the FileHelpers library.  It allows you to create classes to store your data and provides an easy way to then parse a data store (including csv) to fill those classes.

But, as you've suggested, this seems like a job for a database.  I'd consider SQLite.

OwnerDisplayName: johnny

Body:
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

OwnerDisplayName: MattyT


问:
How to convert facebook Graph date time into c# DateTime
I have "2010-12-20T11:36:28+0000".
How do I parse it into DateTime?

Thanks

答:
You can use ParseExact or TryParseExact with a Custom Date and Time Format String.

Tested:

```<code>var myDate = DateTime.ParseExact("2010-12-20T11:36:28+0000",
                                 @"yyyy-MM-dd\THH:mm:ssK",
                                 CultureInfo.InvariantCulture);
</code>```

Having said that, DateTime.Parse works perfectly well.

Body:
You can use ParseExact or TryParseExact with a Custom Date and Time Format String.

Tested:

var myDate = DateTime.ParseExact("2010-12-20T11:36:28+0000",
                                 @"yyyy-MM-dd\THH:mm:ssK",
                                 CultureInfo.InvariantCulture);

Having said that, DateTime.Parse works perfectly well.


问:
How to validate user input with filter_var?
I'm creating a basic sign up form, where I want to validate the user input. I've read a LOT of different methods of doing this. First of all, mine is not working because it echoes "Email is valid" when it is not a valid email. I really wish I could figure out the most efficient, succinct way of doing this!

So my two questions are:

1.) Is there something wrong in my code that says it's a valid email even though it isn't?

2.) How can I make this as efficient as possible?

Here is the code:

```<code><?php
include('functions.php');

$server = "localhost";
$auth = "root";
$pass = "password";
$db = "users";

$conn = connect_to_db($server, $auth, $pass, $db);

$signup = isset($_POST['submit']);
$output = NULL;

if( $signup ){
  $username = htmlspecialchars($_POST['username']);
  $password = md5($_POST['password']);
  $email = $_POST['email'];
  if( filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($username) && !empty($password) && !empty($email) ){
    echo 'Email is valid';
      $sql = "SELECT username FROM info WHERE username = '$username'";
      $result = mysqli_query($conn, $sql);
      if( mysqli_num_rows($result) > 0 ){
        echo "Sorry, there is already an account registered with that username";
      } else {
        $sql = "INSERT INTO info (username, password, date_created) VALUES ('$username', '$password', NOW())";
        mysqli_query($conn, $sql);
        $output = "<p> Username: $username <br />" . "Password: $password </p>";
      }
  } elseif ( empty($username) || empty($password) ) {
        $output = "<p> Both fields are required </p>";
  }
  echo $output;
}

?>

<!DOCTYPE html>
<html>

<head>
  <title>My Website</title>
</head>

<body>

<form method="POST">
  <h1>Signup: </h1><br />
  Choose a username: <input type="text" name="username" /> <br />
  Choose a password: <input type="password" name="password" /> <br />
  Enter your email: <input type="email" name="email" /> <br />
  <input type="submit" name="submit" value="Signup" />
  <p>Already have an account? Login here: <br /> <a href="index.php">Login</a></p>
</form>

</body>
</html>
</code>```

答:
I use the code below to validate for email addresses. I then require a user to confirm their email to complete signup as there is no true way to know if an email is actually real or not.

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // invalid emailaddress
}
</code>```

Also, you should create a function to check your POST data.

```<code>function checkData($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
</code>```

Body:
I'm creating a basic sign up form, where I want to validate the user input. I've read a LOT of different methods of doing this. First of all, mine is not working because it echoes "Email is valid" when it is not a valid email. I really wish I could figure out the most efficient, succinct way of doing this!

So my two questions are:

1.) Is there something wrong in my code that says it's a valid email even though it isn't?

2.) How can I make this as efficient as possible?

Here is the code:

<?php
include('functions.php');

$server = "localhost";
$auth = "root";
$pass = "password";
$db = "users";

$conn = connect_to_db($server, $auth, $pass, $db);

$signup = isset($_POST['submit']);
$output = NULL;

if( $signup ){
  $username = htmlspecialchars($_POST['username']);
  $password = md5($_POST['password']);
  $email = $_POST['email'];
  if( filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($username) && !empty($password) && !empty($email) ){
    echo 'Email is valid';
      $sql = "SELECT username FROM info WHERE username = '$username'";
      $result = mysqli_query($conn, $sql);
      if( mysqli_num_rows($result) > 0 ){
        echo "Sorry, there is already an account registered with that username";
      } else {
        $sql = "INSERT INTO info (username, password, date_created) VALUES ('$username', '$password', NOW())";
        mysqli_query($conn, $sql);
        $output = "
 Username: $username
" . "Password: $password
";
      }
  } elseif ( empty($username) || empty($password) ) {
        $output = "
 Both fields are required
";
  }
  echo $output;
}

?>

<!DOCTYPE html>

  <title>My Website</title>

<form method="POST">

Signup:

  Choose a username: <input type="text" name="username" />

  Choose a password: <input type="password" name="password" />

  Enter your email: <input type="email" name="email" />

  <input type="submit" name="submit" value="Signup" />

Already have an account? Login here:
 Login

</form>

Body:
I use the code below to validate for email addresses. I then require a user to confirm their email to complete signup as there is no true way to know if an email is actually real or not.

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // invalid emailaddress
}

Also, you should create a function to check your POST data.

function checkData($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


问:
gcc makefile error: "No rule to make target ..."
I'm trying to use GCC (linux) with a makefile to compile my project.

I get the following error which is can't seem to decipher in this context:

```<code>"No rule to make target 'vertex.cpp', needed by 'vertex.o'.  Stop."
</code>```

This is the makefile:

```<code>a.out: vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
    g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o

main.o: main.cpp main.h
    g++ -c main.cpp

vertex.o: vertex.cpp vertex.h
    g++ -c vertex.cpp

edge.o: edge.cpp edge.h
    g++ -c num.cpp

vlist.o: vlist.cpp vlist.h
    g++ -c vlist.cpp

elist.o: elist.cpp elist.h
    g++ -c elist.cpp

vnode.o: vnode.cpp vnode.h
    g++ -c vnode.cpp

enode.o: enode.cpp enode.h
    g++ -c node.cpp
</code>```

答:
One of frequent mistakes might be typo in another file name.

You example is quite straightforward but what may sometimes confuse are
messages of make itself. Lets consider an example.

My folder contents is:

```<code>$ ls -1
another_file
index.md
makefile
</code>```

Whereas my makefile looks like

```<code>all: index.html

%.html: %.md wrong_path_to_another_file
    @echo $@ $<
</code>```

Although I do have index.md where it should be and there is no mistake in the name of it, the message from make will be

```<code>make: *** No rule to make target `index.html', needed by `all'.  Stop.
</code>```

To be honest the message is confusing. It just says, that there is no rule. In fact, it means that the rule is wrong, but due to wildcard (pattern) rules make cannot determine what exactly caused the issue.

Lets alter makefile a little, which is to say replace patterns with explicit rules:

```<code>index.html: index.md wrong_path_to_another_file
</code>```

And now the message we get will be:

```<code>make: *** No rule to make target `wrong_path_to_another_file', needed by `index.html'.  Stop.
</code>```

Miracle! The following might be concluded:

Messages of make depends on rules and does not always point to the root of problems

There might be other problems in your makefile different from specified by this message

Now we've come up with the idea of checking other dependencies in a rule as well:

```<code>all: index.html

%.html: %.md another_file
    @echo $@ $<
</code>```

Only this will provide us with the desired result:

```<code>$ make
index.html index.md
</code>```

Body:
I'm trying to use GCC (linux) with a makefile to compile my project.

I get the following error which is can't seem to decipher in this context:

"No rule to make target 'vertex.cpp', needed by 'vertex.o'.  Stop."

This is the makefile:

a.out: vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o
    g++ vertex.o edge.o elist.o main.o vlist.o enode.o vnode.o

main.o: main.cpp main.h
    g++ -c main.cpp

vertex.o: vertex.cpp vertex.h
    g++ -c vertex.cpp

edge.o: edge.cpp edge.h
    g++ -c num.cpp

vlist.o: vlist.cpp vlist.h
    g++ -c vlist.cpp

elist.o: elist.cpp elist.h
    g++ -c elist.cpp

vnode.o: vnode.cpp vnode.h
    g++ -c vnode.cpp

enode.o: enode.cpp enode.h
    g++ -c node.cpp

Body:
One of frequent mistakes might be typo in another file name.

You example is quite straightforward but what may sometimes confuse are
messages of make itself. Lets consider an example.

My folder contents is:

$ ls -1
another_file
index.md
makefile

Whereas my makefile looks like

all: index.html

%.html: %.md wrong_path_to_another_file
    @echo $@ $<

Although I do have index.md where it should be and there is no mistake in the name of it, the message from make will be

make: *** No rule to make target `index.html', needed by `all'.  Stop.

To be honest the message is confusing. It just says, that there is no rule. In fact, it means that the rule is wrong, but due to wildcard (pattern) rules make cannot determine what exactly caused the issue.

Lets alter makefile a little, which is to say replace patterns with explicit rules:

index.html: index.md wrong_path_to_another_file

And now the message we get will be:

make: *** No rule to make target `wrong_path_to_another_file', needed by `index.html'.  Stop.

Miracle! The following might be concluded:

Messages of make depends on rules and does not always point to the root of problems

There might be other problems in your makefile different from specified by this message

Now we've come up with the idea of checking other dependencies in a rule as well:

all: index.html

%.html: %.md another_file
    @echo $@ $<

Only this will provide us with the desired result:

$ make
index.html index.md


问:
What unit should I use for HTML?
I like to use em, and tend to stay away from % because it tends to screw up the design easily, and pt, px, cm... Because they aren't that friendly to all devices. Am I right in doing so?</p>

答: There are reasons why css offers you a choice.  So it isn't really a question of right or wrong.  But if you are looking for a way to make your site more accessible by making fonts and elements scale easier, then you are on the right path.  Go with em.</p>

Title: What unit should I use for HTML?


问:
Datetime format in MSSQL
In my aplication I use a DateEdit control and show the date using this format dd/MM/yyyy so the date is save correctly when I use mssql-server 2014 (spanish) but whe I use mssql-server 2008 (english) the date is stored with this fomat MM/dd/yyyy so what I need to know is if there is a way to store the date with the format dd/MM/yyyy no matter the versión of mssql-server I use or the lenguage I use?

EDIT: to explain better this is the problem, this text 03/07/2017 is stored in the sqlserver 2014 as july 3 of 2017 and in the sqlserver 2008 is stored as march 7 of 2017.

Title: Datetime format in MSSQL

Body: Convert.ToDateTime(String).ToString("dd-MM-yyyy")


问:
Tensorflow error on mamp server
I can run these codes on editor but when i tried to run on mamp server i got this error

type 'exceptions.ImportError'>: No module named tensorflow

args = ('No module named tensorflow',)

```<code> message = 'No module named tensorflow'"
</code>```

Here is my HTML codes

```<code><html>
<body>
<form enctype="multipart/form-data" action="index.cgi" method="post">
<p>File: <input type="file" name="file"></p>
<p><input type="submit" value="Upload"></p>
</form>
</body>
</html>
</code>```

My python codes are too long so i upload these to web

My python codes' link : https://paste.ee/p/5q8xV#s=0

Screenshot of error

I need help immediately please help me

答:
Sounds like TensorFlow is installed on your local machine but not your server.

Installing TensorFlow

Title: Tensorflow error on mamp server

Body:
I can run these codes on editor but when i tried to run on mamp server i got this error

type 'exceptions.ImportError'>: No module named tensorflow

args = ('No module named tensorflow',)

 message = 'No module named tensorflow'"

Here is my HTML codes

<form enctype="multipart/form-data" action="index.cgi" method="post">

File: <input type="file" name="file">

<input type="submit" value="Upload">

</form>

My python codes are too long so i upload these to web

My python codes' link : https://paste.ee/p/5q8xV#s=0

Screenshot of error

I need help immediately please help me


问:
Is it possible to make Plotly choropleth use ISO 3166-1 alpha-2 country codes instead of ISO 3166-1 alpha-3 to map countries?
I've just recently started using Plotly and decided to give the "World Choropleth Map" a go due to how simple it seems to be. I was using a data set that has two digit country codes in the column that specifies what country the respondent is from (for example, BR for Brazil, or DE for Germany, also known as ISO 3166-1 alpha-2 codes, I believe.) When I first managed to run the file and make it load up in a web browser, no map appeared on the screen, which I found quite puzzling. I looked at the example csv and noticed that it uses three digit country codes (for example, ITA for Italy or SWE for Sweden, these are known as ISO 3166-1 alpha 3  codes.) I made a small test set and applied the three digit codes to my data set and the map loaded up with all the data I put in, all within the correct countries I specified. This leads me to believe that choropleth looks in the data for the three digit country code by default in order to know where to place the data on the map.

Before I set something up that loops through the data we receive and changes all the codes to a 3 letter format from a 2 letter format, I was wondering if there is an easy way within Plotly choropleths that allows you to specify what type of country code you want?

答:
Check the link below to get the mapping of 2 letter to 3 letter.

http://www.nationsonline.org/oneworld/country_code_list.htm

```<code>Countrylet     2let  3let
Afghanistan    AF    AFG
Aland Islands  AX    ALA
</code>```

```<code>dfcountry = pd.read_csv('countryMap.txt',sep='\t') # mapping of 2 letter to 3 letter
</code>```

```<code>    Country  min    avg     max
    AD       5251   5251    5251
</code>```

```<code>dfData = pd.read_csv('myData.txt',sep='\t') # My Source data

df = dfData.merge(dfcountry,how='inner',left_on=['Country'],right_on=['2let'])
</code>```

Now you can use the 3 Char country code. I was under a timeline so just took a short cut to it. Hope this helps.

Body:
Check the link below to get the mapping of 2 letter to 3 letter.

http://www.nationsonline.org/oneworld/country_code_list.htm

Countrylet     2let  3let
Afghanistan    AF    AFG
Aland Islands  AX    ALA

dfcountry = pd.read_csv('countryMap.txt',sep='\t') # mapping of 2 letter to 3 letter

    Country  min    avg     max
    AD       5251   5251    5251

dfData = pd.read_csv('myData.txt',sep='\t') # My Source data

df = dfData.merge(dfcountry,how='inner',left_on=['Country'],right_on=['2let'])

Now you can use the 3 Char country code. I was under a timeline so just took a short cut to it. Hope this helps.


问:
How to get sidebar full length of page below top navigation with bootstrap 4?
New to bootstrap and using the alpha version of bootstrap 4 to create a site for my home network.

I'd like the sidebar to fill the entire left side of the page, starting below the top nav bar. Right now there is a small 20 or so pixel gap between the top navbar and sidebar. I'd also like it to continue all the way down, despite the size of the page.

I'm using the admin template from bootstrap and modified it to my needs.

https://jsfiddle.net/ced6ee78/

CSS:

```<code>body, html {
  height: 100%;
}

body {
  padding-top: 70px;
}

/* BrandName Top Navbar */
.so-navbar-top {
    background-color: #087ca7;
    height: 48px;
}

.so-navbar-top .navbar-brand {
  font-size: 1.5em;
}

.so-navbar-top .nav-item {
  font-size: 0.75em;
}

/* BrandName Sidebar */
.so-sidebar {
  background-color: #13293d;
}

/* workaround modal-open padding issue */

body.modal-open {

padding-right: 0 !important;

}

#sidebar {

padding-left:0;

}

/*

* Off Canvas at medium breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 48em) {

  .row-offcanvas {

    position: relative;

    -webkit-transition: all 0.25s ease-out;

    -moz-transition: all 0.25s ease-out;

    transition: all 0.25s ease-out;

  }

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -33%;
  }

  .row-offcanvas-left.active {

    left: 33%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    position: absolute;

    top: 0;

    width: 33%;

    height: 100%;

  }

}

/*

* Off Canvas wider at sm breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 34em) {

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -45%;

  }

  .row-offcanvas-left.active {

    left: 45%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    width: 45%;

  }

}

.card {

    overflow:hidden;

}

.card-block .rotate {

    z-index: 8;

    float: right;

    height: 100%;

}

.card-block .rotate i {

    color: rgba(20, 20, 20, 0.15);

    position: absolute;

    left: 0;

    left: auto;

    right: -10px;

    bottom: 0;

    display: block;

    -webkit-transform: rotate(-44deg);

    -moz-transform: rotate(-44deg);

    -o-transform: rotate(-44deg);

    -ms-transform: rotate(-44deg);
    transform: rotate(-44deg);

}
</code>```

HTML

```<code><!DOCTYPE html>

<html lang="en">

  <head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/brandname/css/style.css" rel="stylesheet">

    <script src="assets/jquery/jquery.min.js"></script>
    <script src="assets/jquery-ui/jquery-ui.min.js"></script>

    <title>Dashboard | BrandName</title>

  </head>

  <body>

    <nav class="navbar fixed-top navbar-toggleable-sm navbar-light bg-fade mb-3 so-navbar-top">

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="flex-row d-flex">

        <a class="navbar-brand mb-1" href="#" title="ServiceOps">BrandName</a>

        <button type="button" class="hidden-md-up navbar-toggler" data-toggle="offcanvas" title="Toggle responsive left sidebar">
          <span class="navbar-toggler-icon"></span>
        </button>

      </div>

      <div class="navbar-collapse collapse" id="collapsingNavbar">

        <ul class="navbar-nav ml-auto">

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-bell-o"></i><span class="badge badge-pill badge-danger">1</span> Alerts</a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-cog"></i> Settings
            </a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-user"></i> Profile
            </a>
          </li>

          <li class="nav-item">
            <a class="nav-link" href="#">
              <i class="fa fa-sign-out"></i> Logout
            </a>
          </li>

        </ul>

      </div>

    </nav>

    <div class="container-fluid" id="main">

      <div class="row row-offcanvas row-offcanvas-left">

        <div class="col-md-3 col-lg-2 sidebar-offcanvas so-sidebar" id="sidebar" role="navigation">

          <ul class="nav flex-column pl-1">

            <li class="nav-item"><a class="nav-link" href="#">Dashboard</a></li>

            <li class="nav-item">

              <a class="nav-link" href="#submenu1" data-toggle="collapse" data-target="#submenu1">Sites</a>

              <ul class="list-unstyled flex-column pl-3 collapse" id="submenu1" aria-expanded="false">
                <li class="nav-item"><a class="nav-link" href="">Item 1</a></li>
                <li class="nav-item"><a class="nav-link" href="">Item 2</a></li>
              </ul>

            </li>

          </ul>

        </div>

        <div class="col-md-9 col-lg-10 main">

          <!--toggle sidebar button
          <p class="hidden-md-up">
            <button type="button" class="btn btn-primary-outline btn-sm" data-toggle="offcanvas"><i class="fa fa-chevron-left"></i> Menu</button>
          </p>-->

          <h1 class="display-2 hidden-xs-down">Dashboard</h1>

          <div class="row mb-3">

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-success">

                <div class="card-block bg-success">

                  <div class="rotate">
                    <i class="fa fa-user fa-5x"></i>
                  </div>

                  <h6 class="text-uppercase">Users</h6>
                  <h1 class="display-1">134</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-danger">

                <div class="card-block bg-danger">

                  <div class="rotate">

                    <i class="fa fa-list fa-4x"></i>

                  </div>

                  <h6 class="text-uppercase">Posts</h6>
                  <h1 class="display-1">87</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-info">

                <div class="card-block bg-info">

                  <div class="rotate">

                    <i class="fa fa-twitter fa-5x"></i>

                  </div>

                  <h6 class="text-uppercase">Tweets</h6>
                  <h1 class="display-1">125</h1>

                </div>

              </div>

            </div>

            <div class="col-xl-3 col-lg-6">

              <div class="card card-inverse card-warning">

                <div class="card-block bg-warning">

                  <div class="rotate">

                    <i class="fa fa-share fa-5x"></i>

                  </div>

                  <h6 class="text-uppercase">Shares</h6>
                  <h1 class="display-1">36</h1>

                </div>

              </div>

            </div>

          </div>

        </div>

      </div>

    </div>

    <footer class="container-fluid">

      <p class="text-right small">©2017 BrandName</p>

    </footer>

  </body>

</html>
</code>```

答:
padding-top on body should be the same height as your navbar.

In this case:

```<code>body { padding-top: 48px; }
</code>```

If you need more spacing for the content in the left nav and main content area, add padding/margin to .so-sidebar and .main.

Body:
New to bootstrap and using the alpha version of bootstrap 4 to create a site for my home network.

I'd like the sidebar to fill the entire left side of the page, starting below the top nav bar. Right now there is a small 20 or so pixel gap between the top navbar and sidebar. I'd also like it to continue all the way down, despite the size of the page.

I'm using the admin template from bootstrap and modified it to my needs.

https://jsfiddle.net/ced6ee78/

CSS:

body, html {
  height: 100%;
}

body {
  padding-top: 70px;
}

/* BrandName Top Navbar */
.so-navbar-top {
    background-color: #087ca7;
    height: 48px;
}

.so-navbar-top .navbar-brand {
  font-size: 1.5em;
}

.so-navbar-top .nav-item {
  font-size: 0.75em;
}

/* BrandName Sidebar */
.so-sidebar {
  background-color: #13293d;
}

/* workaround modal-open padding issue */

body.modal-open {

padding-right: 0 !important;

}

#sidebar {

padding-left:0;

}

/*

* Off Canvas at medium breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 48em) {

  .row-offcanvas {

    position: relative;

    -webkit-transition: all 0.25s ease-out;

    -moz-transition: all 0.25s ease-out;

    transition: all 0.25s ease-out;

  }

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -33%;
  }

  .row-offcanvas-left.active {

    left: 33%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    position: absolute;

    top: 0;

    width: 33%;

    height: 100%;

  }

}

/*

* Off Canvas wider at sm breakpoint

* --------------------------------------------------

*/

@media screen and (max-width: 34em) {

  .row-offcanvas-left
  .sidebar-offcanvas {

    left: -45%;

  }

  .row-offcanvas-left.active {

    left: 45%;

    margin-left: -6px;

  }

  .sidebar-offcanvas {

    width: 45%;

  }

}

.card {

    overflow:hidden;

}

.card-block .rotate {

    z-index: 8;

    float: right;

    height: 100%;

}

.card-block .rotate i {

    color: rgba(20, 20, 20, 0.15);

    position: absolute;

    left: 0;

    left: auto;

    right: -10px;

    bottom: 0;

    display: block;

    -webkit-transform: rotate(-44deg);

    -moz-transform: rotate(-44deg);

    -o-transform: rotate(-44deg);

    -ms-transform: rotate(-44deg);
    transform: rotate(-44deg);

}

HTML

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/brandname/css/style.css" rel="stylesheet">

    <title>Dashboard | BrandName</title>

      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">

      </button>

        BrandName

        <button type="button" class="hidden-md-up navbar-toggler" data-toggle="offcanvas" title="Toggle responsive left sidebar">

        </button>

              1 Alerts

               Settings

               Profile

               Logout

Dashboard

              Sites

Item 1

Item 2

Dashboard

Users

134

Posts

87

Tweets

125

Shares

36

©2017 BrandName

Body:
padding-top on body should be the same height as your navbar.

In this case:

body { padding-top: 48px; }

If you need more spacing for the content in the left nav and main content area, add padding/margin to .so-sidebar and .main.


问:
Comprehensive list of programs on different operating systems
How would I get a list of EVERY program into a text file for windows 95-windows 10. The uninstall programs in control panel doesn't have the version and publisher for the older operating systems, and wmic does not display every program. Even the uninstall registry, which I thought would be my savior, does not list every program. I can see discrepancies between that and the uninstall programs tab. Powershell and the like are off the table since it is relatively new.</p>

答:
Some combination of the following:

Enumerate registry for HKEY_CURRENT_USER\Software\Microsoft\CurrentVersion\Uninstall and HKEY_LOCAL_MACHINE\Software\Microsoft\CurrentVersion\Uninstall. And probably HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall on 64-bit os (might be duplicated).  These are the list of installed programs that appear in the Control Panel's "Program and Features" section.  Notice that some of the entries are straight-forward and have most of the data you want.  Others are a GUID - this corresponds to an MSI installation.

For all the entries obtained in #1 that reference a GUID, use the MSI API to find the installation information you seek.  Start with MsiEnumProducts. From there you can get at version info of installed applications.

Brute force search for EXEs installed in C:\Program Files and C:\Program Files (x86). For each EXE found, you can use this method to get the version information.

You want a list of applications installed from the Windows Store? Ask me for a code sample if that's important too.


问:
AsyncTask: where does the return value of doInBackground() go?
When calling AsyncTask<Integer,Integer,Boolean>, where is the return value of:

protected Boolean doInBackground(Integer... params)?

Usually we start AsyncTask with new AsyncTaskClassName().execute(param1,param2......); but it doesn't appear to return a value.

Where can the return value of doInBackground() be found?

答:
The value is then available in onPostExecute which you may want to override in order to work with the result.

Here is example code snippet from Google's docs:

```<code> private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
      protected Long doInBackground(URL... urls) {
          int count = urls.length;
          long totalSize = 0;
          for (int i = 0; i < count; i++) {
              totalSize += Downloader.downloadFile(urls[i]);
              publishProgress((int) ((i / (float) count) * 100));
          }
          return totalSize;
      }

      protected void onProgressUpdate(Integer... progress) {
          setProgressPercent(progress[0]);
      }

      protected void onPostExecute(Long result) {
          showDialog("Downloaded " + result + " bytes");
      }
 }
</code>```

Body:
The value is then available in onPostExecute which you may want to override in order to work with the result.

Here is example code snippet from Google's docs:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
      protected Long doInBackground(URL... urls) {
          int count = urls.length;
          long totalSize = 0;
          for (int i = 0; i < count; i++) {
              totalSize += Downloader.downloadFile(urls[i]);
              publishProgress((int) ((i / (float) count) * 100));
          }
          return totalSize;
      }

      protected void onProgressUpdate(Integer... progress) {
          setProgressPercent(progress[0]);
      }

      protected void onPostExecute(Long result) {
          showDialog("Downloaded " + result + " bytes");
      }
 }


问:
is postdelayed within postdelayed dangerous?
I am trying to loop a short animation for an app and i found this solution or several of them in many sites and forums. However, the lead developer is telling me that this code will eventually crash the app and i should be using threading instead. Could anyone provide me a detailed explanation why this code would not be efficient to loop an animation? And if possible, does anyone know a way to use threads to accomplish what i stated in the previous lines. Thank you.</p>

```<code>@Override
protected void onStart() {

    h.postDelayed(new Runnable() {
        public void run() {
            LoopImage(rocketAnimation,rocketImage,R.drawable.loops);

            runnable=this;

            h.postDelayed(runnable, delay);
        }
    }, delay);

    super.onStart();
}
</code>```

答: You lead developer needs to educate himself a bit at first. Your code, albeit ugly, will work and I do not see any reason why it would eventually fail or crash the app. Anyway, I also see no much reason you would need that code at all as you should loop the animation using android:repeatCount="infinite" or AnimationUtils calls instead.

Body:
I am trying to loop a short animation for an app and i found this solution or several of them in many sites and forums. However, the lead developer is telling me that this code will eventually crash the app and i should be using threading instead. Could anyone provide me a detailed explanation why this code would not be efficient to loop an animation? And if possible, does anyone know a way to use threads to accomplish what i stated in the previous lines. Thank you.

@Override
protected void onStart() {

    h.postDelayed(new Runnable() {
        public void run() {
            LoopImage(rocketAnimation,rocketImage,R.drawable.loops);

            runnable=this;

            h.postDelayed(runnable, delay);
        }
    }, delay);

    super.onStart();
}


问:
How can I connect a knockout observable with jquery barrating plugin?
http://antenna.io/demo/jquery-bar-rating/examples/

I am using the jquery bar-rating plugin with a knockout viewModel.
Right now, all ratings have to be manually selected,
but I want to make the variable (let's say rating) into observable
and make the bar change when I type something like

```<code>viewModel.rating(2);
</code>```

In this case, only two bars will be selected.

Is there an idea how to do  this?

答:
You'll have to make a custom binding to initialize the element and update its value when the observable changes. You can try using something like the following, but I haven't tested it:

```<code>ko.bindingHandlers.barrating = {
  init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
      $(element).barrating();
  },
  update: function(element, valueAccessor, allBindings, viewModel, bindingContext){
      var value = ko.unwrap(valueAccessor());
      $(element).barrating('set', value);
  }
}
</code>```

...

```<code><select data-bind="barrating: myRatingObservable">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
</code>```

Body:
http://antenna.io/demo/jquery-bar-rating/examples/

I am using the jquery bar-rating plugin with a knockout viewModel.
Right now, all ratings have to be manually selected,
but I want to make the variable (let's say rating) into observable
and make the bar change when I type something like

viewModel.rating(2);

In this case, only two bars will be selected.

Is there an idea how to do  this?

Body:
You'll have to make a custom binding to initialize the element and update its value when the observable changes. You can try using something like the following, but I haven't tested it:

ko.bindingHandlers.barrating = {
  init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
      $(element).barrating();
  },
  update: function(element, valueAccessor, allBindings, viewModel, bindingContext){
      var value = ko.unwrap(valueAccessor());
      $(element).barrating('set', value);
  }
}

...

<select data-bind="barrating: myRatingObservable">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>


问:
how to increase length of edges when plotting a graph in R
Is there a way to plot a graph in r with bigger edge lengths?
I am simply using

library(igraph)

plot(graph)

and do anybody knows why all the edges have variable length?

```<code>**    V1    V2
1      6     1
2      6     5
3      1     0
4      1     6
5      1   385
6      5     4
7      5     6
8      5    98
9      0     1
10     0     2
</code>```

I have data in this format and I am generating a network graph.

答:
You could try a few things:

You could change the margins on your plot:

```<code>par(mar=c(0,0,0,0))
plot(graph)
</code>```

You could change the layout parameters by exploring the igraph documentation on layouts to do things like:

```<code>test.layout <- layout_(g,with_dh(weight.edge.lengths = edge_density(g)/1000))
plot(g, layout = test.layout)
</code>```

Body:
Is there a way to plot a graph in r with bigger edge lengths?
I am simply using

library(igraph)

plot(graph)

and do anybody knows why all the edges have variable length?

**    V1    V2
1      6     1
2      6     5
3      1     0
4      1     6
5      1   385
6      5     4
7      5     6
8      5    98
9      0     1
10     0     2

I have data in this format and I am generating a network graph.

Body:
You could try a few things:

You could change the margins on your plot:

par(mar=c(0,0,0,0))
plot(graph)

You could change the layout parameters by exploring the igraph documentation on layouts to do things like:

test.layout <- layout_(g,with_dh(weight.edge.lengths = edge_density(g)/1000))
plot(g, layout = test.layout)