问:
Hive Hbase JOIN performance & KUDU
Reading the Cloudera documentation using Impala to join a Hive table against HBase smaller tables as stated below, then in the absence of a Big Data appliance such as OBDA and a largish HBase dimension table that is mutable:

If you have join queries that do aggregation operations on large fact
  tables  and join the results against small dimension tables, consider
  using Impala for  the fact tables and HBase for the dimension tables.
  (Because Impala does a  full scan on the HBase table in this case,
  rather than doing single-row HBase  lookups based on the join column,
  only use this technique where the HBase  table is small enough that
  doing a full table scan does not cause a  performance bottleneck for
  the query.)

Is there any way to get that single key look up in another way?

In addition I noted the following on KUDU and HDFS, presumably HIVE. Does anybody have experience here? Keen to know. I will be tryiong it myself in due course, but installing parcels on non-parcelled quickstarts is not so easy...

Mix and match storage managers within a single application (or query)

```<code>• SELECT COUNT(*) FROM my_fact_table_on_hdfs JOIN
my_dim_table_in_kudu ON ...
</code>```

答:
Erring on the side of caution, linking with KUDU for dimensions would be the way to go so as to avoid a scan on a large dimension in HBASE when a lkp is only required.

I am retracting the latter point, I am sure that a JOIN will not cause an HBASE scan if it is an equijoin.

That said, IMPALA with MPP allows an MPP approach w/o MR and JOINing of dimensions with fact tables. The advantage of the OBDA is less obvious now. imo.

Title: Hive Hbase JOIN performance & KUDU

Body:
Reading the Cloudera documentation using Impala to join a Hive table against HBase smaller tables as stated below, then in the absence of a Big Data appliance such as OBDA and a largish HBase dimension table that is mutable:

If you have join queries that do aggregation operations on large fact
  tables  and join the results against small dimension tables, consider
  using Impala for  the fact tables and HBase for the dimension tables.
  (Because Impala does a  full scan on the HBase table in this case,
  rather than doing single-row HBase  lookups based on the join column,
  only use this technique where the HBase  table is small enough that
  doing a full table scan does not cause a  performance bottleneck for
  the query.)

Is there any way to get that single key look up in another way?

In addition I noted the following on KUDU and HDFS, presumably HIVE. Does anybody have experience here? Keen to know. I will be tryiong it myself in due course, but installing parcels on non-parcelled quickstarts is not so easy...

Mix and match storage managers within a single application (or query)

• SELECT COUNT(*) FROM my_fact_table_on_hdfs JOIN
my_dim_table_in_kudu ON ...


来源: stackexchange

问:
How to set the image to image view that is downloaded to your application in android local
I have a image downloaded locally in application

```<code>/data/data/com.starboard.stella/files/Stella/FragranceFinder/QuestionImages/option1_woman.png
</code>```

How do I access the image to set for image view?

答:
you can use Picasso for that

Picasso.with(context).load(new File(...)).into(imageView);

refernce: http://square.github.io/picasso/

ContentLicense: CC BY-SA 3.0

Body:
I have a image downloaded locally in application

/data/data/com.starboard.stella/files/Stella/FragranceFinder/QuestionImages/option1_woman.png

How do I access the image to set for image view?


问:
PyQt Copy folder with progress and transfer rate/speed
I'd like to expand my current code with the ability to show the transfer rate/speed of the files being copied. Im working on Windows 10 with py 3.6 and Qt 5.8. Here is my code:

```<code>import os
import shutil
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QProgressBar, QFileDialog

class FileCopyProgress(QWidget):

    def __init__(self, parent=None, src=None, dest=None):
        super(FileCopyProgress, self).__init__()

        self.src = src
        self.dest = dest
        self.build_ui()

    def build_ui(self):

        hbox = QVBoxLayout()

        lbl_src = QLabel('Source: ' + self.src)
        lbl_dest = QLabel('Destination: ' + self.dest)
        self.pb = QProgressBar()

        self.pb.setMinimum(0)
        self.pb.setMaximum(100)
        self.pb.setValue(0)

        hbox.addWidget(lbl_src)
        hbox.addWidget(lbl_dest)
        hbox.addWidget(self.pb)
        self.setLayout(hbox)

        self.setWindowTitle('File copy')
        self.auto_start_timer = QTimer()
        self.auto_start_timer.singleShot(2000, lambda: self.copyFilesWithProgress(self.src, self.dest, self.progress, self.copydone))
        self.show()

    def progress(self, done, total):
        progress = int(round((done/float(total))*100))

        try:
            self.pb.setValue(progress)
        except:
            pass

        app.processEvents()

    def copydone(self):
        self.pb.setValue(100)
        self.close()

    def countfiles(self, _dir):
        files = []

        if os.path.isdir(_dir):
            for path, dirs, filenames in os.walk(_dir):
                files.extend(filenames)
        return len(files)

    def makedirs(self, dest):
        if not os.path.exists(dest):
            os.makedirs(dest)

    @pyqtSlot()
    def copyFilesWithProgress(self, src, dest, callback_progress, callback_copydone):
        numFiles = self.countfiles(src)
        if numFiles > 0:
            dest = os.path.join(dest, src.replace(BASE_DIR, '').replace('\\', ''))
            print(''.join(['Destination: ', dest]))
            self.makedirs(dest)

            numCopied = 0
            for path, dirs, filenames in os.walk(src):
                for directory in dirs:
                    destDir = path.replace(src,dest)
                    self.makedirs(os.path.join(destDir, directory))
                for sfile in filenames:
                    srcFile = os.path.join(path, sfile)
                    destFile = os.path.join(path.replace(src, dest), sfile)
                    shutil.copy(srcFile, destFile)

                    numCopied += 1
                    callback_progress(numCopied, numFiles)
            callback_copydone()

BASE_DIR = 'C:\\dev'

app = QApplication([])
FileCopyProgress(src="C:\dev\pywin32-221", dest='C:\dev\copied')

# Run the app
app.exec_()
</code>```

This code opens a gui with a progressbar showing progress while copying files. A simple label with the current transfer rate/speed (approximate) would be rlly nice :)

Unfortuanetly i can't find any examples, can someone give me a hint or maybe a working example please?

EDIT:
I did a remake and now I have transfer rate, time elapsed and time remaining. The data seems to be realistic. I have only one problem: Lets assume i have a folder/file that time remaining is 7 sec -> currently it starts with 7 sec and gets an update every 1 second. We expect that in the next step it would display 6 sec but instead it goes:
  5 sec
  3 sec
  1.5 sec
  1.4 sec
  1.3 sec
  1.2 sec
  1.1 sec and so on

Where is the mistake?

```<code>class FileCopyProgress(QWidget):

    def __init__(self, parent=None, src=None, dest=None):
        super(FileCopyProgress, self).__init__()

        self.src = src
        self.dest = dest
        self.rate = "0"
        self.total_time = "0 s"
        self.time_elapsed = "0 s"
        self.time_remaining = "0 s"
        self.build_ui()

    def build_ui(self):

        hbox = QVBoxLayout()

        lbl_src = QLabel('Source: ' + self.src)
        lbl_dest = QLabel('Destination: ' + self.dest)
        self.pb = QProgressBar()
        self.lbl_rate = QLabel('Transfer rate: ' + self.rate)
        self.lbl_time_elapsed = QLabel('Time Elapsed: ' + self.time_elapsed)
        self.lbl_time_remaining = QLabel('Time Remaining: ' + self.time_remaining)

        self.pb.setMinimum(0)
        self.pb.setMaximum(100)
        self.pb.setValue(0)

        hbox.addWidget(lbl_src)
        hbox.addWidget(lbl_dest)
        hbox.addWidget(self.pb)
        hbox.addWidget(self.lbl_rate)
        hbox.addWidget(self.lbl_time_elapsed)
        hbox.addWidget(self.lbl_time_remaining)
        self.setLayout(hbox)

        self.setWindowTitle('File copy')

        self.auto_start_timer = QTimer()
        self.auto_start_timer.singleShot(100, lambda: self.copy_files_with_progress(self.src, self.dest, self.progress, self.copy_done))

        self.copy_timer = QTimer()
        self.copy_timer.timeout.connect(lambda: self.process_informations())
        self.copy_timer.start(1000)
        self.show()

    @pyqtSlot()
    def process_informations(self):

        time_elapsed_raw = time.clock() - self.start_time
        self.time_elapsed = '{:.2f} s'.format(time_elapsed_raw)
        self.lbl_time_elapsed.setText('Time Elapsed: ' + self.time_elapsed)

        # example - Total: 100 Bytes, bisher kopiert 12 Bytes/s
        time_remaining_raw = self._totalSize/self._copied
        self.time_remaining = '{:.2f} s'.format(time_remaining_raw) if time_remaining_raw < 60. else '{:.2f} min'.format(time_remaining_raw)
        self.lbl_time_remaining.setText('Time Remaining: ' + self.time_remaining)

        rate_raw = (self._copied - self._copied_tmp)/1024/1024
        self.rate = '{:.2f} MB/s'.format(rate_raw)
        self.lbl_rate.setText('Transfer rate: ' + self.rate)

        self._copied_tmp = self._copied

    def progress(self):
        self._progress = (self._copied/self._totalSize)*100

        try:
            self.pb.setValue(self._progress)
        except:
            pass

        app.processEvents()

    def get_total_size(self, src):
        return sum( os.path.getsize(os.path.join(dirpath,filename)) for dirpath, dirnames, filenames in os.walk(src) for filename in filenames ) # total size of files in bytes

    def copy_done(self):
        self.pb.setValue(100)
        print("done")
        self.close()

    def make_dirs(self, dest):
        if not os.path.exists(dest):
            os.makedirs(dest)

    @pyqtSlot()
    def copy_files_with_progress(self, src, dst, callback_progress, callback_copydone, length=16*1024*1024):
        self._copied = 0
        self._copied_tmp = 0
        self._totalSize = self.get_total_size(src)

        print(''.join(['Pre Dst: ', dst]))

        dst = os.path.join(dst, src.replace(BASE_DIR, '').replace('\\', ''))

        print(''.join(['Src: ', src]))
        print(''.join(['Dst: ', dst]))
        self.make_dirs(dst)

        self.start_time = time.clock()
        for path, dirs, filenames in os.walk(src):
            for directory in dirs:
                destDir = path.replace(src, dst)
                self.make_dirs(os.path.join(destDir, directory))
            for sfile in filenames:
                srcFile = os.path.join(path, sfile)
                destFile = os.path.join(dst, sfile)
#                     destFile = os.path.join(path.replace(src, dst), sfile)

                with open(srcFile, 'rb') as fsrc:
                    with open(destFile, 'wb') as fdst:
                        while 1:
                            buf = fsrc.read(length)
                            if not buf:
                                break
                            fdst.write(buf)
                            self._copied += len(buf)
                            callback_progress()
        try:
            self.copy_timer.stop()
        except:
            print('Error: could not stop QTimer')

        callback_copydone()
</code>```

答:
That's all about logic, think in the following way:

You have a TOTAL size of all files, let's say you have 100 dashes: [----- ... -----]

Now you get the starting time when you started transferring your files.

Choose some interval, let's have for example 2 secs.

So, after 2 secs see how much of the total you already transferred, in other words how much of files you already have in the new dir. Let's say you transferred 26 dashes.

The calc would be, 26 dashes/2secs = 13dashes per seconds.

Going deeper we have 26% of the content downloaded in 2 seconds since the total is 100 or 13% per second.

Even further we can calc also the prediction of time.

Total Time = 100%/13% = 7.6 secs

Time Elapsed = 2secs

Time Remaining = 7.6 - 2 = 5.6 secs

I think you got the idea...

Note: You just gotta keep verifying and remaking all these calcs in each 2 seconds, if you choose 2 secs of course, and updating the information to the user. If you wanna be even more precise or show more frequently updated information to the user just reduce that interval to let's say 0.5 secs and make the calc on top of milliseconds. It's up to you how often you update the information, that's just an overview of how to do the math. ")

Body:
I'd like to expand my current code with the ability to show the transfer rate/speed of the files being copied. Im working on Windows 10 with py 3.6 and Qt 5.8. Here is my code:

import os
import shutil
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QProgressBar, QFileDialog

class FileCopyProgress(QWidget):

    def __init__(self, parent=None, src=None, dest=None):
        super(FileCopyProgress, self).__init__()

        self.src = src
        self.dest = dest
        self.build_ui()

    def build_ui(self):

        hbox = QVBoxLayout()

        lbl_src = QLabel('Source: ' + self.src)
        lbl_dest = QLabel('Destination: ' + self.dest)
        self.pb = QProgressBar()

        self.pb.setMinimum(0)
        self.pb.setMaximum(100)
        self.pb.setValue(0)

        hbox.addWidget(lbl_src)
        hbox.addWidget(lbl_dest)
        hbox.addWidget(self.pb)
        self.setLayout(hbox)

        self.setWindowTitle('File copy')
        self.auto_start_timer = QTimer()
        self.auto_start_timer.singleShot(2000, lambda: self.copyFilesWithProgress(self.src, self.dest, self.progress, self.copydone))
        self.show()

    def progress(self, done, total):
        progress = int(round((done/float(total))*100))

        try:
            self.pb.setValue(progress)
        except:
            pass

        app.processEvents()

    def copydone(self):
        self.pb.setValue(100)
        self.close()

    def countfiles(self, _dir):
        files = []

        if os.path.isdir(_dir):
            for path, dirs, filenames in os.walk(_dir):
                files.extend(filenames)
        return len(files)

    def makedirs(self, dest):
        if not os.path.exists(dest):
            os.makedirs(dest)

    @pyqtSlot()
    def copyFilesWithProgress(self, src, dest, callback_progress, callback_copydone):
        numFiles = self.countfiles(src)
        if numFiles > 0:
            dest = os.path.join(dest, src.replace(BASE_DIR, '').replace('\\', ''))
            print(''.join(['Destination: ', dest]))
            self.makedirs(dest)

            numCopied = 0
            for path, dirs, filenames in os.walk(src):
                for directory in dirs:
                    destDir = path.replace(src,dest)
                    self.makedirs(os.path.join(destDir, directory))
                for sfile in filenames:
                    srcFile = os.path.join(path, sfile)
                    destFile = os.path.join(path.replace(src, dest), sfile)
                    shutil.copy(srcFile, destFile)

                    numCopied += 1
                    callback_progress(numCopied, numFiles)
            callback_copydone()

BASE_DIR = 'C:\\dev'

app = QApplication([])
FileCopyProgress(src="C:\dev\pywin32-221", dest='C:\dev\copied')

# Run the app
app.exec_()

This code opens a gui with a progressbar showing progress while copying files. A simple label with the current transfer rate/speed (approximate) would be rlly nice :)

Unfortuanetly i can't find any examples, can someone give me a hint or maybe a working example please?

EDIT:
I did a remake and now I have transfer rate, time elapsed and time remaining. The data seems to be realistic. I have only one problem: Lets assume i have a folder/file that time remaining is 7 sec -> currently it starts with 7 sec and gets an update every 1 second. We expect that in the next step it would display 6 sec but instead it goes:
  5 sec
  3 sec
  1.5 sec
  1.4 sec
  1.3 sec
  1.2 sec
  1.1 sec and so on

Where is the mistake?

class FileCopyProgress(QWidget):

    def __init__(self, parent=None, src=None, dest=None):
        super(FileCopyProgress, self).__init__()

        self.src = src
        self.dest = dest
        self.rate = "0"
        self.total_time = "0 s"
        self.time_elapsed = "0 s"
        self.time_remaining = "0 s"
        self.build_ui()

    def build_ui(self):

        hbox = QVBoxLayout()

        lbl_src = QLabel('Source: ' + self.src)
        lbl_dest = QLabel('Destination: ' + self.dest)
        self.pb = QProgressBar()
        self.lbl_rate = QLabel('Transfer rate: ' + self.rate)
        self.lbl_time_elapsed = QLabel('Time Elapsed: ' + self.time_elapsed)
        self.lbl_time_remaining = QLabel('Time Remaining: ' + self.time_remaining)

        self.pb.setMinimum(0)
        self.pb.setMaximum(100)
        self.pb.setValue(0)

        hbox.addWidget(lbl_src)
        hbox.addWidget(lbl_dest)
        hbox.addWidget(self.pb)
        hbox.addWidget(self.lbl_rate)
        hbox.addWidget(self.lbl_time_elapsed)
        hbox.addWidget(self.lbl_time_remaining)
        self.setLayout(hbox)

        self.setWindowTitle('File copy')

        self.auto_start_timer = QTimer()
        self.auto_start_timer.singleShot(100, lambda: self.copy_files_with_progress(self.src, self.dest, self.progress, self.copy_done))

        self.copy_timer = QTimer()
        self.copy_timer.timeout.connect(lambda: self.process_informations())
        self.copy_timer.start(1000)
        self.show()

    @pyqtSlot()
    def process_informations(self):

        time_elapsed_raw = time.clock() - self.start_time
        self.time_elapsed = '{:.2f} s'.format(time_elapsed_raw)
        self.lbl_time_elapsed.setText('Time Elapsed: ' + self.time_elapsed)

        # example - Total: 100 Bytes, bisher kopiert 12 Bytes/s
        time_remaining_raw = self._totalSize/self._copied
        self.time_remaining = '{:.2f} s'.format(time_remaining_raw) if time_remaining_raw < 60. else '{:.2f} min'.format(time_remaining_raw)
        self.lbl_time_remaining.setText('Time Remaining: ' + self.time_remaining)

        rate_raw = (self._copied - self._copied_tmp)/1024/1024
        self.rate = '{:.2f} MB/s'.format(rate_raw)
        self.lbl_rate.setText('Transfer rate: ' + self.rate)

        self._copied_tmp = self._copied

    def progress(self):
        self._progress = (self._copied/self._totalSize)*100

        try:
            self.pb.setValue(self._progress)
        except:
            pass

        app.processEvents()

    def get_total_size(self, src):
        return sum( os.path.getsize(os.path.join(dirpath,filename)) for dirpath, dirnames, filenames in os.walk(src) for filename in filenames ) # total size of files in bytes

    def copy_done(self):
        self.pb.setValue(100)
        print("done")
        self.close()

    def make_dirs(self, dest):
        if not os.path.exists(dest):
            os.makedirs(dest)

    @pyqtSlot()
    def copy_files_with_progress(self, src, dst, callback_progress, callback_copydone, length=16*1024*1024):
        self._copied = 0
        self._copied_tmp = 0
        self._totalSize = self.get_total_size(src)

        print(''.join(['Pre Dst: ', dst]))

        dst = os.path.join(dst, src.replace(BASE_DIR, '').replace('\\', ''))

        print(''.join(['Src: ', src]))
        print(''.join(['Dst: ', dst]))
        self.make_dirs(dst)

        self.start_time = time.clock()
        for path, dirs, filenames in os.walk(src):
            for directory in dirs:
                destDir = path.replace(src, dst)
                self.make_dirs(os.path.join(destDir, directory))
            for sfile in filenames:
                srcFile = os.path.join(path, sfile)
                destFile = os.path.join(dst, sfile)
#                     destFile = os.path.join(path.replace(src, dst), sfile)

                with open(srcFile, 'rb') as fsrc:
                    with open(destFile, 'wb') as fdst:
                        while 1:
                            buf = fsrc.read(length)
                            if not buf:
                                break
                            fdst.write(buf)
                            self._copied += len(buf)
                            callback_progress()
        try:
            self.copy_timer.stop()
        except:
            print('Error: could not stop QTimer')

        callback_copydone()


问:
What is LDAP used for?
I know that LDAP is used to provide some information and to help facilitate authorization. </p>

<p>But what are the other usages of LDAP? </p>

答:
LDAP main usage is to provider faster retrieval of data . It acts as a central repository for storing user details that can be accessed by various application at same time .

The data that is read various time  but we rarely update the data then LDAP is better option as it is faster  to read in it because of its structure but updating(add/updatee or delete) is bit tedious job in case of LDAP

Security provided by LDAP : LDAP can work with SSL & TLS and thus can be used for sensitive information .

LDAP also can work with number of database providing greater flexibility to choose database best suited for our environment

Can be a better option for synchronising information between master and its replicase

LDAP apart from supporting the data recovery capability .Also , allows us to export data into LDIF file that can be read by various software available in the market

OwnerDisplayName: gizmo

ContentLicense: CC BY-SA 2.5

Title: What is LDAP used for?

Body:
I know that LDAP is used to provide some information and to help facilitate authorization.

But what are the other usages of LDAP?


问:
Hibernate throws HibernateQueryException: could not resolve property
So I have a table that I've defined as an entity in hibernate like this:

```<code>@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}
</code>```

When I tried to write a simple query against this table:

```<code>public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}
</code>```

I got the following error:

```<code>org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference
</code>```

Why can't hibernate figure out what dbgroupid is on my class?

答:
Well I made some progress on this but I still don't understand where hibernate gets its names.  I debugged into the guts of hibernate and found the following class:

```<code>org.hibernate.persister.entity.AbstractPropertyMapping
</code>```

In this class there is a method:

```<code>public Type toType(String propertyName) throws QueryException {
    Type type = (Type) typesByPropertyPath.get(propertyName);
    if (type == null) {
        throw propertyException(propertyName);
    }
    return type;
}
</code>```

Which tries to resolve the name given in the criteria against the object.  So in the typesByPropertyPath map I found the following values:

```<code>id -> DBGroupId=org.hibernate.type.LongType@1e96ffd
key -> value=org.hibernate.type.StringType@aa2ee4
value -> value=org.hibernate.type.StringType@aa2ee4
systemUserId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
securityRoleId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
externalGroupId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
DBGroupId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
</code>```

Here you can see that the CAPITALIZATION of DBGroupId did not match what I had in my criteria.  So I changed that from dbgroupid to DBGroupId like this:

```<code>public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("DBGroupId", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}
</code>```

Now it works.

Body:
So I have a table that I've defined as an entity in hibernate like this:

@Entity
@Table(name = "sec_Preference")
public class Preference {
private long id;

@Column(name = "PreferenceId", nullable = false, insertable = true, updatable = true, length = 19, precision = 0)
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

private long systemuserid;

@Column(name = "SystemUserId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSystemUserId() {
    return systemuserid;
}

public void setSystemUserId(long systemuserid) {
    this.systemuserid = systemuserid;
}

private long dbgroupid;

@Column(name = "DBGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getDBGroupId() {
    return dbgroupid;
}

public void setDBGroupId(long dbgroupid) {
    this.dbgroupid = dbgroupid;
}

private long externalgroupid;

@Column(name = "ExternalGroupId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getExternalGroupId() {
    return externalgroupid;
}

public void setExternalGroupId(long externalgroupid) {
    this.externalgroupid = externalgroupid;
}

private long securityroleid;

@Column(name = "SecurityRoleId", nullable = true, insertable = true, updatable = true, length = 19, precision = 0)
@Basic
public long getSecurityRoleId() {
    return securityroleid;
}

public void setSecurityRoleId(long securityroleid) {
    this.securityroleid = securityroleid;
}

public void setEnum(com.vitalimages.common.server.security.Preference pref) {
    this.preferencekey = pref.name();
}

private String preferencekey;

@Column(name = "PreferenceKey", nullable = false, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getKey() {
    return preferencekey;
}

public void setKey(String key) {
    this.preferencekey = key;
}

private String preferencevalue;

@Column(name = "PreferenceValue", nullable = true, insertable = true, updatable = true, length = 255, precision = 0)
@Basic
public String getValue() {
    return preferencevalue;
}

public void setValue(String value) {
    this.preferencevalue = value;
}

}

When I tried to write a simple query against this table:

public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("dbgroupid", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}

I got the following error:

org.springframework.orm.hibernate3.HibernateQueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference; nested exception is org.hibernate.QueryException: could not resolve property: dbgroupid of: com.common.server.domain.sec.Preference

Why can't hibernate figure out what dbgroupid is on my class?

Body:
Well I made some progress on this but I still don't understand where hibernate gets its names.  I debugged into the guts of hibernate and found the following class:

org.hibernate.persister.entity.AbstractPropertyMapping

In this class there is a method:

public Type toType(String propertyName) throws QueryException {
    Type type = (Type) typesByPropertyPath.get(propertyName);
    if (type == null) {
        throw propertyException(propertyName);
    }
    return type;
}

Which tries to resolve the name given in the criteria against the object.  So in the typesByPropertyPath map I found the following values:

id -> DBGroupId=org.hibernate.type.LongType@1e96ffd
key -> value=org.hibernate.type.StringType@aa2ee4
value -> value=org.hibernate.type.StringType@aa2ee4
systemUserId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
securityRoleId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
externalGroupId -> DBGroupId=org.hibernate.type.LongType@1e96ffd
DBGroupId -> DBGroupId=org.hibernate.type.LongType@1e96ffd

Here you can see that the CAPITALIZATION of DBGroupId did not match what I had in my criteria.  So I changed that from dbgroupid to DBGroupId like this:

public Collection<Preference> getPreferencesForDBGroup(long dbgroupId) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(Preference.class)
            .add(Restrictions.eq("DBGroupId", dbgroupId))
            .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);

    return getHibernateTemplate().findByCriteria(criteria);
}

Now it works.


问:
I want 3 toolbars floating on each side and bottom of the screen and SVG should take rest of the space. How to model this?

I want a full screen page without scrolling. The page should take out the entire screen with 3 toolbars ( 2 on both sides of the screen and a bottom toolbar ). how can i set svg dimensions?. Help please.

答:
In your CSS you could try using "calc()".

As an example:

```<code>.my-svg-container {
    height: calc(100vh - 50px - 40px);
    width: calc(100vw - 20px - 10px);
}
</code>```

Where: Top bar = 50px, Bottom bar = 40px, Left bar = 20px, and Right bar = 10px

Should note that this method will only work if you know the dimensions of each bar, otherwise you could just use "height: (a number)vh; width: (a number)vw;" where (a number) is a number between 0 - 100 and represents a percentage of the screen size (i.e. where 100vh is 100% screen height, 40vw is 40% screen width)

Body:
In your CSS you could try using "calc()".

As an example:

.my-svg-container {
    height: calc(100vh - 50px - 40px);
    width: calc(100vw - 20px - 10px);
}

Where: Top bar = 50px, Bottom bar = 40px, Left bar = 20px, and Right bar = 10px

Should note that this method will only work if you know the dimensions of each bar, otherwise you could just use "height: (a number)vh; width: (a number)vw;" where (a number) is a number between 0 - 100 and represents a percentage of the screen size (i.e. where 100vh is 100% screen height, 40vw is 40% screen width)


答:
You may try grep with like this:

```<code>df[,grep("^best\\.\\.F",names(df))]
</code>```

Title: how to search and retrieve specific columns from a huge data

Body:
I have a data looks like this

df<- structure(list(X..taminn = c(86L, 102L, 34L, 35L, 53L, 54L, 43L,
31L, 62L, 54L), X..turtia = c(413L, 322L, 525L, 535L, 247L, 207L,
241L, 440L, 189L, 221L), X..bestt = c(82L, 102L, 6L, 2L, 46L,
1L, 39L, 7L, 62L, 54L), Best..F1..129..test = c(3079.3, 1512.9,
497, 2804.5, 1353.7, 1597.6, 2005.1, 186.4, 1847.5, 1558.2),
    best..F1..130..test = c(8972.7, 1944, 2022.7, 13001.7, 2085,
    3228.6, 4948.5, 943.6, 1329, 2655.9), best..F1..131..test = c(2634.4,
    1181.3, 505.2, 2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2,
    1219), how1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
    2L, 1L), .Label = c("", "High", "Not Found"), class = "factor"),
    how2 = structure(c(2L, 2L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 1L
    ), .Label = c("", "High", "Not Found"), class = "factor"),
    how3 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L
    ), .Label = c("", "High"), class = "factor"), Best.test...F1..129..test = c(3079.3,
    1512.9, 497, 2804.5, 1353.7, 1597.6, 2005.1, 186.4, 1847.5,
    1558.2), best.test...F1..130..test = c(8972.7, 1944, 2022.7,
    13001.7, 2085, 3228.6, 4948.5, 943.6, 1329, 2655.9), best.test...F1..131..test = c(2634.4,
    1181.3, 505.2, 2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2,
    1219), Best..test..129..test = c(3079.3, 1512.9, 497, 2804.5,
    1353.7, 1597.6, 2005.1, 186.4, 1847.5, 1558.2), best..test..130..test = c(8972.7,
    1944, 2022.7, 13001.7, 2085, 3228.6, 4948.5, 943.6, 1329,
    2655.9), best..test..131..test = c(2634.4, 1181.3, 505.2,
    2802.4, 1573.2, 1707.6, 1585.9, 192.1, 809.2, 1219)), .Names = c("X..taminn",
"X..turtia", "X..bestt", "Best..F1..129..test", "best..F1..130..test",
"best..F1..131..test", "how1", "how2", "how3", "Best.test...F1..129..test",
"best.test...F1..130..test", "best.test...F1..131..test", "Best..test..129..test",
"best..test..130..test", "best..test..131..test"), class = "data.frame", row.names = c(NA,
-10L))

Basically, I want to extract all those columns that their name starts with

best..F1
best..F2
.
.

is there a way to do it without going to the data one by one and find its place ?

Body:
You may try grep with like this:

df[,grep("^best\\.\\.F",names(df))]


问:
google cloud aspnetcore default builder yaml missing
Starting Friday afternoon last week, I'm suddenly unable to deploy to GCP for my project and I receive the following error:

```<code>...
Building and pushing image for service [myService]
ERROR: (gcloud.beta.app.deploy) Could not read [<googlecloudsdk.api_lib.s
storage_util.ObjectReference object at 0x045FD130>]: HttpError accessing
//www.googleapis.com/storage/v1/b/runtime-builders/o/gs%3A%2F%2Fruntime-b
%2Faspnetcore-default-builder-20170524113403.yaml?alt=media>: response: <
s': '404', 'content-length': '9', 'expires': 'Mon, 05 Jun 2017 14:33:42 G
ary': 'Origin, X-Origin', 'server': 'UploadServer', 'x-guploader-uploadid
B2UpOw2hMicKUV6j5FRap9x4UKxxZsb04j9JxWA_kc27S_AIPf0QZQ40H6OZgZcLJxCnnx5m4
8x3JV3p9kvZZy-A', 'cache-control': 'private, max-age=0', 'date': 'Mon, 05
17 14:33:42 GMT', 'alt-svc': 'quic=":443"; ma=2592000; v="38,37,36,35"',
t-type': 'text/html; charset=UTF-8'}>, content <Not Found>. Please retry.
</code>```

I tried again this morning and even updated my gcloud components to version 157.  I continue to see this error.

Item of note, the 20170524113403 value in that YAML filename is, I think, a match to the first successful deploy to .NET App Flex for my project.  I had since deleted that version using the Google Cloud Explorer with a more recent version 'published' early Friday morning.  My publish worked Friday morning, now it doesn't.  I don't see any logs that help me understand why that file is even needed and an Agent Ransack search on my entire drive doesn't reveal where that filename is coming from to try and point it to a more recent version.

I'm doing this through both Google Cloud Tools integrated into my Visual Studio 2017 (Publish to Google Cloud...) as well as running the command lines:

```<code>dotnet restore
dotnet publish -c Release
copy app.yaml -> destination location
gcloud beta app deploy .\app.yaml in destination location
</code>```

答:
Not sure if this was "fixed" by Google or not, but 4 days later, the problem went away.  On some additional information, I was able to locate the logs on my machine during the publish phase and saw something interesting.

When Working:

```<code>2017-05-25 09:36:48,821 DEBUG    root            Calculated builder definition using legacy version [gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]
</code>```

Later when it stopped working:

```<code> 2017-06-02 15:25:15,312 DEBUG    root            Resolved runtime [aspnetcore] as build configuration [gs://runtime-builders/gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]
</code>```

What I noticed was the duplicated "gs://runtime-builders/gs//runtime-builders..."

which disappeared this morning... no, I didn't change a thing besides waiting until today.

```<code>2017-06-07 08:11:37,042 INFO     root            Using runtime builder [gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]
</code>```

You'll see that double "gs://runtime-builders/gs://runtime-builders/" is GONE.

Body:
Starting Friday afternoon last week, I'm suddenly unable to deploy to GCP for my project and I receive the following error:

...
Building and pushing image for service [myService]
ERROR: (gcloud.beta.app.deploy) Could not read [<googlecloudsdk.api_lib.s
storage_util.ObjectReference object at 0x045FD130>]: HttpError accessing
//www.googleapis.com/storage/v1/b/runtime-builders/o/gs%3A%2F%2Fruntime-b
%2Faspnetcore-default-builder-20170524113403.yaml?alt=media>: response: <
s': '404', 'content-length': '9', 'expires': 'Mon, 05 Jun 2017 14:33:42 G
ary': 'Origin, X-Origin', 'server': 'UploadServer', 'x-guploader-uploadid
B2UpOw2hMicKUV6j5FRap9x4UKxxZsb04j9JxWA_kc27S_AIPf0QZQ40H6OZgZcLJxCnnx5m4
8x3JV3p9kvZZy-A', 'cache-control': 'private, max-age=0', 'date': 'Mon, 05
17 14:33:42 GMT', 'alt-svc': 'quic=":443"; ma=2592000; v="38,37,36,35"',
t-type': 'text/html; charset=UTF-8'}>, content <Not Found>. Please retry.

I tried again this morning and even updated my gcloud components to version 157.  I continue to see this error.

Item of note, the 20170524113403 value in that YAML filename is, I think, a match to the first successful deploy to .NET App Flex for my project.  I had since deleted that version using the Google Cloud Explorer with a more recent version 'published' early Friday morning.  My publish worked Friday morning, now it doesn't.  I don't see any logs that help me understand why that file is even needed and an Agent Ransack search on my entire drive doesn't reveal where that filename is coming from to try and point it to a more recent version.

I'm doing this through both Google Cloud Tools integrated into my Visual Studio 2017 (Publish to Google Cloud...) as well as running the command lines:

dotnet restore
dotnet publish -c Release
copy app.yaml -> destination location
gcloud beta app deploy .\app.yaml in destination location

Body:
Not sure if this was "fixed" by Google or not, but 4 days later, the problem went away.  On some additional information, I was able to locate the logs on my machine during the publish phase and saw something interesting.

When Working:

2017-05-25 09:36:48,821 DEBUG    root            Calculated builder definition using legacy version [gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]

Later when it stopped working:

 2017-06-02 15:25:15,312 DEBUG    root            Resolved runtime [aspnetcore] as build configuration [gs://runtime-builders/gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]

What I noticed was the duplicated "gs://runtime-builders/gs//runtime-builders..."

which disappeared this morning... no, I didn't change a thing besides waiting until today.

2017-06-07 08:11:37,042 INFO     root            Using runtime builder [gs://runtime-builders/aspnetcore-default-builder-20170524113403.yaml]

You'll see that double "gs://runtime-builders/gs://runtime-builders/" is GONE.


问:
Java Regex to extract any characters between two tokens
I am trying to parse the following text

```<code>### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices
</code>```

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?

答:
Use Pattern.DOTALL:

```<code>Pattern p = Pattern.compile("### __Description of the report__(.*?)### __Notable filters__", Pattern.DOTALL);
</code>```

Pattern.MULTILINE will match ### __Description of the report__ and ### __Notable filters__ with the start and end of EVERY LINE, so that can't be used. DOTALL will match . with each character, including \n, which won't happen without specifying Pattern.DOTALL.

To store it, do this:

```<code>Matcher m = p.matcher(str); // 'str' is the string with the text
while(m.find())
{
    YourString = m.group(1);
}
</code>```

Later, you can replace the extra spaces like this:

```<code>YourString = YourString.replaceAll("\\s+", " ");
</code>```

Body:
I am trying to parse the following text

### __Description of the report__
Lorem ipsum dolor sit amet,  & mauris elit, blandit a turpis vel nibh,
consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
sagittis, luctus porttitor odit sollicitudin <> vestibulum ultrices erat,
sed eleifend
* amet, sollicitudin sit egestas
* quis eros nulla. Sed donec

### __Notable filters__
* Lorem ipsum dolor sit amet, mauris elit, blandit a turpis vel
* consectetuer aliquam. Nec sem. Venenatis quam etiam donec consequat
* sagittis, luctus porttitor odit sollicitudin vestibulum ultrices

I want to capture all text between the ### __Description of the report__ and ### __Notable filters__ which could be numbers letters, or any combination of special characters.

I thought using ### __Description of the report__(.*?)### __Notable filters__ would work, but it doesn't return any results. How can i extract the text between the two headings?

Body:
Use Pattern.DOTALL:

Pattern p = Pattern.compile("### __Description of the report__(.*?)### __Notable filters__", Pattern.DOTALL);

Pattern.MULTILINE will match ### __Description of the report__ and ### __Notable filters__ with the start and end of EVERY LINE, so that can't be used. DOTALL will match . with each character, including \n, which won't happen without specifying Pattern.DOTALL.

To store it, do this:

Matcher m = p.matcher(str); // 'str' is the string with the text
while(m.find())
{
    YourString = m.group(1);
}

Later, you can replace the extra spaces like this:

YourString = YourString.replaceAll("\\s+", " ");


问:
ActiveRecord Find By Year, Day or Month on a Date field
I have an ActiveRecord model that has a date attribute.  Is it possible to utilize that date attribute to find by Year, Day and Month:

```<code>Model.find_by_year(2012)
Model.find_by_month(12)
Model.find_by_day(1)
</code>```

or is it simply possible to find_by_date(2012-12-1).

I was hoping I could avoid creating Year, Month and Day attributes.

答:
No need for extract method, this works like a charm in postgresql:

```<code>text_value = "1997" # or text_value = '1997-05-19' or '1997-05' or '05', etc
sql_string = "TO_CHAR(date_of_birth::timestamp, 'YYYY-MM-DD') ILIKE '%#{text_value.strip}%'"
YourModel.where(sql_string)
</code>```

Body:
I have an ActiveRecord model that has a date attribute.  Is it possible to utilize that date attribute to find by Year, Day and Month:

Model.find_by_year(2012)
Model.find_by_month(12)
Model.find_by_day(1)

or is it simply possible to find_by_date(2012-12-1).

I was hoping I could avoid creating Year, Month and Day attributes.

Body:
No need for extract method, this works like a charm in postgresql:

text_value = "1997" # or text_value = '1997-05-19' or '1997-05' or '05', etc
sql_string = "TO_CHAR(date_of_birth::timestamp, 'YYYY-MM-DD') ILIKE '%#{text_value.strip}%'"
YourModel.where(sql_string)


问:
SQL Create variables from 2 different tables
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

```<code>Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id
</code>```

will give me:

1 1

1 0

and

```<code>Select observation_id, Count(*) from intervals Group by
observation_id
</code>```

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?

答:
This gave me your desired result. Not proficient enough in SQL to determine if this is the optimal way of solving the issue though.</p>

```<code>SELECT
  observation_id as obs,
  (SELECT COUNT(*) FROM intervals WHERE observation_id = obs AND value = 5)/(SELECT COUNT(*) FROM INTERVALS WHERE observation_id = obs) as percent
FROM observation
JOIN intervals ON observation.id = intervals.observation_id
GROUP BY observation_id;
</code>```

Body:
I have 2 different tables called observations and intervals.

observations:

id,

type,

date

1 recess 03.05.2011 17:00

2 recess 03.06.2011 12:00

intervals:

id,

observation id,

value

1 1 5

2 1 8

3 2 4

4 2 4

I want a view that will display:

observation_id

percent_positive ((count where value = 5)/(total number of observations))

1 .5

2 0

I know

Select observation_id, Count(*) from intervals where value = 5 Group by
observation_id

will give me:

1 1

1 0

and

Select observation_id, Count(*) from intervals Group by
observation_id

will give me:

1 2

2 2

So how do I combine these to create a view with the percent_positive variable I'm looking for?

Body:
This gave me your desired result. Not proficient enough in SQL to determine if this is the optimal way of solving the issue though.

SELECT
  observation_id as obs,
  (SELECT COUNT(*) FROM intervals WHERE observation_id = obs AND value = 5)/(SELECT COUNT(*) FROM INTERVALS WHERE observation_id = obs) as percent
FROM observation
JOIN intervals ON observation.id = intervals.observation_id
GROUP BY observation_id;


问:
DatePicker with data annotation in mvc
I'm using data annotation in my model for a date picker.

Model:

```<code>  [DataType(DataType.Date)]
    public DateTime DueDate { get; set; }
</code>```

View:

```<code> <div class="form-group">
        @Html.LabelFor(model => model.DueDate, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DueDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DueDate, "", new { @class = "text-danger" })
        </div>
    </div>
</code>```

The first time when I am adding date to database it shows me calendar(without time).

next when I want to make changes in my records it does not show calendar. What can I change/add for this ?

And also it has validation for format. When I add date it is dd/mm/yyyy and when I'm making changes it only validates yyyy/mm/dd. How can I change it?

This is quite confusing and rare case and I'm hope you can help me.

答:
I faced the same problem and I solved it putting a script of validation for verify the browser (Google's Chrome works fine and no needs that)

```<code> var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (!isChrome) {
        $(document).ready(function () {
            $("#IdOfDivThatYouNedd").datepicker();
        });
    }
</code>```

For validation you can use this dataanotation:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
 [DataType(DataType.Date, ErrorMessage = "date is not a corret format")]

Title: DatePicker with data annotation in mvc

Body:
I'm using data annotation in my model for a date picker.

Model:

  [DataType(DataType.Date)]
    public DateTime DueDate { get; set; }

View:

        @Html.LabelFor(model => model.DueDate, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.DueDate, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DueDate, "", new { @class = "text-danger" })

The first time when I am adding date to database it shows me calendar(without time).

next when I want to make changes in my records it does not show calendar. What can I change/add for this ?

And also it has validation for format. When I add date it is dd/mm/yyyy and when I'm making changes it only validates yyyy/mm/dd. How can I change it?

This is quite confusing and rare case and I'm hope you can help me.

Body:
I faced the same problem and I solved it putting a script of validation for verify the browser (Google's Chrome works fine and no needs that)

 var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

    if (!isChrome) {
        $(document).ready(function () {
            $("#IdOfDivThatYouNedd").datepicker();
        });
    }

For validation you can use this dataanotation:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
 [DataType(DataType.Date, ErrorMessage = "date is not a corret format")]


问:
Atomic Upgrade Scripts
With my database upgrade scripts, I typically just have one long script that makes the necessary changes for that database version.  However, if one statement fails halfway through the script, it leaves the database in an inconsistent state.

How can I make the entire upgrade script one atomic operation?  I've tried just wrapping all of the statements in a transaction, but that does not work.  Even with SET XACT_ABORT ON, if one statement fails and rolls back the transactions, the rest of the statements just keep going.  I would like a solution that doesn't require me to write IF @@TRANCOUNT > 0... before each and every statement.  For example:

```<code>SET XACT_ABORT ON;
GO

BEGIN TRANSACTION;
GO

CREATE TABLE dbo.Customer
(
        CustomerID int NOT NULL
    ,   CustomerName varchar(100) NOT NULL
);
GO

CREATE TABLE [dbo].[Order]
(
        OrderID int NOT NULL
    ,   OrderDesc varchar(100) NOT NULL
);
GO

/* This causes error and should terminate entire script. */
ALTER TABLE dbo.Order2 ADD
    A int;
GO

CREATE TABLE dbo.CustomerOrder
(
        CustomerID int NOT NULL
    ,   OrderID int NOT NULL
);
GO

COMMIT TRANSACTION;
GO
</code>```

答:
Something like:

```<code>TRY
 ....
CATCH
ROLLBACK TRAN
</code>```

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Title: Atomic Upgrade Scripts

Body:
With my database upgrade scripts, I typically just have one long script that makes the necessary changes for that database version.  However, if one statement fails halfway through the script, it leaves the database in an inconsistent state.

How can I make the entire upgrade script one atomic operation?  I've tried just wrapping all of the statements in a transaction, but that does not work.  Even with SET XACT_ABORT ON, if one statement fails and rolls back the transactions, the rest of the statements just keep going.  I would like a solution that doesn't require me to write IF @@TRANCOUNT > 0... before each and every statement.  For example:

SET XACT_ABORT ON;
GO

BEGIN TRANSACTION;
GO

CREATE TABLE dbo.Customer
(
        CustomerID int NOT NULL
    ,   CustomerName varchar(100) NOT NULL
);
GO

CREATE TABLE [dbo].[Order]
(
        OrderID int NOT NULL
    ,   OrderDesc varchar(100) NOT NULL
);
GO

/* This causes error and should terminate entire script. */
ALTER TABLE dbo.Order2 ADD
    A int;
GO

CREATE TABLE dbo.CustomerOrder
(
        CustomerID int NOT NULL
    ,   OrderID int NOT NULL
);
GO

COMMIT TRANSACTION;
GO

Body:
Something like:

TRY
 ....
CATCH
ROLLBACK TRAN

http://msdn.microsoft.com/en-us/library/ms175976.aspx


问:
What is the difference between CouchDB and Couchbase?
Are there any essential differences between CouchDB and Couchbase?</p>

答:
They are different yet similar pieces of software. I've remixed the content from the top answer into a picture that might help clarify the "difference" as well as the common things:

A comment from Matt Ingenthron adds to this:

To add some context/corrections: NorthScale founders are Steve Yen and Dustin Sallings. I joined them shortly after founding. Also, Damien didn't later join Couchbase, he was part of CouchIO/Couch One prior to the merger. Citing a fun, historical source: https://youtube.com/watch?v=aZ_JOnU8tkI

ContentLicense: CC BY-SA 4.0


问:
Bootstrap:why intlTelinput changes the width of the input element?
I would like to put a number phone input in a subscription form with the validation made by the intlTelInput library, here is my code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="flags.min.css">
  <link rel="stylesheet" type="text/css" href="css2.css">
  <link rel="stylesheet" type="text/css" href="bootstrap-social.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="build/css/intlTelInput.css">
  <script src="google/jquery-1.11.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>

<div class="container">

  <div class="row flex-grow">

    <div class="col-xs-offset-1 col-xs-10 col-lg-12 col-lg-offset-0">

      <div class="row" id="grad1">
      <br>

          <div class="col-xs-offset-1 col-xs-10 col-lg-offset-4 col-lg-4">

                <form method="post" action="serv2.php" onsubmit="return submitForm(this);">

                  <fieldset>

                    <div class="row">

                        <div class="form-group phone">

                            <input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone number" />
                       </div>

                        <div class="form-group country">
                            <input type="text" id="country" name="country" class="form-control" placeholder="Country" />
                        </div>

                          <div class="form-group col-lg-6 col-lg-offset-3">
                            <div>
                              <label for="bouton"><br></label>
                              <div>
                                <button type="submit" class="btn btn-default" style="background-color: #00B0F0; color:white; width: 100%;border:none;">Valider</button>
                              </div>
                            </div>
                          </div>

                    </div>

                  </fieldset>

                </form>
            </div>

      </div>

    </div>

  </div>

</div>

</html>

</body>

<script src="build/js/intlTelInput.min.js"></script>

<script>

  $("#phone").intlTelInput({

    initialCountry: "auto",
    geoIpLookup: function(callback) {
      $.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
        var countryCode = (resp && resp.country) ? resp.country : "";
        callback(countryCode);
      });
    },
    utilsScript: "build/js/utils.js"
  });

  var telInput = $("#phone"),
  errorMsg = $("#error-msg"),
  validMsg = $("#valid-msg");

  telInput.intlTelInput({
    utilsScript: "build/js/utils.js"
  });

</script>
</code>```

The problem is that the phone input does not take the full width of the form like the country does.

I have tried to change it with document.getElementById('phone').style.minWidth = 100%; but it remove the action of the intlTelInput library (i.e no more flag icon).

Any idea ?

Thank you

答:
Ok, I eventually found the answer, It was in the documentation, one just have to add the class to the container:

.intl-tel-input {
  width: 100%;
}
```

Body:
I would like to put a number phone input in a subscription form with the validation made by the intlTelInput library, here is my code:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="flags.min.css">
  <link rel="stylesheet" type="text/css" href="css2.css">
  <link rel="stylesheet" type="text/css" href="bootstrap-social.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="build/css/intlTelInput.css">

                <form method="post" action="serv2.php" onsubmit="return submitForm(this);">

                  <fieldset>

                            <input type="tel" class="form-control" id="phone" name="phone" placeholder="Phone number" />

                            <input type="text" id="country" name="country" class="form-control" placeholder="Country" />

                                <button type="submit" class="btn btn-default" style="background-color: #00B0F0; color:white; width: 100%;border:none;">Valider</button>

                  </fieldset>

                </form>

The problem is that the phone input does not take the full width of the form like the country does.

I have tried to change it with document.getElementById('phone').style.minWidth = 100%; but it remove the action of the intlTelInput library (i.e no more flag icon).

Any idea ?

Thank you


问:
Ch7 "Ruby on Rails tutorial" by Michael Hartl error
The link that you provided as the answer doesn't exact the same and it doesn't help me to  get rid from the error. it said that need to use /index, so I've used in my case
/new - and I've got even more error....
So, getting the answer that clarify issue was pretty helpful because  this question  even it was similar was not duplicate - and I could not use the link that you provide to solve this issue.
Once again finding the solution is the most important criteria even for some not understandable reason I've got (-) for asking the question.
thanks.
I would like to clarify issue as below and don't want to receive (-) for just asking question.

My instructor said that "there are no stupid questions but rather no answered ones.."

I've recently asked 2 questions.
One of them was answered immediately, second one was not answered yet. Regardless of this, I've got -2 for both questions...

The question below is regarding ch7, Michael Hartl "Ruby on Rails tutorial":
I have error and related file as below.
How to fix it?

```<code>ERROR["test_should_get_new", UsersControllerTest, 1.258815998211503]
 test_should_get_new#UsersControllerTest (1.26s)
URI::InvalidURIError:         URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80new
            test/controllers/users_controller_test.rb:4:in `block in <class:UsersControllerTest>'
</code>```

test/controllers/users_controller_test.rb

```<code>require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
  test "should get new" do
    get :new
    assert_response :success
  end
end
</code>```

答:
For testing controllers refer your routes as the full path, instead :new use /users/new, or whatever is the route for the method new in the UsersController:

```<code>test 'should get new' do
  get '/users/new'
  assert_response :success
end
</code>```

Or also you can use the prefix for such route "new_user_path".

Body:
The link that you provided as the answer doesn't exact the same and it doesn't help me to  get rid from the error. it said that need to use /index, so I've used in my case
/new - and I've got even more error....
So, getting the answer that clarify issue was pretty helpful because  this question  even it was similar was not duplicate - and I could not use the link that you provide to solve this issue.
Once again finding the solution is the most important criteria even for some not understandable reason I've got (-) for asking the question.
thanks.
I would like to clarify issue as below and don't want to receive (-) for just asking question.

My instructor said that "there are no stupid questions but rather no answered ones.."

I've recently asked 2 questions.
One of them was answered immediately, second one was not answered yet. Regardless of this, I've got -2 for both questions...

The question below is regarding ch7, Michael Hartl "Ruby on Rails tutorial":
I have error and related file as below.
How to fix it?

ERROR["test_should_get_new", UsersControllerTest, 1.258815998211503]
 test_should_get_new#UsersControllerTest (1.26s)
URI::InvalidURIError:         URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80new
            test/controllers/users_controller_test.rb:4:in `block in <class:UsersControllerTest>'

test/controllers/users_controller_test.rb

require 'test_helper'
class UsersControllerTest < ActionDispatch::IntegrationTest
  test "should get new" do
    get :new
    assert_response :success
  end
end

Body:
For testing controllers refer your routes as the full path, instead :new use /users/new, or whatever is the route for the method new in the UsersController:

test 'should get new' do
  get '/users/new'
  assert_response :success
end

Or also you can use the prefix for such route "new_user_path".


问:
Can Meteor 1.5 dynamic importing be done on multiple scripts simultaneously?
Meteor 1.5 was recently released, and it has... dynamic imports!

All the examples I see are for dynamically importing one file, and then running code for it. I'm curious if there is a way to dynamically import multiple files with one declaration?

Thanks. :)

答:
Depends on what you mean by "import multiple files"…

Whenever you request a dynamic import, Meteor will fetch the required module and all its dependencies which are not already available in the browser cache.

On the contrary of classic HTTP request, the downloading is not parallelized, but goes through the already available Websocket. So all modules go through a pipe / queue.

If your code depends on multiple modules, you could simply write a "parent" module.

Or you could also aggregate your dynamic imports with Promise.all, since they return Promises.


问:
i18next to do formatting of dates, numbers with the Intl Api
On this link, https://www.i18next.com/formatting.html it says that we can use the Intl api for formatting, but doesn't show how to use it.

How can we configure i18next to use the Intl api for all dates, times and number formats? The example says it should be easy but doesn't show a reference example.

答:
You could:

```<code>i18next.init({
    interpolation: {
        format: function(value, format, lng) {
            if (format === 'intlDate') return new Intl.DateTimeFormat().format(value); // -> "12/20/2012" if run in en-US locale with time zone America/Los_Angeles
            return value;
        }
    }
});
</code>```

json: key: today is the {{now, intlDate}}

call t: i18next.t('key', { now: new Date() })

Body:
You could:

i18next.init({
    interpolation: {
        format: function(value, format, lng) {
            if (format === 'intlDate') return new Intl.DateTimeFormat().format(value); // -> "12/20/2012" if run in en-US locale with time zone America/Los_Angeles
            return value;
        }
    }
});

json: key: today is the {{now, intlDate}}

call t: i18next.t('key', { now: new Date() })


问:
What is the most pythonic way to check if an object is a number?
Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances.

For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector.

Checking if something is int, float, long, bool is annoying and doesn't cover user-defined objects that might act like numbers. But, checking for __mul__, for example, isn't good enough because the vector class I just described would define __mul__, but it wouldn't be the kind of number I want.

答:
Multiply the object by zero.  Any number times zero is zero.  Any other result means that the object is not a number (including exceptions)

```<code>def isNumber(x):
    try:
        return bool(0 == x*0)
    except:
        return False
</code>```

Using isNumber thusly will give the following output:

```<code>class A: pass

def foo(): return 1

for x in [1,1.4, A(), range(10), foo, foo()]:
    answer = isNumber(x)
    print('{answer} == isNumber({x})'.format(**locals()))
</code>```

Output:

```<code>True == isNumber(1)
True == isNumber(1.4)
False == isNumber(<__main__.A instance at 0x7ff52c15d878>)
False == isNumber([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
False == isNumber(<function foo at 0x7ff52c121488>)
True == isNumber(1)
</code>```

There probably are some non-number objects in the world that define __mul__ to return zero when multiplied by zero but that is an extreme exception. This solution should cover all normal and sane code that you generate/encouter.

numpy.array example:

```<code>import numpy as np

def isNumber(x):
    try:
        return bool(x*0 == 0)
    except:
        return False

x = np.array([0,1])

answer = isNumber(x)
print('{answer} == isNumber({x})'.format(**locals()))
</code>```

output:

```<code>False == isNumber([0 1])
</code>```

Body:
Multiply the object by zero.  Any number times zero is zero.  Any other result means that the object is not a number (including exceptions)

def isNumber(x):
    try:
        return bool(0 == x*0)
    except:
        return False

Using isNumber thusly will give the following output:

class A: pass

def foo(): return 1

for x in [1,1.4, A(), range(10), foo, foo()]:
    answer = isNumber(x)
    print('{answer} == isNumber({x})'.format(**locals()))

Output:

True == isNumber(1)
True == isNumber(1.4)
False == isNumber(<__main__.A instance at 0x7ff52c15d878>)
False == isNumber([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
False == isNumber(<function foo at 0x7ff52c121488>)
True == isNumber(1)

There probably are some non-number objects in the world that define __mul__ to return zero when multiplied by zero but that is an extreme exception. This solution should cover all normal and sane code that you generate/encouter.

numpy.array example:

import numpy as np

def isNumber(x):
    try:
        return bool(x*0 == 0)
    except:
        return False

x = np.array([0,1])

answer = isNumber(x)
print('{answer} == isNumber({x})'.format(**locals()))

output:

False == isNumber([0 1])


问:
Out of memory error in Mapreduce shuffle phase
I am getting strange errors while running a wordcount-like mapreduce program. I have a hadoop cluster with 20 slaves, each having 4 GB RAM. I configured my map tasks to have a heap of 300MB and my reduce task slots get 1GB. I have 2 map slots and 1 reduce slot per node. Everything goes well until the first round of map tasks finishes. Then there progress remains at 100%. I suppose then the copy phase is taking place. Each map task generates something like:

```<code>Map output bytes    4,164,335,564
Map output materialized bytes   608,800,675
</code>```

(I am using SnappyCodec for compression)

After stalling for about an hour the reduce tasks crach with the following exception:

```<code>    Error: java.lang.OutOfMemoryError: Java heap space at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.shuffleInMemory(ReduceTask.java:1703) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.getMapOutput(ReduceTask.java:1563) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.copyOutput(ReduceTask.java:1401) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.run(ReduceTask.java:1333
</code>```

I was googling and found this link but I don't really know what to make of it:
hadoop common link

I don't understand why hadoop would experience any problems in copying and merging if it is able to perform a terasort benchmark. It cannot be that all map output should fit into the RAM of the reducer thread. So what is going on here?

In the link provided above they have a discussion about tuning the following parameters:

```<code>mapreduce.reduce.shuffle.input.buffer.percent = 0.7
mapreduce.reduce.shuffle.memory.limit.percent = 0.25
mapreduce.reduce.shuffle.parallelcopies = 5
</code>```

They claim that the fact that the product of the parameters is >1 allows for heapsize errors.
EDIT: Note that 5*1.25*0.7 is still <1 so focus om my second solution post!)
Before restarting this intensive simulation I would be very happy to hear about someone's opinion concerning the problem I am facing since it is bothering for almost a week now. I also seem to not completely understand what is happening in this copy phase, I'd expect a merge sort on disk not to require much heap size?

Thanks a lot in advance for any helpful comments and answers!

答:
Related bug - https://issues.apache.org/jira/browse/MAPREDUCE-6724

Can cause a NegativeArraySizeException if the calculated maxSingleShuffleLimit > MAX_INT

Body:
I am getting strange errors while running a wordcount-like mapreduce program. I have a hadoop cluster with 20 slaves, each having 4 GB RAM. I configured my map tasks to have a heap of 300MB and my reduce task slots get 1GB. I have 2 map slots and 1 reduce slot per node. Everything goes well until the first round of map tasks finishes. Then there progress remains at 100%. I suppose then the copy phase is taking place. Each map task generates something like:

Map output bytes    4,164,335,564
Map output materialized bytes   608,800,675

(I am using SnappyCodec for compression)

After stalling for about an hour the reduce tasks crach with the following exception:

    Error: java.lang.OutOfMemoryError: Java heap space at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.shuffleInMemory(ReduceTask.java:1703) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.getMapOutput(ReduceTask.java:1563) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.copyOutput(ReduceTask.java:1401) at
org.apache.hadoop.mapred.ReduceTask$ReduceCopier$MapOutputCopier.run(ReduceTask.java:1333

I was googling and found this link but I don't really know what to make of it:
hadoop common link

I don't understand why hadoop would experience any problems in copying and merging if it is able to perform a terasort benchmark. It cannot be that all map output should fit into the RAM of the reducer thread. So what is going on here?

In the link provided above they have a discussion about tuning the following parameters:

mapreduce.reduce.shuffle.input.buffer.percent = 0.7
mapreduce.reduce.shuffle.memory.limit.percent = 0.25
mapreduce.reduce.shuffle.parallelcopies = 5

They claim that the fact that the product of the parameters is >1 allows for heapsize errors.
EDIT: Note that 5*1.25*0.7 is still <1 so focus om my second solution post!)
Before restarting this intensive simulation I would be very happy to hear about someone's opinion concerning the problem I am facing since it is bothering for almost a week now. I also seem to not completely understand what is happening in this copy phase, I'd expect a merge sort on disk not to require much heap size?

Thanks a lot in advance for any helpful comments and answers!


问:
Wildfly CLI "resolve-parameter-values" does not work as expected
I am using JBoss EAP 7.0.5 and I want to use internal configuration values in my standalone-ha.xml like:

```<code><property name="javax.net.ssl.trustStore" value="${jboss.server.config.dir}/stores/trustCA.jks"/>
</code>```

I added this value using the wildly maven plugin 1.2.0 Alpha 5 and CLI command:

```<code>/system-property=javax.net.ssl.trustStore:add(value="${jboss.server.config.dir}/stores/trustCA.jks")
</code>```

Sadly it didnt went as expected:

```<code><property name="javax.net.ssl.trustStore" value="/stores/trustCA.jks"/>
</code>```

The jboss-cli.xml looks like this:

```<code><?xml version='1.0' encoding='UTF-8'?>

<!--
   WildFly Command-line Interface configuration.
-->
<jboss-cli xmlns="urn:jboss:cli:2.0">

    <default-protocol use-legacy-override="true">http-remoting</default-protocol>

    <!-- The default controller to connect to when 'connect' command is executed w/o arguments -->
    <default-controller>
        <protocol>http-remoting</protocol>
        <host>localhost</host>
        <port>9990</port>
    </default-controller>

    <!-- Example controller alias named 'Test'
    <controllers>
        <controller name="Test">
            <protocol>http-remoting</protocol>
            <host>localhost</host>
            <port>9990</port>
        </controller>
    </controllers>
    -->

    <validate-operation-requests>true</validate-operation-requests>

    <!-- Command and operation history log configuration -->
    <history>
        <enabled>true</enabled>
        <file-name>.jboss-cli-history</file-name>
        <file-dir>${user.home}</file-dir>
        <max-size>500</max-size>
    </history>

    <!-- whether to resolve system properties specified as command argument or operation parameter values
                  in the CLI VM before sending the operation requests to the controller -->
    <resolve-parameter-values>false</resolve-parameter-values>

    <!-- Whether to write info and error messages to the terminal output -->
    <silent>false</silent>

    <!-- Whether to filter out commands and attributes based on user's permissions -->
    <access-control>false</access-control>
</jboss-cli>
</code>```

I also tried using the variable like this and it still gets resolved:

```<code>${jboss.server.config.dir:}
</code>```

Am I just using it wrong or can this possibly be a CLI or maven plugin error?

答: This behavior is not caused by Wildfly itself, but probably by the Maven Wildfly plugin. This plugin does not invoke the command line native admin interface, therefore it ignores the <resolve-parameter-values> value. It uses the jboss client java api and it seems to perform expression evaluation - see CommandExecutor.java#executeCommands.  If you try to execute your cli command directly via jboss-cli.sh, it would work as you expect i.e. the variable would not get interpolated.

Body:
I am using JBoss EAP 7.0.5 and I want to use internal configuration values in my standalone-ha.xml like:

<property name="javax.net.ssl.trustStore" value="${jboss.server.config.dir}/stores/trustCA.jks"/>

I added this value using the wildly maven plugin 1.2.0 Alpha 5 and CLI command:

/system-property=javax.net.ssl.trustStore:add(value="${jboss.server.config.dir}/stores/trustCA.jks")

Sadly it didnt went as expected:

<property name="javax.net.ssl.trustStore" value="/stores/trustCA.jks"/>

The jboss-cli.xml looks like this:

<?xml version='1.0' encoding='UTF-8'?>

<jboss-cli xmlns="urn:jboss:cli:2.0">

    <default-protocol use-legacy-override="true">http-remoting</default-protocol>

    <default-controller>
        <protocol>http-remoting</protocol>
        <host>localhost</host>
        <port>9990</port>
    </default-controller>

    <validate-operation-requests>true</validate-operation-requests>

    <history>
        <enabled>true</enabled>
        <file-name>.jboss-cli-history</file-name>
        <file-dir>${user.home}</file-dir>
        <max-size>500</max-size>
    </history>

    <resolve-parameter-values>false</resolve-parameter-values>

    <silent>false</silent>

    <access-control>false</access-control>
</jboss-cli>

I also tried using the variable like this and it still gets resolved:

${jboss.server.config.dir:}

Am I just using it wrong or can this possibly be a CLI or maven plugin error?


问:
How to run console command in yii2 from web
I have created a console command in console/controllers with SuggestionController .

If i run command like php yii suggestions, its working.

I want to know how to execute console command from web without any extensions of yii2.

答:
As of Yii2 - 2.0.11.2 advanced app -- this works

First let's make sure controller and namespace correct. In this case frontend app accessing console application import method()

In console\controllers\FhirController

Set the alias to be available in the console\config\main.php [OPTIONAL]

```<code>'aliases' => [
    '@common' => dirname(__DIR__),
    '@frontend' =>  dirname(dirname(__DIR__)) . '/frontend',
    '@backend' =>  dirname(dirname(__DIR__)) . '/backend',
    '@console' =>  dirname(dirname(__DIR__)) . '/console',
],
</code>```

Finally from the frontend view, make the call like this:
In this case, calling the controller route fhir then method import()

```<code>$consoleController = new console\controllers\FhirController('fhir', Yii::$app);
$consoleController->runAction('import');
</code>```

Body:
As of Yii2 - 2.0.11.2 advanced app -- this works

First let's make sure controller and namespace correct. In this case frontend app accessing console application import method()

In console\controllers\FhirController

Set the alias to be available in the console\config\main.php [OPTIONAL]

'aliases' => [
    '@common' => dirname(__DIR__),
    '@frontend' =>  dirname(dirname(__DIR__)) . '/frontend',
    '@backend' =>  dirname(dirname(__DIR__)) . '/backend',
    '@console' =>  dirname(dirname(__DIR__)) . '/console',
],

Finally from the frontend view, make the call like this:
In this case, calling the controller route fhir then method import()

$consoleController = new console\controllers\FhirController('fhir', Yii::$app);
$consoleController->runAction('import');


问:
Count of each unique element in a list
Say I have a list of countries

```<code>l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']
</code>```

and then I have a list of unique countries

```<code>ul = ['India', 'China', 'Japan', 'USA']
</code>```

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

```<code>Japan 1
China 2
India 2
USA   2
</code>```

答:
You can use Counter from collections:</p>

```<code>from collections import Counter

l = ["India", "China", "China", "Japan", "USA", "India", "USA"]

new_vals = Counter(l).most_common()
new_vals = new_vals[::-1] #this sorts the list in ascending order

for a, b in new_vals:
    print a, b
</code>```

Title: Count of each unique element in a list

Body:
Say I have a list of countries

l = ['India', 'China', 'China', 'Japan', 'USA', 'India', 'USA']

and then I have a list of unique countries

ul = ['India', 'China', 'Japan', 'USA']

I want to have a count of each unique country in the list in ascending order. So output should be as follows:

Japan 1
China 2
India 2
USA   2

Body:
You can use Counter from collections:

from collections import Counter

l = ["India", "China", "China", "Japan", "USA", "India", "USA"]

new_vals = Counter(l).most_common()
new_vals = new_vals[::-1] #this sorts the list in ascending order

for a, b in new_vals:
    print a, b


问:
Rename EKCalendar in iOS
How do I change the name of a calendar? I have:

```<code>EKCalendar *cal;

cal=[store calendarWithIdentifier:@"5F9A5BE0-03A9-4FE8-BD1E-2647F39E268F"];

cal.title = @"Calendar custom 2";
cal.source = localSource;
NSError *error = nil;
BOOL saved = [store saveCalendar:cal commit:YES error:&error];
NSLog(@"%d -> %@",saved,error);
</code>```

But this doesn't save, this print:

```<code>0 -> Error Domain=EKErrorDomain Code=15 "That calendar may not be moved to another account." UserInfo=0xb05c8a0 {NSLocalizedDescription=That calendar may not be moved to another account.}
</code>```

Someone could help me!!

答: I too faced the same problem. The issue is that, you should not be setting the source for existing calendar. EKSource should only be set while creating new calendar.</p>

Title: Rename EKCalendar in iOS

Body:
How do I change the name of a calendar? I have:

EKCalendar *cal;

cal=[store calendarWithIdentifier:@"5F9A5BE0-03A9-4FE8-BD1E-2647F39E268F"];

cal.title = @"Calendar custom 2";
cal.source = localSource;
NSError *error = nil;
BOOL saved = [store saveCalendar:cal commit:YES error:&error];
NSLog(@"%d -> %@",saved,error);

But this doesn't save, this print:

0 -> Error Domain=EKErrorDomain Code=15 "That calendar may not be moved to another account." UserInfo=0xb05c8a0 {NSLocalizedDescription=That calendar may not be moved to another account.}

Someone could help me!!


问:
how can i make a button on click move a div?
I created a div that I only want to be seen when a button is pressed to I positioned the div with a margin of -600 then when the button is pressed, it moves the div to margin: 0.

Here is the HTML for the div and button:

```<code><div id="mobile">
    <hr id="line">
    <ul id="listMobile">
        <li class="smallList"><span style="color:#ffe700">Home</span>
        </li>
        <li class="smallList">
            Gallery
        </li>
        <li class="smallList">
            Order Form
        </li>
        <li class="smallList">
            The Arena
        </li>
        <li class="smallList">
            Contact Us
        </li>
    </ul>

</div>

<button id="slideButton" onClick="toggleMenu();">
    <hr class="slider">
    <hr class="slider">
    <hr class="slider">
</button>
</code>```

Here is the JavaScript (I'm still a beginner with JavaScript so go easy on me):

```<code>function toggleMenu () {
    if (document.getElementById("mobile").style.left == "0px") {
        document.getElementById("mobile").style.left = "-630px";
    } else {
        document.getElementById("mobile").style.left = "0px";
    }
}
</code>```

Here is my CSS:

```<code>#mobile {
  margin:           0;
  margin-top:       0px;
  width:            250px;
  height:           1000px;
  background-color: #333333;
  margin-left:      -600px;
  position:         absolute;
  z-index:          -5;
}

.slider {
  border: none;
  background-color: white;
  height:           3px;
  width:            45px;
  margin-top:       10px;
  border-radius:    15px;
}

#slideButton {
  background-color: rgba(255, 255, 255, 0);
  border:           0;
  margin-top:       12px;
  margin-left:      15px;
  padding-right:    7px;
  padding-top:      7px;
  position:         fixed;
  border-radius:    5px;
  padding-left:     18px;
  visibility:       hidden;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100,100,100,0.1);
  transition:       ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display:        block;
  padding-top:    15px;
  padding-bottom: 15px;
  padding-left:   0px;
  font-size:      45px;
}
</code>```

Can anyone explain why this is not working? Thanks!

答:
You're using margin-left to move the element off screen, then altering left in your JS. You need to use one or the other.

function toggleMenu(){

  if(document.getElementById("mobile").style.left == "0px")
 {document.getElementById("mobile").style.left ="-630px"

}
 else{
 document.getElementById("mobile").style.left = "0px"
}
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mobile {
 margin: 0;
 margin-top: 0px;
 width: 250px;
 height: 1000px;
 background-color: #333333;
 left: -600px;
 position: absolute;
 z-index: -5;
 transition: left .5s;
}

.slider {
   border: none;
   background-color: white;
   height: 3px;
   width: 45px;
   margin-top: 10px;
   border-radius:15px;
}

#slideButton {
  border: 0;
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
   outline: none;
}

#slideButton:hover {
   background-color: rgba(100,100,100,0.1);
   transition: ease 0.6s;
}

#listMobile {
   margin-top: 100px;
}

.smallList {
   display: block;
   padding-top: 15px;
   padding-bottom: 15px;
   padding-left: 0px;
   font-size: 45px;
}</code>```

           Home

           Gallery

           Order Form

           The Arena

           Contact Us

      <button id="slideButton" onClick="toggleMenu()">
          asdf
       </button>```
</div>
</div>
</p>

<p>Or you can continue to use <code>margin-left</code> to hide the menu, then use <code>left</code> to show it, but you need to use a positive value for <code>left</code>, not a negative one, and set the initial state of the menu to <code>left: 0px</code> for your conditional to work on the first click.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function toggleMenu() {
  if (document.getElementById("mobile").style.left == "0px") {
    document.getElementById("mobile").style.left = "630px";
  } else {
    document.getElementById("mobile").style.left = "0px";
  }
} </code>```

#mobile {
 margin: 0;
 margin-top: 0px;
 width: 250px;
 height: 1000px;
 background-color: #333333;
 margin-left: -600px;
 position: absolute;
 z-index: -5;
 transition: left .5s;
}

.slider {
   border: none;
   background-color: white;
   height: 3px;
   width: 45px;
   margin-top: 10px;
   border-radius:15px;
}

#slideButton {
  border: 0;
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
   outline: none;
}

#slideButton:hover {
   background-color: rgba(100,100,100,0.1);
   transition: ease 0.6s;
}

#listMobile {
   margin-top: 100px;
}

.smallList {
   display: block;
   padding-top: 15px;
   padding-bottom: 15px;
   padding-left: 0px;
   font-size: 45px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mobile" style="left:0px">
  <hr id="line">
  <ul id="listMobile">
        <li class="smallList"><span style="color:#ffe700">
           Home</span>
        </li>
     <li class="smallList">
           Gallery
        </li>
     <li class="smallList">
           Order Form
        </li>
     <li class="smallList">
           The Arena
        </li>
     <li class="smallList">
           Contact Us
        </li>
  </ul>

    </div>

      <button id="slideButton" onClick="toggleMenu()">
          asdf
       </button></code>```

Body:
I created a div that I only want to be seen when a button is pressed to I positioned the div with a margin of -600 then when the button is pressed, it moves the div to margin: 0.

Here is the HTML for the div and button:

Home

            Gallery

            Order Form

            The Arena

            Contact Us

<button id="slideButton" onClick="toggleMenu();">

</button>

Here is the JavaScript (I'm still a beginner with JavaScript so go easy on me):

function toggleMenu () {
    if (document.getElementById("mobile").style.left == "0px") {
        document.getElementById("mobile").style.left = "-630px";
    } else {
        document.getElementById("mobile").style.left = "0px";
    }
}

Here is my CSS:

#mobile {
  margin:           0;
  margin-top:       0px;
  width:            250px;
  height:           1000px;
  background-color: #333333;
  margin-left:      -600px;
  position:         absolute;
  z-index:          -5;
}

.slider {
  border: none;
  background-color: white;
  height:           3px;
  width:            45px;
  margin-top:       10px;
  border-radius:    15px;
}

#slideButton {
  background-color: rgba(255, 255, 255, 0);
  border:           0;
  margin-top:       12px;
  margin-left:      15px;
  padding-right:    7px;
  padding-top:      7px;
  position:         fixed;
  border-radius:    5px;
  padding-left:     18px;
  visibility:       hidden;
}

#slideButton:focus {
  outline: none;
}

#slideButton:hover {
  background-color: rgba(100,100,100,0.1);
  transition:       ease 0.6s;
}

#listMobile {
  margin-top: 100px;
}

.smallList {
  display:        block;
  padding-top:    15px;
  padding-bottom: 15px;
  padding-left:   0px;
  font-size:      45px;
}

Can anyone explain why this is not working? Thanks!

Body:
You're using margin-left to move the element off screen, then altering left in your JS. You need to use one or the other.

function toggleMenu(){

  if(document.getElementById("mobile").style.left == "0px")
 {document.getElementById("mobile").style.left ="-630px"

}
 else{
 document.getElementById("mobile").style.left = "0px"
}
}

#mobile {
 margin: 0;
 margin-top: 0px;
 width: 250px;
 height: 1000px;
 background-color: #333333;
 left: -600px;
 position: absolute;
 z-index: -5;
 transition: left .5s;
}

.slider {
   border: none;
   background-color: white;
   height: 3px;
   width: 45px;
   margin-top: 10px;
   border-radius:15px;
}

#slideButton {
  border: 0;
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
   outline: none;
}

#slideButton:hover {
   background-color: rgba(100,100,100,0.1);
   transition: ease 0.6s;
}

#listMobile {
   margin-top: 100px;
}

.smallList {
   display: block;
   padding-top: 15px;
   padding-bottom: 15px;
   padding-left: 0px;
   font-size: 45px;
}

<div id="mobile">
  <hr id="line">
  <ul id="listMobile">
        <li class="smallList"><span style="color:#ffe700">
           Home</span>
        </li>
     <li class="smallList">
           Gallery
        </li>
     <li class="smallList">
           Order Form
        </li>
     <li class="smallList">
           The Arena
        </li>
     <li class="smallList">
           Contact Us
        </li>
  </ul>

    </div>

      <button id="slideButton" onClick="toggleMenu()">
          asdf
       </button>

Or you can continue to use margin-left to hide the menu, then use left to show it, but you need to use a positive value for left, not a negative one, and set the initial state of the menu to left: 0px for your conditional to work on the first click.

function toggleMenu() {
  if (document.getElementById("mobile").style.left == "0px") {
    document.getElementById("mobile").style.left = "630px";
  } else {
    document.getElementById("mobile").style.left = "0px";
  }
}

#mobile {
 margin: 0;
 margin-top: 0px;
 width: 250px;
 height: 1000px;
 background-color: #333333;
 margin-left: -600px;
 position: absolute;
 z-index: -5;
 transition: left .5s;
}

.slider {
   border: none;
   background-color: white;
   height: 3px;
   width: 45px;
   margin-top: 10px;
   border-radius:15px;
}

#slideButton {
  border: 0;
  margin-top: 12px;
  margin-left: 15px;
  padding-right: 7px;
  padding-top: 7px;
  position: fixed;
  border-radius: 5px;
  padding-left: 18px;
}

#slideButton:focus {
   outline: none;
}

#slideButton:hover {
   background-color: rgba(100,100,100,0.1);
   transition: ease 0.6s;
}

#listMobile {
   margin-top: 100px;
}

.smallList {
   display: block;
   padding-top: 15px;
   padding-bottom: 15px;
   padding-left: 0px;
   font-size: 45px;
}

<div id="mobile" style="left:0px">
  <hr id="line">
  <ul id="listMobile">
        <li class="smallList"><span style="color:#ffe700">
           Home</span>
        </li>
     <li class="smallList">
           Gallery
        </li>
     <li class="smallList">
           Order Form
        </li>
     <li class="smallList">
           The Arena
        </li>
     <li class="smallList">
           Contact Us
        </li>
  </ul>

    </div>

      <button id="slideButton" onClick="toggleMenu()">
          asdf
       </button>


问:
Straight line planar embedding of a graph structure
Here is my problem: I have a graph structure (with straight line edges) which I know to be planar (i.e. there exists an embedding of the graph where no edges cross). I need an algorithm which will take my graph and produce a straight line planar embedding of it. The algorithm does not need to be too efficient (an O(N^2) algorithm would do fine). Any ideas/suggestions?</p>

答:
you may want at graphviz ( http://www.graphviz.org/ ). This will be able to draw it in many different formats and a pretty simple input definition. Several algorithms can be used to create graphs.

otherwise, scheck out Boyer-Myrvold planarity algorithm and assorted c code from wikipedia: http://jgaa.info/accepted/2004/BoyerMyrvold2004.8.3/planarity.zip