问:
How can I improve this nested asynchronous loop?
The problem is as follows. I have an array of objects like so:

```<code>let myObj = [
{'db1':['doc1','doc2','doc3']},
{'db2':['doc4','doc5']},
{'db3':['doc7','doc8','doc9','doc10']}
]
</code>```

Note that this is a data structure I decided to use for the problem and can be changed if it can improve the overall implementation. The actual db and doc Ids are read from a text file formatted as below.

```<code>"db1","doc1"
"db1","doc2"
...
</code>```

My app will iterate through the db list synchronously. Inside each db iteration, there will be an asynchronous iteration of the document list. Each document will be retrieved, processed and saved back to the db.

So basically at any given instance: one db, but multiple documents.

I have a working implementation of the above like so:

dbIterator: the synchronous outer loop to iterate dbs. The callback passed to docIterator will trigger the next iteration.

```<code>const dbIterator = function (x) {
  if (x < myObj.length) {
    let dbObj = myObj[x];
    let dbId = Object.keys(dbObj)[0];
    docIterator(dbId, dbObj[dbId], ()=>merchantIterator(x+1));
  } else {
    logger.info('All dbs processed');
  }
};
</code>```

docIterator: the asynchronous loop to iterate docs. The callback cb is called after all documents are processed. This is tracked via the docsProcessed and docsToBeProcessed variables

```<code>const docIterator = function(dbId, docIds, cb){
  //create connection
  targetConnection = //some config for connection to dbId
  let docsProcessed = 0;
  let docsToBeProcessed = docIds.length;

  //asynchronous iteration of documents
  docIds.forEach((docId)=>{
    getDocument(docId, targetConnection).then((doc)=>{
      //process document
      processDoc(doc, targetConnection).then(()=>{
        //if processing is successful
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      })
       //if processing fails
      .catch((e) => {
        logger.error('error when processing document');
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      });

    }).catch((e)=>{
      logger.error('error when retrieving document: ');
      if (++docsProcessed >= docsToBeProcessed) {
        cb();
      }
    });
  });
};
</code>```

processDoc: used to process and save an individual document. This returns a promise that gets resolved when the document processing is done which in turn increments docsProcessed and conditionally (docsProcessed >= docsToBeProcessed) calls the call back passed into docIterator

```<code>const processDoc = function(doc, targetConnection) {

  return new Promise(function(resolve, reject) {
    if(shouldThisDocBeProcessed(doc){
      let updatedDoc = logic(doc);
      targetConnection.insert(updatedDoc, updatedDoc._id,
        function (error, response) {
          if (!error){
            logger.info('updated successfully');
          } else {
            logger.error('error when saving doc');
          }
          resolve();
        }
      );
    } else {
      resolve();
    }
  })
};
</code>```

This works as expected but for me this implementation is sub-optimal and messy. I'm pretty sure this can be improved upon and most importantly a chance to better understand and implement solutions to synchronous and asynchronous problems.

I'm open to constructive criticism. So how can this be improved?

答:
Maybe something like this?

An example implementation of throttle can be found here.

```<code>//this should be available in both modules so you can filter
const Fail = function(details){this.details=details;};
// docIterator(dbId,docIds)
// .then(
//   results =>{
//     const failedResults = results.filter(
//       result => (result&&result.constructor)===Failed
//     );
//     const successfullResults = results.filter(
//       result => (result&&result.constructor)!==Failed
//     );
//   }
// )

const docIterator = function(dbId, docIds){
  //create connection
  // targetConnection = //some config for connection to dbId
  let docsProcessed = 0;
  let docsToBeProcessed = docIds.length;
  //asynchronous iteration of documents
  docIds.map(
    docId =>
      new Promise(
        (resolve,reject) =>
          //if you use throttled you can do:
          // max10(
          //   ([docId,targetConnection])=>
          //     getDocument(docId,targetConnection)
          // )([docId, targetConnection])
          getDocument(docId, targetConnection)
      )
      .then(
        doc =>
          //if this returns nothing then maybe you'd like to return the document
          processDoc(doc, targetConnection)
          .then(
            _ => doc
          )
      )
      .catch(
        err => new fail([err,docId])
      )

  )
};
</code>```

Body:
The problem is as follows. I have an array of objects like so:

let myObj = [
{'db1':['doc1','doc2','doc3']},
{'db2':['doc4','doc5']},
{'db3':['doc7','doc8','doc9','doc10']}
]

Note that this is a data structure I decided to use for the problem and can be changed if it can improve the overall implementation. The actual db and doc Ids are read from a text file formatted as below.

"db1","doc1"
"db1","doc2"
...

My app will iterate through the db list synchronously. Inside each db iteration, there will be an asynchronous iteration of the document list. Each document will be retrieved, processed and saved back to the db.

So basically at any given instance: one db, but multiple documents.

I have a working implementation of the above like so:

dbIterator: the synchronous outer loop to iterate dbs. The callback passed to docIterator will trigger the next iteration.

const dbIterator = function (x) {
  if (x < myObj.length) {
    let dbObj = myObj[x];
    let dbId = Object.keys(dbObj)[0];
    docIterator(dbId, dbObj[dbId], ()=>merchantIterator(x+1));
  } else {
    logger.info('All dbs processed');
  }
};

docIterator: the asynchronous loop to iterate docs. The callback cb is called after all documents are processed. This is tracked via the docsProcessed and docsToBeProcessed variables

const docIterator = function(dbId, docIds, cb){
  //create connection
  targetConnection = //some config for connection to dbId
  let docsProcessed = 0;
  let docsToBeProcessed = docIds.length;

  //asynchronous iteration of documents
  docIds.forEach((docId)=>{
    getDocument(docId, targetConnection).then((doc)=>{
      //process document
      processDoc(doc, targetConnection).then(()=>{
        //if processing is successful
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      })
       //if processing fails
      .catch((e) => {
        logger.error('error when processing document');
        if (++docsProcessed >= docsToBeProcessed) {
          cb();
        }
      });

    }).catch((e)=>{
      logger.error('error when retrieving document: ');
      if (++docsProcessed >= docsToBeProcessed) {
        cb();
      }
    });
  });
};

processDoc: used to process and save an individual document. This returns a promise that gets resolved when the document processing is done which in turn increments docsProcessed and conditionally (docsProcessed >= docsToBeProcessed) calls the call back passed into docIterator

const processDoc = function(doc, targetConnection) {

  return new Promise(function(resolve, reject) {
    if(shouldThisDocBeProcessed(doc){
      let updatedDoc = logic(doc);
      targetConnection.insert(updatedDoc, updatedDoc._id,
        function (error, response) {
          if (!error){
            logger.info('updated successfully');
          } else {
            logger.error('error when saving doc');
          }
          resolve();
        }
      );
    } else {
      resolve();
    }
  })
};

This works as expected but for me this implementation is sub-optimal and messy. I'm pretty sure this can be improved upon and most importantly a chance to better understand and implement solutions to synchronous and asynchronous problems.

I'm open to constructive criticism. So how can this be improved?

Body:
Maybe something like this?

An example implementation of throttle can be found here.

//this should be available in both modules so you can filter
const Fail = function(details){this.details=details;};
// docIterator(dbId,docIds)
// .then(
//   results =>{
//     const failedResults = results.filter(
//       result => (result&&result.constructor)===Failed
//     );
//     const successfullResults = results.filter(
//       result => (result&&result.constructor)!==Failed
//     );
//   }
// )

const docIterator = function(dbId, docIds){
  //create connection
  // targetConnection = //some config for connection to dbId
  let docsProcessed = 0;
  let docsToBeProcessed = docIds.length;
  //asynchronous iteration of documents
  docIds.map(
    docId =>
      new Promise(
        (resolve,reject) =>
          //if you use throttled you can do:
          // max10(
          //   ([docId,targetConnection])=>
          //     getDocument(docId,targetConnection)
          // )([docId, targetConnection])
          getDocument(docId, targetConnection)
      )
      .then(
        doc =>
          //if this returns nothing then maybe you'd like to return the document
          processDoc(doc, targetConnection)
          .then(
            _ => doc
          )
      )
      .catch(
        err => new fail([err,docId])
      )

  )
};


来源: stackexchange

问:
How can one parse a ZIP file using Crypto++?
Crypto++ includes

DEFLATE (RFC 1951) compression/decompression with gzip (RFC 1952) and zlib (RFC 1950) format support

, but I'm not sure how I could translate that into reading a ZIP file. (I'm not averse to implementing my own ZIP traversing logic; but of course if the library already has that built in I don't want to duplicate things).

If the library doesn't provide this functionality out of the box, how does one access the zlib and gzip bits (in order to implement the compression/decompression steps)?

答:
I am not sure about the latest versions of Crypto++ but it was something like this before</p>

```<code>// write to file
Gzip zip(new FileSink (output_filename, true ), Gzip::DEFAULT_DEFLATE_LEVEL);
zip.Put(buf, dwBufSize);
zip.MessageEnd();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am not sure about the latest versions of Crypto++ but it was something like this before

// write to file
Gzip zip(new FileSink (output_filename, true ), Gzip::DEFAULT_DEFLATE_LEVEL);
zip.Put(buf, dwBufSize);
zip.MessageEnd();


问:
map.setCenter undefined
I'm using GoogleMaps and want to centre it when the orientation changes, but when I call

```<code>map.setCenter({...})
</code>```

I'm receiving an undefined error for setCenter.

Here's my code:

```<code>let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.doOnOrientationChange);
  },

  doOnOrientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap
</code>```

Docs: https://developers.google.com/maps/documentation/javascript/reference#Map

And I grab the google maps api from: https://maps.googleapis.com/maps/api/js?key=KEY&libraries=geometry,places

Any ideas?

答:
Thanks to geocodezip, the issue was scoping, and this wasn't in the correct scope in the orientation event handler.

The fix was to use the bind method

```<code>window.addEventListener('orientationchange', this.orientationChange.bind(this));
</code>```

Full working code:

```<code>let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.orientationChange.bind(this));
  },

  orientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap
</code>```

The map now centres itself as expected when the orientation changes.

ContentLicense: CC BY-SA 3.0

Title: map.setCenter undefined

Body:
I'm using GoogleMaps and want to centre it when the orientation changes, but when I call

map.setCenter({...})

I'm receiving an undefined error for setCenter.

Here's my code:

let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.doOnOrientationChange);
  },

  doOnOrientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap

Docs: https://developers.google.com/maps/documentation/javascript/reference#Map

And I grab the google maps api from: https://maps.googleapis.com/maps/api/js?key=KEY&libraries=geometry,places

Any ideas?

Body:
Thanks to geocodezip, the issue was scoping, and this wasn't in the correct scope in the orientation event handler.

The fix was to use the bind method

window.addEventListener('orientationchange', this.orientationChange.bind(this));

Full working code:

let GoogleMap = {
  lat : "",
  lng : "",
  map : {},
  marker : {},
  point : {},

  init() {
    return this
  },

  create(lat, lng) {
    this.lat = lat
    this.lng = lng
    this.point = {lat: lat,lng: lng};

    this.map = new google.maps.Map(document.getElementById('map'), {
      center: this.point,
      zoom: 17
    });

    this.marker = new google.maps.Marker({
      map: this.map,
      position: this.point
    });

    window.addEventListener('orientationchange', this.orientationChange.bind(this));
  },

  orientationChange() {
    this.map.setCenter({lat: this.lat, lng: this.lng})
  }
}

export default GoogleMap

The map now centres itself as expected when the orientation changes.


问:
RuntimeError when running a setuptools install command with custom options
I'm using a custom install option in setup.py by subclasssing setuptools.Command but it throws an exception when the parent run function is called. Here's the setup.py code

```<code>from setuptools import setup
from setuptools import Command
import os, json, sys

class vboxcustom(Command):
    user_options = [
            ("disk-path=", "d", "Location where vbox disk files will be stored."),
            ]

    def initialize_options(self):
        self.disk_path = None

    def finalize_options(self):
        if self.disk_path is None:
            self.disk_path = os.path.expanduser("~/vbox")

    def run(self):
        settings_file = os.path.expanduser("~/.vbox")

        settings = {"disk_path": self.disk_path}

        f = open(settings_file, 'w')
        f.write(json.dumps(settings))

        super(vboxcustom, self).run()

setup(
        name="vbox",
        version="1.0",
        author="Ravi",
        author_email="email@email",
        python_requires=">=3",
        install_requires=["dnspython"],
        packages=["vboxhelper"],
        scripts=["scripts/vbox"],
        cmdclass={
            "install": vboxcustom,
            }
        )
</code>```

The exception thrown is this:
RuntimeError: abstract method -- subclass <class '__main__.vboxcustom'> must override . It seems I have to override a method but what method(Im just guessing, the error is pretty non specific)

The stack trace is:

```<code>Traceback (most recent call last):
  File "setup.py", line 37, in <module>
    "install": vboxcustom,
  File "/home/ravi/work/virenvs/testvbox/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup
    return distutils.core.setup(**attrs)
  File "/usr/lib/python3.6/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/usr/lib/python3.6/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "setup.py", line 25, in run
    super(vboxcustom, self).run()
  File "/usr/lib/python3.6/distutils/cmd.py", line 176, in run
    % self.__class__)
RuntimeError: abstract method -- subclass <class '__main__.vboxcustom'> must override
</code>```

I think I am not supposed to subclass from setuptools.Command to override the install command so I subclassed from setuptools.command.install.install and now I get a different error. The new exception thrown is this:

```<code>distutils.errors.DistutilsGetoptError: invalid negative alias 'no-compile': option 'no-compile' not defined
</code>```

答:
You need to preserve user_options from the class install:

```<code>class vboxcustom(install):
    user_options = install.user_options + [
        ("disk-path=", "d", "Location where vbox disk files will be stored."),
    ]
</code>```

Body:
I'm using a custom install option in setup.py by subclasssing setuptools.Command but it throws an exception when the parent run function is called. Here's the setup.py code

from setuptools import setup
from setuptools import Command
import os, json, sys

class vboxcustom(Command):
    user_options = [
            ("disk-path=", "d", "Location where vbox disk files will be stored."),
            ]

    def initialize_options(self):
        self.disk_path = None

    def finalize_options(self):
        if self.disk_path is None:
            self.disk_path = os.path.expanduser("~/vbox")

    def run(self):
        settings_file = os.path.expanduser("~/.vbox")

        settings = {"disk_path": self.disk_path}

        f = open(settings_file, 'w')
        f.write(json.dumps(settings))

        super(vboxcustom, self).run()

setup(
        name="vbox",
        version="1.0",
        author="Ravi",
        author_email="email@email",
        python_requires=">=3",
        install_requires=["dnspython"],
        packages=["vboxhelper"],
        scripts=["scripts/vbox"],
        cmdclass={
            "install": vboxcustom,
            }
        )

The exception thrown is this:
RuntimeError: abstract method -- subclass <class '__main__.vboxcustom'> must override . It seems I have to override a method but what method(Im just guessing, the error is pretty non specific)

The stack trace is:

Traceback (most recent call last):
  File "setup.py", line 37, in <module>
    "install": vboxcustom,
  File "/home/ravi/work/virenvs/testvbox/lib/python3.6/site-packages/setuptools/__init__.py", line 129, in setup
    return distutils.core.setup(**attrs)
  File "/usr/lib/python3.6/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/usr/lib/python3.6/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "setup.py", line 25, in run
    super(vboxcustom, self).run()
  File "/usr/lib/python3.6/distutils/cmd.py", line 176, in run
    % self.__class__)
RuntimeError: abstract method -- subclass <class '__main__.vboxcustom'> must override

I think I am not supposed to subclass from setuptools.Command to override the install command so I subclassed from setuptools.command.install.install and now I get a different error. The new exception thrown is this:

distutils.errors.DistutilsGetoptError: invalid negative alias 'no-compile': option 'no-compile' not defined

Body:
You need to preserve user_options from the class install:

class vboxcustom(install):
    user_options = install.user_options + [
        ("disk-path=", "d", "Location where vbox disk files will be stored."),
    ]


问:
Prevent the object from moving certain objects?
I think it is simple, but I don't find the solution. I want my player to move some times red boxes and others blue boxes. I tried to freeze box X position when player collides, but then I have moving platforms so it doesn´t work. I tried to increase the mass, but I have also problems with some situations. Can I know the force that the player is applying in the box in order to apply exactly the inverse force ? Do you think another way ?</p>

答:
Yous shouldn't be freezing the position or changing the mass to get this effect.

If you don't want move any object to be moved by another object, enable Is Kinematic on that Object.

Is Kinematic description from the doc:

If enabled, the object will not be driven by the physics engine, and
  can only be manipulated by its Transform

```<code>public Rigidbody redBoxes;
public Rigidbody blueBoxes;
</code>```

Don't move Red and Blue Boxes by another object(Player)

```<code>redBoxes.isKinematic = true;
blueBoxes.isKinematic = true;
</code>```

Allow movement of Red and Blue Boxes by another object(Player)

```<code>redBoxes.isKinematic = false;
blueBoxes.isKinematic = false;
</code>```

Body:
Yous shouldn't be freezing the position or changing the mass to get this effect.

If you don't want move any object to be moved by another object, enable Is Kinematic on that Object.

Is Kinematic description from the doc:

If enabled, the object will not be driven by the physics engine, and
  can only be manipulated by its Transform

public Rigidbody redBoxes;
public Rigidbody blueBoxes;

Don't move Red and Blue Boxes by another object(Player)

redBoxes.isKinematic = true;
blueBoxes.isKinematic = true;

Allow movement of Red and Blue Boxes by another object(Player)

redBoxes.isKinematic = false;
blueBoxes.isKinematic = false;


问:
Stop and deallocate an Azure VM within the guest OS
The VM info:

Basic A1 Serie VM with Ubuntu 16 on it

How to shutdown (or Stop) and de-allocate the VM in Azure without having to go to the azure portal?

Bearing in mind in Azure if you execute shutdown -h 0; it will stop the VM but won't deallocate it.

I'm asking this because I don't have a direct connection to the Azure portal nor do I have logins to it. I want to deallocate the VM using the guest OS only.

答:
Do you have a login to the subscription?  If so you could use the azure CLI to deallocate.  The VM always has access to the Azure Fabric even if you don't.

To login without access to portal:

az login -u johndoe@contoso.com -p VerySecret

To Deallocate:

az vm deallocate --resource-group myResourceGroup --name myVM


问:
Remove noise from grayscale image PIL
I am working on a handwriting recognition code for a school project. We want to collect the data our self, and I’m currently working on a program that scans a document with handwritten letters on it and create a own image for every letter. I cut the image to the exact size of the letter, resize the letter so every letter has the same dimensions and place them on a white background so they have the same dimensions but the original ratio stays the same. I already have it working quite well, the only problem is when I have a little bit of noise in the picture, it doesn’t work. I have the image (see attachment) and a list of all the pixels of the image. What would be a good way to cut the image to the image boundaries and not to the noise.

the code I use to cut the image:

```<code>def cut_to_edge(image, data, width, height):
    left = width
    right = 0
    down = 0
    up = height

    for i in range(len(data)):
        for j in range(len(data[i])):
            if data[i][j] < 225:
                if j < left:
                    left = j
                if j > right:
                    right = j
                if i < up:
                    up = i
                if i > down:
                    down = i

    letter = image.crop((left, up, right, down))

    return letter
</code>```

image is the image (obviously),
data is a 2 dimensional list with every pixel ([[row1][row2]etc.]),
width and height are the dimensions of the image

The image I need to cut,
how it should look,
How it looks now

答:
If your noise is like little points, you can write a Median filter and that will solve your problem. The main idea of this filter is to loop through the image pixel by pixel and replace each pixel value with the median of the neighboring pixels.

But first you need to identify the type of noise you have and then apply the right filter.

Title: Remove noise from grayscale image PIL

Body:
I am working on a handwriting recognition code for a school project. We want to collect the data our self, and I’m currently working on a program that scans a document with handwritten letters on it and create a own image for every letter. I cut the image to the exact size of the letter, resize the letter so every letter has the same dimensions and place them on a white background so they have the same dimensions but the original ratio stays the same. I already have it working quite well, the only problem is when I have a little bit of noise in the picture, it doesn’t work. I have the image (see attachment) and a list of all the pixels of the image. What would be a good way to cut the image to the image boundaries and not to the noise.

the code I use to cut the image:

def cut_to_edge(image, data, width, height):
    left = width
    right = 0
    down = 0
    up = height

    for i in range(len(data)):
        for j in range(len(data[i])):
            if data[i][j] < 225:
                if j < left:
                    left = j
                if j > right:
                    right = j
                if i < up:
                    up = i
                if i > down:
                    down = i

    letter = image.crop((left, up, right, down))

    return letter

image is the image (obviously),
data is a 2 dimensional list with every pixel ([[row1][row2]etc.]),
width and height are the dimensions of the image

The image I need to cut,
how it should look,
How it looks now


问:
warning in NSMutableArray
warning: (Messages without a matching method signature

warning: no '-eventListArray' method found

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[[popularListArray objectAtIndex:section]eventListArray]count];

}
</code>```

@Thanks in advance

答:
Your problem is most likely that you need to #import the header file in which the -eventListArray method is declared.

Files are compiled one at a time, so if you don't import the header, the compiler won't know about the method when compiling this file and will therefore issue a warning.

Title: warning in NSMutableArray

Body:
warning: (Messages without a matching method signature

warning: no '-eventListArray' method found

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [[[popularListArray objectAtIndex:section]eventListArray]count];

}

@Thanks in advance


问:
R - Spatial Join Between SpatialPoints (GPS coordinates) and SpatialLinesDataFrame
I am working on a university project which combines data science and GIS. We need to find an open-source solution capable of obtaining additional information from a massive GPS coordinates dataset. Clearly, I cannot use any API with daily request limit.

THE DATA

Here you can find a sample of the dataset the Professor provided us:

```<code>longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- seq.int(1, 10)
</code>```

FIRST TASK: Already Accomplished!

The first step was joining my SpatialPoints with a SpatialPolygonsDataFrame using over() of rgeos. The SpatialPolygonsDataFrame was obtained through getData('GADM', country='ITA', level=3) of rgeos.

For this first accomplished task, the objective was to associate to each GPS coordinates the information about City and Region which they belong to.

An example of the result I was able to obtain is:

```<code>require(sp)
require(rgeos)
my_spdf <- SpatialPointsDataFrame(coords = longlat, data = ID, proj4string = CRS(" +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 "))
italy_administrative_boundaries_level3 <- getData('GADM', country='ITA', level=3)
result <- over(my_spdf, italy_administrative_boundaries_level3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
result$ID <- ID
print(result)
</code>```

SECOND TASK: MY QUESTION

Now the stuff become tricky because I need to associate additional and deeper information like road_name and road_type.

This information are contained in the shapefiles created on OpenStreetMap and available at: download.geofabrik.de/europe/italy.html.
I loaded the shapefile in R obtaining a SpatialLinesDataFrame:

```<code>require(rgdal)
shapefile_roads <- readOGR(dsn = "./road", layer = "roads")
</code>```

Then, I naively tried to apply the same technique as for joining SpatialPoints and SpatialPolygonsDataFrame:

```<code>result <- over(my_spdf, shapefile_roads)
</code>```

Clearly, the result is just NA. One possible reason that came into my mind was that the coordinates of my_df are not in the exact position of the Lines in shapefile_roads, therefore, I should need some kind of radius parameter. However, I am not really sure.

Can you suggest me the correct approach to perform this spatial join between my SpatialPoints and the attributes of the SpatialLinesDataFrame obtained from the road_shapefile of OpenStreetMap?

Please if something is not very clear do not hesitate to ask.

答:
You need to join polygons with your points, not Lines. To do so, you can create a buffer area around your Lines using rgeos::gBuffer(). Be careful, because the buffer area will be in the coordinate system of your Lines. Probably degrees (wgs84) in your case (Verify it). Choose the correct distance (width) according to your case.

```<code>LinesBuffer <- rgeos::gBuffer(shapefile_roads, width = 0.01)
</code>```

Then you will be able to join points with "LinesBuffer" using over (if they are in the same coordinates system).

```<code>result <- over(my_spdf, LinesBuffer)
</code>```

Body:
I am working on a university project which combines data science and GIS. We need to find an open-source solution capable of obtaining additional information from a massive GPS coordinates dataset. Clearly, I cannot use any API with daily request limit.

THE DATA

Here you can find a sample of the dataset the Professor provided us:

longitude <- c(10.86361, 10.96062, 10.93032, 10.93103, 10.93212)
latitude <- c(44.53355, 44.63234, 44.63470, 44.63634, 44.64559)
longlat <- data.frame(longitude, latitude)
ID <- seq.int(1, 10)

FIRST TASK: Already Accomplished!

The first step was joining my SpatialPoints with a SpatialPolygonsDataFrame using over() of rgeos. The SpatialPolygonsDataFrame was obtained through getData('GADM', country='ITA', level=3) of rgeos.

For this first accomplished task, the objective was to associate to each GPS coordinates the information about City and Region which they belong to.

An example of the result I was able to obtain is:

require(sp)
require(rgeos)
my_spdf <- SpatialPointsDataFrame(coords = longlat, data = ID, proj4string = CRS(" +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 "))
italy_administrative_boundaries_level3 <- getData('GADM', country='ITA', level=3)
result <- over(my_spdf, italy_administrative_boundaries_level3)[, c("NAME_0", "NAME_1", "NAME_2", "NAME_3")]
result$ID <- ID
print(result)

SECOND TASK: MY QUESTION

Now the stuff become tricky because I need to associate additional and deeper information like road_name and road_type.

This information are contained in the shapefiles created on OpenStreetMap and available at: download.geofabrik.de/europe/italy.html.
I loaded the shapefile in R obtaining a SpatialLinesDataFrame:

require(rgdal)
shapefile_roads <- readOGR(dsn = "./road", layer = "roads")

Then, I naively tried to apply the same technique as for joining SpatialPoints and SpatialPolygonsDataFrame:

result <- over(my_spdf, shapefile_roads)

Clearly, the result is just NA. One possible reason that came into my mind was that the coordinates of my_df are not in the exact position of the Lines in shapefile_roads, therefore, I should need some kind of radius parameter. However, I am not really sure.

Can you suggest me the correct approach to perform this spatial join between my SpatialPoints and the attributes of the SpatialLinesDataFrame obtained from the road_shapefile of OpenStreetMap?

Please if something is not very clear do not hesitate to ask.

Body:
You need to join polygons with your points, not Lines. To do so, you can create a buffer area around your Lines using rgeos::gBuffer(). Be careful, because the buffer area will be in the coordinate system of your Lines. Probably degrees (wgs84) in your case (Verify it). Choose the correct distance (width) according to your case.

LinesBuffer <- rgeos::gBuffer(shapefile_roads, width = 0.01)

Then you will be able to join points with "LinesBuffer" using over (if they are in the same coordinates system).

result <- over(my_spdf, LinesBuffer)


问:
Scraping flight data with Python requests
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

```<code>import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)
</code>```

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

```<code>headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}
</code>```

And then have

```<code>response = requests.post(API_url, headers = headers)
</code>```

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?

答:
The page makes 3 XHR requests as you said. You can make these requests using POST. You just need to get the right parameters for the payload. You can do this using BeautifulSoup and urllib which you may need to install if you have not done so already. This is for Python 3, Python 2 has a different implementation of urllib.</p>

```<code>import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs

# Get the web page.
url = "https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729"
page = requests.get(url).text

# Extract the first parameter you need for the POST request from the URL.
parsed_url = urlparse(url)
id = parse_qs(parsed_url.query)['dsId'][0]
print (id) # 6188729

# Get the first XML.
payload = {'nature':'dsstat','id': id}
data1 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data1.text)

# Get the ref attribute for the second POST request using BeautifulSoup.
soup = BeautifulSoup(page, 'html.parser')
dsstat = soup.find("meta", {'name':"og:image"})
parsed_url = urlparse(dsstat['content'])
ref = parse_qs(parsed_url.query)['ref'][0]
print (ref) # 977301232

# Get the second XML.
payload = {'nature':'track','ref': ref}
data2 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data2.text)

# Get the thrd XML. The id is the first ID + 1.
id2 = (int (id) + 1)
print (id2) # 6188730
payload = {'nature':'dsstat','id':id2}
data3 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data3.text)
</code>```

Body:
The following URL shows a flight and offers further details (toggle e.g. "Flugweg" or "Statistik" on the left side). I would like to read this data and later convert that into lists.

https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729

So what I have been doing so far is the following:

import requests
API_url = "https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html"
response = requests.post(API_url)

doing a response.text gives me a page back, basically telling me that "The requested page doesn't exist".

I then tried to add header information, as I read that sometimes this is a reason a request is denied:

headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36",
            "Referer":"https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729",
          "Origin":"https://www.onlinecontest.org"}

And then have

response = requests.post(API_url, headers = headers)

This did not change anything and is simply fishing in murky waters.

Searching with Chrome for XHR offers three files and they contain what I want, but I am running out of ideas, how to get them. What would be the correct approach to access the data?

Body:
The page makes 3 XHR requests as you said. You can make these requests using POST. You just need to get the right parameters for the payload. You can do this using BeautifulSoup and urllib which you may need to install if you have not done so already. This is for Python 3, Python 2 has a different implementation of urllib.

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs

# Get the web page.
url = "https://www.onlinecontest.org/olc-2.0/gliding/flightinfo.html?dsId=6188729"
page = requests.get(url).text

# Extract the first parameter you need for the POST request from the URL.
parsed_url = urlparse(url)
id = parse_qs(parsed_url.query)['dsId'][0]
print (id) # 6188729

# Get the first XML.
payload = {'nature':'dsstat','id': id}
data1 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data1.text)

# Get the ref attribute for the second POST request using BeautifulSoup.
soup = BeautifulSoup(page, 'html.parser')
dsstat = soup.find("meta", {'name':"og:image"})
parsed_url = urlparse(dsstat['content'])
ref = parse_qs(parsed_url.query)['ref'][0]
print (ref) # 977301232

# Get the second XML.
payload = {'nature':'track','ref': ref}
data2 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data2.text)

# Get the thrd XML. The id is the first ID + 1.
id2 = (int (id) + 1)
print (id2) # 6188730
payload = {'nature':'dsstat','id':id2}
data3 = requests.post("https://www.onlinecontest.org/olc-2.0/gliding/dataprov.html", data =payload)
print (data3.text)


问:
getting timestamp in php
How can I get the timestamp of a desired hour?  The hour is in a variable that the user set.</p>

答:
```<code>$hr = 10;
echo strtotime("today +$hr hours");
</code>```

Title: getting timestamp in php


问:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'payments' already exists (SQL: create table `payments`
When I migrate a table I see this error,

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
  'payments' already exists (SQL: create table payments

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('resnumber');
            $table->string('course_id')->default('vip');
            $table->string('price');
            $table->boolean('payment')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payments');
    }
}
</code>```

Error

答:
If you want to recreate the table, run php migrate:rollback first to delete the existing one. This command will run the down() method in the migration.

Then run php migrate to create the table again.

Body:
When I migrate a table I see this error,

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
  'payments' already exists (SQL: create table payments

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePaymentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->string('resnumber');
            $table->string('course_id')->default('vip');
            $table->string('price');
            $table->boolean('payment')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('payments');
    }
}

Error


问:
Bitbucket webhook to Jenkins
I want to configure Jenkins build on every commit to specific branch. I am trying to use Bitbucket Webhook to Jenkins but it is not working as per expectations. To run it successfully I need to select following two options in Jenkins job
1.Build when a change is pushed to BitBucket
and 2. Poll SCM(keeping it blank)

and in webhook as below screenshot

When I untick Omit Branch Name it gives following error.

When I mention branch name to build from in Advance Configurations to Build Options : as below

it give following error in logs and do not trigger any build in Jenkins.

```<code>2017-07-28 19:18:49,382 ERROR [AtlassianEvent::thread-3] XXXXXXX @4NXRG4x1158x165x0 s2l8ua 10.229.17.70 "PUT /rest/api/latest/projects/STCPLAY/repos/mavensample/browse/pom.xml HTTP/1.1" c.a.s.i.e.AsyncBatchingInvokersTransformer There was an exception thrown trying to dispatch event 'com.atlassian.bitbucket.event.content.FileEditedEvent[source=com.atlassian.stash.internal.content.DefaultContentService@72ae21ba]' for the invoker 'SingleParameterMethodListenerInvoker{method=public void com.nerdwin15.stash.webhook.RepositoryChangeListener.onRefsChangedEvent(com.atlassian.bitbucket.event.repository.RepositoryRefsChangedEvent), listener=com.nerdwin15.stash.webhook.RepositoryChangeListener@356e810b}'
java.lang.RuntimeException: com.atlassian.bitbucket.repository.RefChange.getRefId()Ljava/lang/String;. Listener: com.nerdwin15.stash.webhook.RepositoryChangeListener event: com.atlassian.bitbucket.event.content.FileEditedEvent
    at com.atlassian.event.internal.SingleParameterMethodListenerInvoker.invoke(SingleParameterMethodListenerInvoker.java:55)
    at com.atlassian.stash.internal.event.AsyncBatchingInvokersTransformer$AsyncInvokerBatch.invoke(AsyncBatchingInvokersTransformer.java:109)
    at com.atlassian.event.internal.AsynchronousAbleEventDispatcher$1$1.run(AsynchronousAbleEventDispatcher.java:38)
    at com.atlassian.sal.core.executor.ThreadLocalDelegateRunnable.run(ThreadLocalDelegateRunnable.java:34)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    ... 1 frame trimmed
</code>```

Anyone faced this issue and fixed it ?
Or
there is any other better way to trigger builds on commits pushed to bitbucket on specific branch.

答:
A couple of suggestions:

You may need to ensure that the branch spec on the Jenkins job (Branches to build) matches the branches that you specify in Branch Options in the BitBucket plugin configuration.

As far as I know, the Build when a change is pushed to BitBucket option is irrelevant in this case.

You can find more detailed instructions here - https://support.cloudbees.com/hc/en-us/articles/226568007-How-to-Trigger-Non-Multibranch-Jobs-from-BitBucket-Server-

Title: Bitbucket webhook to Jenkins

Body:
I want to configure Jenkins build on every commit to specific branch. I am trying to use Bitbucket Webhook to Jenkins but it is not working as per expectations. To run it successfully I need to select following two options in Jenkins job
1.Build when a change is pushed to BitBucket
and 2. Poll SCM(keeping it blank)

and in webhook as below screenshot

When I untick Omit Branch Name it gives following error.

When I mention branch name to build from in Advance Configurations to Build Options : as below

it give following error in logs and do not trigger any build in Jenkins.

2017-07-28 19:18:49,382 ERROR [AtlassianEvent::thread-3] XXXXXXX @4NXRG4x1158x165x0 s2l8ua 10.229.17.70 "PUT /rest/api/latest/projects/STCPLAY/repos/mavensample/browse/pom.xml HTTP/1.1" c.a.s.i.e.AsyncBatchingInvokersTransformer There was an exception thrown trying to dispatch event 'com.atlassian.bitbucket.event.content.FileEditedEvent[source=com.atlassian.stash.internal.content.DefaultContentService@72ae21ba]' for the invoker 'SingleParameterMethodListenerInvoker{method=public void com.nerdwin15.stash.webhook.RepositoryChangeListener.onRefsChangedEvent(com.atlassian.bitbucket.event.repository.RepositoryRefsChangedEvent), listener=com.nerdwin15.stash.webhook.RepositoryChangeListener@356e810b}'
java.lang.RuntimeException: com.atlassian.bitbucket.repository.RefChange.getRefId()Ljava/lang/String;. Listener: com.nerdwin15.stash.webhook.RepositoryChangeListener event: com.atlassian.bitbucket.event.content.FileEditedEvent
    at com.atlassian.event.internal.SingleParameterMethodListenerInvoker.invoke(SingleParameterMethodListenerInvoker.java:55)
    at com.atlassian.stash.internal.event.AsyncBatchingInvokersTransformer$AsyncInvokerBatch.invoke(AsyncBatchingInvokersTransformer.java:109)
    at com.atlassian.event.internal.AsynchronousAbleEventDispatcher$1$1.run(AsynchronousAbleEventDispatcher.java:38)
    at com.atlassian.sal.core.executor.ThreadLocalDelegateRunnable.run(ThreadLocalDelegateRunnable.java:34)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    ... 1 frame trimmed

Anyone faced this issue and fixed it ?
Or
there is any other better way to trigger builds on commits pushed to bitbucket on specific branch.


问:
How i can show same data from listView to second activity in android like, if i clicked on google , it show google on second activity
This code fetching data from database using wamp server in listView, but I have to do if I click on row # 1 it shows row # 1 on second activity , if I click on 2 it shows row # 2 on second activity,

```<code>import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class attendence extends AppCompatActivity {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendence);

        String name = getIntent().getExtras().getString("username");
        getJSON("http://192.168.0.102/A/select.php" + "?username=" + name);
        listView = (ListView) findViewById(R.id.LV);

        // TextView txtname = (TextView) findViewById(R.id.txt_success_name);
        //
        // Intent intent = getIntent();
        // String loginName = intent.getStringExtra("username");
        // txtname.setText("Welcome, " +loginName);
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                try {

                    loadIntoListView(s);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();

    }

    //
    private void loadIntoListView(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        JSONArray jsonArray = object.getJSONArray("Result");
        String[] heroes = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("ID") + " " + obj.getString("STATUS") + "  " + obj.getString("ATD_DATE");
            if (!obj.getString("STATUS").toString().equals("A")) {
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent i = new Intent(attendence.this, atd_leave_form.class);
                        startActivity(i);
                    }
                });
            } else {

            }

            // Toast.makeText(getApplication(),"GREEN",Toast.LENGTH_LONG).show();
            // listView.setBackgroundColor(Color.GREEN);
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
        listView.setAdapter(arrayAdapter);
    }
}
</code>```

I just want to show same single data on which I clicked in list view in android.
thanks in advance for help.

答:
By using intents you have to implement that in onItemClick method

Check this Passing Data between activities

also you can find useful info in the android site

Body:
This code fetching data from database using wamp server in listView, but I have to do if I click on row # 1 it shows row # 1 on second activity , if I click on 2 it shows row # 2 on second activity,

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class attendence extends AppCompatActivity {

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_attendence);

        String name = getIntent().getExtras().getString("username");
        getJSON("http://192.168.0.102/A/select.php" + "?username=" + name);
        listView = (ListView) findViewById(R.id.LV);

        // TextView txtname = (TextView) findViewById(R.id.txt_success_name);
        //
        // Intent intent = getIntent();
        // String loginName = intent.getStringExtra("username");
        // txtname.setText("Welcome, " +loginName);
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                try {

                    loadIntoListView(s);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();

    }

    //
    private void loadIntoListView(String json) throws JSONException {
        JSONObject object = new JSONObject(json);
        JSONArray jsonArray = object.getJSONArray("Result");
        String[] heroes = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("ID") + " " + obj.getString("STATUS") + "  " + obj.getString("ATD_DATE");
            if (!obj.getString("STATUS").toString().equals("A")) {
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent i = new Intent(attendence.this, atd_leave_form.class);
                        startActivity(i);
                    }
                });
            } else {

            }

            // Toast.makeText(getApplication(),"GREEN",Toast.LENGTH_LONG).show();
            // listView.setBackgroundColor(Color.GREEN);
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
        listView.setAdapter(arrayAdapter);
    }
}

I just want to show same single data on which I clicked in list view in android.
thanks in advance for help.


问:
.NET: Connecting to MySQL issues
I have a .NET app which uses a MySQL database.

The problem is that if I want to run it, the local computer requires the MySQL Connector to be installed.

How could I make this easier ?
Can I "embed" everything and provide in one pack with my app ?
Should I create an installer that does install the connector if missing and automatically creates the data source ?

Which is the best way to go ?
Thanks.

答:
I think MySql connector comes with a DLL which just needs to be copied in youir BIN folder to let it go.

Just add the DLL with Setup project and it will copy the DLL while installing your app.

Title: .NET: Connecting to MySQL issues


问:
Java set timezone does not default to gmt+0
I have the following codes. The string form of the java date time is gmt+0. Thus I need to later convert it according to different local timezone but when I try to set the default timezone it keep going back another 8 hours cause my machine is on gmt+8.The output is showing me 2017-12-09 09:00:00 but I want to remain as 2017-12-09 17:00:00 because this is gmt+0.</p>

```<code>    String existingTime = "2017-12-09 17:00:00";
    String newTime = "2017-12-09 14:00:00";

    Date existingDateTime = null;
    Date newDateTime = null;
    Date localexistingDateTime = null;
    Date localnewDateTime = null;
    DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    // sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:30"));

    try {
        existingDateTime = dateTimeFormat.parse(existingTime);
        newDateTime = dateTimeFormat.parse(newTime);

        System.out.println("GMT existingDateTime" + sdf.format(existingDateTime));
        System.out.println("GMT newDateTime" + sdf.format(newDateTime));
    } catch (ParseException ex) {
        System.out.println("MyError:Parse Error has been caught for date parse close");
        ex.printStackTrace(System.out);
    }
</code>```

答:
This snippet may get you started using java.time, the modern Java date and time API. It is also known as JSR-310 after the Java Specification Request that first described it.

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String existingTime = "2017-12-09 17:00:00";
    OffsetDateTime existingDateTime = LocalDateTime.parse(existingTime, formatter)
            .atOffset(ZoneOffset.UTC);
    System.out.println("UTC existingDateTime: " + existingDateTime.format(formatter));
    System.out.println("Pyongyang existingDateTime: "
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Pyongyang"))
                    .format(formatter));
    System.out.println("Singapore existingDateTime: "
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"))
                    .format(formatter));
</code>```

The output from running the snippet is:

```<code>UTC existingDateTime: 2017-12-09 17:00:00
Pyongyang existingDateTime: 2017-12-10 01:30:00
Singapore existingDateTime: 2017-12-10 01:00:00
</code>```

This was the output I got on my computer (in Europe/Berlin time zone), but it’s easier to keep the modern classes independent of the JVM’s time zone, so you should get the same output on your computer.

EDIT: You asked in a comment if it isn’t possible to use an offset of GMT+09:00 instead of a time zone. I’m unsure why you will want to do that since real people live in time zones rather than in offsets, but it’s easy when you know how:

```<code>    System.out.println("GMT+09:00 existingDateTime: "
            + existingDateTime.withOffsetSameInstant(ZoneOffset.ofHours(9))
                    .format(formatter));
</code>```

Output:

```<code>GMT+09:00 existingDateTime: 2017-12-10 02:00:00
</code>```

A LocalDateTime is a date and time without time zone or offset information. Since your string doesn’t contain offset or zone, I use this for parsing. And since you told me your date-time was in GMT+0, I convert it to an OffsetDateTime with offset UTC first thing. From there it’s straightforward to convert it into different local time zones. So I demonstrate that for a couple of time zones, each time formatting the date-time using the same formatter I used for parsing, since I gather you tend to like the yyyy-MM-dd HH:mm:ss format.

I always give time zone in the region/city format. This is unambiguous (contrary to three letter abbreviations; for example, PYT may mean Paraguay Time or Pyongyang Time). And it will automatically take care of summer time (DST) in case the time zone uses such. Even historic changes in zone offset are built-in.

To learn to use java.time, see the Oracle Tutorial on Date Time and search for relevant questions on Stack Overflow, always looking for the java.time answers (there’s a wealth of old answers using the outdated classes, skip those). Even more places on the net hold valuable resources. Your search engine and your ability to distinguish good from poor are your friends.

Body:
I have the following codes. The string form of the java date time is gmt+0. Thus I need to later convert it according to different local timezone but when I try to set the default timezone it keep going back another 8 hours cause my machine is on gmt+8.The output is showing me 2017-12-09 09:00:00 but I want to remain as 2017-12-09 17:00:00 because this is gmt+0.

    String existingTime = "2017-12-09 17:00:00";
    String newTime = "2017-12-09 14:00:00";

    Date existingDateTime = null;
    Date newDateTime = null;
    Date localexistingDateTime = null;
    Date localnewDateTime = null;
    DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    // sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:30"));

    try {
        existingDateTime = dateTimeFormat.parse(existingTime);
        newDateTime = dateTimeFormat.parse(newTime);

        System.out.println("GMT existingDateTime" + sdf.format(existingDateTime));
        System.out.println("GMT newDateTime" + sdf.format(newDateTime));
    } catch (ParseException ex) {
        System.out.println("MyError:Parse Error has been caught for date parse close");
        ex.printStackTrace(System.out);
    }

Body:
This snippet may get you started using java.time, the modern Java date and time API. It is also known as JSR-310 after the Java Specification Request that first described it.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String existingTime = "2017-12-09 17:00:00";
    OffsetDateTime existingDateTime = LocalDateTime.parse(existingTime, formatter)
            .atOffset(ZoneOffset.UTC);
    System.out.println("UTC existingDateTime: " + existingDateTime.format(formatter));
    System.out.println("Pyongyang existingDateTime: "
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Pyongyang"))
                    .format(formatter));
    System.out.println("Singapore existingDateTime: "
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"))
                    .format(formatter));

The output from running the snippet is:

UTC existingDateTime: 2017-12-09 17:00:00
Pyongyang existingDateTime: 2017-12-10 01:30:00
Singapore existingDateTime: 2017-12-10 01:00:00

This was the output I got on my computer (in Europe/Berlin time zone), but it’s easier to keep the modern classes independent of the JVM’s time zone, so you should get the same output on your computer.

EDIT: You asked in a comment if it isn’t possible to use an offset of GMT+09:00 instead of a time zone. I’m unsure why you will want to do that since real people live in time zones rather than in offsets, but it’s easy when you know how:

    System.out.println("GMT+09:00 existingDateTime: "
            + existingDateTime.withOffsetSameInstant(ZoneOffset.ofHours(9))
                    .format(formatter));

Output:

GMT+09:00 existingDateTime: 2017-12-10 02:00:00

A LocalDateTime is a date and time without time zone or offset information. Since your string doesn’t contain offset or zone, I use this for parsing. And since you told me your date-time was in GMT+0, I convert it to an OffsetDateTime with offset UTC first thing. From there it’s straightforward to convert it into different local time zones. So I demonstrate that for a couple of time zones, each time formatting the date-time using the same formatter I used for parsing, since I gather you tend to like the yyyy-MM-dd HH:mm:ss format.

I always give time zone in the region/city format. This is unambiguous (contrary to three letter abbreviations; for example, PYT may mean Paraguay Time or Pyongyang Time). And it will automatically take care of summer time (DST) in case the time zone uses such. Even historic changes in zone offset are built-in.

To learn to use java.time, see the Oracle Tutorial on Date Time and search for relevant questions on Stack Overflow, always looking for the java.time answers (there’s a wealth of old answers using the outdated classes, skip those). Even more places on the net hold valuable resources. Your search engine and your ability to distinguish good from poor are your friends.


问:
Django Model Form does not display Image field properly and does not Post it
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

```<code>picture = models.ImageField(upload_to=user_directory_path)
</code>```

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

```<code>{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
    <h4 class="modal-title">Create a new book</h4>
  </div>
  <div class="modal-body">
    {% for field in form %}
      <div class="form-group{% if field.errors %} has-error{% endif %}">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <p class="help-block">{{ error }}</p>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>
  </div>
</form>
</code>```

The handling of the form was like this:

```<code>data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
</code>```

答:
You can save link,this way is better i think beacuse of:

1: in image field you save in database.(too heavy)but in link way you have too light.

2: in link way you can set it with static file way.(can delete easy).(imagefield have many problem but link it easy too manage)

I hope it will help you to choose.

Body:
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

picture = models.ImageField(upload_to=user_directory_path)

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

Create a new book

    {% for field in form %}

        {{ field.label }}
        {% render_field field class="form-control" %}
        {% for error in field.errors %}

{{ error }}

        {% endfor %}

    {% endfor %}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>

</form>

The handling of the form was like this:

data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False


问:
Why `minimum (1, 2)` returns 2 in Haskell?
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

```<code>GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2
</code>```

Shouldn't it return 1?

答:
When you look to the documentation you will find out that minimum can have various inputs (in the sense of argument's type).

In your case you want to apply a list to the minimum function to get a minimal element, so try

```<code>minimum [1,2]
</code>```

Body:
Why minimum (1, 2) is 2 in Haskell?

My test result in GHCi,

GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Prelude> minimum (1, 2)
2

Shouldn't it return 1?

Body:
When you look to the documentation you will find out that minimum can have various inputs (in the sense of argument's type).

In your case you want to apply a list to the minimum function to get a minimal element, so try

minimum [1,2]


问:
CodeIgniter 500 error
I'm really new to CodeIgniter and am having some trouble getting started. I see a lot of articles addressing the 500 Internal Server Error that I'm getting, but ALL of the authors of these articles seem to at least have gotten farther than I am able to.

So here's the situation. I have MAMP running correctly on my Mac. I downloaded CodeIgniter from their website (twice, actually) for a fresh start and extracted it in the correct MAMP folder. If I go to the index page, it works:

http://localhost:8888/index.php

But that's the only page that doesn't give me a 500 error. I create a really simple controller from CodeIgniter's video tutorial and save it in application/controllers.

```<code><?php
class Blog extends Controller {
    function index()
    {
        echo 'Hello World';
    }
}
?>
</code>```

Then I try to access it and get the 500 error:

http://localhost:8888/index.php/blog/

I tried several other tutorials as well, but I always get the error. What am I doing wrong? I tried several .htaccess variations suggested in other posts; right now I just have the default which only includes Deny from all, which shouldn't be pretty but should at least work. I also tried modifying the config.php file, setting $config['base_url'] and moving around the files as well as trying every variation of $config['uri_protocol'] as suggested in another post, all to no avail.

What am I doing wrong? Kind of disheartening having such a progress-stopping problem right of the bat.

答: I have faced same issue and solved by giving permission to all the folders</p>

Title: CodeIgniter 500 error

Body:
I'm really new to CodeIgniter and am having some trouble getting started. I see a lot of articles addressing the 500 Internal Server Error that I'm getting, but ALL of the authors of these articles seem to at least have gotten farther than I am able to.

So here's the situation. I have MAMP running correctly on my Mac. I downloaded CodeIgniter from their website (twice, actually) for a fresh start and extracted it in the correct MAMP folder. If I go to the index page, it works:

http://localhost:8888/index.php

But that's the only page that doesn't give me a 500 error. I create a really simple controller from CodeIgniter's video tutorial and save it in application/controllers.

<?php
class Blog extends Controller {
    function index()
    {
        echo 'Hello World';
    }
}
?>

Then I try to access it and get the 500 error:

http://localhost:8888/index.php/blog/

I tried several other tutorials as well, but I always get the error. What am I doing wrong? I tried several .htaccess variations suggested in other posts; right now I just have the default which only includes Deny from all, which shouldn't be pretty but should at least work. I also tried modifying the config.php file, setting $config['base_url'] and moving around the files as well as trying every variation of $config['uri_protocol'] as suggested in another post, all to no avail.

What am I doing wrong? Kind of disheartening having such a progress-stopping problem right of the bat.


答:
Use following code:</p>

```<code>f=open('f.txt','r') #input file . change file name to your file name
f1=open('o.txt','w')  # output file
d=f.readlines()
for i in d:
    k=i.strip().split()
    f1.write((k[1]+k[0]+' '+k[2]+"\n"))
f.close()
f1.close()
</code>```

Title: how to merge two columns into one (using Python)?

Body:
I need to merge two columns (first and second) into one column, using Python.
Here is my file:

   0 C   -0.053959    0.000000
   1 C   -0.053862    0.000000
   2 C   -0.059245    0.000000
   3 C   -0.058925    0.000000
   4 S    0.050616    0.000000
   5 H    0.040353    0.000000
   6 H    0.040480    0.000000
   7 H    0.045907    0.000000
   8 H    0.045941    0.000000

I already managed to reach my goal with Bash:

awk '{print $2 "" $1 "\ t" $3}' <MYfile.txt >> OUTPUT.txt

The result is :

C0      -0.053959
C1      -0.053862
C2      -0.059245
C3      -0.058925
S4      0.050616
H5      0.040353
H6      0.040480
H7      0.045907
H8      0.045941

Is it possible with Python ???

Body:
Use following code:

f=open('f.txt','r') #input file . change file name to your file name
f1=open('o.txt','w')  # output file
d=f.readlines()
for i in d:
    k=i.strip().split()
    f1.write((k[1]+k[0]+' '+k[2]+"\n"))
f.close()
f1.close()


问:
Apache Spark SQL get values in dataframe from SQL query
I'm trying to get a string value from a SQL query with Apache Spark 2.2.0 as follows:

```<code>val result = spark.sql("SELECT AnswerText FROM datatable WHERE participantUUID='010A0550' AND assessmentNumber=0 AND Q_id_string = '1_Age'")

assertResult("23") {
  result.collect.head.getString(0)
}
</code>```

I get the following exception:

```<code>next on empty iterator
java.util.NoSuchElementException: next on empty iterator
</code>```

I've tried collectAsList to return a row but not getting any joy from that, either. I simply want to return the actual value from the query in the DataFrame, not the column, row or field. In this case, the result is a string but it could also be an int - the age of the person = 23.

答:
This happens probably because query doesn't return any items. It would be better to use headOption

```<code>assertResult(Some("23")) {
  result.take(1).headOption.map(_.getAs[String]("AnswerText"))
}
</code>```

or push it to SQL:

```<code>assertResult(1) {
  spark
    .sql("""SELECT AnswerText
            FROM datatable
            WHERE participantUUID='010A0550' AND
                  assessmentNumber=0 AND
                  Q_id_string = '1_Age'""")
   .where($"AnswerText" === "23").count
}
</code>```

Body:
I'm trying to get a string value from a SQL query with Apache Spark 2.2.0 as follows:

val result = spark.sql("SELECT AnswerText FROM datatable WHERE participantUUID='010A0550' AND assessmentNumber=0 AND Q_id_string = '1_Age'")

assertResult("23") {
  result.collect.head.getString(0)
}

I get the following exception:

next on empty iterator
java.util.NoSuchElementException: next on empty iterator

I've tried collectAsList to return a row but not getting any joy from that, either. I simply want to return the actual value from the query in the DataFrame, not the column, row or field. In this case, the result is a string but it could also be an int - the age of the person = 23.

Body:
This happens probably because query doesn't return any items. It would be better to use headOption

assertResult(Some("23")) {
  result.take(1).headOption.map(_.getAs[String]("AnswerText"))
}

or push it to SQL:

assertResult(1) {
  spark
    .sql("""SELECT AnswerText
            FROM datatable
            WHERE participantUUID='010A0550' AND
                  assessmentNumber=0 AND
                  Q_id_string = '1_Age'""")
   .where($"AnswerText" === "23").count
}


问:
Handling links in my application
I want handle this URL but my code is not work true.

http://melkplus.com/#!/property/details/765

Actually when I click on this URL, my phone does not suggest me my application and it just open by browser.

I think application has problem with #! in URL.

```<code><intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
    android:host="melkplus.com"
    android:scheme="http"
    android:pathPrefix="/#!/property/details/" />
</intent-filter>
</code>```

答: Everything starting with the # is not part of the path of the URL, but rather is the fragment. You cannot filter on fragments.

Title: Handling links in my application

Body:
I want handle this URL but my code is not work true.

http://melkplus.com/#!/property/details/765

Actually when I click on this URL, my phone does not suggest me my application and it just open by browser.

I think application has problem with #! in URL.

<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
    android:host="melkplus.com"
    android:scheme="http"
    android:pathPrefix="/#!/property/details/" />
</intent-filter>


问:
python scheduler on bluemix
I am using the schedule package in python, to invoke a function for every 15 seconds, and want to run this code on IBM Bluemix.
Have pushed the application using the -no-route option to Bluemix, though the application is deployed to Bluemix, Bluemix is not able to start the application

Below is the sample code that I tried

```<code>import schedule
import time

def printMyName():
    print("NAME...")

schedule.every(15).seconds.do(printMyName)

while 1:
   schedule.run_pending()
   time.sleep(10)
</code>```

Messages in the Bluemix logs for this application:

```<code>Destroying container
Successfully destroyed container

0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
</code>```

And after a while, I see this message in the logs

```<code>ERR Timed out after 1m0s: health check never passed.
</code>```

Python version: 3.4.4

答:
I got my scheduler to work by setting

```<code>health-check-type: process
</code>```

The cloud foundry docs on this are here: https://docs.cloudfoundry.org/devguide/deploy-apps/healthchecks.html#types

My project is here: https://github.com/snowch/bluemix_retail_demo/tree/master/messagehub2elasticsearch/purge_old_indices

Title: python scheduler on bluemix

Body:
I am using the schedule package in python, to invoke a function for every 15 seconds, and want to run this code on IBM Bluemix.
Have pushed the application using the -no-route option to Bluemix, though the application is deployed to Bluemix, Bluemix is not able to start the application

Below is the sample code that I tried

import schedule
import time

def printMyName():
    print("NAME...")

schedule.every(15).seconds.do(printMyName)

while 1:
   schedule.run_pending()
   time.sleep(10)

Messages in the Bluemix logs for this application:

Destroying container
Successfully destroyed container

0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting
0 of 1 instances running, 1 starting

And after a while, I see this message in the logs

ERR Timed out after 1m0s: health check never passed.

Python version: 3.4.4

Body:
I got my scheduler to work by setting

health-check-type: process

The cloud foundry docs on this are here: https://docs.cloudfoundry.org/devguide/deploy-apps/healthchecks.html#types

My project is here: https://github.com/snowch/bluemix_retail_demo/tree/master/messagehub2elasticsearch/purge_old_indices


问:
[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object', Thread: SIGABRT

I was building a To-do-list app. And when I press the "Add Task" button, my app crashes and gives me the following error:

[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

It also returns me to Thread SIGABRT error. Any help would be appreciated.

Here is my SecondViewController

```<code>class SecondViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var taskValue: UITextField!
    @IBAction func addTask(_ sender: Any) {
        let itemsObject = UserDefaults.standard.object(forKey: "items")

        var items:NSMutableArray!

        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
            items.addObjects(from: [taskValue.text!])
        } else{
            items = [taskValue.text!]
        }

        UserDefaults.standard.set(items, forKey: "items")

        taskValue.text = ""
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
</code>```

My first view controller is here:

```<code>class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    var items: NSMutableArray = []

    //table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellContent = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

        var cellLabel = ""

        if let tempLabel = items[indexPath.row] as? String{
            cellLabel = tempLabel
        }
        cellContent.textLabel?.text = cellLabel
        return cellContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let itemsObject = UserDefaults.standard.object(forKey: "items")

        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
        }
    }
}
</code>```

答:
The error occurs because you can't cast a Swift array to NSMutableArray. Don't use NSMutable... Foundation types in Swift at all.

In Swift it's very easy to get a mutable object, just use the var keyword.

And UserDefaults has a dedicated method to get a string array.

```<code>@IBAction func addTask(_ sender: Any) {

    var items : [String]
    if let itemsObject = UserDefaults.standard.stringArray(forKey: "items") {
        items = itemsObject
        items.append(taskValue.text!) // it's pointless to use the API to append an array.
    } else{
        items = [taskValue.text!]

    }
    UserDefaults.standard.set(items, forKey: "items")
    taskValue.text = ""

}
</code>```

Body:
I was building a To-do-list app. And when I press the "Add Task" button, my app crashes and gives me the following error:

[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

It also returns me to Thread SIGABRT error. Any help would be appreciated.

Here is my SecondViewController

class SecondViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var taskValue: UITextField!
    @IBAction func addTask(_ sender: Any) {
        let itemsObject = UserDefaults.standard.object(forKey: "items")

        var items:NSMutableArray!

        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
            items.addObjects(from: [taskValue.text!])
        } else{
            items = [taskValue.text!]
        }

        UserDefaults.standard.set(items, forKey: "items")

        taskValue.text = ""
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

My first view controller is here:

class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
    var items: NSMutableArray = []

    //table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellContent = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

        var cellLabel = ""

        if let tempLabel = items[indexPath.row] as? String{
            cellLabel = tempLabel
        }
        cellContent.textLabel?.text = cellLabel
        return cellContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let itemsObject = UserDefaults.standard.object(forKey: "items")

        if let tempItems = itemsObject as? NSMutableArray{
            items = tempItems
        }
    }
}

Body:
The error occurs because you can't cast a Swift array to NSMutableArray. Don't use NSMutable... Foundation types in Swift at all.

In Swift it's very easy to get a mutable object, just use the var keyword.

And UserDefaults has a dedicated method to get a string array.

@IBAction func addTask(_ sender: Any) {

    var items : [String]
    if let itemsObject = UserDefaults.standard.stringArray(forKey: "items") {
        items = itemsObject
        items.append(taskValue.text!) // it's pointless to use the API to append an array.
    } else{
        items = [taskValue.text!]

    }
    UserDefaults.standard.set(items, forKey: "items")
    taskValue.text = ""

}


问:
How to do edit text multi line with fixed height and width with out scrollbar?
I woud like to EditText multi line text with fixed height and width without  scrollbar. The scrollbar stays and I don't want it.
This my code for EditText:

```<code>  <EditText
            android:id="@+id/write_text"
            android:layout_width="@dimen/_200mdp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:textStyle="bold"
            android:layout_centerInParent="true"
            android:inputType="textMultiLine|textCapWords"
            android:background="@null"
            android:textSize="@dimen/xxxl_fontsize"
            android:lines="3"
            android:maxLines="3"
            android:minLines="1"
            android:maxLength="144"
            android:scrollHorizontally="false"
            android:scrollbars="none"
            />
</code>```

I have tried a lot but the scrollbar remains, I want the fixed height and width with inputType="textMultiLine|textCapWords"  without scrollbar

Can any one help me.

答:
you must not make the height warp_content.</p>

```<code>    android:layout_height="@dimen/yourHeight"
</code>```

Body:
I woud like to EditText multi line text with fixed height and width without  scrollbar. The scrollbar stays and I don't want it.
This my code for EditText:

  <EditText
            android:id="@+id/write_text"
            android:layout_width="@dimen/_200mdp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@color/colorWhite"
            android:textStyle="bold"
            android:layout_centerInParent="true"
            android:inputType="textMultiLine|textCapWords"
            android:background="@null"
            android:textSize="@dimen/xxxl_fontsize"
            android:lines="3"
            android:maxLines="3"
            android:minLines="1"
            android:maxLength="144"
            android:scrollHorizontally="false"
            android:scrollbars="none"
            />

I have tried a lot but the scrollbar remains, I want the fixed height and width with inputType="textMultiLine|textCapWords"  without scrollbar

Can any one help me.

Body:
you must not make the height warp_content.

    android:layout_height="@dimen/yourHeight"

ContentLicense: CC BY-SA 4.0


问:
Fill data frame by column with for loop
I created an empty data frame with 11 columns and 15 rows and subsequently named the columns.

```<code>L_df <- data.frame(matrix(ncol = 11, nrow = 15))
names(L_df) <- paste0("L_por", 0:10)

w <- c(0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6,  2.8, 3)
wu <- 0
L <- 333.7
pm <- c(2600, 2574, 2548, 2522, 2496, 2470, 2444, 2418, 2392, 2366,  2340)
</code>```

The data frame looks like this:

```<code>head(L_df)
  L_por0 L_por1 L_por2 L_por3 L_por4 L_por5 L_por6 L_por7 L_por8 L_por9 L_por10
1     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
2     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
3     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
4     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
5     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
6     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
</code>```

Now, I would like to fill the data frame by column, based on a formula.  I tried to express this with a nested for loop:

```<code> for (i in 1:ncol(L_df)) {
  pm_tmp <- pm[i]
  col_tmp <- colnames(L_df)[i]
  for (j in 1:nrow(L_df)) {
    w_tmp <- w[j]
    L_por_tmp <- pm_tmp*L*((w_tmp-wu)/100)
    col_tmp[j] <- L_por_tmp
  }
}
</code>```

For each column, I iterate over a predefined vector pm of length 11. For each row, I iterate over a predefined vector w of length 15 (repeats each column).

Example: First, select pm[1] for the first column. Second, select w[i] for each row in the first column. Store the formula in L_por_tmp and use it to fill the first column from row1 to row15. The whole procedure should start all over again for the second column (with pm[2]) with w[i] for each row and so on. wu and L are fixed in the formula.

R executes the code without an error. When I check the tmp values, they are correct. However, the data frame remains empty. L_df does not get filled. I would like solve this with a loop but if you have other solutions, I am happy to hear them! I get the impression there might be a smoother way of doing this. Cheers!

Title: Fill data frame by column with for loop

Body:
I created an empty data frame with 11 columns and 15 rows and subsequently named the columns.

L_df <- data.frame(matrix(ncol = 11, nrow = 15))
names(L_df) <- paste0("L_por", 0:10)

w <- c(0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6,  2.8, 3)
wu <- 0
L <- 333.7
pm <- c(2600, 2574, 2548, 2522, 2496, 2470, 2444, 2418, 2392, 2366,  2340)

The data frame looks like this:

head(L_df)
  L_por0 L_por1 L_por2 L_por3 L_por4 L_por5 L_por6 L_por7 L_por8 L_por9 L_por10
1     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
2     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
3     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
4     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
5     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA
6     NA     NA     NA     NA     NA     NA     NA     NA     NA     NA      NA

Now, I would like to fill the data frame by column, based on a formula.  I tried to express this with a nested for loop:

 for (i in 1:ncol(L_df)) {
  pm_tmp <- pm[i]
  col_tmp <- colnames(L_df)[i]
  for (j in 1:nrow(L_df)) {
    w_tmp <- w[j]
    L_por_tmp <- pm_tmp*L*((w_tmp-wu)/100)
    col_tmp[j] <- L_por_tmp
  }
}

For each column, I iterate over a predefined vector pm of length 11. For each row, I iterate over a predefined vector w of length 15 (repeats each column).

Example: First, select pm[1] for the first column. Second, select w[i] for each row in the first column. Store the formula in L_por_tmp and use it to fill the first column from row1 to row15. The whole procedure should start all over again for the second column (with pm[2]) with w[i] for each row and so on. wu and L are fixed in the formula.

R executes the code without an error. When I check the tmp values, they are correct. However, the data frame remains empty. L_df does not get filled. I would like solve this with a loop but if you have other solutions, I am happy to hear them! I get the impression there might be a smoother way of doing this. Cheers!

Body:
Solution

L_df <- data.frame(sapply(pm, function(x) x * L * ((w - wu) / 100)))
names(L_df) <- c("L_por0", "L_por1", "L_por2", "L_por3", "L_por4", "L_por5",
                 "L_por6", "L_por7", "L_por8", "L_por9", "L_por10")
L_df
 L_por0    L_por1    L_por2    L_por3    L_por4    L_por5    L_por6    L_por7
1   1735.24  1717.888  1700.535  1683.183  1665.830  1648.478  1631.126  1613.773
2   3470.48  3435.775  3401.070  3366.366  3331.661  3296.956  3262.251  3227.546
3   5205.72  5153.663  5101.606  5049.548  4997.491  4945.434  4893.377  4841.320
4   6940.96  6871.550  6802.141  6732.731  6663.322  6593.912  6524.502  6455.093
5   8676.20  8589.438  8502.676  8415.914  8329.152  8242.390  8155.628  8068.866
6  10411.44 10307.326 10203.211 10099.097  9994.982  9890.868  9786.754  9682.639
7  12146.68 12025.213 11903.746 11782.280 11660.813 11539.346 11417.879 11296.412
8  13881.92 13743.101 13604.282 13465.462 13326.643 13187.824 13049.005 12910.186
9  15617.16 15460.988 15304.817 15148.645 14992.474 14836.302 14680.130 14523.959
10 17352.40 17178.876 17005.352 16831.828 16658.304 16484.780 16311.256 16137.732
11 19087.64 18896.764 18705.887 18515.011 18324.134 18133.258 17942.382 17751.505
12 20822.88 20614.651 20406.422 20198.194 19989.965 19781.736 19573.507 19365.278
13 22558.12 22332.539 22106.958 21881.376 21655.795 21430.214 21204.633 20979.052
14 24293.36 24050.426 23807.493 23564.559 23321.626 23078.692 22835.758 22592.825
15 26028.60 25768.314 25508.028 25247.742 24987.456 24727.170 24466.884 24206.598
      L_por8    L_por9   L_por10
1   1596.421  1579.068  1561.716
2   3192.842  3158.137  3123.432
3   4789.262  4737.205  4685.148
4   6385.683  6316.274  6246.864
5   7982.104  7895.342  7808.580
6   9578.525  9474.410  9370.296
7  11174.946 11053.479 10932.012
8  12771.366 12632.547 12493.728
9  14367.787 14211.616 14055.444
10 15964.208 15790.684 15617.160
11 17560.629 17369.752 17178.876
12 19157.050 18948.821 18740.592
13 20753.470 20527.889 20302.308
14 22349.891 22106.958 21864.024
15 23946.312 23686.026 23425.740

Explanation

The sapply() function can be used to iterate over vectors in a more idiomatic way for R programming. We iterate over pm and use your formula once since R is vectorised; each time it creates a vector of length 15 (so 11 vectors of length 15), and when we wrap it in data.frame() returns the data frame you want and we add in the column names.

NOTE: Applying functions to every element of a vector using an apply() family function has some different implications than iterating using for loops. In your case, I think sapply() is easier and more understandable. For more information on when you need a loop or when something like apply is better, see for example this discussion from Hadley Wickham's Advanced R book.