问:
REST API Call from VB ( ZOHO CREATOR )
Trying to make out this call

https://www.zoho.com/creator/help/api/rest-api/rest-api-edit-records.html

I did tried everything but seems i need basic knowledge. Can anyone give me directions what is wrong with my code

```<code>Public Sub updateRecord(ByVal ht As Hashtable, ByVal criteriaField As String)

        Dim apiUrl As String = "https://creator.zoho.com/api/xml/write/apikey=xxxx"
        Dim xmlStr As New System.Text.StringBuilder
        Dim newvalue As New System.Text.StringBuilder

        newvalue.AppendLine("<newvalues>")
        xmlStr.Append("<ZohoCreator><applicationlist>")
        xmlStr.Append("<application name=copy-of-ebay-inventory><formlist><form name=Ebay_Inventory>")
        xmlStr.AppendLine("<update>")
        xmlStr.AppendLine("<criteria>")
        xmlStr.AppendLine("<field name='Ticket Number' compOperator='Equals' value='20573'></field>")
        xmlStr.AppendLine("</criteria>")
        newvalue.AppendLine("<field name='Found on site' value='1'></field>")
        newvalue.AppendLine("</newvalues>")
        xmlStr.Append(newvalue.ToString)
        xmlStr.AppendLine("</update>")
        xmlStr.AppendLine("</form></formlist></application></applicationlist></ZohoCreator>")

        Dim params As String = "XMLString=" + xmlStr.ToString

        Dim res As String = getResponseFromUrl(apiUrl, params)

    End Sub
Public Function getResponseFromUrl(ByVal url As String, ByVal params As String)
        Dim str As String = ""
        Try
            Dim webreq As HttpWebRequest = WebRequest.Create(url)
            webreq.Method = "POST"
            webreq.ContentType = "application/x-www-form-urlencoded"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(params)
            Dim dataStream As Stream = webreq.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()

            Dim res As WebResponse = webreq.GetResponse()
            Dim stream As Stream = res.GetResponseStream()
            Dim streamReader As New StreamReader(stream)
            str = streamReader.ReadToEnd
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return str.ToString
    End Function
</code>```

At the end of formating my xml looks like

But that is not that.
Found a good example on ..

LINK DEMO

Reposnse

答:
The error message is telling you that the value of the name attribute must be wrapped in quotes on the application node/element:

xmlStr.Append("<application name='copy-of-ebay-inventory'><formlist><form name=Ebay_Inventory>")

Note the ' single-quotes around "copy-of-ebay-inventory"...

Title: REST API Call from VB ( ZOHO CREATOR )

Body:
Trying to make out this call

https://www.zoho.com/creator/help/api/rest-api/rest-api-edit-records.html

I did tried everything but seems i need basic knowledge. Can anyone give me directions what is wrong with my code

Public Sub updateRecord(ByVal ht As Hashtable, ByVal criteriaField As String)

        Dim apiUrl As String = "https://creator.zoho.com/api/xml/write/apikey=xxxx"
        Dim xmlStr As New System.Text.StringBuilder
        Dim newvalue As New System.Text.StringBuilder

        newvalue.AppendLine("<newvalues>")
        xmlStr.Append("<ZohoCreator><applicationlist>")
        xmlStr.Append("<application name=copy-of-ebay-inventory><formlist><form name=Ebay_Inventory>")
        xmlStr.AppendLine("<update>")
        xmlStr.AppendLine("<criteria>")
        xmlStr.AppendLine("<field name='Ticket Number' compOperator='Equals' value='20573'></field>")
        xmlStr.AppendLine("</criteria>")
        newvalue.AppendLine("<field name='Found on site' value='1'></field>")
        newvalue.AppendLine("</newvalues>")
        xmlStr.Append(newvalue.ToString)
        xmlStr.AppendLine("</update>")
        xmlStr.AppendLine("</form></formlist></application></applicationlist></ZohoCreator>")

        Dim params As String = "XMLString=" + xmlStr.ToString

        Dim res As String = getResponseFromUrl(apiUrl, params)

    End Sub
Public Function getResponseFromUrl(ByVal url As String, ByVal params As String)
        Dim str As String = ""
        Try
            Dim webreq As HttpWebRequest = WebRequest.Create(url)
            webreq.Method = "POST"
            webreq.ContentType = "application/x-www-form-urlencoded"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(params)
            Dim dataStream As Stream = webreq.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()

            Dim res As WebResponse = webreq.GetResponse()
            Dim stream As Stream = res.GetResponseStream()
            Dim streamReader As New StreamReader(stream)
            str = streamReader.ReadToEnd
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return str.ToString
    End Function

At the end of formating my xml looks like

But that is not that.
Found a good example on ..

LINK DEMO

Reposnse


来源: stackexchange

问:
fill column with previous column if NA
I have a data frame like this

```<code>df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4
</code>```

I now want to fill the NAs with the value of the previous column, so it looks like this:

```<code>  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4
</code>```

I know how to do this manually, like this:

```<code>df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)
</code>```

How can I automate this for a full data frame with many columns?

答:
By using zoo na.locf

```<code>data.frame(t(apply(df,1,function(x) na.locf(x))))
  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4
</code>```

ContentLicense: CC BY-SA 3.0

Title: fill column with previous column if NA

Body:
I have a data frame like this

df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4

I now want to fill the NAs with the value of the previous column, so it looks like this:

  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4

I know how to do this manually, like this:

df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)

How can I automate this for a full data frame with many columns?

Body:
By using zoo na.locf

data.frame(t(apply(df,1,function(x) na.locf(x))))
  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4


问:
How to convert a year to the Japanese calendar?
I have this code that converts the CURRENT Gregorian year to the Japanese era year.

```<code>var date = new Date().toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));
</code>```

However, I want to input the year myself instead of getting the present year.
I tried like this:

```<code>var myyear = 2018;
var date = myyear.toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));
</code>```

It didn't work though. How should I do it?

答:
You can set the year on the Date object:

var date = new Date();
date.setFullYear(2018);
console.log(date, date.toLocaleDateString("ja-JP-u-ca-japanese"));```

ContentLicense: CC BY-SA 4.0

Body:
I have this code that converts the CURRENT Gregorian year to the Japanese era year.

var date = new Date().toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));

However, I want to input the year myself instead of getting the present year.
I tried like this:

var myyear = 2018;
var date = myyear.toLocaleDateString("ja-JP-u-ca-japanese");
var year = date.substring(0, date.indexOf("/"));

It didn't work though. How should I do it?


问:
nodejs - sinon stub not being called
For some reason I am having a little trouble getting this simple test to run correctly with a similar set-up I have used multiple times before.

Perhaps a fresh pair of eyes could help me understand why my method generateReport is not being invoked and none of my stubs are being triggered with the intended arguments?

BYE nor GOOD are ever logged and the tests are returning the error: AssertError: expected stub to be called with arguments

My index file:

```<code>const errorHandler = require('./lib/handlers/error-handler')
const transformRequest = require('./lib/handlers/request-converter')
const convert = require('./lib/convert')

exports.generateReport = function generateReport(req, res) {
  console.log('HELLO')
  const objectToPopulateTemplate = transformRequest(req.body)
  convert(objectToPopulateTemplate, function (e, data) {
    if (e) {
      console.log('BYE')
      const error = errorHandler(e)
      return res.send(error.httpCode).json(error)
    }
    console.log('GOOD')
    res
      .set('Content-Type', 'application/pdf')
      .set('Content-Disposition', `attachment; filename=velocity_report_${new Date()}.pdf`)
      .set('Content-Length', data.length)
      .status(200)
      .end(data)
  })
}
</code>```

My test file:

```<code>const proxyquire = require('proxyquire')
const assert = require('assert')
const sinon = require('sinon')
const fakeData = require('./data/sample-request.json')

describe('report-exporter', () => {
  describe('generateReport', () => {
    const fakeError = new Error('Undefined is not a function')

    let res, resSendStub, resStatusStub, resEndStub, resSetStub, resJsonStub, req, convertStub, generate
    before(() => {
      resSendStub = sinon.stub()
      resJsonStub = sinon.stub()
      resStatusStub = sinon.stub()
      resEndStub = sinon.stub()
      resSetStub = sinon.stub()
      convertStub = sinon.stub()

      res = {
        send: function(errorCode) {
          return resSendStub(errorCode)
        },
        json: function(object) {
          return resJsonStub(object)
        },
        set: function(arg1, arg2) {
          return resSetStub(arg1, arg2)
        },
        status: function(code) {
          return resStatusStub(code)
        },
        end: function(data) {
          return resEndStub(data)
        }
      }
      req = {
        body: {}
      }

      generate = proxyquire('./../index', {
        './lib/convert': function() {
          return convertStub
        }
      })
    })

    it('Should return an error response', () => {
      convertStub.throws(fakeError)
      generate.generateReport(req, res)
      sinon.assert.calledWith(resSendStub, '500')
    })
  })
})
</code>```

答:
It looks like you are proxyquireing your ./lib/convert incorrectly. Original convert is called with objectToPopulateTemplate and a callback function (e, data). And that's the callback who is responsible for error handling and sending a response.

The stubbed convert function though doesn't care about about the provided callback at all, so the callback never gets called.

Most likely what you want is to pass the parameters to convertStub and deal with them later:

```<code>'./lib/convert': function(objectToPopulateTemplate, cb) {
    return convertStub(objectToPopulateTemplate, cb);
}
</code>```

and then

```<code>it('Should return an error response', () => {
  generate.generateReport(req, res);
  const cb = convertStub.getCall(0).args[1];

  // simulate `convert` to fail
  cb(fakeError);

  sinon.assert.calledWith(resSendStub, '500')
})
</code>```

Title: nodejs - sinon stub not being called

Body:
For some reason I am having a little trouble getting this simple test to run correctly with a similar set-up I have used multiple times before.

Perhaps a fresh pair of eyes could help me understand why my method generateReport is not being invoked and none of my stubs are being triggered with the intended arguments?

BYE nor GOOD are ever logged and the tests are returning the error: AssertError: expected stub to be called with arguments

My index file:

const errorHandler = require('./lib/handlers/error-handler')
const transformRequest = require('./lib/handlers/request-converter')
const convert = require('./lib/convert')

exports.generateReport = function generateReport(req, res) {
  console.log('HELLO')
  const objectToPopulateTemplate = transformRequest(req.body)
  convert(objectToPopulateTemplate, function (e, data) {
    if (e) {
      console.log('BYE')
      const error = errorHandler(e)
      return res.send(error.httpCode).json(error)
    }
    console.log('GOOD')
    res
      .set('Content-Type', 'application/pdf')
      .set('Content-Disposition', `attachment; filename=velocity_report_${new Date()}.pdf`)
      .set('Content-Length', data.length)
      .status(200)
      .end(data)
  })
}

My test file:

const proxyquire = require('proxyquire')
const assert = require('assert')
const sinon = require('sinon')
const fakeData = require('./data/sample-request.json')

describe('report-exporter', () => {
  describe('generateReport', () => {
    const fakeError = new Error('Undefined is not a function')

    let res, resSendStub, resStatusStub, resEndStub, resSetStub, resJsonStub, req, convertStub, generate
    before(() => {
      resSendStub = sinon.stub()
      resJsonStub = sinon.stub()
      resStatusStub = sinon.stub()
      resEndStub = sinon.stub()
      resSetStub = sinon.stub()
      convertStub = sinon.stub()

      res = {
        send: function(errorCode) {
          return resSendStub(errorCode)
        },
        json: function(object) {
          return resJsonStub(object)
        },
        set: function(arg1, arg2) {
          return resSetStub(arg1, arg2)
        },
        status: function(code) {
          return resStatusStub(code)
        },
        end: function(data) {
          return resEndStub(data)
        }
      }
      req = {
        body: {}
      }

      generate = proxyquire('./../index', {
        './lib/convert': function() {
          return convertStub
        }
      })
    })

    it('Should return an error response', () => {
      convertStub.throws(fakeError)
      generate.generateReport(req, res)
      sinon.assert.calledWith(resSendStub, '500')
    })
  })
})

Body:
It looks like you are proxyquireing your ./lib/convert incorrectly. Original convert is called with objectToPopulateTemplate and a callback function (e, data). And that's the callback who is responsible for error handling and sending a response.

The stubbed convert function though doesn't care about about the provided callback at all, so the callback never gets called.

Most likely what you want is to pass the parameters to convertStub and deal with them later:

'./lib/convert': function(objectToPopulateTemplate, cb) {
    return convertStub(objectToPopulateTemplate, cb);
}

and then

it('Should return an error response', () => {
  generate.generateReport(req, res);
  const cb = convertStub.getCall(0).args[1];

  // simulate `convert` to fail
  cb(fakeError);

  sinon.assert.calledWith(resSendStub, '500')
})


问:
In Clojure, how can I do a performant version of `frequencies` with transducers?
(Question credit: Fernando Abrao.)

I hear about the performance benefits of transducers in Clojure, but I'm not sure how to use them.

Say I have a qos/device-qos-range function that returns sequence of maps, some of which contain a decimal :samplevalue, like so:

```<code>[
  { :samplevalue 1.3, ... },
  { :othervalue -27.7, ... },
  { :samplevalue 7.5, ... },
  { :samplevalue 1.9, ... },
]
</code>```

I'd like to see how many :samplevalues fall into each integer bin, like so:

```<code>(frequencies
  (reduce #(if (not (nil? (:samplevalue %2)))
             (conj %1 (.intValue (:samplevalue %2))))
          []
          (qos/device-qos-range origem device qos alvo inicio fim)))

;; => {1 2, 7 1}
</code>```

How can I turn this into a fast version with transducers that eliminates intermediate data structures (such as the one returned by reduce)? Bonus points for code that can take advantage of multiple cores to do parallel processing.

答:
(Answer credit: Renzo Borgatti (@reborg).)

First, let's set up some sample data, which we'll use for performance tests later. This vector contains 500k maps with the same key. Values are overlapping 1/5th of the time.

```<code>(def data
 (mapv hash-map
       (repeat :samplevalue)
       (concat (range 1e5)
               (range 1e5)
               (range 1e5)
               (range 1e5)
               (range 1e5))))
</code>```

Now let's do your transformation with transducers. Note that this solution is not parallel. I shortened your .intValue to just int, which does the same thing. Also, conditionally fetching :samplevalue from each map can be shortened to just (keep :samplevalue sequence), which is equivalent to (remove nil? (map :samplevalue sequence)). We'll use Criterium to benchmark.

```<code>(require '[criterium.core :refer [quick-bench]])
(quick-bench
  (transduce
    (comp
      (keep :samplevalue)
      (map int))
    (completing #(assoc! %1 %2 (inc (get %1 %2 0))) persistent!)
    (transient {})
    data))
;; My execution time mean: 405 ms
</code>```

Note that we're not calling frequencies as an external step this time. Instead, we've woven it into the operation. And just like what frequencies does, we've done the operations on a transient hashmap for extra performance. We do this by using a transient hashmap as the seed and completing the final value by calling persistent! on it.

We can make this parallel. For maximum performance, we use a mutable Java ConcurrentHashMap instead of an immutable Clojure data structure.

```<code>(require '[clojure.core.reducers :as r])
(import '[java.util HashMap Collections Map]
        'java.util.concurrent.atomic.AtomicInteger
        'java.util.concurrent.ConcurrentHashMap)

(quick-bench
  (let [concurrency-level (.availableProcessors (Runtime/getRuntime))
        m (ConcurrentHashMap. (quot (count data) 2) 0.75 concurrency-level)
        combinef (fn ([] m) ([_ _]))  ; just return `m` from the combine step
        rf (fn [^Map m k]
             (let [^AtomicInteger v (or (.get m k) (.putIfAbsent m k (AtomicInteger. 1)))]
               (when v (.incrementAndGet v))
               m))
        reducef ((comp (keep :samplevalue) (map int)) rf)]
    (r/fold combinef reducef data)
    (into {} m)))
;; My execution time mean: 70 ms
</code>```

Here we use fold from the clojure.core.reducers library to achieve parallelism. Note that in a parallel context any transducers one uses need to be stateless. Also note that a ConcurrentHashMap doesn't support using nil as a key or value; fortunately, we don't need to do that here.

The output is converted into an immutable Clojure hashmap at the end. You can remove that step and just use the ConcurrentHashMap instance for an additional speedup—on my machine, removing the into step makes the whole fold take about 26ms.

Edit 2017-11-20: User @clojuremostly correctly pointed out that an earlier version of this answer had the call to quick-bench inside the let block that initialized the concurrent hash map instance, which meant that the benchmark used the same instance for all of its runs. I moved the call to quick-bench to be outside the let block. It did not significantly affect the results.

Body:
(Question credit: Fernando Abrao.)

I hear about the performance benefits of transducers in Clojure, but I'm not sure how to use them.

Say I have a qos/device-qos-range function that returns sequence of maps, some of which contain a decimal :samplevalue, like so:

[
  { :samplevalue 1.3, ... },
  { :othervalue -27.7, ... },
  { :samplevalue 7.5, ... },
  { :samplevalue 1.9, ... },
]

I'd like to see how many :samplevalues fall into each integer bin, like so:

(frequencies
  (reduce #(if (not (nil? (:samplevalue %2)))
             (conj %1 (.intValue (:samplevalue %2))))
          []
          (qos/device-qos-range origem device qos alvo inicio fim)))

;; => {1 2, 7 1}

How can I turn this into a fast version with transducers that eliminates intermediate data structures (such as the one returned by reduce)? Bonus points for code that can take advantage of multiple cores to do parallel processing.

Body:
(Answer credit: Renzo Borgatti (@reborg).)

First, let's set up some sample data, which we'll use for performance tests later. This vector contains 500k maps with the same key. Values are overlapping 1/5th of the time.

(def data
 (mapv hash-map
       (repeat :samplevalue)
       (concat (range 1e5)
               (range 1e5)
               (range 1e5)
               (range 1e5)
               (range 1e5))))

Now let's do your transformation with transducers. Note that this solution is not parallel. I shortened your .intValue to just int, which does the same thing. Also, conditionally fetching :samplevalue from each map can be shortened to just (keep :samplevalue sequence), which is equivalent to (remove nil? (map :samplevalue sequence)). We'll use Criterium to benchmark.

(require '[criterium.core :refer [quick-bench]])
(quick-bench
  (transduce
    (comp
      (keep :samplevalue)
      (map int))
    (completing #(assoc! %1 %2 (inc (get %1 %2 0))) persistent!)
    (transient {})
    data))
;; My execution time mean: 405 ms

Note that we're not calling frequencies as an external step this time. Instead, we've woven it into the operation. And just like what frequencies does, we've done the operations on a transient hashmap for extra performance. We do this by using a transient hashmap as the seed and completing the final value by calling persistent! on it.

We can make this parallel. For maximum performance, we use a mutable Java ConcurrentHashMap instead of an immutable Clojure data structure.

(require '[clojure.core.reducers :as r])
(import '[java.util HashMap Collections Map]
        'java.util.concurrent.atomic.AtomicInteger
        'java.util.concurrent.ConcurrentHashMap)

(quick-bench
  (let [concurrency-level (.availableProcessors (Runtime/getRuntime))
        m (ConcurrentHashMap. (quot (count data) 2) 0.75 concurrency-level)
        combinef (fn ([] m) ([_ _]))  ; just return `m` from the combine step
        rf (fn [^Map m k]
             (let [^AtomicInteger v (or (.get m k) (.putIfAbsent m k (AtomicInteger. 1)))]
               (when v (.incrementAndGet v))
               m))
        reducef ((comp (keep :samplevalue) (map int)) rf)]
    (r/fold combinef reducef data)
    (into {} m)))
;; My execution time mean: 70 ms

Here we use fold from the clojure.core.reducers library to achieve parallelism. Note that in a parallel context any transducers one uses need to be stateless. Also note that a ConcurrentHashMap doesn't support using nil as a key or value; fortunately, we don't need to do that here.

The output is converted into an immutable Clojure hashmap at the end. You can remove that step and just use the ConcurrentHashMap instance for an additional speedup—on my machine, removing the into step makes the whole fold take about 26ms.

Edit 2017-11-20: User @clojuremostly correctly pointed out that an earlier version of this answer had the call to quick-bench inside the let block that initialized the concurrent hash map instance, which meant that the benchmark used the same instance for all of its runs. I moved the call to quick-bench to be outside the let block. It did not significantly affect the results.


问:
image are not getting loaded using firebaseRecyclerAdapter
everything is working fine but images are not getting loaded

this image from emulator

this image display the value log of image-getimgUrl

this image frome firebase database

the problem her is the value of image and getimgUrl = NULL

public class MainScreen extends AppCompatActivity {

```<code>RecyclerView recyclerView;
DatabaseReference mRef;

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

    recyclerView = (RecyclerView)findViewById(R.id.recyclerView_main);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getBaseContext()));

    mRef = FirebaseDatabase.getInstance().getReference("Data");

    FirebaseRecyclerAdapter<Model,mViewHolder> adapter =
            new FirebaseRecyclerAdapter<Model, mViewHolder>(Model.class,R.layout.row,mViewHolder.class,mRef) {
        @Override
        protected void populateViewHolder(mViewHolder viewHolder, Model model, int position) {

            viewHolder.setTitle(model.getTitle());
            viewHolder.setImage(getBaseContext(),model.getImgUrl());

            Log.e("getImgUrl", "value : "+model.getImgUrl());
            Log.e("getTitle", "value : "+model.getTitle());
        }
    };

    recyclerView.setAdapter(adapter);
}

public static class mViewHolder extends RecyclerView.ViewHolder{
    View mview;

    public mViewHolder(View itemView) {
        super(itemView);

        mview = itemView;

    }

    public void setTitle(String title){

        TextView postTitle = (TextView) mview.findViewById(R.id.text_row);
        postTitle.setText(title);

        Log.e("title", "value : "+title);
        }
    public void setImage(Context ctx,String image){

        ImageView postImage = (ImageView) mview.findViewById(R.id.image_row);

        Picasso.with(ctx).load(image).into(postImage);

        Log.e("image", "value : "+image);
    }
}
</code>```

}

答:
use Glide 3.7.0 version Library instead of Picasso and use itemView context intead of ApplicationContext

```<code>public void setImage(String imageUrl){

    ImageView post_image = (ImageView) mview.findViewById(R.id.imageViewCardRow);

    Glide.with(mview.getContext).load(imageUrl).into(post_image);
}
</code>```

Body:
everything is working fine but images are not getting loaded

this image from emulator

this image display the value log of image-getimgUrl

this image frome firebase database

the problem her is the value of image and getimgUrl = NULL

public class MainScreen extends AppCompatActivity {

RecyclerView recyclerView;
DatabaseReference mRef;

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

    recyclerView = (RecyclerView)findViewById(R.id.recyclerView_main);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getBaseContext()));

    mRef = FirebaseDatabase.getInstance().getReference("Data");

    FirebaseRecyclerAdapter<Model,mViewHolder> adapter =
            new FirebaseRecyclerAdapter<Model, mViewHolder>(Model.class,R.layout.row,mViewHolder.class,mRef) {
        @Override
        protected void populateViewHolder(mViewHolder viewHolder, Model model, int position) {

            viewHolder.setTitle(model.getTitle());
            viewHolder.setImage(getBaseContext(),model.getImgUrl());

            Log.e("getImgUrl", "value : "+model.getImgUrl());
            Log.e("getTitle", "value : "+model.getTitle());
        }
    };

    recyclerView.setAdapter(adapter);
}

public static class mViewHolder extends RecyclerView.ViewHolder{
    View mview;

    public mViewHolder(View itemView) {
        super(itemView);

        mview = itemView;

    }

    public void setTitle(String title){

        TextView postTitle = (TextView) mview.findViewById(R.id.text_row);
        postTitle.setText(title);

        Log.e("title", "value : "+title);
        }
    public void setImage(Context ctx,String image){

        ImageView postImage = (ImageView) mview.findViewById(R.id.image_row);

        Picasso.with(ctx).load(image).into(postImage);

        Log.e("image", "value : "+image);
    }
}

}

Body:
use Glide 3.7.0 version Library instead of Picasso and use itemView context intead of ApplicationContext

public void setImage(String imageUrl){

    ImageView post_image = (ImageView) mview.findViewById(R.id.imageViewCardRow);

    Glide.with(mview.getContext).load(imageUrl).into(post_image);
}


问:
i want to send receive and receive data from Alexa lambda node JS
```<code>Alexa should ask for use strict';

const Alexa      = require('alexa-sdk');
exports.handler  = (event, context) => {
  const alexa    = Alexa.handler(event, context);
  var APP_ID     = "amzn1.ask.skill.[XXXXX-45cc-9558-3c284b72148f]";
  alexa.APP_ID   = APP_ID;

  alexa.dynamoDBTableName = 'LongFormAudioSample'; // creates new table for session.attributes
  alexa.registerHandlers(handlers);
  alexa.execute();
};

const handlers = {
  'LaunchRequest': function() {
  },
  'NewSession': function() {
    this.attributes['eventType'] = "";
  },
  'SessionEndedRequest': function() {
    //this.attributesp["crash:emergency"] = null;
    this.emit(':tell', "Thank you");
  },

  'WishingWelcomeIntent': function( ) {
    // here I want to send  username
    var username = ''; // should get from request
    var json = {
      place : "USA";
    }

    // this.emit(":tell", "Hi", +username, "you'r welcome", json should
      send along with the audio response from Alexa );

     },

    };
</code>```

How can we send data to Alexa?
POST data Alexa to the app.

Actually, I want to send data to the lambda function along with the audio.

I want to send some JSON data from Alexa to my application.

I am developing the mobile app. with Alexa voice service.

Is there any way to send and receive data using Alexa?

答:
If I understand your question correctly, you could use AWS API Gateway and setup an endpoint that would let you POST data from a mobile app to the Lambda function you use for your Alexa skill.

Here is a link to the documentation for setting up API Gateway with Lambda.

http://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html

However, if what you're trying to do is send something like an "alert" to an Alexa device when you post from the mobile app - that's not possible at this point.

Body:
Alexa should ask for use strict';

const Alexa      = require('alexa-sdk');
exports.handler  = (event, context) => {
  const alexa    = Alexa.handler(event, context);
  var APP_ID     = "amzn1.ask.skill.[XXXXX-45cc-9558-3c284b72148f]";
  alexa.APP_ID   = APP_ID;

  alexa.dynamoDBTableName = 'LongFormAudioSample'; // creates new table for session.attributes
  alexa.registerHandlers(handlers);
  alexa.execute();
};

const handlers = {
  'LaunchRequest': function() {
  },
  'NewSession': function() {
    this.attributes['eventType'] = "";
  },
  'SessionEndedRequest': function() {
    //this.attributesp["crash:emergency"] = null;
    this.emit(':tell', "Thank you");
  },

  'WishingWelcomeIntent': function( ) {
    // here I want to send  username
    var username = ''; // should get from request
    var json = {
      place : "USA";
    }

    // this.emit(":tell", "Hi", +username, "you'r welcome", json should
      send along with the audio response from Alexa );

     },

    };

How can we send data to Alexa?
POST data Alexa to the app.

Actually, I want to send data to the lambda function along with the audio.

I want to send some JSON data from Alexa to my application.

I am developing the mobile app. with Alexa voice service.

Is there any way to send and receive data using Alexa?


问:
Unexpected end of JSON input at JSON.parse
I made my RESTful mysql backend everything is good except that my
feteched query has problem.I mean ,it show me nothing when my returned json is more than 2 objects.
I'm working with ionic3 / http.

my select.php:

```<code>$sql = "SELECT * FROM products ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
     $data = array() ;
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
} else {
    echo "0";
}
</code>```

my service file in ionic:

```<code>getProducts(){
    return this.http.get("http://localhost/api/products/select.php")
    .map(res=>{
      this.checkMe = res;

      if(this.checkMe._body !== "0"){
         return res.json()
      }

    } );
  }
</code>```

I realy need your help.
Thank you all.

答:
have you tried to do ..</p>

```<code>getProducts(){
    return this.http.get("http://localhost/api/products/select.php")
    .map(res=>{
      this.checkMe = res.json() as any;

      if(this.checkMe._body !== "0"){
         return res.json()
      }

    } );
  }
</code>```

Body:
I made my RESTful mysql backend everything is good except that my
feteched query has problem.I mean ,it show me nothing when my returned json is more than 2 objects.
I'm working with ionic3 / http.

my select.php:

$sql = "SELECT * FROM products ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
     $data = array() ;
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
} else {
    echo "0";
}

my service file in ionic:

getProducts(){
    return this.http.get("http://localhost/api/products/select.php")
    .map(res=>{
      this.checkMe = res;

      if(this.checkMe._body !== "0"){
         return res.json()
      }

    } );
  }

I realy need your help.
Thank you all.

Body:
have you tried to do ..

getProducts(){
    return this.http.get("http://localhost/api/products/select.php")
    .map(res=>{
      this.checkMe = res.json() as any;

      if(this.checkMe._body !== "0"){
         return res.json()
      }

    } );
  }


问:
What is the best column type for a United States ZIP code?
I want to store Zip Code (within United States) in MySQL database. Saving space is a priority.  which is better option using VARCHAR - limited to maximum length of 6 digit or using INT or using MEDIUM Int . The Zip code will not be used for any calculation. The Zip code will be used to insert (Once), Updated (if required) and Retrieved - Once (but it can be more than once) .

Which is better option to use here VARCHAR or INT or MEDIUM  IN MYSQL ? Please suggest anything else ?

答: I would suggest, use VARCHAR data type because in some countries zip codes are used as alphanumeric and in other places as an integer. So we cannot use an integer for global use. Also, zip code may start with zero like 001101 so in this case if we take data type integer then leading zero will be lost so we cannot pass actual zip code.


问:
BLAST: can't find reference file in db
I am trying to run the standalone ncbi-blast-2.2.29+ on my machine (Mac) but get this error message when running blastx (or blastn) with my database:

```<code>No alias or index file found for nucleotide database [db/viral.1.1.genomic] in search path [~/Users/KK/ncbi-blast-2.3.0+/Virus::]
</code>```

The way I run it:

```<code>blastn -query input.fasta -out out.blast.txt -db db/viral.1.1.genomic
</code>```

My working directory is ~/Users/KK/ncbi-blast-2.3.0+/Virus and there is a  sub-directory db (~/Users/KK/ncbi-blast-2.3.0+/Virus/db) and db has viral.1.1.genomic.phr, viral.1.1.genomic.pin, viral.1.1.genomic.pnd, viral.1.1.genomic.pni, viral.1.1.genomic.pog, viral.1.1.genomic.psd, viral.1.1.genomic.psi, viral.1.1.genomic.psq, viral.1.1.genomic.fasta. and I made all these files using this command line

```<code>makeblastdb -in viral.1.1.genomic.fasta -out viral1.1.genomic -dbtype prot -parse_seqids
</code>```

I just don't know why I keep getting error message saying no alias or index file found. I have read other similar questions posted by others but don't seem finding answer to my problem. And I try other tblast and blastx and both of them return similar error except it said protein database instead of nucleotide

答: If I recall correctly you need to create the index-file separately. But also pay attention between building nucleotide and/or protein dbs and than search then with the wrong BLAST n/p engin. So 2004. I assume you fixed it and reconstructed your DB the rightway by now?</p>

Title: BLAST: can't find reference file in db

Body:
I am trying to run the standalone ncbi-blast-2.2.29+ on my machine (Mac) but get this error message when running blastx (or blastn) with my database:

No alias or index file found for nucleotide database [db/viral.1.1.genomic] in search path [~/Users/KK/ncbi-blast-2.3.0+/Virus::]

The way I run it:

blastn -query input.fasta -out out.blast.txt -db db/viral.1.1.genomic

My working directory is ~/Users/KK/ncbi-blast-2.3.0+/Virus and there is a  sub-directory db (~/Users/KK/ncbi-blast-2.3.0+/Virus/db) and db has viral.1.1.genomic.phr, viral.1.1.genomic.pin, viral.1.1.genomic.pnd, viral.1.1.genomic.pni, viral.1.1.genomic.pog, viral.1.1.genomic.psd, viral.1.1.genomic.psi, viral.1.1.genomic.psq, viral.1.1.genomic.fasta. and I made all these files using this command line

makeblastdb -in viral.1.1.genomic.fasta -out viral1.1.genomic -dbtype prot -parse_seqids

I just don't know why I keep getting error message saying no alias or index file found. I have read other similar questions posted by others but don't seem finding answer to my problem. And I try other tblast and blastx and both of them return similar error except it said protein database instead of nucleotide


问:
Attempted to load class "ObjectID" from namespace "MongoDB\BSON"
I'm trying to use DoctrineMongoDBBundle but it gives me this error :

Attempted to load class "ObjectID" from namespace "MongoDB\BSON". Did
  you forget a "use" statement for another namespace?

I've searched all over for a reason, but I could not find why I get this error.

My mongodb is installed alright, a mongodb status tells me it's active. I think I correctly set up the classes... etc. Where can the error be coming from?

Stack trace :

Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to
  load class "ObjectID" from namespace "MongoDB\BSON". Did you forget a
  "use" statement for another namespace?

at vendor/alcaeus/mongo-php-adapter/lib/Mongo/MongoId.php:224

at MongoId->createObjectID(null)
       (vendor/alcaeus/mongo-php-adapter/lib/Mongo/MongoId.php:41)

at MongoId->__construct()
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php:34)

at
  Doctrine\ODM\MongoDB\Id\AutoGenerator->generate(object(DocumentManager),
  object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1107)

at
  Doctrine\ODM\MongoDB\UnitOfWork->persistNew(object(ClassMetadata),
  object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1710)

at Doctrine\ODM\MongoDB\UnitOfWork->doPersist(object(Product),
  array('000000002ed55d6b00000000057952ca' => object(Product)))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1674)

at Doctrine\ODM\MongoDB\UnitOfWork->persist(object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/DocumentManager.php:412)

at Doctrine\ODM\MongoDB\DocumentManager->persist(object(Product))
       (src/Acme/StoreBundle/Controller/DefaultController.php:30)

at Acme\StoreBundle\Controller\DefaultController->createAction()

at call_user_func_array(array(object(DefaultController),
  'createAction'), array())
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:153)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request),
  1)
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:68)

at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request),
  1, true)
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php:169)

at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
       (web/app_dev.php:29)

at require('/var/www/html/geoservicesgrandnancy/web/app_dev.php')
       (vendor/symfony/symfony/src/Symfony/Bundle/WebServerBundle/Resources/router.php:42)

php --ri mongodb | grep version outputs:

MongoDB extension version => 1.3.2, libbson bundled version => 1.8.1,
  libmongoc bundled version => 1.8.1

Simple example to demonstrate :

```<code><?php

namespace Acme\StoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use MongoDB\BSON\ObjectID; //Adding this or not doesn't change anything

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        var_dump(new MongoDB\BSON\ObjectID); die();
        return $this->render('AcmeStoreBundle:Default:index.html.twig');
    }
}
</code>```

And composer.json requires got :

```<code>"require": {
        "php": ">=5.5.9",
        "alcaeus/mongo-php-adapter": "^1.1",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/mongodb-odm": "^1.2",
        "doctrine/mongodb-odm-bundle": "^3.4",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },
</code>```

答:
Hello you need to include "alcaeus/mongo-php-adapter": "^1.1" as part of your packages and also expose the expected mongo extension as a failure resolution like

```<code>  "provide": {
    "ext-mongo": "1.6.12"
  },
</code>```

a complete composer file may be like

```<code>{
  "require": {
    "php": "^7.1.3",
    "ext-mongodb": ">=1.1.2",
    "alcaeus/mongo-php-adapter": "^1.1",
    "doctrine/mongodb-odm-bundle": "^3.3",
    ...
  },
  "provide": {
    "ext-mongo": "1.6.12"
  }
  ...
}
</code>```

Body:
I'm trying to use DoctrineMongoDBBundle but it gives me this error :

Attempted to load class "ObjectID" from namespace "MongoDB\BSON". Did
  you forget a "use" statement for another namespace?

I've searched all over for a reason, but I could not find why I get this error.

My mongodb is installed alright, a mongodb status tells me it's active. I think I correctly set up the classes... etc. Where can the error be coming from?

Stack trace :

Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to
  load class "ObjectID" from namespace "MongoDB\BSON". Did you forget a
  "use" statement for another namespace?

at vendor/alcaeus/mongo-php-adapter/lib/Mongo/MongoId.php:224

at MongoId->createObjectID(null)
       (vendor/alcaeus/mongo-php-adapter/lib/Mongo/MongoId.php:41)

at MongoId->__construct()
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/Id/AutoGenerator.php:34)

at
  Doctrine\ODM\MongoDB\Id\AutoGenerator->generate(object(DocumentManager),
  object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1107)

at
  Doctrine\ODM\MongoDB\UnitOfWork->persistNew(object(ClassMetadata),
  object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1710)

at Doctrine\ODM\MongoDB\UnitOfWork->doPersist(object(Product),
  array('000000002ed55d6b00000000057952ca' => object(Product)))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php:1674)

at Doctrine\ODM\MongoDB\UnitOfWork->persist(object(Product))
       (vendor/doctrine/mongodb-odm/lib/Doctrine/ODM/MongoDB/DocumentManager.php:412)

at Doctrine\ODM\MongoDB\DocumentManager->persist(object(Product))
       (src/Acme/StoreBundle/Controller/DefaultController.php:30)

at Acme\StoreBundle\Controller\DefaultController->createAction()

at call_user_func_array(array(object(DefaultController),
  'createAction'), array())
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:153)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request),
  1)
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php:68)

at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request),
  1, true)
       (vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php:169)

at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
       (web/app_dev.php:29)

at require('/var/www/html/geoservicesgrandnancy/web/app_dev.php')
       (vendor/symfony/symfony/src/Symfony/Bundle/WebServerBundle/Resources/router.php:42)

php --ri mongodb | grep version outputs:

MongoDB extension version => 1.3.2, libbson bundled version => 1.8.1,
  libmongoc bundled version => 1.8.1

Simple example to demonstrate :

<?php

namespace Acme\StoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use MongoDB\BSON\ObjectID; //Adding this or not doesn't change anything

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        var_dump(new MongoDB\BSON\ObjectID); die();
        return $this->render('AcmeStoreBundle:Default:index.html.twig');
    }
}

And composer.json requires got :

"require": {
        "php": ">=5.5.9",
        "alcaeus/mongo-php-adapter": "^1.1",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/mongodb-odm": "^1.2",
        "doctrine/mongodb-odm-bundle": "^3.4",
        "doctrine/orm": "^2.5",
        "incenteev/composer-parameter-handler": "^2.0",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^3.0.2",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.3.10",
        "symfony/symfony": "3.3.*",
        "twig/twig": "^1.0||^2.0"
    },

Body:
Hello you need to include "alcaeus/mongo-php-adapter": "^1.1" as part of your packages and also expose the expected mongo extension as a failure resolution like

  "provide": {
    "ext-mongo": "1.6.12"
  },

a complete composer file may be like

{
  "require": {
    "php": "^7.1.3",
    "ext-mongodb": ">=1.1.2",
    "alcaeus/mongo-php-adapter": "^1.1",
    "doctrine/mongodb-odm-bundle": "^3.3",
    ...
  },
  "provide": {
    "ext-mongo": "1.6.12"
  }
  ...
}


问:
SQL Server Triggers, Stored Procedures
I dont ever used triggers or stored procedures. Now i want to study how and when i use that.
I have table named Products, when products table filling with row i want to copy ProductID and UnitsInStock and paset into Inventory table. There is one problem in inventory table is column which must fill buy user when row is filling. Would triggers or stored procedures will be useful for this situation?</p>

答: Use a stored procedure, pass in all the values that are needed as parameters, then within a transaction post changes to the products table and then the inventory table and then commit your changes to both tables at once - so either both tables get updated, or neither does.</p>

ContentLicense: CC BY-SA 2.5

Title: SQL Server Triggers, Stored Procedures


问:
SQL server, difference two tables and mix together
For example I have two tables: tbMetals and tbSells

tbMetals

```<code>mId - name   - cost
1   - Iron   - 100
2   - Steel  - 200
3   - Copper - 300
4   - Zinc   - 150
</code>```

tbSells

```<code>CustomerId - mId - SellDate - weight
100        - 1   - 2017/1/1 - 1.2
100        - 2   - 2017/1/2 - 3.5
111        - 1   - 2017/3/3 - 2.1
</code>```

I need like this output for ClientId=100

```<code>mId - SellDate - weight
1   - 2017/1/1 - 1.2
2   - 2017/1/2 - 3.5
3   - NULL     - NULL
4   - NULL     - NULL
</code>```

答:
This is a simple left join.</p>

```<code>select
    m.mId
    ,s.SellDate
    ,s.weight
from
    tbMetals m
left join
    tbSells s on
    s.mId = m.mId
    and s.ClientId = 100   --optional, if you really want it.
</code>```

Body:
For example I have two tables: tbMetals and tbSells

tbMetals

mId - name   - cost
1   - Iron   - 100
2   - Steel  - 200
3   - Copper - 300
4   - Zinc   - 150

tbSells

CustomerId - mId - SellDate - weight
100        - 1   - 2017/1/1 - 1.2
100        - 2   - 2017/1/2 - 3.5
111        - 1   - 2017/3/3 - 2.1

I need like this output for ClientId=100

mId - SellDate - weight
1   - 2017/1/1 - 1.2
2   - 2017/1/2 - 3.5
3   - NULL     - NULL
4   - NULL     - NULL

Body:
This is a simple left join.

select
    m.mId
    ,s.SellDate
    ,s.weight
from
    tbMetals m
left join
    tbSells s on
    s.mId = m.mId
    and s.ClientId = 100   --optional, if you really want it.


问:
Tic Tac Toe checking winner in boolean method
I'm playing a TicTacToe game where the user plays the computer. The user is always X and the computer is O. I have my code written to check every row, column, and diagonal to see if the user or computer wins. If neither then it just prints false. I would like the game to print out if the user win Human player won" or if the computer wins "Computer won". I just don't know how to add it to the boolean method.</p>

```<code>public static boolean checkWin()
{
    //checks for human win
    if ("X".equals(board[0][0]) && "X".equals(board[0][1]) && "X".equals(board[0][2]))
        return true;
    else if ("X".equals(board[1][0]) && "X".equals(board[1][1]) && "X".equals(board[1][2]))
        return true;
    else if ("X".equals(board[2][0]) && "X".equals(board[2][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][0]) && "X".equals(board[2][0]))
        return true;
    else if ("X".equals(board[0][1]) && "X".equals(board[1][1]) && "X".equals(board[2][1]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][2]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][1]) && "X".equals(board[2][0]))
        return true;
    //checks if computer has won
    else if ("O".equals(board[0][0]) && "O".equals(board[0][1]) && "O".equals(board[0][2]))
        return true;
    else if ("O".equals(board[1][0]) && "O".equals(board[1][1]) && "O".equals(board[1][2]))
        return true;
    else if ("O".equals(board[2][0]) && "O".equals(board[2][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][0]) && "O".equals(board[2][0]))
        return true;
    else if ("O".equals(board[0][1]) && "O".equals(board[1][1]) && "O".equals(board[2][1]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][2]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][1]) && "O".equals(board[2][0]))
        return true;
    else
        //it's a tie
        return false;
}
</code>```

答:
After the human's turn, call checkWin.  If it returns true, then print the "human won" message and end the game.

After the computer's turn, call checkWin.  If it returns true, then print the "computer won" message and end the game.

If nine moves have occurred and checkWin hasn't returned true, the game is a tie.

Body:
I'm playing a TicTacToe game where the user plays the computer. The user is always X and the computer is O. I have my code written to check every row, column, and diagonal to see if the user or computer wins. If neither then it just prints false. I would like the game to print out if the user win Human player won" or if the computer wins "Computer won". I just don't know how to add it to the boolean method.

public static boolean checkWin()
{
    //checks for human win
    if ("X".equals(board[0][0]) && "X".equals(board[0][1]) && "X".equals(board[0][2]))
        return true;
    else if ("X".equals(board[1][0]) && "X".equals(board[1][1]) && "X".equals(board[1][2]))
        return true;
    else if ("X".equals(board[2][0]) && "X".equals(board[2][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][0]) && "X".equals(board[2][0]))
        return true;
    else if ("X".equals(board[0][1]) && "X".equals(board[1][1]) && "X".equals(board[2][1]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][2]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][0]) && "X".equals(board[1][1]) && "X".equals(board[2][2]))
        return true;
    else if ("X".equals(board[0][2]) && "X".equals(board[1][1]) && "X".equals(board[2][0]))
        return true;
    //checks if computer has won
    else if ("O".equals(board[0][0]) && "O".equals(board[0][1]) && "O".equals(board[0][2]))
        return true;
    else if ("O".equals(board[1][0]) && "O".equals(board[1][1]) && "O".equals(board[1][2]))
        return true;
    else if ("O".equals(board[2][0]) && "O".equals(board[2][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][0]) && "O".equals(board[2][0]))
        return true;
    else if ("O".equals(board[0][1]) && "O".equals(board[1][1]) && "O".equals(board[2][1]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][2]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][0]) && "O".equals(board[1][1]) && "O".equals(board[2][2]))
        return true;
    else if ("O".equals(board[0][2]) && "O".equals(board[1][1]) && "O".equals(board[2][0]))
        return true;
    else
        //it's a tie
        return false;
}


问:
openacc compiler supporting nested compute constructs
I'm studying the OpenaAcc Programming guide at openacc.org. A lot of nested compute regions are widely used in this book. But my compiler (version 17.4-0 64-bit target on x86-64 Linux -tp sandybridge year 2017) writes that my version of the compiler does not support nested compute constructs. Does this version of the compiler really not support nested compute constructs? If it is so, which compiler to use if i need nested compute constructs support? Do latest versions of gcc support this option? </p>

答:
Correct, PGI does not yet support nested parallelism (i.e. compute regions within other compute regions).  I don't think GNU supports it as well.

Can you point the specific section of the OpenACC programming guide you are referring?  I don't remember any nested parallelism examples and am wondering if you are meaning the addition of "loop" directives within a compute region which is supported by both compilers.


问:
Is creating a new array in a loop in Javascript a bad practice?
Sometimes we need to use temporary array in a loop to store data. For example, when we need to deal with 2 dimension arrays. But I am not sure if it is a bad practice to create a new array in a loop, especially if I need to do it often, such as in animation.

```<code>for (let i = 0; i < 10000; i++) {
    const temp = [];
    for (let j = 0; j < 10; j++) {
        temp.push(j);
    }
    arr.push(temp);
}
</code>```

If this is a variable I should be able to use a global variable and reassign value to it. So I have tried to use a global array and clear the array using temp.length = 0 but then because the array's reference is stored the data will all become the last pushed values. I have also tried a global const temp = new Set() but then when I push the temp set into the arr array it will be arr.push([...temp]). So is it inevitable to create new array in such situation?

答:
Typed arrays

TypedArrays should always be the first option when you need an array. They offer massive performance and memory benefits over standard arrays.

The quickest way to create an array of numbers is

```<code>var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = new Float64Array(10);
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}
</code>```

Which benchmarked at 634, a huge 5.5 times quicker than the fastest Array method

```<code>var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = [];
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}
</code>```

Which benchmarked 3664 which is another  3.4 times quicker than

```<code>const arr = [...Array(10000)];
for (let i = 0; i < arr.length; i ++) {
  arr[i] = [...Array(10).keys()]
}
</code>```

That benchmarks a sad 12352

Typed arrays are fixed size, and when declared they are pre filled with zero. They will never become sparse and if use well can eliminate GC overheads.

With Atomics and you can share them with workers via SharedArrayBuffers(True sharing a shared array only has one address)

Though they are limited to Doubles, floats, signed and unsigned integers, they can hold any type of data (computers are just binary processing machines after all) and will give noticeable performance increases for any type of array work

Is creating arrays in loops bad.

There nothing wrong with creating arrays in loops.

Body:
Sometimes we need to use temporary array in a loop to store data. For example, when we need to deal with 2 dimension arrays. But I am not sure if it is a bad practice to create a new array in a loop, especially if I need to do it often, such as in animation.

for (let i = 0; i < 10000; i++) {
    const temp = [];
    for (let j = 0; j < 10; j++) {
        temp.push(j);
    }
    arr.push(temp);
}

If this is a variable I should be able to use a global variable and reassign value to it. So I have tried to use a global array and clear the array using temp.length = 0 but then because the array's reference is stored the data will all become the last pushed values. I have also tried a global const temp = new Set() but then when I push the temp set into the arr array it will be arr.push([...temp]). So is it inevitable to create new array in such situation?

Body:
Typed arrays

TypedArrays should always be the first option when you need an array. They offer massive performance and memory benefits over standard arrays.

The quickest way to create an array of numbers is

var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = new Float64Array(10);
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}

Which benchmarked at 634, a huge 5.5 times quicker than the fastest Array method

var i,j,b,a = [];
for (i = 0; i < 100000; i += 1) {
    a[i] = b = [];
    for (j = 0; j < 10; j += 1) {
        b[j] = j;
    }
}

Which benchmarked 3664 which is another  3.4 times quicker than

const arr = [...Array(10000)];
for (let i = 0; i < arr.length; i ++) {
  arr[i] = [...Array(10).keys()]
}

That benchmarks a sad 12352

Typed arrays are fixed size, and when declared they are pre filled with zero. They will never become sparse and if use well can eliminate GC overheads.

With Atomics and you can share them with workers via SharedArrayBuffers(True sharing a shared array only has one address)

Though they are limited to Doubles, floats, signed and unsigned integers, they can hold any type of data (computers are just binary processing machines after all) and will give noticeable performance increases for any type of array work

Is creating arrays in loops bad.

There nothing wrong with creating arrays in loops.


问:
Access not going to new record
I have an access app that is quite complicated and old, and really shouldn't be in access at all.

I am trying to add a new form.  I copied the old form and changed the SQL table names to the new ones. I added test data in SQL and everything looks fine.

However I can't add new records.  The other forms have a new button that works, or you can just click on the little arrow at the bottom.  In this case it's greyed out.

The New button gives me error 2046 The command or action RecordsGoToNew isn't available now.  Tried both and they don't work.

```<code>' DoCmd.GoToRecord , , acNewRec
  DoCmd.RunCommand acCmdRecordsGoToNew
</code>```

What am I missing?  I don't use Access often and this code is so old I'm having a hard time understanding it.  There is a lot of on error resume next. So I don't think it's written well either.  But that's not the point.

Any help would be appreciated.  Thanks.

ETA I think this might be an SSMS issue and tagged it as such.  If I do an unlinked table it works.  What would cause that to happen?

Thanks.

答:
I fixed it. Thank you for your help everyone.  I created an unlinked version of the tables to narrow it down.  That worked so I knew it was an issue with the database and not Access.  My tables were identical.

I readded the tables in and I think my problem was I didn't select the primary key or I selected the wrong one.  I could tell that helped. But it still didn't fix it.

I did notice that some columns that do have nulls before it's finished were set to not allow nulls.  So I changed that and got it to work.  I have no idea how the others are working but this program is so bad and breaks all the time so I'm just going to run with it and keep moving forward.  It isn't life or death information and I'll test it like crazy.

Thanks again everyone.

Title: Access not going to new record

Body:
I have an access app that is quite complicated and old, and really shouldn't be in access at all.

I am trying to add a new form.  I copied the old form and changed the SQL table names to the new ones. I added test data in SQL and everything looks fine.

However I can't add new records.  The other forms have a new button that works, or you can just click on the little arrow at the bottom.  In this case it's greyed out.

The New button gives me error 2046 The command or action RecordsGoToNew isn't available now.  Tried both and they don't work.

' DoCmd.GoToRecord , , acNewRec
  DoCmd.RunCommand acCmdRecordsGoToNew

What am I missing?  I don't use Access often and this code is so old I'm having a hard time understanding it.  There is a lot of on error resume next. So I don't think it's written well either.  But that's not the point.

Any help would be appreciated.  Thanks.

ETA I think this might be an SSMS issue and tagged it as such.  If I do an unlinked table it works.  What would cause that to happen?

Thanks.


问:
Dapper incorrectly thinking Column Numeric
I have been using dapper for a while but have come across a strange issue.

I have a Column in a database table called , in my query my Table

my dapper query is

SELECT p.Id PaymentId, p.AmountPaid PaymentAmountPaid, np.NoticeNo PaymentRef

In the Database the column NoticeNo is defined as nchar

When I query it, its mapped to class with the following property

```<code>public string PaymentRef { get; set; }
</code>```

I query as follows connection.Query<PaymentSummary>(sqlStr)

but very strange, dapper seems to think that the NoticeNo column is a  number, so if the store notice no as 1234 then when its queried the result is 1234.00

Most of the notice numbers are numeric, but they don't have to be.

Any ideas?

Thanks ash.

答: Turns out it wasn't Dapper's Fault.  The query was part of a union, and I had the notice no and the amount column in a different order in two if the queries, which was forcing the result to be a Number!!</p>

Body:
I have been using dapper for a while but have come across a strange issue.

I have a Column in a database table called , in my query my Table

my dapper query is

SELECT p.Id PaymentId, p.AmountPaid PaymentAmountPaid, np.NoticeNo PaymentRef

In the Database the column NoticeNo is defined as nchar

When I query it, its mapped to class with the following property

public string PaymentRef { get; set; }

I query as follows connection.Query<PaymentSummary>(sqlStr)

but very strange, dapper seems to think that the NoticeNo column is a  number, so if the store notice no as 1234 then when its queried the result is 1234.00

Most of the notice numbers are numeric, but they don't have to be.

Any ideas?

Thanks ash.


问:
mumps lanaguage FOR loop related
if i define For K="ABC":1:3 now what is the value of "ABC",how the loop to excute "ABC" or instead of that ABC if i take any "string", how does increment the string "ABC".

Bhas

答:
Very sorry for the munged formatting. Mea culpa!

The program listing should have been:

```<code>for3

; routine to test FOR command

   FOR K="ABC":1:3 WRITE "K=",K,! QUIT
</code>```

And the output should have been:

```<code>$ gtm -run for3
K=0
K=1
K=2
K=3
</code>```

Title: mumps lanaguage FOR loop related

Body:
Very sorry for the munged formatting. Mea culpa!

The program listing should have been:

for3

; routine to test FOR command

   FOR K="ABC":1:3 WRITE "K=",K,! QUIT

And the output should have been:

$ gtm -run for3
K=0
K=1
K=2
K=3


问:
PCA difference between python numpy and sklearn
I am trying to implement the PCA using numpy.linalg.eig with two differents methods(with the covariance and the pca method used in eigenface) and I compare my results with the PCA from sklearn. But I observe that my results are differents so I was wondering which mistake I am doing. I have 3 samples, and each sample have 4 features. I am trying to reduce then the dimension of the samples to 3.
EDIT : add with the SVD method.  IThe results I get using the covariance PCA , the SVD and the PCA from sklearn are pretty close. But with the "eigenface" method it is totally different why ?
    import numpy as np
    from sklearn.decomposition import PCA</p>

```<code>x = np.array([[0.5, 0.8, 1.5, -2.4], [-1.9, -8.7, 0.02, 4.9], [5.5,6.1, -8.1,3.0]])
print(x)
K = 3

# -- sklearn -- #
pca = PCA(n_components=K).fit(x)
res = pca.transform(x)
print('sklearn :', res)

# -- numpy covariance -- #
X = x - np.mean(x, axis = 0)

cov = np.cov(X.T)
print("covariance :", cov.shape)

evals , evecs = np.linalg.eig(cov)

idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

res2 = X.dot(evecs[:,:K])
print("numpy with cov:", res2)

# -- numpy scatter matrix -- #
X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

v = np.dot(evecs, X)
print("v :", v.shape)
res3= X[:, :K].dot(v)
print('numpy with scatter matrix : ', res3)

# -- numpy svd -- #
X = x - np.mean(x, axis = 0)
U, S, V = np.linalg.svd(X, full_matrices=False)
U, V = svd_flip(U, V)
res2 = X.dot(V.T)
print("numpy with svd:", res2)
</code>```

答:
My guess would be that your two methods of computing eigenvectors are giving different results than scipy.linalg.svd, which is what scipy's PCA implementation uses (https://github.com/scikit-learn/scikit-learn/blob/f3320a6f/sklearn/decomposition/pca.py#L399).

This could be a good place to start: Eigenvectors computed with numpy's eigh and svd do not match

Body:
I am trying to implement the PCA using numpy.linalg.eig with two differents methods(with the covariance and the pca method used in eigenface) and I compare my results with the PCA from sklearn. But I observe that my results are differents so I was wondering which mistake I am doing. I have 3 samples, and each sample have 4 features. I am trying to reduce then the dimension of the samples to 3.
EDIT : add with the SVD method.  IThe results I get using the covariance PCA , the SVD and the PCA from sklearn are pretty close. But with the "eigenface" method it is totally different why ?
    import numpy as np
    from sklearn.decomposition import PCA

x = np.array([[0.5, 0.8, 1.5, -2.4], [-1.9, -8.7, 0.02, 4.9], [5.5,6.1, -8.1,3.0]])
print(x)
K = 3

# -- sklearn -- #
pca = PCA(n_components=K).fit(x)
res = pca.transform(x)
print('sklearn :', res)

# -- numpy covariance -- #
X = x - np.mean(x, axis = 0)

cov = np.cov(X.T)
print("covariance :", cov.shape)

evals , evecs = np.linalg.eig(cov)

idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

res2 = X.dot(evecs[:,:K])
print("numpy with cov:", res2)

# -- numpy scatter matrix -- #
X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

v = np.dot(evecs, X)
print("v :", v.shape)
res3= X[:, :K].dot(v)
print('numpy with scatter matrix : ', res3)

# -- numpy svd -- #
X = x - np.mean(x, axis = 0)
U, S, V = np.linalg.svd(X, full_matrices=False)
U, V = svd_flip(U, V)
res2 = X.dot(V.T)
print("numpy with svd:", res2)


问:
How to create dynamic link in jsp?
I get the list of records using request.getAttribute() method. After that, I show this list using for loop on jsp. But each record(blog) has feature as 'delete' , 'edit' . For this, I really need to generate links with path containing id of blog. That is why I need dynamic links. But I couldn't generate it. How to do that? Below is part of my code:

```<code><%
    ArrayList<Blogs> blogs = (ArrayList<Blogs>) request.getAttribute("blogList");

    for (Blogs blog : blogs) {
%>
<br>
<h2>
    <%=blog.getTitle()%>
</h2>
<p>
    <%=blog.getContent()%>
</p>
<b>
    Written at : <%=blog.getPost_data().toString()%>
</b>
<br>
<!-- <a href="/delete?id=">How to pass the id to link?</a> -->
<hr>
<%
    }
%>
</code>```

答:
```<code><a href="/delete?id=<%= blog.getId()%>">
</code>```

assuming Blog has a getId() method.

More appropriately though, you should consider using jstl <c:forEach> with el.

http://www.java2s.com/Tutorial/Java/0380__JSTL/UseForEachtoLoopThroughArrayList.htm

Title: How to create dynamic link in jsp?

Body:
I get the list of records using request.getAttribute() method. After that, I show this list using for loop on jsp. But each record(blog) has feature as 'delete' , 'edit' . For this, I really need to generate links with path containing id of blog. That is why I need dynamic links. But I couldn't generate it. How to do that? Below is part of my code:

<%
    ArrayList<Blogs> blogs = (ArrayList<Blogs>) request.getAttribute("blogList");

    for (Blogs blog : blogs) {
%>

    <%=blog.getTitle()%>

    <%=blog.getContent()%>

    Written at : <%=blog.getPost_data().toString()%>

<%
    }
%>

Body:
<a href="/delete?id=<%= blog.getId()%>">

assuming Blog has a getId() method.

More appropriately though, you should consider using jstl <c:forEach> with el.

http://www.java2s.com/Tutorial/Java/0380__JSTL/UseForEachtoLoopThroughArrayList.htm


问:
360works how to attach file inline to embed image
I have 360works for filemaker and want to place a image inside a html email. How is this image embedded?

For example:

```<code><img src=\"cid:footergif456\ ">"
</code>```

答:
From the documentation:

You set your message body to some HTML which has an image tag like you have.

Then you need to call EmailAttachFileInline, eg

EmailAttachFileInline( Globals::headerContainer ; "footergif456" )

The plugin will send a multi-part email, and email clients are supposed to get the image from the appropriate part.

Body:
I have 360works for filemaker and want to place a image inside a html email. How is this image embedded?

For example:

"


问:
Cannot use dput for data.table in R
I have following data.table for which I cannot use output of dput command to recreate it:

```<code>> ddt
   Unit Anything index new
1:    A      3.4     1   1
2:    A      6.9     2   1
3:   A1      1.1     1   2
4:   A1      2.2     2   2
5:    B      2.0     1   3
6:    B      3.0     2   3
>
>
> str(ddt)
Classes ‘data.table’ and 'data.frame':  6 obs. of  4 variables:
 $ Unit    : Factor w/ 3 levels "A","A1","B": 1 1 2 2 3 3
 $ Anything: num  3.4 6.9 1.1 2.2 2 3
 $ index   : num  1 2 1 2 1 2
 $ new     : int  1 1 2 2 3 3
 - attr(*, ".internal.selfref")=<externalptr>
 - attr(*, "sorted")= chr  "Unit" "Anything"
>
>
> dput(ddt)
structure(list(Unit = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("A",
"A1", "B"), class = "factor"), Anything = c(3.4, 6.9, 1.1, 2.2,
2, 3), index = c(1, 2, 1, 2, 1, 2), new = c(1L, 1L, 2L, 2L, 3L,
3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x8948f68>, sorted = c("Unit",
"Anything"))
>
</code>```

On pasting I get following error:

```<code>> dt = structure(list(Unit = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("A",
+ "A1", "B"), class = "factor"), Anything = c(3.4, 6.9, 1.1, 2.2,
+ 2, 3), index = c(1, 2, 1, 2, 1, 2), new = c(1L, 1L, 2L, 2L, 3L,
+ 3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
+ -6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x8948f68>, sorted = c("Unit",
Error: unexpected '<' in:
"3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <"
> "Anything"))
Error: unexpected ')' in ""Anything")"
</code>```

Where is the problem and how can it be corrected? Thanks for your help.

答:
If you've already dput the file and you don't feel much like manually editing before dget, you can use the following

```<code>data.table.parse<-function (file = "", n = NULL, text = NULL, prompt = "?", keep.source = getOption("keep.source"),
                            srcfile = NULL, encoding = "unknown")
{
  keep.source <- isTRUE(keep.source)
  if (!is.null(text)) {
    if (length(text) == 0L)
      return(expression())
    if (missing(srcfile)) {
      srcfile <- "<text>"
      if (keep.source)
        srcfile <- srcfilecopy(srcfile, text)
    }
    file <- stdin()
  }
  else {
    if (is.character(file)) {
      if (file == "") {
        file <- stdin()
        if (missing(srcfile))
          srcfile <- "<stdin>"
      }
      else {
        filename <- file
        file <- file(filename, "r")
        if (missing(srcfile))
          srcfile <- filename
        if (keep.source) {
          text <- readLines(file, warn = FALSE)
          if (!length(text))
            text <- ""
          close(file)
          file <- stdin()
          srcfile <- srcfilecopy(filename, text, file.mtime(filename),
                                 isFile = TRUE)
        }
        else {
          text <- readLines(file, warn = FALSE)
          if (!length(text)) {
            text <- ""
          } else {
            text <- gsub("(, .internal.selfref = <pointer: 0x[0-9A-Fa-f]+>)","",text,perl=TRUE)
          }
          on.exit(close(file))
        }
      }
    }
  }
  #  text <- gsub("(, .internal.selfref = <pointer: 0x[0-9A-F]+>)","",text)
  .Internal(parse(file, n, text, prompt, srcfile, encoding))
}
data.table.get <- function(file, keep.source = FALSE)
  eval(data.table.parse(file = file, keep.source = keep.source))
dtget <- data.table.get
</code>```

then change your calls of dget to dtget. Note that due to the inline parsing, this will make dtget slower than dget, so use it only in circumstances where you could be retrieving an object of type data.table.

Title: Cannot use dput for data.table in R

Body:
I have following data.table for which I cannot use output of dput command to recreate it:

> ddt
   Unit Anything index new
1:    A      3.4     1   1
2:    A      6.9     2   1
3:   A1      1.1     1   2
4:   A1      2.2     2   2
5:    B      2.0     1   3
6:    B      3.0     2   3
>
>
> str(ddt)
Classes ‘data.table’ and 'data.frame':  6 obs. of  4 variables:
 $ Unit    : Factor w/ 3 levels "A","A1","B": 1 1 2 2 3 3
 $ Anything: num  3.4 6.9 1.1 2.2 2 3
 $ index   : num  1 2 1 2 1 2
 $ new     : int  1 1 2 2 3 3
 - attr(*, ".internal.selfref")=<externalptr>
 - attr(*, "sorted")= chr  "Unit" "Anything"
>
>
> dput(ddt)
structure(list(Unit = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("A",
"A1", "B"), class = "factor"), Anything = c(3.4, 6.9, 1.1, 2.2,
2, 3), index = c(1, 2, 1, 2, 1, 2), new = c(1L, 1L, 2L, 2L, 3L,
3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x8948f68>, sorted = c("Unit",
"Anything"))
>

On pasting I get following error:

> dt = structure(list(Unit = structure(c(1L, 1L, 2L, 2L, 3L, 3L), .Label = c("A",
+ "A1", "B"), class = "factor"), Anything = c(3.4, 6.9, 1.1, 2.2,
+ 2, 3), index = c(1, 2, 1, 2, 1, 2), new = c(1L, 1L, 2L, 2L, 3L,
+ 3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
+ -6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x8948f68>, sorted = c("Unit",
Error: unexpected '<' in:
"3L)), .Names = c("Unit", "Anything", "index", "new"), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <"
> "Anything"))
Error: unexpected ')' in ""Anything")"

Where is the problem and how can it be corrected? Thanks for your help.

Body:
If you've already dput the file and you don't feel much like manually editing before dget, you can use the following

data.table.parse<-function (file = "", n = NULL, text = NULL, prompt = "?", keep.source = getOption("keep.source"),
                            srcfile = NULL, encoding = "unknown")
{
  keep.source <- isTRUE(keep.source)
  if (!is.null(text)) {
    if (length(text) == 0L)
      return(expression())
    if (missing(srcfile)) {
      srcfile <- "<text>"
      if (keep.source)
        srcfile <- srcfilecopy(srcfile, text)
    }
    file <- stdin()
  }
  else {
    if (is.character(file)) {
      if (file == "") {
        file <- stdin()
        if (missing(srcfile))
          srcfile <- "<stdin>"
      }
      else {
        filename <- file
        file <- file(filename, "r")
        if (missing(srcfile))
          srcfile <- filename
        if (keep.source) {
          text <- readLines(file, warn = FALSE)
          if (!length(text))
            text <- ""
          close(file)
          file <- stdin()
          srcfile <- srcfilecopy(filename, text, file.mtime(filename),
                                 isFile = TRUE)
        }
        else {
          text <- readLines(file, warn = FALSE)
          if (!length(text)) {
            text <- ""
          } else {
            text <- gsub("(, .internal.selfref = <pointer: 0x[0-9A-Fa-f]+>)","",text,perl=TRUE)
          }
          on.exit(close(file))
        }
      }
    }
  }
  #  text <- gsub("(, .internal.selfref = <pointer: 0x[0-9A-F]+>)","",text)
  .Internal(parse(file, n, text, prompt, srcfile, encoding))
}
data.table.get <- function(file, keep.source = FALSE)
  eval(data.table.parse(file = file, keep.source = keep.source))
dtget <- data.table.get

then change your calls of dget to dtget. Note that due to the inline parsing, this will make dtget slower than dget, so use it only in circumstances where you could be retrieving an object of type data.table.


问:
"node with name "rabbit" already running", but also "unable to connect to node 'rabbit'"
Rabbitmq server does not start, saying it's already running:

```<code>$: rabbitmq-server
Activating RabbitMQ plugins ...
0 plugins activated:

node with name "rabbit" already running on "android-d1af002161676bee"
diagnostics:
- nodes and their ports on android-d1af002161676bee: [{rabbit,52176},
                                                      {rabbitmqprelaunch2254,
                                                       59205}]
- current node: 'rabbitmqprelaunch2254@android-d1af002161676bee'
- current node home dir: /Users/Jordan
- current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ==
</code>```

But, rabbitmqctl seems to think otherwise:

```<code>rabbitmqctl -n rabbit status
Status of node 'rabbit@android-d1af002161676bee' ...
Error: unable to connect to node 'rabbit@android-d1af002161676bee': nodedown
diagnostics:
- nodes and their ports on android-d1af002161676bee: [{rabbit,52176},
                                                      {rabbitmqctl2462,59256}]
- current node: 'rabbitmqctl2462@android-d1af002161676bee'
- current node home dir: /Users/Jordan
- current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ==
</code>```

Any takers?

答: I used rabbitmqctl stop and then restarted using rabbitmq-server as root.

Body:
Rabbitmq server does not start, saying it's already running:

$: rabbitmq-server
Activating RabbitMQ plugins ...
0 plugins activated:

node with name "rabbit" already running on "android-d1af002161676bee"
diagnostics:
- nodes and their ports on android-d1af002161676bee: [{rabbit,52176},
                                                      {rabbitmqprelaunch2254,
                                                       59205}]
- current node: 'rabbitmqprelaunch2254@android-d1af002161676bee'
- current node home dir: /Users/Jordan
- current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ==

But, rabbitmqctl seems to think otherwise:

rabbitmqctl -n rabbit status
Status of node 'rabbit@android-d1af002161676bee' ...
Error: unable to connect to node 'rabbit@android-d1af002161676bee': nodedown
diagnostics:
- nodes and their ports on android-d1af002161676bee: [{rabbit,52176},
                                                      {rabbitmqctl2462,59256}]
- current node: 'rabbitmqctl2462@android-d1af002161676bee'
- current node home dir: /Users/Jordan
- current node cookie hash: ZSx3slRJURGK/nHXDTBRqQ==

Any takers?


问:
Where is the appropriate place to put font-awesome files in React apps?
I downloaded the latest font-awesome 4.7 and extracted the files in my public folder of the react app. I linked it in the index.html like this <link href="./fontawesome/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet">. Should I be doing this? Or should I put these in a a folder within the src directory? I never quite understood what I should be putting in the public folder.

答:
You should use one of the well known open source projects for react \ react-native icons:

React: react-icons

React-Native: react-native-vector-icons

You should then import only the icon you want, for example (from Font Awesome):

```<code>import FaBeer from 'react-icons/lib/fa/beer';
</code>```

Body:
You should use one of the well known open source projects for react \ react-native icons:

React: react-icons

React-Native: react-native-vector-icons

You should then import only the icon you want, for example (from Font Awesome):

import FaBeer from 'react-icons/lib/fa/beer';


问:
Parallax mid-way through page
I am triggering a parallax effect on an element half-way through my page. As I am attaching this to scrollTop() it is causing the element to jump when initialised.

```<code>var feedPos = $(".feed").offset().top - 100;

$(window).scroll(function(){
    if($(window).scrollTop() >= feedPos) {
        $(".feed").css("top", 150 - $(window).scrollTop() / 100);
    }
});
</code>```

Any ideas?

答:
Something along these lines may help you.

For the html, I made 100 divs of 80px tall with some text, and 25 divs of 80px call with a background color and bottom border, just so you could see the difference in scrolling speed.  I used c# mvc with razor to generate them but however you want to create those divs is fine.

```<code><div id="container">
    <div class="fast">
        @for (var i = 1; i <= 100; i++)
        {
            <div>@i. This is row @i</div>

        }
    </div>

    <div class="slow">
        @for (var j = 0; j < 25; j++)
        {
            var r = 255 - j;
            var g = 127 + (int)(.5 * j);
            var b = 10 + j;
            <div class="color" style="background-color:rgb(@r, @g, @b)"></div>
        }
    </div>
</div>
</code>```

For css I use scss but again, you can create the css however you want.

```<code>#container {
    height: 700px;
    width: 250px;
    overflow-y: hidden;
    position: relative;

    .fast {
        position: absolute;
        top: 0;
        div {
            height: 80px;
            width: 100%;
        }
    }

    .slow {
        width:100%;
        position: absolute;
        top: 0;
        div {
            height: 80px;
            width: 100%;
            opacity: .3;
            border-bottom:1px dotted white;
        }
    }
}
</code>```

And no the javascript:

```<code>var isAnimating = false;
$(document).ready(function ()
{
    $('#container').on('DOMMouseScroll mousewheel', function (e)
    {
        if (!isAnimating)
        {
            isAnimating = true;
            e.preventDefault();

            var delta = e.originalEvent.wheelDeltaY;
            var $this = $(this);

            console.log(delta);

            var newFast = parseInt($this.find('.fast').css('top'), 10) + delta;
            var newSlow = parseInt($this.find('.slow').css('top'), 10) + delta / 4;

            if (newFast > 0)
                newFast = 0;
            if (newSlow > 0)
                newSlow = 0;

            console.log(newFast + "   |   " + newSlow);

            $this.find('.fast').animate({ top: newFast + 'px' }, 100);
            $this.find('.slow').animate({ top: newSlow + 'px' }, 100, function () { isAnimating = false; });

        }
    });

});
</code>```

Note:  This only handles mouse wheel scrolling, not drag bar scrolling.  Actually, I didn't create a scrolling div so all of the scrolling you see is from the wheel.  You can make a .scroll(...) event also but those tend to be very finicky from one browser to the next.  Even with this there is some jitteriness.  Messing with scroll events can be a tricky thing.

Title: Parallax mid-way through page

Body:
I am triggering a parallax effect on an element half-way through my page. As I am attaching this to scrollTop() it is causing the element to jump when initialised.

var feedPos = $(".feed").offset().top - 100;

$(window).scroll(function(){
    if($(window).scrollTop() >= feedPos) {
        $(".feed").css("top", 150 - $(window).scrollTop() / 100);
    }
});

Any ideas?

Body:
Something along these lines may help you.

For the html, I made 100 divs of 80px tall with some text, and 25 divs of 80px call with a background color and bottom border, just so you could see the difference in scrolling speed.  I used c# mvc with razor to generate them but however you want to create those divs is fine.

<div id="container">
    <div class="fast">
        @for (var i = 1; i <= 100; i++)
        {
            <div>@i. This is row @i</div>

        }
    </div>

    <div class="slow">
        @for (var j = 0; j < 25; j++)
        {
            var r = 255 - j;
            var g = 127 + (int)(.5 * j);
            var b = 10 + j;
            <div class="color" style="background-color:rgb(@r, @g, @b)"></div>
        }
    </div>
</div>

For css I use scss but again, you can create the css however you want.

#container {
    height: 700px;
    width: 250px;
    overflow-y: hidden;
    position: relative;

    .fast {
        position: absolute;
        top: 0;
        div {
            height: 80px;
            width: 100%;
        }
    }

    .slow {
        width:100%;
        position: absolute;
        top: 0;
        div {
            height: 80px;
            width: 100%;
            opacity: .3;
            border-bottom:1px dotted white;
        }
    }
}

And no the javascript:

var isAnimating = false;
$(document).ready(function ()
{
    $('#container').on('DOMMouseScroll mousewheel', function (e)
    {
        if (!isAnimating)
        {
            isAnimating = true;
            e.preventDefault();

            var delta = e.originalEvent.wheelDeltaY;
            var $this = $(this);

            console.log(delta);

            var newFast = parseInt($this.find('.fast').css('top'), 10) + delta;
            var newSlow = parseInt($this.find('.slow').css('top'), 10) + delta / 4;

            if (newFast > 0)
                newFast = 0;
            if (newSlow > 0)
                newSlow = 0;

            console.log(newFast + "   |   " + newSlow);

            $this.find('.fast').animate({ top: newFast + 'px' }, 100);
            $this.find('.slow').animate({ top: newSlow + 'px' }, 100, function () { isAnimating = false; });

        }
    });

});

Note:  This only handles mouse wheel scrolling, not drag bar scrolling.  Actually, I didn't create a scrolling div so all of the scrolling you see is from the wheel.  You can make a .scroll(...) event also but those tend to be very finicky from one browser to the next.  Even with this there is some jitteriness.  Messing with scroll events can be a tricky thing.


问:
How to sort multiple ascending/descending columns in a data.frame: R
I am fairly new to R and perhaps don't know the best way to tackle this task but I have attempted a few various suggestions and none of them have allowed me to sort multiple columns in a data.frame.

Essentially for:

```<code>df = data.frame(matrix(c(-1,3,6,1,3,-5,2,4,9,-3,-1,-6,1,4,5), ncol=3)

       X1 X2 X3
   [1] -1 -5 -1
   [2]  3  2 -6
   [3]  6  4  1
   [4]  1  9  4
   [5]  3 -3  5
</code>```

I want to sort all of the columns independently from one another such that I could make all columns sort "descending", make half of the columns sort "ascending" and half "descending" etc.

```<code>       X1 X2 X3
   [1] -1 -5  5
   [2]  1 -3  4
   [3]  3  2  1
   [4]  3  4 -1
   [5]  6  9 -6
</code>```

The purpose of this is create column-wise gradients for use in heatmap.2 while also being able to control the mean, variance etc. of the columns. For example my data.frame would most likely be along the lines of:

```<code>df <- data.frame(matrix(runif(5200,0,1), ncol=10))
</code>```

However, when I attempt to use the sort or order command, I fail to be able to sort the columns independently of one another.

```<code>dfi <- df[order(df[[1]], decreasing =FALSE),]

        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

dfi <- df[order(df[[1]], df[[2]], decreasing =FALSE),]
        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1
</code>```

I have attempted using for loops but to no success. I faced an inability to sort or order the columns independently (I don't have a reasonable for loop to show that someone could reproduce, and if this is the route to solve this problem, whoever answers will be much more knowledgable than I at the appropriate notation.)

Does anyone have any advice as to how to best go about this? I have been able to get the desired result by individually creating the columns, sorting them and then binding them together. However, since I need to make many many varying iterations of this (different variances, means, numbers of columns etc), that process is way too inefficient unless.

答:
How about sapply:

```<code>n   <- ncol(df)
as  <- 3 # columns to be sorted ascending
de  <- 2 # columns to be sorted descending
out <- sapply(1:n, function(x) {
  if(x %in% as) {
    return(sort(df[,x], decreasing = F))
  } else if (x %in% de) {
    return(sort(df[,x], decreasing = T))
  }
  return(df[,x])
})
out

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

We simply loop over all columns and apply a function on each of them checking if they are either part of the vector as (ascending) or the vector de (descending). If a column is part in neither of them we just return it as it is.

Body:
I am fairly new to R and perhaps don't know the best way to tackle this task but I have attempted a few various suggestions and none of them have allowed me to sort multiple columns in a data.frame.

Essentially for:

df = data.frame(matrix(c(-1,3,6,1,3,-5,2,4,9,-3,-1,-6,1,4,5), ncol=3)

       X1 X2 X3
   [1] -1 -5 -1
   [2]  3  2 -6
   [3]  6  4  1
   [4]  1  9  4
   [5]  3 -3  5

I want to sort all of the columns independently from one another such that I could make all columns sort "descending", make half of the columns sort "ascending" and half "descending" etc.

       X1 X2 X3
   [1] -1 -5  5
   [2]  1 -3  4
   [3]  3  2  1
   [4]  3  4 -1
   [5]  6  9 -6

The purpose of this is create column-wise gradients for use in heatmap.2 while also being able to control the mean, variance etc. of the columns. For example my data.frame would most likely be along the lines of:

df <- data.frame(matrix(runif(5200,0,1), ncol=10))

However, when I attempt to use the sort or order command, I fail to be able to sort the columns independently of one another.

dfi <- df[order(df[[1]], decreasing =FALSE),]

        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

dfi <- df[order(df[[1]], df[[2]], decreasing =FALSE),]
        X1 X2 X3
    [1] -1 -5 -1
    [4]  1  9  4
    [2]  3  2 -6
    [5]  3 -3  5
    [3]  6  4  1

I have attempted using for loops but to no success. I faced an inability to sort or order the columns independently (I don't have a reasonable for loop to show that someone could reproduce, and if this is the route to solve this problem, whoever answers will be much more knowledgable than I at the appropriate notation.)

Does anyone have any advice as to how to best go about this? I have been able to get the desired result by individually creating the columns, sorting them and then binding them together. However, since I need to make many many varying iterations of this (different variances, means, numbers of columns etc), that process is way too inefficient unless.

Body:
How about sapply:

n   <- ncol(df)
as  <- 3 # columns to be sorted ascending
de  <- 2 # columns to be sorted descending
out <- sapply(1:n, function(x) {
  if(x %in% as) {
    return(sort(df[,x], decreasing = F))
  } else if (x %in% de) {
    return(sort(df[,x], decreasing = T))
  }
  return(df[,x])
})
out

    [,1] [,2] [,3]
[1,]   -1   -5   -1
[2,]    3   -3   -6
[3,]    6    2    1
[4,]    1    4    4
[5,]    3    9    5

We simply loop over all columns and apply a function on each of them checking if they are either part of the vector as (ascending) or the vector de (descending). If a column is part in neither of them we just return it as it is.


问:
Setting the validity of a Angular 2 control from within a custom component
I have a custom Ng2 component a I am using the Model-Driven approach.

```<code><form [ngFormModel]="myForm" class="layout vertical relative">
    <my-custom-comp ngControl="currentValue"></my-custom-comp>
</form>
</code>```

So inside my custom component I have all the logic I need but I can't find a way to get a reference to the ngControl to set it to valid or invalid from inside my custom component.

答:
How to set VALID or INVALID on any formGroup

```<code>// Where this.form === FormGroup;
// FormGroup can be deeply nested, just call at the level you want to update.
// That level should have direct access to base FormControls

// Can be done in a validator function;
this.form.get('name').setErrors({required: true});
// => this.form.get('name').invalid === true;

// Perhaps on Submit, click, event NOT in validator function
Object.entries(this.form.controls).forEach(([key, ctrl]) => {
  ctrl.updateValueAndValidity();
});
// => this.form.get('name').invalid === false;
// => this.form.get('name').valid === true;
// => this.form.get('name').errors === null;
</code>```

Body:
I have a custom Ng2 component a I am using the Model-Driven approach.

<form [ngFormModel]="myForm" class="layout vertical relative">
    <my-custom-comp ngControl="currentValue"></my-custom-comp>
</form>

So inside my custom component I have all the logic I need but I can't find a way to get a reference to the ngControl to set it to valid or invalid from inside my custom component.

Body:
How to set VALID or INVALID on any formGroup

// Where this.form === FormGroup;
// FormGroup can be deeply nested, just call at the level you want to update.
// That level should have direct access to base FormControls

// Can be done in a validator function;
this.form.get('name').setErrors({required: true});
// => this.form.get('name').invalid === true;

// Perhaps on Submit, click, event NOT in validator function
Object.entries(this.form.controls).forEach(([key, ctrl]) => {
  ctrl.updateValueAndValidity();
});
// => this.form.get('name').invalid === false;
// => this.form.get('name').valid === true;
// => this.form.get('name').errors === null;