问:
Sequence does not exist when it does - Postgres/Spring Boot
I am writing a Spring Boot web-app and using a Postgres db to persist my data. I created a table in Postgres using create table user (id bigserial primary key not null, name text not null; and identified its sequence_name by looking at the schema (in this case, it is user_id_seq). Then, in my User entity class in Spring Boot, I added the following:

```<code>@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @SequenceGenerator(name = "user_local_seq", sequenceName = "user_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_local_seq")
    private Long id;
...
</code>```

making sure that the sequenceName matches what I saw earlier. Now when I start my spring boot app, I am able to successfully boot it but I get the following "error" in the trace:

```<code>main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: sequence "user_id_seq" does not exist
</code>```

I killed the app and started it again and this time, I got:

```<code>main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: drop sequence user_id_seq
main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: sequence "user_id_seq" does not exist
</code>```

What does this mean? Am I missing something? Any help/insight is appreciated.

答:
Here is insight.

```<code>ERROR: sequence "user_id_seq" does not exist
</code>```

It mean your sequence either not exist in database  OR the user doesn't has permission to access it.

Solution:

Check user_id_seq in database by command \ds

Grant access on sequence to specific user.

GRANT ALL ON ALL SEQUENCES IN SCHEMA schema_name TO user_name;

Body:
I am writing a Spring Boot web-app and using a Postgres db to persist my data. I created a table in Postgres using create table user (id bigserial primary key not null, name text not null; and identified its sequence_name by looking at the schema (in this case, it is user_id_seq). Then, in my User entity class in Spring Boot, I added the following:

@Entity
@Table(name = "user")
public class User implements Serializable {

    @Id
    @SequenceGenerator(name = "user_local_seq", sequenceName = "user_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_local_seq")
    private Long id;
...

making sure that the sequenceName matches what I saw earlier. Now when I start my spring boot app, I am able to successfully boot it but I get the following "error" in the trace:

main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: sequence "user_id_seq" does not exist

I killed the app and started it again and this time, I got:

main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: drop sequence user_id_seq
main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: sequence "user_id_seq" does not exist

What does this mean? Am I missing something? Any help/insight is appreciated.

Body:
Here is insight.

ERROR: sequence "user_id_seq" does not exist

It mean your sequence either not exist in database  OR the user doesn't has permission to access it.

Solution:

Check user_id_seq in database by command \ds

Grant access on sequence to specific user.

GRANT ALL ON ALL SEQUENCES IN SCHEMA schema_name TO user_name;


来源: stackexchange

问:
Data coming back as undefined in react
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

```<code>    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

And my React Route:

```<code>    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />
</code>```

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

```<code>import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>
        <div className="Router">
          <div className="Navbar">
            <Header />
          </div>
          <div className="Wrapper">
            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />
          </div>
        </div>
      </Router>

    );
  }
}

export default App;
</code>```

答:
After hours of trying different things, I finally got it working. This is how.

Instead of making another API call, I decided to use the already stored pages data in the state. I pass it down as props to the edit page:

```<code>    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} pages={this.state.pages} />
    )} />
</code>```

Then inside the AddEditPage component I did:

```<code>  componentWillReceiveProps(nextProps) {
    const page = nextProps.pages[this.props.match.params.id]
    this.setState(page)
  }
</code>```

I still don't know what is better speed wise though. To reuse the data in the state, or to make another api call for a single object.

ContentLicense: CC BY-SA 3.0

Title: Data coming back as undefined in react

Body:
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

And my React Route:

    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>

            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />

      </Router>

    );
  }
}

export default App;

Body:
After hours of trying different things, I finally got it working. This is how.

Instead of making another API call, I decided to use the already stored pages data in the state. I pass it down as props to the edit page:

    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} pages={this.state.pages} />
    )} />

Then inside the AddEditPage component I did:

  componentWillReceiveProps(nextProps) {
    const page = nextProps.pages[this.props.match.params.id]
    this.setState(page)
  }

I still don't know what is better speed wise though. To reuse the data in the state, or to make another api call for a single object.


问:
How can I consistently handle vertical scroll bars in table with scrollable tbody?
I have a table with a thead and tbody. The table with thead is "fixed", but the div that contains the table with the tbody scrolls. The problem is that I cannot find a consistent way to handle the scroll bars. For example, if the user has (via their system settings) the scrollbars set to always show, then the columns inside the tbody are pushed to the left. If they have their scroll bars set to only show on scroll, then it looks fine.

Here is a simplified version of what I'm trying to do:

```<code><div class="this_is_fixed">
    <table class="my_table">
        <thead>
            <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </thead>
    </table>
</div>
<div class="scroll_container">
    <div class="scroll">
        <table class="my_table">
            <tbody>
                <tr>
                    <td>Col 1</td>
                    <td>Col 2</td>
                    <td>Col 3</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

CSS:

```<code>.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}
</code>```

The table inside .scroll is shifted to the left if the user has their scrollbars set to always show, but is fine if they have it set to only show scrollbars when scrolling. Is there a consistent way for me to handle this (cross browser)? I don't want solutions that involve hiding the scroll bars. Thanks in advance for any solutions!

答:
Solution #1:  Avoid the effect that scrollbars have on width

This is a very simple solution to avoid scrollbars from having an effect on the width of your page.

```<code>html {
    width: 100vw;
}
</code>```

Solution #2:  Always show scrollbars

This is a widely used method to always show scrollbars.

```<code>html {
    overflow-y: scroll;
}
</code>```

To always show an active scrollbar, make the height 101%...

```<code>html {
    height: 101%;
}
</code>```

Example - always showing scrollbar:

html {
    height: 101%;
}
.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="this_is_fixed">
    <table class="my_table">
        <thead>
            <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </thead>
    </table>
</div>
<div class="scroll_container">
    <div class="scroll">
        <table class="my_table">
            <tbody>
                <tr>
                    <td>Col 1</td>
                    <td>Col 2</td>
                    <td>Col 3</td>
                </tr>
            </tbody>
        </table>
    </div>
</div></code>```

Body:
I have a table with a thead and tbody. The table with thead is "fixed", but the div that contains the table with the tbody scrolls. The problem is that I cannot find a consistent way to handle the scroll bars. For example, if the user has (via their system settings) the scrollbars set to always show, then the columns inside the tbody are pushed to the left. If they have their scroll bars set to only show on scroll, then it looks fine.

Here is a simplified version of what I'm trying to do:

                Col 1
                Col 2
                Col 3

                    Col 1
                    Col 2
                    Col 3

CSS:

.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}

The table inside .scroll is shifted to the left if the user has their scrollbars set to always show, but is fine if they have it set to only show scrollbars when scrolling. Is there a consistent way for me to handle this (cross browser)? I don't want solutions that involve hiding the scroll bars. Thanks in advance for any solutions!

Body:
Solution #1:  Avoid the effect that scrollbars have on width

This is a very simple solution to avoid scrollbars from having an effect on the width of your page.

html {
    width: 100vw;
}

Solution #2:  Always show scrollbars

This is a widely used method to always show scrollbars.

html {
    overflow-y: scroll;
}

To always show an active scrollbar, make the height 101%...

html {
    height: 101%;
}

Example - always showing scrollbar:

html {
    height: 101%;
}
.this_is_fixed {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 40px;
}

.scroll_container {
    position: absolute;
    top: 40px;
    left: 0;
    right: 0;
    bottom: 0;
}

.scroll {
    overflow-y: auto;
    width: 100%;
    height: 100%;
}

.my_table thead tr th {
     width: 33.33333%
}

.my_table tbody tr td {
     width: 33.33333%
}

<div class="this_is_fixed">
    <table class="my_table">
        <thead>
            <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </thead>
    </table>
</div>
<div class="scroll_container">
    <div class="scroll">
        <table class="my_table">
            <tbody>
                <tr>
                    <td>Col 1</td>
                    <td>Col 2</td>
                    <td>Col 3</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>


问:
Webbased MySQL interface better that phpMyAdmin
Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes.

I'd like to have deep export functionality like phpMyAdmin but more design features

答:
try checking these out http://www.webresourcesdepot.com/category/goodies/database/

as a client, I recommend EMS Manager, as well as for Posgtres

OwnerDisplayName: Siamak

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: JZ


问:
Function kepps after return ( Recursion C)
This is my code:

```<code>int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            Binary (arr, size, num);
        }
        else
        {
            Binary (&arr[size+1], size, num);
        }
    }

    return -1;
}
</code>```

It doesn't work.
When I debug it (trying to search a number that appears in an array), I see that it goes into the line of 'return size', which it should do (side question- is there a way to put line numbers in the code..) but then it keeps going to the last line and returns -1.
How come I have a return and it doesn't go out of the function?
I first tried not to put any return in the end because I am not supposed to reach to the end, but the compiler says "control reaches end of non-void function" so I added the last return, but obviously it is not the right thing to do..

Thanks

答:
You should return the results of the recursive call</p>

```<code>int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            return Binary (arr, size, num); // Added return
        }
        else
        {
            return Binary (&arr[size+1], size, num); // Added return
        }
    }
}
</code>```

Body:
This is my code:

int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            Binary (arr, size, num);
        }
        else
        {
            Binary (&arr[size+1], size, num);
        }
    }

    return -1;
}

It doesn't work.
When I debug it (trying to search a number that appears in an array), I see that it goes into the line of 'return size', which it should do (side question- is there a way to put line numbers in the code..) but then it keeps going to the last line and returns -1.
How come I have a return and it doesn't go out of the function?
I first tried not to put any return in the end because I am not supposed to reach to the end, but the compiler says "control reaches end of non-void function" so I added the last return, but obviously it is not the right thing to do..

Thanks

Body:
You should return the results of the recursive call

int Binary (int* arr, unsigned int size, int num)
{

    if (0 == size)
    {
        return -1;
    }
    if (1 == size)
    {
        if (arr[0] == num)
        {
            return 0;
        }
        return -1;
    }

    size/= 2;
    if (num == arr[size])
    {
        return size;
    }
    else
    {
        if (num < arr[size])
        {
            return Binary (arr, size, num); // Added return
        }
        else
        {
            return Binary (&arr[size+1], size, num); // Added return
        }
    }
}


问:
context showing nil when trying to send data across Interface Controllers in WatchKit
I have two Interface Controllers with FirstInterfaceController being the one where I have a context object I want to send to SecondInterfaceController. I am wondering why context is showing up as nil when I expect it to be 0 when I tap the buttonAction.

Metadata is defined as follows:

```<code>class Metadata {
    var x = 0

    init (x_parameter: Int) {
        x = x_parameter
    }
}
</code>```

Here is my definition of FirstInterfaceController:

```<code>class FirstInterfaceController: WKInterfaceController {

    var metadata = Metadata(x: 1)

    @IBAction func buttonAction() {
        metadata.x = 0

        // Use pushControllerWithName for a push segue
        pushController(withName: "Ten Point Tiebreaker", context: metadata)
    }
}
</code>```

Here is my Identifier for the SecondInterfaceController

Here is the definition of SecondInterfaceController:

```<code>class SecondInterfaceController: WKInterfaceController {

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        print("context: \(String(describing: context))")    // This prints nil

        // Configure interface objects here.
        if let metadata = context as? Metadata {
            print("x: \(metadata.x)")
        }
    }
}
</code>```

答: The problem I had was that I also had a Push segue so that was causing some issues. I just removed the Push segue and it worked fine.</p>

Body:
I have two Interface Controllers with FirstInterfaceController being the one where I have a context object I want to send to SecondInterfaceController. I am wondering why context is showing up as nil when I expect it to be 0 when I tap the buttonAction.

Metadata is defined as follows:

class Metadata {
    var x = 0

    init (x_parameter: Int) {
        x = x_parameter
    }
}

Here is my definition of FirstInterfaceController:

class FirstInterfaceController: WKInterfaceController {

    var metadata = Metadata(x: 1)

    @IBAction func buttonAction() {
        metadata.x = 0

        // Use pushControllerWithName for a push segue
        pushController(withName: "Ten Point Tiebreaker", context: metadata)
    }
}

Here is my Identifier for the SecondInterfaceController

Here is the definition of SecondInterfaceController:

class SecondInterfaceController: WKInterfaceController {

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        print("context: \(String(describing: context))")    // This prints nil

        // Configure interface objects here.
        if let metadata = context as? Metadata {
            print("x: \(metadata.x)")
        }
    }
}


问:
Jenkins Extended Choice Parameter - using the values
I'm new to Jenkins so this is probably an easy one.  I have the Extended Choice Parameter plugin installed.  I'm using the Multi Select parameter type to pick from a list of servers (SERVER1,SERVER2,SERVER3)  I've set Source for Value, Default Value, and Value Description.

I save it, and it looks great.  I can pick any or all servers for the build.  Now for the big question.. how do I use these values in the build?  Basically I have a step in the build that can take in a comma separated list that is called by a shell command:

```<code>d:\python\deploy.py?serverlist=$blah
</code>```

What do I put in for $blah to use that list of servers?

Just to be clear, if I'm on command line I would do the following:

```<code>d:\python\deploy.py?serverlist=SERVER1,SERVER2,SERVER3
</code>```

I'm sure it's something simple but I just cannot find it in the docs or an example.

答:
We could get the servers list like this

```<code>d:\python\deploy.py?serverlist=$SERVERLIST
</code>```

or this on Windows

```<code>d:\python\deploy.py?serverlist=%SERVERLIST%
</code>```

To see the list of environment variables which we could you, try this URL (change localhost by your Jenkins URL, TEST by the job name, 10 by the build number)

https://localhost:8080/job/TEST/10/injectedEnvVars/

UPDATE to @sniperd's edition:

This URL will shows us the parameters list in the Job:

http://localhost:8080/job/TEST/59/parameters/

Body:
I'm new to Jenkins so this is probably an easy one.  I have the Extended Choice Parameter plugin installed.  I'm using the Multi Select parameter type to pick from a list of servers (SERVER1,SERVER2,SERVER3)  I've set Source for Value, Default Value, and Value Description.

I save it, and it looks great.  I can pick any or all servers for the build.  Now for the big question.. how do I use these values in the build?  Basically I have a step in the build that can take in a comma separated list that is called by a shell command:

d:\python\deploy.py?serverlist=$blah

What do I put in for $blah to use that list of servers?

Just to be clear, if I'm on command line I would do the following:

d:\python\deploy.py?serverlist=SERVER1,SERVER2,SERVER3

I'm sure it's something simple but I just cannot find it in the docs or an example.

Body:
We could get the servers list like this

d:\python\deploy.py?serverlist=$SERVERLIST

or this on Windows

d:\python\deploy.py?serverlist=%SERVERLIST%

To see the list of environment variables which we could you, try this URL (change localhost by your Jenkins URL, TEST by the job name, 10 by the build number)

https://localhost:8080/job/TEST/10/injectedEnvVars/

UPDATE to @sniperd's edition:

This URL will shows us the parameters list in the Job:

http://localhost:8080/job/TEST/59/parameters/


问:
ImportError: No module named anorm
I got the below shown error. Can anyone please help me with a solution?

```<code>from common import anorm, getsize
</code>```

Exception:

```<code>Traceback (most recent call last):   File "<pyshell#10>", line 1, in <module>
   from common import anorm, getsize
ImportError: cannot import name anorm
</code>```

答:
The common module does not contain an importable item named anorm.  Simple as that.

Some possible reasons why:

The common module was not installed correctly.

Misspelling of the name of the item to be imported.

A file named common.py exists in the current directory, which takes precedence over the real common module (wherever it is).

Circular imports (which don't appear to be the case here, given the error traceback).

Title: ImportError: No module named anorm

Body:
I got the below shown error. Can anyone please help me with a solution?

from common import anorm, getsize

Exception:

Traceback (most recent call last):   File "<pyshell#10>", line 1, in <module>
   from common import anorm, getsize
ImportError: cannot import name anorm


问:
Where is the Run Script and Build Phase in Xcode?
To get Carthage set up, the documentation says that you need to add a Run Script.

On your application targets’ “Build Phases” settings tab, click the
  “+” icon and choose “New Run Script Phase”. Create a Run Script in
  which you specify your shell (ex: bin/sh), add the following contents
  to the script area below the shell:

```<code>/usr/local/bin/carthage copy-frameworks
</code>```

and add the paths to the frameworks you want to use under “Input
  Files”, e.g.:

```<code>$(SRCROOT)/Carthage/Build/iOS/Box.framework
$(SRCROOT)/Carthage/Build/iOS/Result.framework
$(SRCROOT)/Carthage/Build/iOS/ReactiveCocoa.framework
</code>```

This script works around an App Store submission bug triggered by
  universal binaries and ensures that necessary bitcode-related files
  and dSYMs are copied when archiving.

However, I can't find the Build Phases tab anymore or Run Script in the Build Settings search. The Xcode 8 Release Notes mention

Xcode 8 provides completely rewritten AppleScript support. A new
  scripting dictionary provides the ability to automate Xcode workflows.

Does that mean there is no more Run Script? I looked at AppleScript but honestly it looks overwhelmingly complex. Do I need to learn AppleScript just to add the simple one liner that I used to do in Xcode?

```<code>/usr/local/bin/carthage copy-frameworks
</code>```

答: Carthage maintainers updated README, it is necessary to add output paths too to prevent useful copying of frameworks. I have released simple script named Carting to automate these steps.</p>

ContentLicense: CC BY-SA 4.0

Body:
To get Carthage set up, the documentation says that you need to add a Run Script.

On your application targets’ “Build Phases” settings tab, click the
  “+” icon and choose “New Run Script Phase”. Create a Run Script in
  which you specify your shell (ex: bin/sh), add the following contents
  to the script area below the shell:

/usr/local/bin/carthage copy-frameworks

and add the paths to the frameworks you want to use under “Input
  Files”, e.g.:

$(SRCROOT)/Carthage/Build/iOS/Box.framework
$(SRCROOT)/Carthage/Build/iOS/Result.framework
$(SRCROOT)/Carthage/Build/iOS/ReactiveCocoa.framework

This script works around an App Store submission bug triggered by
  universal binaries and ensures that necessary bitcode-related files
  and dSYMs are copied when archiving.

However, I can't find the Build Phases tab anymore or Run Script in the Build Settings search. The Xcode 8 Release Notes mention

Xcode 8 provides completely rewritten AppleScript support. A new
  scripting dictionary provides the ability to automate Xcode workflows.

Does that mean there is no more Run Script? I looked at AppleScript but honestly it looks overwhelmingly complex. Do I need to learn AppleScript just to add the simple one liner that I used to do in Xcode?

/usr/local/bin/carthage copy-frameworks


问:
Apache toree - pySpark not loading packages
I have Apache Toree installed following the instructions at https://medium.com/@faizanahemad/machine-learning-with-jupyter-using-scala-spark-and-python-the-setup-62d05b0c7f56.

However I do not manage to import packages in the pySpark kernel by using the PYTHONPATH variable in the kernel file at:

/usr/local/share/jupyter/kernels/apache_toree_pyspark/kernel.json.

Using the notebook I can see the the required .zip in the sys.path and in the os.environ[‘PYTHONPATH’], and the relevant .jar is at os.environ[‘SPARK_CLASSPATH'] the but I get

“No module named graphframe” when importing it with: import graphframe.

Any suggestion on how to get graphframe imported?

Thank you.

答:
I was using the .zip from the dataframes's download page but it does not solve the problem. The correct .zip can be created following the steps in:

https://github.com/graphframes/graphframes/issues/172

Another solution was given at: Importing PySpark packages, although the --packages parameter didn't work for me.

Hope this help.


问:
What is the typeof keyword
I couldn't find what it means in Kotlin docs nor through googling it. It certainly does exist though as IntelliJ highlights it as a keyword an Kotlin's autogenerated keyword list file contains it too. I tried to figure out myself what it does but the only result I got is IntelliJ telling me Unexpected tokens (use ';' to separate expressions on the same line)

What is it and what it does?

答:
Have a look at the list of keywords in Kotlin at https://github.com/JetBrains/kotlin/blob/master/compiler/frontend/src/org/jetbrains/kotlin/lexer/KtTokens.java

```<code>// Reserved for future use: KtKeywordToken TYPEOF_KEYWORD =
KtKeywordToken.keyword("typeof");
</code>```

So this one is not used currently but might be in the future

Title: What is the typeof keyword

Body:
Have a look at the list of keywords in Kotlin at https://github.com/JetBrains/kotlin/blob/master/compiler/frontend/src/org/jetbrains/kotlin/lexer/KtTokens.java

// Reserved for future use: KtKeywordToken TYPEOF_KEYWORD =
KtKeywordToken.keyword("typeof");

So this one is not used currently but might be in the future


问:
Anomaly in output from enumerators in typescript
Can anyone explain the output i am getting from the below code?

enum days { sun = 1, mon = 0, tues };

console.log(days[1]); // returns tues // expected output --  mon

console.log(days[0]); // returns mon // expected output -- sun

Also, please explain how can i get sun printed in this case? This scenario is baffling me. Request you guys to provide valid explanations only after you have executed the code and observed the output.

答:
The way you have constructed your enum is unusual.
As per the documentation undefined enums will automatically create a value for themselves by +1 to the previous value.

Your current enum structure will have two values set to 1. Typescript/javascript seems to select the last item with the desired value.

Your code:

```<code>enum days{
sun = 1,
mon = 0,
tues
}
</code>```

VS    (a similar enum from a project of mine that works fine)

```<code>enum days{
Sun = 0,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
</code>```

As per documentation (https://www.typescriptlang.org/docs/handbook/enums.html)

It does not have an initializer and the preceding enum member was
  constant. In this case the value of the current enum member will be
  the value of the preceding enum member plus one. One exception to this
  rule is the first element on an enum. If it does not have initializer
  it is assigned the value 0

Body:
The way you have constructed your enum is unusual.
As per the documentation undefined enums will automatically create a value for themselves by +1 to the previous value.

Your current enum structure will have two values set to 1. Typescript/javascript seems to select the last item with the desired value.

Your code:

enum days{
sun = 1,
mon = 0,
tues
}

VS    (a similar enum from a project of mine that works fine)

enum days{
Sun = 0,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}

As per documentation (https://www.typescriptlang.org/docs/handbook/enums.html)

It does not have an initializer and the preceding enum member was
  constant. In this case the value of the current enum member will be
  the value of the preceding enum member plus one. One exception to this
  rule is the first element on an enum. If it does not have initializer
  it is assigned the value 0


问:
How to Convert factors to Dates in R
I have a set of dates from this csv file and want to convert them to a date format in R

```<code>BPL16_17 <- read.csv("BPL16:17.csv")
attach(BPL16_17)
newdate<-strptime(Date,format =("%Y-%m-%d"))
newdate
</code>```

for newdate i get; [1] NA NA NA NA NA NA NA NA...

答:
Dataset used in example is flight-data from here .

```<code>#read the dataset
df<-read.csv("D:/data/airline_delay_2014_1.csv", stringsAsFactors = FALSE)

str(df)
'data.frame':   471949 obs. of  27 variables:
 $ YEAR             : int  2014 2014 2014 2014 2014 2014 2014 2014 2014 2014 ...
 $ MONTH            : int  1 1 1 1 1 1 1 1 1 1 ...
 $ DAY_OF_MONTH     : int  25 30 24 1 3 4 5 9 13 12 ...
 $ FL_DATE          : chr  "2014-01-25" "2014-01-30" "2014-01-24" "2014-01-01" ...
 $ CARRIER          : chr  "EV" "EV" "EV" "EV" ...
 $ TAIL_NUM         : chr  "N12530" "N15527" "N11526" "N28529" ...
 $ FL_NUM           : int  4524 4524 4524 4524 4524 4524 4524 4524 4524 4524 ...
 $ ORIGIN           : chr  "LFT" "LFT" "LFT" "LFT" ...
 $ ORIGIN_CITY_NAME : chr  "Lafayette, LA" "Lafayette, LA" "Lafayette, LA" "Lafayette, LA" ...
 $ ORIGIN_STATE_ABR : chr  "LA" "LA" "LA" "LA" ...
 $ ORIGIN_STATE_NM  : chr  "Louisiana" "Louisiana" "Louisiana" "Louisiana" ...
 $ DEST_AIRPORT_ID  : int  12266 12266 12266 12266 12266 12266 12266 12266 12266 12266 ...
 $ DEST             : chr  "IAH" "IAH" "IAH" "IAH" ...
 $ DEST_CITY_NAME   : chr  "Houston, TX" "Houston, TX" "Houston, TX" "Houston, TX" ...
 $ DEST_STATE_ABR   : chr  "TX" "TX" "TX" "TX" ...
 $ DEST_STATE_NM    : chr  "Texas" "Texas" "Texas" "Texas" ...
 $ DEP_TIME         : int  NA NA NA 636 959 700 654 656 651 656 ...
 $ DEP_DELAY        : num  NA NA NA -12 191 12 6 1 -9 1 ...
 $ ARR_TIME         : int  NA NA NA 733 1057 811 757 804 749 800 ...
 $ ARR_DELAY        : num  NA NA NA -23 181 15 1 2 -18 -2 ...
 $ CANCELLED        : num  1 1 1 0 0 0 0 0 0 0 ...
 $ CANCELLATION_CODE: chr  "B" "B" "B" "" ...
 $ AIR_TIME         : num  NA NA NA 38 39 40 43 52 47 40 ...
 $ DISTANCE         : num  201 201 201 201 201 201 201 201 201 201 ...
 $ CARRIER_DELAY    : num  NA NA NA NA 181 12 NA NA NA NA ...
 $ WEATHER_DELAY    : num  NA NA NA NA 0 0 NA NA NA NA ...
 $ X                : logi  NA NA NA NA NA NA ...

class(df$FL_DATE)
[1] "character"
</code>```

convert FL_DATE column to Date class,

```<code>df$FL_DATE<- as.Date(df$FL_DATE, format = "%Y-%m-%d")

#check class now
class(df$FL_DATE)
[1] "Date"
</code>```

Title: How to Convert factors to Dates in R

Body:
I have a set of dates from this csv file and want to convert them to a date format in R

BPL16_17 <- read.csv("BPL16:17.csv")
attach(BPL16_17)
newdate<-strptime(Date,format =("%Y-%m-%d"))
newdate

for newdate i get; [1] NA NA NA NA NA NA NA NA...

Body:
Dataset used in example is flight-data from here .

#read the dataset
df<-read.csv("D:/data/airline_delay_2014_1.csv", stringsAsFactors = FALSE)

str(df)
'data.frame':   471949 obs. of  27 variables:
 $ YEAR             : int  2014 2014 2014 2014 2014 2014 2014 2014 2014 2014 ...
 $ MONTH            : int  1 1 1 1 1 1 1 1 1 1 ...
 $ DAY_OF_MONTH     : int  25 30 24 1 3 4 5 9 13 12 ...
 $ FL_DATE          : chr  "2014-01-25" "2014-01-30" "2014-01-24" "2014-01-01" ...
 $ CARRIER          : chr  "EV" "EV" "EV" "EV" ...
 $ TAIL_NUM         : chr  "N12530" "N15527" "N11526" "N28529" ...
 $ FL_NUM           : int  4524 4524 4524 4524 4524 4524 4524 4524 4524 4524 ...
 $ ORIGIN           : chr  "LFT" "LFT" "LFT" "LFT" ...
 $ ORIGIN_CITY_NAME : chr  "Lafayette, LA" "Lafayette, LA" "Lafayette, LA" "Lafayette, LA" ...
 $ ORIGIN_STATE_ABR : chr  "LA" "LA" "LA" "LA" ...
 $ ORIGIN_STATE_NM  : chr  "Louisiana" "Louisiana" "Louisiana" "Louisiana" ...
 $ DEST_AIRPORT_ID  : int  12266 12266 12266 12266 12266 12266 12266 12266 12266 12266 ...
 $ DEST             : chr  "IAH" "IAH" "IAH" "IAH" ...
 $ DEST_CITY_NAME   : chr  "Houston, TX" "Houston, TX" "Houston, TX" "Houston, TX" ...
 $ DEST_STATE_ABR   : chr  "TX" "TX" "TX" "TX" ...
 $ DEST_STATE_NM    : chr  "Texas" "Texas" "Texas" "Texas" ...
 $ DEP_TIME         : int  NA NA NA 636 959 700 654 656 651 656 ...
 $ DEP_DELAY        : num  NA NA NA -12 191 12 6 1 -9 1 ...
 $ ARR_TIME         : int  NA NA NA 733 1057 811 757 804 749 800 ...
 $ ARR_DELAY        : num  NA NA NA -23 181 15 1 2 -18 -2 ...
 $ CANCELLED        : num  1 1 1 0 0 0 0 0 0 0 ...
 $ CANCELLATION_CODE: chr  "B" "B" "B" "" ...
 $ AIR_TIME         : num  NA NA NA 38 39 40 43 52 47 40 ...
 $ DISTANCE         : num  201 201 201 201 201 201 201 201 201 201 ...
 $ CARRIER_DELAY    : num  NA NA NA NA 181 12 NA NA NA NA ...
 $ WEATHER_DELAY    : num  NA NA NA NA 0 0 NA NA NA NA ...
 $ X                : logi  NA NA NA NA NA NA ...

class(df$FL_DATE)
[1] "character"

convert FL_DATE column to Date class,

df$FL_DATE<- as.Date(df$FL_DATE, format = "%Y-%m-%d")

#check class now
class(df$FL_DATE)
[1] "Date"


问:
Database design to manage data from Serial Port?
I'm writing codes to capture Serial Port data (e.g. micrometer) and do the following

real time display and graphing

delete/modify/replace existing data by focus and re-measurement,

save data somewhere for additional statistical analysis (e.g. in Excel).  So out put as .csv is also an option

Because each measurement may capture hundreds to thousands of data (measurement points), I'm not sure how shall go about to design my database - shall I create a new row for each data received, or shall I push all data into an array and store as a super long string separated by a comma into the database? For such application, do I need Server 2008 or would Server 2008 Express will be sufficient. What are their pros/cons in terms of performance?

Is it possible to create such as application where client won't need to install sql server?

答:
What do you want (or what do you think you want) a relational database for?

Based on the simple requirements you expressed here (and assuming there are none other), I would suggest flat files (this could be either plain text, one sample per line, or binary). But I really don't think I have enough information to make a decision on your behalf. Some key questions are:

Do you need to share the data with others, who uses the data, where, over the network? (this will dictate the format you save the data in and a few other things)

How much data do you need to store, how fast does it get measured and over what period of time to measure and store this data? (this will tell you whether to use compression, or some other space saving scheme or not, this will also give you pointers to resource requirements)

How easily retrievable does it need to be? (this will give pointers as to what data management you need: how to name files, where to store them...)

What sort of analysis do you need to do on it? (do you want to analyse several files together, just one file, data from a given day, data for a given port... ?)

... and many more such questions.

Depending on answers to these questions you might be happy with an old 386 computer, or you might need a modern 8-core.


问:
Check or uncheck all radio inputs by id on radio yes/no selection
My issue is that i cannot edit the form code output so would like to target radio ids to check or uncheck depending on if a different radio button is selected. Would this is be possible? - i can add a function call on the  tag or use jquery - but i cannot edit the form code itself like adding onclick events.

Pseudo code would be:

```<code>If #unsubYes is checked Then
uncheck #option1Yes + #option2Yes AND
check #option1No + #option2No

If #unsubNo is checked Then
uncheck #option1No + #option2No AND
check #option1Yes + #option2Yes
</code>```

Link to JS fiddle html

Any help appreciated.

Cheers,
Chris

答:
$("[name='unsub']").on('change', function(){
    var val = $(this).val();
    var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
    $("input[value='"+reverseVal+"']:not([name='unsub'])").prop('checked', true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span>Option 1</span><br />
<label>
  <input type="radio" name="option1" id="option1Yes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="option1" id="option1No" value="No">
  No
</label>
<br /><br />
<span>Option 2</span><br />
<label>
  <input type="radio" name="option2" id="option2Yes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="option2" id="option2No" value="No">
  No
</label>
<hr />
<span>Unsubscribe from all</span><br />
<label>
  <input type="radio" name="unsub" id="unsubYes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="unsub" id="unsubNo" value="No">
  No
</label>
<br /><br />
<input type="submit" value="submit">
</form></code>```

Body:
My issue is that i cannot edit the form code output so would like to target radio ids to check or uncheck depending on if a different radio button is selected. Would this is be possible? - i can add a function call on the  tag or use jquery - but i cannot edit the form code itself like adding onclick events.

Pseudo code would be:

If #unsubYes is checked Then
uncheck #option1Yes + #option2Yes AND
check #option1No + #option2No

If #unsubNo is checked Then
uncheck #option1No + #option2No AND
check #option1Yes + #option2Yes

Link to JS fiddle html

Any help appreciated.

Cheers,
Chris

Body:
$("[name='unsub']").on('change', function(){
    var val = $(this).val();
    var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
    $("input[value='"+reverseVal+"']:not([name='unsub'])").prop('checked', true);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span>Option 1</span><br />
<label>
  <input type="radio" name="option1" id="option1Yes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="option1" id="option1No" value="No">
  No
</label>
<br /><br />
<span>Option 2</span><br />
<label>
  <input type="radio" name="option2" id="option2Yes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="option2" id="option2No" value="No">
  No
</label>
<hr />
<span>Unsubscribe from all</span><br />
<label>
  <input type="radio" name="unsub" id="unsubYes" value="Yes">
  Yes
</label>
<label>
  <input type="radio" name="unsub" id="unsubNo" value="No">
  No
</label>
<br /><br />
<input type="submit" value="submit">
</form>


问:
The requested PHP extension dom is missing from your system
So I just installed Scotchbox (a vagrant setup).
https://github.com/scotch-io/scotch-box

I'm trying to install a composer dependancy when I get the following error.

```<code>Problem 1
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- Installation request for phpunit/php-code-coverage (locked at 4.0.8) -> satisfiable by phpunit/php-code-coverage[4.0.8].
</code>```

What I've tried

Some other thread suggested that this is included in the php-xml package. I tried installing this doing

```<code>sudo apt-get install php7.0-xml
sudo service apache2 restart
</code>```

But that didn't work.
Any idea what other solutions might work? I'm starting to pull my hair out.

答:
Try</p>

```<code>sudo apt-get install php7.0-common
</code>```

Body:
So I just installed Scotchbox (a vagrant setup).
https://github.com/scotch-io/scotch-box

I'm trying to install a composer dependancy when I get the following error.

Problem 1
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
- Installation request for phpunit/php-code-coverage (locked at 4.0.8) -> satisfiable by phpunit/php-code-coverage[4.0.8].

What I've tried

Some other thread suggested that this is included in the php-xml package. I tried installing this doing

sudo apt-get install php7.0-xml
sudo service apache2 restart

But that didn't work.
Any idea what other solutions might work? I'm starting to pull my hair out.

Body:
Try

sudo apt-get install php7.0-common


问:
Enter-PSSession to remote server fails with "cannot find the computer"
My desktop is win7 and I am trying to connect to a server 2012.

Both hosts are on the same domain.

If I do:

```<code>Enter-PSSession -ComputerName *ServerName***
</code>```

I get the following failure message from winrm

Enter-PSSession : Connecting to remote server xxx failed with the
  following error message : WinRM cannot process the request. The following error occurred while using
  Kerberos authentication: Cannot find the computer xxx. Verify that the
  computer exists on the network and that the name provided is spelled correctly.*

It doesn't matter if I use just the server name or if I enter it fully qualified.

Both systems show $PSVersionTable.PSVersion  4 0 -1 -1

I have tried the various troubleshooting hints that I found i.e.

run Enable-PSRemoting -Force and also set TrustedHosts = * on both sides.

I also disabled the firewall service on both sides.

When I try to Enter-PSSession from the server to my desktop it works as desired.

But from my desktop to the server I always get the error message that the computer cannot be found.

答:
This is most likely caused by your netbios name being different from the server's hostname. Try to connect with the netbios name instead.

Determine the correct name by running the following command in powershell:

"$env:COMPUTERNAME.$env:USERDNSDOMAIN"

Body:
My desktop is win7 and I am trying to connect to a server 2012.

Both hosts are on the same domain.

If I do:

Enter-PSSession -ComputerName *ServerName***

I get the following failure message from winrm

Enter-PSSession : Connecting to remote server xxx failed with the
  following error message : WinRM cannot process the request. The following error occurred while using
  Kerberos authentication: Cannot find the computer xxx. Verify that the
  computer exists on the network and that the name provided is spelled correctly.*

It doesn't matter if I use just the server name or if I enter it fully qualified.

Both systems show $PSVersionTable.PSVersion  4 0 -1 -1

I have tried the various troubleshooting hints that I found i.e.

run Enable-PSRemoting -Force and also set TrustedHosts = * on both sides.

I also disabled the firewall service on both sides.

When I try to Enter-PSSession from the server to my desktop it works as desired.

But from my desktop to the server I always get the error message that the computer cannot be found.


问:
Unable to access GZipStrean due to protection level
I just want to access System.IO.Compression.GZipStream class to decompress Web Http response. But I am unable to access GZipStream class due to protection level. I am using Mvvm cross for mobile development.

Here is GZipStream class code :

namespace System.IO.Compression

{

```<code>internal class GZipStream : Stream

{
    public GZipStream(Stream stream, CompressionMode mode);
    public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen);
</code>```

}
}

I need to access first constructor to create instance of GZipStream.

So is there any other way to create GZipStream type instance ?

答:
In Xamarin Forms for PCL I resolve this problem just replaced TargetFrameworkProfile in your_project_name .csproj

FROM:

Profile259

TO:

Profile111

Also possible to try install NuGet package Microsoft.Bcl.Compression, this option although resolve problem with access to GZipStream, but in time compilation I had System.TypeLoadException.

Body:
I just want to access System.IO.Compression.GZipStream class to decompress Web Http response. But I am unable to access GZipStream class due to protection level. I am using Mvvm cross for mobile development.

Here is GZipStream class code :

namespace System.IO.Compression

{

internal class GZipStream : Stream

{
    public GZipStream(Stream stream, CompressionMode mode);
    public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen);

}
}

I need to access first constructor to create instance of GZipStream.

So is there any other way to create GZipStream type instance ?


问:
What does $ tag mean in Appcelerator Titanium
What does $ tag mean in Appcelerator? When I use this tag in any controller.js it works. But when I use it in libs js file I get error.</p>

```<code>$.resetClass(someController, 'someClass')
</code>```

答:
$ tag is the holder for a controller file. It is autogenerated by Titanium for every controller file.

Let's say you have these sets of files :
1 - index.xml, index.js, index.tss
2 - win.xml, win.js, win.tss
3 - dialog.xml, dialog.js, dialog.tss

So, $ is available for every .js file & it is the same thing which is returned by this:

dialog.js

```<code>var dollar = Alloy.createController('win');
// now dollar is exactly equal to ($ in win.js) & so does for other .js files.
</code>```

In win.xml, suppose you have a topmost Window or View with an id='topView' & some internal child views lets say having ids = view1, view2, etc...

win.xml

```<code><Alloy>
 <View id='topView'>
   <View id='view1'>
     <View id='view2'></View>
   </View>
 </View>
</Alloy>
</code>```

now in win.js file, you can access these view ids like $.topView, $.view1, $.view2 & so on like this...

Finally in that var dollar code, you can access these ids from any other js file just like this:

```<code>var topView = dollar.topView;
var view1 = dollar.view1;
var view2 = dollar.view2;
</code>```

To elaborate more, suppose you want to export some functionality from a controller to any other controller, you can do it this way:

win.js

```<code>$.methodNameToAccess = function () {alert('Kerberos!')};
</code>```

here is the magic of exporting methods

dialog.js

```<code>dollar.methodNameToAccess();    // alerts your name :)
</code>```

This was the basic guide what $ is and it's beyond that.. so it's your task now to explore it & use it efficiently.

Code Strong!

Body:
What does $ tag mean in Appcelerator? When I use this tag in any controller.js it works. But when I use it in libs js file I get error.

$.resetClass(someController, 'someClass')

Body:
$ tag is the holder for a controller file. It is autogenerated by Titanium for every controller file.

Let's say you have these sets of files :
1 - index.xml, index.js, index.tss
2 - win.xml, win.js, win.tss
3 - dialog.xml, dialog.js, dialog.tss

So, $ is available for every .js file & it is the same thing which is returned by this:

dialog.js

var dollar = Alloy.createController('win');
// now dollar is exactly equal to ($ in win.js) & so does for other .js files.

In win.xml, suppose you have a topmost Window or View with an id='topView' & some internal child views lets say having ids = view1, view2, etc...

win.xml

<Alloy>
 <View id='topView'>
   <View id='view1'>
     <View id='view2'></View>
   </View>
 </View>
</Alloy>

now in win.js file, you can access these view ids like $.topView, $.view1, $.view2 & so on like this...

Finally in that var dollar code, you can access these ids from any other js file just like this:

var topView = dollar.topView;
var view1 = dollar.view1;
var view2 = dollar.view2;

To elaborate more, suppose you want to export some functionality from a controller to any other controller, you can do it this way:

win.js

$.methodNameToAccess = function () {alert('Kerberos!')};

here is the magic of exporting methods

dialog.js

dollar.methodNameToAccess();    // alerts your name :)

This was the basic guide what $ is and it's beyond that.. so it's your task now to explore it & use it efficiently.

Code Strong!


问:
Python unexpectedly moving files with os.rename
I have a script that:

Loops through all the files in a directory + its subdirectories

Creates folder for each unique year in the list of files

Moves files to their respective folder years

Renames them based on timestamp + unique number.

When I run parts 1-3 only, it moves the files to the folders correctly.

When I run parts 1-4 (including the os.rename part), it renames the files AFTER moving them back to the parent directory.

Start file structure:

```<code>parent_folder
      --> file.txt    modified 01-21-2012
      --> file2.txt   modified 09-30-2013
      --> file3.txt   modified 06-21-2017
</code>```

Expected result:

```<code>parent_folder
--> '2012'
      --> 2012-01-21-1.txt
--> '2013'
      --> 2013-09-30-2.txt
--> '2017'
      --> 2017-06-21-3.txt
</code>```

Actual result:

```<code>parent_folder
--> '2012'
--> '2013'
--> '2017'
--> '2012-01-21-1.txt'
--> '2013-09-30-2.txt'
--> '2017-06-21-4.txt'
</code>```

As you can see, it renamed the files but moved them out of their folders. Why is it doing this?

My code (I inserted print statements for logging):

```<code>import os, datetime, sys, shutil

#PART 1 : Change to the inputted directory
#===============================

# This is the directory I will work on.
p = 'ENTER_FOLDER_PATH_HERE'
print('This is the directory that will be organized:')
print(os.getcwd())
if os.path.isdir(p): # check if directory exists
    print("Step 1: Changing directory")
    os.chdir(p)

#PART 2 : Make a folder for each unique year
#===========================================
    fileNames = next(os.walk(os.getcwd()))[2] # list files, excluding subdirectories
    f = {}
    filename = []
    dates = []

    # Loop through each file and grab the unique year.
    # Store the file (key) and its modified year (value) into dictionary 'f'.
    for name in fileNames:
        f[name] = datetime.datetime.fromtimestamp(os.path.getmtime(name)).strftime("%Y")
        dates = list(set(f.values()))

    # Create the list of unique folders from the dictionary.
    print("Step 2: Creating the following folders:\n", dates)
    print('\n')
    [os.mkdir(folder) for folder in dates]

#PART 3: Move all files to their respective folders based on modified year.
#==========================================================================
    if sys.platform == 'Windows':
        print("Step 3: moving files...")
        [shutil.move(key, os.getcwd() + '\\' + value) for key, value in f.items()]
    elif sys.platform == 'darwin':
        print("Step 3: moving files...")
        [shutil.move(key, os.getcwd() + '//' + value) for key, value in f.items()]
    else:
        print("Sorry, this script is not supported in your OS.")
else:
    print("Oops, seems like that directory doesn't exist. Please try again.")

#PART 4: Rename the files
#==========================================================================
# Get each file in directory and renames it to its modified date, Y-M-D format
count=1
for root, dir, files in os.walk(p):
    for file in files:
        if not file.startswith('.'): # ignore hidden files
            filePath = os.path.join(root,file)
            ext = os.path.splitext(filePath)[1]
            print("File number: ", count, file, ext)
            print('\n')
            os.rename(filePath, datetime.datetime.fromtimestamp(os.path.getmtime(filePath)).strftime("%Y-%m-%d") + '-' + str(count) + ext)
        count += 1
        print(filePath)
</code>```

Logs:

```<code>This is the directory that will be organized:
TEST_PATH
Step 1: Changing directory
Step 2: Creating the following folders:
 ['2013', '2012', '2017']

Step 3: moving files...
File number:  1 2012-01-21-1.jpg TEST_PATH/2012/2012-01-21-1.jpg
TEST_PATH//2012/2012-01-21-1.jpg

File number:  2 2013-09-30-2.jpg TEST_PATH/2013/2013-09-30-2.jpg
TEST_PATH/2013/2013-09-30-2.jpg
TEST_PATH/2013/2013-09-30-2.jpg

File number:  4 June 21 2017.txt TEST_PATH/2017/June 21 2017.txt
TEST_PATH/2017/June 21 2017.txt
</code>```

答:
It moves the file, because of the working directory you are currently in. I gues it works just like mv command. The resulting file, after raname, will be put in a path specified by the second argument of the os.rename function, relative to cwd. If you want it to work correctly you need to specify the relative path with the new filename.

Btw. you can do steps 3&4 at once this way.

Body:
I have a script that:

Loops through all the files in a directory + its subdirectories

Creates folder for each unique year in the list of files

Moves files to their respective folder years

Renames them based on timestamp + unique number.

When I run parts 1-3 only, it moves the files to the folders correctly.

When I run parts 1-4 (including the os.rename part), it renames the files AFTER moving them back to the parent directory.

Start file structure:

parent_folder
      --> file.txt    modified 01-21-2012
      --> file2.txt   modified 09-30-2013
      --> file3.txt   modified 06-21-2017

Expected result:

parent_folder
--> '2012'
      --> 2012-01-21-1.txt
--> '2013'
      --> 2013-09-30-2.txt
--> '2017'
      --> 2017-06-21-3.txt

Actual result:

parent_folder
--> '2012'
--> '2013'
--> '2017'
--> '2012-01-21-1.txt'
--> '2013-09-30-2.txt'
--> '2017-06-21-4.txt'

As you can see, it renamed the files but moved them out of their folders. Why is it doing this?

My code (I inserted print statements for logging):

import os, datetime, sys, shutil

#PART 1 : Change to the inputted directory
#===============================

# This is the directory I will work on.
p = 'ENTER_FOLDER_PATH_HERE'
print('This is the directory that will be organized:')
print(os.getcwd())
if os.path.isdir(p): # check if directory exists
    print("Step 1: Changing directory")
    os.chdir(p)

#PART 2 : Make a folder for each unique year
#===========================================
    fileNames = next(os.walk(os.getcwd()))[2] # list files, excluding subdirectories
    f = {}
    filename = []
    dates = []

    # Loop through each file and grab the unique year.
    # Store the file (key) and its modified year (value) into dictionary 'f'.
    for name in fileNames:
        f[name] = datetime.datetime.fromtimestamp(os.path.getmtime(name)).strftime("%Y")
        dates = list(set(f.values()))

    # Create the list of unique folders from the dictionary.
    print("Step 2: Creating the following folders:\n", dates)
    print('\n')
    [os.mkdir(folder) for folder in dates]

#PART 3: Move all files to their respective folders based on modified year.
#==========================================================================
    if sys.platform == 'Windows':
        print("Step 3: moving files...")
        [shutil.move(key, os.getcwd() + '\\' + value) for key, value in f.items()]
    elif sys.platform == 'darwin':
        print("Step 3: moving files...")
        [shutil.move(key, os.getcwd() + '//' + value) for key, value in f.items()]
    else:
        print("Sorry, this script is not supported in your OS.")
else:
    print("Oops, seems like that directory doesn't exist. Please try again.")

#PART 4: Rename the files
#==========================================================================
# Get each file in directory and renames it to its modified date, Y-M-D format
count=1
for root, dir, files in os.walk(p):
    for file in files:
        if not file.startswith('.'): # ignore hidden files
            filePath = os.path.join(root,file)
            ext = os.path.splitext(filePath)[1]
            print("File number: ", count, file, ext)
            print('\n')
            os.rename(filePath, datetime.datetime.fromtimestamp(os.path.getmtime(filePath)).strftime("%Y-%m-%d") + '-' + str(count) + ext)
        count += 1
        print(filePath)

Logs:

This is the directory that will be organized:
TEST_PATH
Step 1: Changing directory
Step 2: Creating the following folders:
 ['2013', '2012', '2017']

Step 3: moving files...
File number:  1 2012-01-21-1.jpg TEST_PATH/2012/2012-01-21-1.jpg
TEST_PATH//2012/2012-01-21-1.jpg

File number:  2 2013-09-30-2.jpg TEST_PATH/2013/2013-09-30-2.jpg
TEST_PATH/2013/2013-09-30-2.jpg
TEST_PATH/2013/2013-09-30-2.jpg

File number:  4 June 21 2017.txt TEST_PATH/2017/June 21 2017.txt
TEST_PATH/2017/June 21 2017.txt


问:
Satellite 6 Job Invocation search query : using facts (faster)
I'm using Satellite 6 to manage EL 5, 6 and 7x hosts.
I've been trying to perform a Job Invocation (via Monitor-> Jobs -> Run Jobs) on a host of servers, based on a custom fact that I wrote (the fact is called ad_domain and basically tells you whether its active directory joined or not).

However I can't figure out how to do this....is this even possible?
I'm a Satellite newbie...I don't even even know what parameters I can use in the Search Query to do this. Can anyone help enlighten? Is it possible to specify a factor/facter value(s) in the Search Query so that it will resolve only to hosts that match that value(s)?

Appreciate your help in advance,
Sue

答:
You can try

facts.ad_domain = value

Body:
You can try

facts.ad_domain = value


问:
Tuple and List to formatted string in python
In Python3.4 I have a tuple

```<code>t = ('A', 'B', 'C')
</code>```

and a list

```<code>l = ['P', 'Q', 'R']
</code>```

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

答:
If you really insist on your format and no for loops, then probably try something like the following:</p>

```<code>l_result = '(@' + '; @'.join(l) + ')'
t_result = '(#' + ';#'.join(t) + ')'
</code>```

Body:
In Python3.4 I have a tuple

t = ('A', 'B', 'C')

and a list

l = ['P', 'Q', 'R']

and I need to convert the tuple to a string formatted as "(#A;#B;#C)" and the list to a string formatted as "(@P; @Q; @R)". The obvious way is to traverse using a for loop and string manipulation.

Is there a way to do it without running the loop?

Thanks!

Body:
If you really insist on your format and no for loops, then probably try something like the following:

l_result = '(@' + '; @'.join(l) + ')'
t_result = '(#' + ';#'.join(t) + ')'


问:
Twitter Bootstrap tags input doesn't remove placeholder when onfocus
I have been scratching my head since yesterday on this problem, which I cannot solve. I am a new starter to Twitter Bootstrap and everything was going well until yesterday.

I am using the latest JQuery v1.11.1 and Twitter Bootstrap v3.3.1. Yesterday I downloaded Bootstrap Tags Input, from here: http://timschlechter.github.io/bootstrap-tagsinput/examples/

The plugin works and I have changed the CSS styles to match my page layout but the problem I am having is that the placeholder attribute will not disappear when on focus. If I type in a tag and add a comma value the placeholder will show until I start typing and then it will disappear again.

I have tried using JQuery onfocus function to remove the attribute when onfocus but it doesn't do anything. What I want to achieve is that when onfocus the placeholder does not show at that point not even on blur.

My input field is demonstrated below:

<input type="text" name="customer_tags" id="customer_tags" value="" placeholder="Enter you tags" data-role="tagsinput" required />

答:
I was able to do a quick fix using jquery. The behavior I wanted should do two things:

1) Remove placeholder while on page after I've focused and started typing. So I will run it on keyup.

```<code>$(document).on('keyup', '.bootstrap-tagsinput input', function(){
    $(this).attr('placeholder', '')
})
</code>```

2) If there are already labels in an input, then I don't obviously need a placeholder. I run this on page load.

```<code>$('.labels').each(function(){
    var len = $(this).tagsinput('items');
    if(len){
        var $input = $($(this).prev().children('input').get(0));
        $input.attr('placeholder', '');
    }
})
</code>```

Body:
I was able to do a quick fix using jquery. The behavior I wanted should do two things:

1) Remove placeholder while on page after I've focused and started typing. So I will run it on keyup.

$(document).on('keyup', '.bootstrap-tagsinput input', function(){
    $(this).attr('placeholder', '')
})

2) If there are already labels in an input, then I don't obviously need a placeholder. I run this on page load.

$('.labels').each(function(){
    var len = $(this).tagsinput('items');
    if(len){
        var $input = $($(this).prev().children('input').get(0));
        $input.attr('placeholder', '');
    }
})


问:
ASP.NET MVC Populate DropDown thru ViewBag
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

```<code>        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }
</code>```

View file :

```<code>@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

<!-- data is used for grid -->
var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

<!-- ERROR LINE   -->
@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")
</code>```

ERROR

```<code>Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active
</code>```

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

```<code>       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }
</code>```

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

答:
Please use below code i hope that will help your query.</p>

```<code>ViewBag.TableList = DataFiller.GetTableNames();

@Html.DropDownList("ID", new SelectList(ViewBag.TableList, "ID", "Name"));
</code>```

Body:
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }

View file :

@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")

ERROR

Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

Body:
Please use below code i hope that will help your query.

ViewBag.TableList = DataFiller.GetTableNames();

@Html.DropDownList("ID", new SelectList(ViewBag.TableList, "ID", "Name"));


问:
How to add number of views in database in php mysql
How do we add number of views ( eg  most viewed articles) in php mysql database. How to add numbers when a person click to database? </p>

答:
There are a couple different options.  If you have a Sproc that gets your data you could have it increment the counter every time it does so.  That would not give you unique views, but i think it would do the trick for you.

You could run the update yourself, maybe base it off a session value to make it a unique view.  If you want more details on either of these, let me know.


问:
Using disassembler to debug error Python
Reading "97 things every programmer should know" I found interesting essay about code analysis tools.

Author claims that disassembler from Python standard library can be very useful to debug your every day code

Here it goes:
"One thing this library(Python standard library disassembler) can disassemble
is your last stack trace, giving you feedback on exactly which bytecode instruction threw the last uncaught exception."

But there is no explanation of this in the book

So does anybody has idea how above module could be useful for debugging ?

答:
While a disassembler can be a tool to help you understand how Python understands what you write, it is not the only tool. there are other tools that can help as well. And as we will see some of them can work together.

So here's a little piece of Python:

```<code>def five():
    return 5
print(five())
</code>```

And here part of a disassembly of it using the cross platform disassembler I wrote which is called xdis:

```<code># Python bytecode 3.4 (3310)
# Disassembled from Python 3.4.2 (default, May 17 2015, 22:17:04)
# [GCC 4.8.2]
# Timestamp in code: 1499405520 (2017-07-07 01:32:00)
# Source code size mod 2**32: 39 bytes

# Method Name:       <module>
# Filename:          five.py
# Argument count:    0
# Kw-only arguments: 0
# Number of locals:  0
# Stack size:        2
# Flags:             0x00000040 (NOFREE)
# First Line:        1
# Constants:
#    0: <code object five at 0x7f99dd4e88a0, file "five.py", line 1>
#    1: 'five'
#    2: None
# Names:
#    0: five
#    1: print
  1:
        LOAD_CONST                0 (<code object five at 0x7f99dd4e88a0, file "five.py", line 1>)
        LOAD_CONST                1 ('five')
        MAKE_FUNCTION             0 (0 positional, 0 name and default, 0 annotations)
        STORE_NAME                0 (five)

  3:
        LOAD_NAME                 1 (print)
        LOAD_NAME                 0 (five)
        CALL_FUNCTION             0 (0 positional, 0 keyword pair)
        CALL_FUNCTION             1 (1 positional, 0 keyword pair)
        POP_TOP
        LOAD_CONST                2 (None)
        RETURN_VALUE
...
</code>```

(This is Python 3.4, other versions vary the details a little.)

The first thing to note is that python thinks this code comes from a file with a path name  five.py. If you've happened to rename the file but not the python code, this can confuse Python. Or the filename could be tmp/five.py instead and then you should look for that instead. Also, in Python versions 3 and up there is the size of the file (modulo 2**32) as a check to see if the five.py on the filesystem is the same as the one Python saw when it compiled the file.

I draw your attention to the beginning of the code: we are loading a constant object which happens to be code for a function! And then then name of the function and finally calling MAKE_FUNCTION and storing that in a variable called five.

The thing that is a bit unusual if you are used to a compiled language like C++, Go, or Java which doesn't do this, is that the function is created right there on the spot when you run the program. If my program had another instruction before and were instead:

```<code>x = five()  # five is hasn't been defined here!
def five(): ...
</code>```

This would fail because that the MAKE_FUNCTION hasn't been run and so at the beginning five hasn't been defined yet.

Now I'll also suggest that you might be able to learn this using a debugger as well and I suggest again trepan2 or trepan3 which has a disassembly command built into them and even a deparser for that assembly.

Another place where disassembly can be elucidating is in the rare cases where Python does optimization on the code.

Consider this Python source code:

```<code>if 1:
   y = 5
</code>```

Here, in Python versions after around 2.3 will simply notice that if 1: is superfluous and remove that code. But if you had say instead:

```<code>x = 1
if x:
   y = 5
</code>```

That is enough to confound Python to keep the test in. Disassembly is the only way I think you can know this.

The last aspect, is understanding exactly where you are when you stopped in a debugger or hit an error.  You often (but not always) get the line you had the error, but sometimes that can be confusing.  Normal
Python masks information that is useful here, the instruction offset, but I'll show you how to get that and the instruction where you had the error.

Suppose my code is:

```<code>prev = [100] + range(3)
x = prev[prev[prev[0]]]
</code>```

If I run this I will get an IndexError exception.  But which "prev" was it?

trepan2 (or trepan3k) exposes the instruction pointer here. It also gives access to both a disassembler and a deparser. So let's see how that can be used here:

```<code>trepan2 /tmp/boom.py
-> 2 prev = [100] + range(3)
(trepan2) next
(/tmp/boom.py:3 @19): <module>
-- 3 x = prev[prev[prev[0]]]
(trepan2) next
(/tmp/boom.py:3 @32): <module>
!! 3 x = prev[prev[prev[0]]]
R=> (<type 'exceptions.IndexError'>, 'list index out of range', <traceback object at
(trepan2) info pc
PC offset is 32.
  2        0 LOAD_CONST          0          100
           3 BUILD_LIST          1
           6 LOAD_NAME           0          0
           9 LOAD_CONST          1          3
          12 CALL_FUNCTION       1          1 positional, 0 keyword pair
          15 BINARY_ADD          None
          16 STORE_NAME          1          1

  3       19 LOAD_NAME           1          1
          22 LOAD_NAME           1          1
          25 LOAD_NAME           1          1
          28 LOAD_CONST          2          0
          31 BINARY_SUBSCR       None
   -->    32 BINARY_SUBSCR       None
          33 BINARY_SUBSCR       None
          34 STORE_NAME          2          2
          37 LOAD_CONST          3          None
          40 RETURN_VALUE        None
</code>```

Ok. So we see where exactly we were, offset 32 (@32 after previously stopping at offset @19), but what does this mean? The trepan debuggers will convert this back into Python so you don't have to do that yourself:

```<code>(trepan2) deparse -p
instruction: 32 BINARY_SUBSCR
x = prev[prev[prev[0]]]
         -------------
Contained in...
Grammar Symbol: binary_subscr
x = prev[prev[prev[0]]]
    -------------------
(trepan2) prev
[100, 0, 1, 2]
</code>```

The above, then, shows you were at offset 32 (not 31 or 33) and that particular prev access wasn't the first access prev[0] but the one after that prev[prev[0]].

Although having both a disasembler, deparser inside the debugger, makes it so you don't have to know that much about what's going on. But I don't think it hurts to know what the instructions do or what the sequence of instructions is.

Body:
While a disassembler can be a tool to help you understand how Python understands what you write, it is not the only tool. there are other tools that can help as well. And as we will see some of them can work together.

So here's a little piece of Python:

def five():
    return 5
print(five())

And here part of a disassembly of it using the cross platform disassembler I wrote which is called xdis:

# Python bytecode 3.4 (3310)
# Disassembled from Python 3.4.2 (default, May 17 2015, 22:17:04)
# [GCC 4.8.2]
# Timestamp in code: 1499405520 (2017-07-07 01:32:00)
# Source code size mod 2**32: 39 bytes

# Method Name:       <module>
# Filename:          five.py
# Argument count:    0
# Kw-only arguments: 0
# Number of locals:  0
# Stack size:        2
# Flags:             0x00000040 (NOFREE)
# First Line:        1
# Constants:
#    0: <code object five at 0x7f99dd4e88a0, file "five.py", line 1>
#    1: 'five'
#    2: None
# Names:
#    0: five
#    1: print
  1:
        LOAD_CONST                0 (<code object five at 0x7f99dd4e88a0, file "five.py", line 1>)
        LOAD_CONST                1 ('five')
        MAKE_FUNCTION             0 (0 positional, 0 name and default, 0 annotations)
        STORE_NAME                0 (five)

  3:
        LOAD_NAME                 1 (print)
        LOAD_NAME                 0 (five)
        CALL_FUNCTION             0 (0 positional, 0 keyword pair)
        CALL_FUNCTION             1 (1 positional, 0 keyword pair)
        POP_TOP
        LOAD_CONST                2 (None)
        RETURN_VALUE
...

(This is Python 3.4, other versions vary the details a little.)

The first thing to note is that python thinks this code comes from a file with a path name  five.py. If you've happened to rename the file but not the python code, this can confuse Python. Or the filename could be tmp/five.py instead and then you should look for that instead. Also, in Python versions 3 and up there is the size of the file (modulo 2**32) as a check to see if the five.py on the filesystem is the same as the one Python saw when it compiled the file.

I draw your attention to the beginning of the code: we are loading a constant object which happens to be code for a function! And then then name of the function and finally calling MAKE_FUNCTION and storing that in a variable called five.

The thing that is a bit unusual if you are used to a compiled language like C++, Go, or Java which doesn't do this, is that the function is created right there on the spot when you run the program. If my program had another instruction before and were instead:

x = five()  # five is hasn't been defined here!
def five(): ...

This would fail because that the MAKE_FUNCTION hasn't been run and so at the beginning five hasn't been defined yet.

Now I'll also suggest that you might be able to learn this using a debugger as well and I suggest again trepan2 or trepan3 which has a disassembly command built into them and even a deparser for that assembly.

Another place where disassembly can be elucidating is in the rare cases where Python does optimization on the code.

Consider this Python source code:

if 1:
   y = 5

Here, in Python versions after around 2.3 will simply notice that if 1: is superfluous and remove that code. But if you had say instead:

x = 1
if x:
   y = 5

That is enough to confound Python to keep the test in. Disassembly is the only way I think you can know this.

The last aspect, is understanding exactly where you are when you stopped in a debugger or hit an error.  You often (but not always) get the line you had the error, but sometimes that can be confusing.  Normal
Python masks information that is useful here, the instruction offset, but I'll show you how to get that and the instruction where you had the error.

Suppose my code is:

prev = [100] + range(3)
x = prev[prev[prev[0]]]

If I run this I will get an IndexError exception.  But which "prev" was it?

trepan2 (or trepan3k) exposes the instruction pointer here. It also gives access to both a disassembler and a deparser. So let's see how that can be used here:

trepan2 /tmp/boom.py
-> 2 prev = [100] + range(3)
(trepan2) next
(/tmp/boom.py:3 @19): <module>
-- 3 x = prev[prev[prev[0]]]
(trepan2) next
(/tmp/boom.py:3 @32): <module>
!! 3 x = prev[prev[prev[0]]]
R=> (<type 'exceptions.IndexError'>, 'list index out of range', <traceback object at
(trepan2) info pc
PC offset is 32.
  2        0 LOAD_CONST          0          100
           3 BUILD_LIST          1
           6 LOAD_NAME           0          0
           9 LOAD_CONST          1          3
          12 CALL_FUNCTION       1          1 positional, 0 keyword pair
          15 BINARY_ADD          None
          16 STORE_NAME          1          1

  3       19 LOAD_NAME           1          1
          22 LOAD_NAME           1          1
          25 LOAD_NAME           1          1
          28 LOAD_CONST          2          0
          31 BINARY_SUBSCR       None
   -->    32 BINARY_SUBSCR       None
          33 BINARY_SUBSCR       None
          34 STORE_NAME          2          2
          37 LOAD_CONST          3          None
          40 RETURN_VALUE        None

Ok. So we see where exactly we were, offset 32 (@32 after previously stopping at offset @19), but what does this mean? The trepan debuggers will convert this back into Python so you don't have to do that yourself:

(trepan2) deparse -p
instruction: 32 BINARY_SUBSCR
x = prev[prev[prev[0]]]
         -------------
Contained in...
Grammar Symbol: binary_subscr
x = prev[prev[prev[0]]]
    -------------------
(trepan2) prev
[100, 0, 1, 2]

The above, then, shows you were at offset 32 (not 31 or 33) and that particular prev access wasn't the first access prev[0] but the one after that prev[prev[0]].

Although having both a disasembler, deparser inside the debugger, makes it so you don't have to know that much about what's going on. But I don't think it hurts to know what the instructions do or what the sequence of instructions is.


问:
Efficient data/string reading and copy from file (CSV) c
I have read other posts regarding copying data from files. Let me show you why my case is different.
With C I must read 43 Million input lines from a csv file. The entries have no errors and are in this form:

```<code>int, int , int , variable length string with only alphanumerics and spaces , int \n
</code>```

Thing is I'm copying all data to memory in array and lists to do some very very simple averages on it and then outputting all processed data to a file, nothing fancy.
There are three main areas where I need help:

Regarding the string, (my BIGGEST problem is here) it is first read from the file, then is copied to an array and then passed to another functions which will copy it into dynamic memory only if a condition is met. Ex:

```<code>fileAnalizer(){
  while ( ! EOF ){
    char * s = function_to_read_string_from_file();
    data_to_array(s);
  }
  ....
  ....
  processData(arrays);
  dataToFiles(arrays);

}

void data_to_structures(char * s){
  if ( condition is met)
    char * aux = malloc((strlen(s)+1 )* sizeof(char));
    strcpy(aux,s);
  ....
  ...
}
</code>```

As you can see the string is traveled through 3 times. I'm needing a way to do this process more efficiently, traveling the string fewer times. I have tried reading char by char and counting the string length but the entire process becomes slower.

Efficient reading of input: would you recommend first copying all data into a buffer? If so: what type of buffer, and in many blocks or just one?
This is my current reading program:

```<code>void
csvReader(FILE* f){
    T_structCDT c;
    c.string = malloc(MAX_STRING_LENGHT*sizeof(char));
    while (fscanf(f,"%d,%d,%d,%[^,],%d\n",&c.a, &c.b, &c.vivienda, c.c, &c.d)==5 ){
        data_to_structures(c);
    }
}
</code>```

I then have nearly 500 hundred csv lines of processed data to dump in to other files. How would you recommend the dumping? Line by line or again sending the data to a buffer and then doing the dump? My code now looks something like this.

```<code>void dataToFiles(arrayOfStructs immenseAr1, arrayOfStructs immenseAr2){
  for (iteration over immenseAr1) {
      fprintf(f1, "%d,%d,%s\n", immenseAr1[i].a, immenseAr1[i].b, inmenseAr1[i].string);
  }
  for (iteration over immenseAr2) {
      fprintf(f2, "%d,%d,%s\n", inmenseAr2[i].a, inmenseAr2[i].b, inmenseAr2[i].string);
  }
}
</code>```

I must read all data before dumping it. Would you recommend a different method other than storing all data into memory and then analyzing it and then dumping all the analyzed data?
With the 20 Million lines the program is currently taking more than 40 seconds.
I really need to lower that time.

答:
Use aux=strdup(s); instead of calloc(), strlen() & strcpy().

Your OS (filesystem) will usually be very efficient at buffering the data stream.  One might find better a more efficient way to buffer the data stream, but such attempts often just end up redundantly buffering what the OS is already buffering. Your OS most likely provides specific functions that would allow you to bypass the buffering usually done by the OS/filesystem.  Generally, this would mean not using "stdio.h" functions such as fscanf(), etc.

Again, be careful not to unnecessarily double buffer your data.  Keep in mind that the OS will buffer your data, and actually write it out when it is generally most efficient to do so.  (That is why there is a fflush() function... to suggest to the OS that you will wait until it has written all your data before proceeding.)  And, just as there are usually specific OS functions to bypass the OS read buffers, there are generally OS specific functions to bypass the OS write buffers.  However, these functions are probably beyond the scope of your needs (and perhaps this audience).

My summary answer (as I stated above) is that attempting to out-think the OS, and the way it is buffering your data streams, will usually result in less efficient code.

Body:
I have read other posts regarding copying data from files. Let me show you why my case is different.
With C I must read 43 Million input lines from a csv file. The entries have no errors and are in this form:

int, int , int , variable length string with only alphanumerics and spaces , int \n

Thing is I'm copying all data to memory in array and lists to do some very very simple averages on it and then outputting all processed data to a file, nothing fancy.
There are three main areas where I need help:

Regarding the string, (my BIGGEST problem is here) it is first read from the file, then is copied to an array and then passed to another functions which will copy it into dynamic memory only if a condition is met. Ex:

fileAnalizer(){
  while ( ! EOF ){
    char * s = function_to_read_string_from_file();
    data_to_array(s);
  }
  ....
  ....
  processData(arrays);
  dataToFiles(arrays);

}

void data_to_structures(char * s){
  if ( condition is met)
    char * aux = malloc((strlen(s)+1 )* sizeof(char));
    strcpy(aux,s);
  ....
  ...
}

As you can see the string is traveled through 3 times. I'm needing a way to do this process more efficiently, traveling the string fewer times. I have tried reading char by char and counting the string length but the entire process becomes slower.

Efficient reading of input: would you recommend first copying all data into a buffer? If so: what type of buffer, and in many blocks or just one?
This is my current reading program:

void
csvReader(FILE* f){
    T_structCDT c;
    c.string = malloc(MAX_STRING_LENGHT*sizeof(char));
    while (fscanf(f,"%d,%d,%d,%[^,],%d\n",&c.a, &c.b, &c.vivienda, c.c, &c.d)==5 ){
        data_to_structures(c);
    }
}

I then have nearly 500 hundred csv lines of processed data to dump in to other files. How would you recommend the dumping? Line by line or again sending the data to a buffer and then doing the dump? My code now looks something like this.

void dataToFiles(arrayOfStructs immenseAr1, arrayOfStructs immenseAr2){
  for (iteration over immenseAr1) {
      fprintf(f1, "%d,%d,%s\n", immenseAr1[i].a, immenseAr1[i].b, inmenseAr1[i].string);
  }
  for (iteration over immenseAr2) {
      fprintf(f2, "%d,%d,%s\n", inmenseAr2[i].a, inmenseAr2[i].b, inmenseAr2[i].string);
  }
}

I must read all data before dumping it. Would you recommend a different method other than storing all data into memory and then analyzing it and then dumping all the analyzed data?
With the 20 Million lines the program is currently taking more than 40 seconds.
I really need to lower that time.


问:
how to use rowcount in mysql using python
We are implementing a database in a student record project. We want to see that how many rows are there in a table before and after deleting a row from a table.
The code we tried is as follows:

```<code>1  roll=5
2  m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
3  cur = m.cursor()
4  rc = cur.rowcount
5  print("%d"%rc)
6  e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
7  print("%d"%cur.rowcount)
</code>```

In the above code, the first rowcount in line 4 is giving -1 as the output and the rowcount in the last line is giving the no of rows that the table has after deleting a row.

Why is the first rowcount in line 4 give -1 as the output?

Any help shall be great.

答:
As per the document of psycopg2, cur.rowcount returns the number of rows affected by the last execute method for the same cur object and thus it returns -1 for the first cur.rowcount call as there is no previous execute() method.

You can try this-

```<code>roll=5
m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
cur = m.cursor()
cur.execute("SELECT * FROM `acc_details`")
cur.fetchall()
rc = cur.rowcount
print("%d"%rc)
e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
print("%d"%cur.rowcount)
</code>```

Body:
We are implementing a database in a student record project. We want to see that how many rows are there in a table before and after deleting a row from a table.
The code we tried is as follows:

1  roll=5
2  m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
3  cur = m.cursor()
4  rc = cur.rowcount
5  print("%d"%rc)
6  e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
7  print("%d"%cur.rowcount)

In the above code, the first rowcount in line 4 is giving -1 as the output and the rowcount in the last line is giving the no of rows that the table has after deleting a row.

Why is the first rowcount in line 4 give -1 as the output?

Any help shall be great.

Body:
As per the document of psycopg2, cur.rowcount returns the number of rows affected by the last execute method for the same cur object and thus it returns -1 for the first cur.rowcount call as there is no previous execute() method.

You can try this-

roll=5
m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
cur = m.cursor()
cur.execute("SELECT * FROM `acc_details`")
cur.fetchall()
rc = cur.rowcount
print("%d"%rc)
e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
print("%d"%cur.rowcount)