问:
What data structure should I use in objC for key-value pair when the key is numeric?
I have sample data as follows

```<code>1 -> Apple
2 -> Banana
3 -> Cherries
4 -> Guava
5 -> Apple
..........
..........
</code>```

Now, I need to store this in a data structure in objective C. Like you can see, the keys are numeric and the values are NSString type. Typically would've used dictionary but in this case, I can't because the key is not a string.

I instead started to use NSMapTable. Only problem with NSMapTable is, there is no easy way to manipulate things such as, [NSDictionary allKeys] etc.

I did see something called as [Maptable keyEnumerator] but keyEnumerator doesn't look like it can be sorted. So I am running out of ideas on what is the best data structure to use in this situation. Any suggestion is welcome.

答:
If you use NSArray then you need to maintain the order of insertion, to use the index as key.

As NSMutableDictionary s are only designed to deal with objects, a simple way to do this is to wrap the integer or float in a NSNumber object.

```<code>NSMutableDictionary *testDictionary = [[NSMutableDictionary alloc] init];
[testDictionary setObject:@"Apple"
                   forKey:[NSNumber numberWithInt:1]];
NSLog(@"Test dictionary: %@", testDictionary);
</code>```

Body:
I have sample data as follows

1 -> Apple
2 -> Banana
3 -> Cherries
4 -> Guava
5 -> Apple
..........
..........

Now, I need to store this in a data structure in objective C. Like you can see, the keys are numeric and the values are NSString type. Typically would've used dictionary but in this case, I can't because the key is not a string.

I instead started to use NSMapTable. Only problem with NSMapTable is, there is no easy way to manipulate things such as, [NSDictionary allKeys] etc.

I did see something called as [Maptable keyEnumerator] but keyEnumerator doesn't look like it can be sorted. So I am running out of ideas on what is the best data structure to use in this situation. Any suggestion is welcome.

Body:
If you use NSArray then you need to maintain the order of insertion, to use the index as key.

As NSMutableDictionary s are only designed to deal with objects, a simple way to do this is to wrap the integer or float in a NSNumber object.

NSMutableDictionary *testDictionary = [[NSMutableDictionary alloc] init];
[testDictionary setObject:@"Apple"
                   forKey:[NSNumber numberWithInt:1]];
NSLog(@"Test dictionary: %@", testDictionary);


来源: stackexchange

问:
Combine two mysql queries with uneven columns
I have two mysql queries that I'd like to combine. I'm shame-posting here as I've tried many combinations to make it work but can't figure it out. I guess I've hit a ceiling in my query writing abilities. :(

Query #1

```<code>        SELECT
        time_clock.id AS clock_id,
        employees.first_name, employees.last_name, employees.nick_name, employees.pay_schedule, time_clock.comments,
        employees.id AS employee_id, time_clock.punch_in,
        UNIX_TIMESTAMP(time_clock.punch_in) AS punch_in_unix,
        UNIX_TIMESTAMP(time_clock.punch_out) AS punch_out_unix,
        TIMESTAMPDIFF(MINUTE, time_clock.punch_in, time_clock.punch_out) AS time_spent
        FROM time_clock
        JOIN employees ON employees.id = time_clock.employee_id
        WHERE time_clock.id IN
            (
            SELECT MAX(time_clock.id)
            FROM time_clock
            WHERE employees.pay_schedule='hourly'
            GROUP BY employee_id
            )
        ORDER BY last_name, first_name ASC
</code>```

Query #2

```<code>        SELECT
        employees.first_name, employees.last_name,
        employees.id AS employee_id,
        SUM(TIME_TO_SEC(time_clock.punch_out) - TIME_TO_SEC(time_clock.punch_in)) AS summed_seconds
        FROM time_clock
        JOIN employees ON employees.id = time_clock.employee_id
        WHERE YEAR(punch_in + interval 4 day) = YEAR(CURDATE()) AND
        WEEK(punch_in + interval 4 day) = WEEK(CURDATE())
        GROUP BY employee_id
</code>```

Each query functions fine on its own. The first query selects the latest time event for each employee. The second query sums the recorded time for each employee in the last pay period (weekly, from Wed. to Tues.).

I'd love to have one query do both: Select the latest time event for each employee and sum the time for those with time recorded in the last pay period. (I'm doing this to present an interface for keeping track of which employees are on overtime.)

Any help I can get would be fantastic. I've also been exploring combining the results as arrays in php to get what I want but that presents its own set of problems for me and I suspect isn't as efficient.

The output of Query #1 is like so:

The output of Query #2 looks like:

And this is essentially the output I'd like to be able to have:

Thank you for any help you can offer. My forehead is denting faster than the desk I'm banging it on.

-Matt

PS - One of my attempts to combine them is below. It seems to produce the most sane error out of all my attempts ("The used SELECT statements have a different number of columns"), so I don't know how close it really is.

```<code>SELECT
        time_clock.id AS clock_id,
        employees.first_name, employees.last_name, employees.nick_name, employees.pay_schedule, time_clock.comments,
        employees.id AS employee_id, time_clock.punch_in,
        UNIX_TIMESTAMP(time_clock.punch_in) AS punch_in_unix,
        UNIX_TIMESTAMP(time_clock.punch_out) AS punch_out_unix,
        TIMESTAMPDIFF(MINUTE, time_clock.punch_in, time_clock.punch_out) AS time_spent
        FROM (
            SELECT *
            FROM time_clock
            LEFT JOIN employees ON employees.id = time_clock.employee_id
            WHERE time_clock.id IN
                (
                SELECT MAX(time_clock.id)
                FROM time_clock
                WHERE employees.pay_schedule='hourly'
                GROUP BY employee_id
                )

            UNION ALL

            SELECT
                employees.first_name, employees.last_name,
                employees.id AS employee_id,
                SUM(TIME_TO_SEC(time_clock.punch_out) - TIME_TO_SEC(time_clock.punch_in)) AS summed_seconds
                FROM time_clock
                LEFT JOIN employees ON employees.id = time_clock.employee_id
                WHERE YEAR(punch_in + interval 4 day) = YEAR(CURDATE()) AND
                      WEEK(punch_in + interval 4 day) = WEEK(CURDATE())
                GROUP BY employee_id
                ) as thing_one
        JOIN employees ON employees.id = time_clock.employee_id
        ORDER BY last_name, first_name ASC
</code>```

答:
You could try</p>

```<code>SELECT     time_clock.id AS clock_id,
           employee_lastest_event.first_name,
           employee_lastest_event.last_name,
           employee_lastest_event.nick_name,
           employee_lastest_event.pay_schedule,
           time_clock.comments,
           time_clock.employee_id,
           time_clock.punch_in,
           UNIX_TIMESTAMP(time_clock.punch_in)                              AS punch_in_unix,
           UNIX_TIMESTAMP(time_clock.punch_out)                             AS punch_out_unix,
           TIMESTAMPDIFF(minute, time_clock.punch_in, time_clock.punch_out) AS time_spent,
           COALESCE(sum_period.summed_seconds, 0)                           AS summed_seconds
FROM       time_clock
           INNER JOIN
            (
              SELECT     time_clock.employee_id,
                         employees.first_name,
                         employees.last_name,
                         employees.nick_name,
                         employees.pay_schedule,
                         MAX(time_clock.id) AS clock_id
              FROM       time_clock
              INNER JOIN employees
              ON         employees.id = time_clock.employee_id
              WHERE      employees.pay_schedule='hourly'
              GROUP BY   time_clock.employee_id ) employee_lastest_event
           ON  (employee_lastest_event.clock_id = time_clock.id)
           LEFT JOIN
           (
              SELECT   time_clock.employee_id, Sum(time_to_sec(time_clock.punch_out) - time_to_sec(time_clock.punch_in)) AS summed_seconds
              FROM     time_clock
              WHERE    year(time_clock.punch_in + INTERVAL 4 day) = year(curdate())
              AND      week(time_clock.punch_in + INTERVAL 4 day) = week(curdate())
              GROUP BY time_clock.employee_id ) sum_period
            ON (sum_period.employee_id = time_clock.employee_id)
ORDER BY last_name, first_name ASC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two mysql queries that I'd like to combine. I'm shame-posting here as I've tried many combinations to make it work but can't figure it out. I guess I've hit a ceiling in my query writing abilities. :(

Query #1

        SELECT
        time_clock.id AS clock_id,
        employees.first_name, employees.last_name, employees.nick_name, employees.pay_schedule, time_clock.comments,
        employees.id AS employee_id, time_clock.punch_in,
        UNIX_TIMESTAMP(time_clock.punch_in) AS punch_in_unix,
        UNIX_TIMESTAMP(time_clock.punch_out) AS punch_out_unix,
        TIMESTAMPDIFF(MINUTE, time_clock.punch_in, time_clock.punch_out) AS time_spent
        FROM time_clock
        JOIN employees ON employees.id = time_clock.employee_id
        WHERE time_clock.id IN
            (
            SELECT MAX(time_clock.id)
            FROM time_clock
            WHERE employees.pay_schedule='hourly'
            GROUP BY employee_id
            )
        ORDER BY last_name, first_name ASC

Query #2

        SELECT
        employees.first_name, employees.last_name,
        employees.id AS employee_id,
        SUM(TIME_TO_SEC(time_clock.punch_out) - TIME_TO_SEC(time_clock.punch_in)) AS summed_seconds
        FROM time_clock
        JOIN employees ON employees.id = time_clock.employee_id
        WHERE YEAR(punch_in + interval 4 day) = YEAR(CURDATE()) AND
        WEEK(punch_in + interval 4 day) = WEEK(CURDATE())
        GROUP BY employee_id

Each query functions fine on its own. The first query selects the latest time event for each employee. The second query sums the recorded time for each employee in the last pay period (weekly, from Wed. to Tues.).

I'd love to have one query do both: Select the latest time event for each employee and sum the time for those with time recorded in the last pay period. (I'm doing this to present an interface for keeping track of which employees are on overtime.)

Any help I can get would be fantastic. I've also been exploring combining the results as arrays in php to get what I want but that presents its own set of problems for me and I suspect isn't as efficient.

The output of Query #1 is like so:

The output of Query #2 looks like:

And this is essentially the output I'd like to be able to have:

Thank you for any help you can offer. My forehead is denting faster than the desk I'm banging it on.

-Matt

PS - One of my attempts to combine them is below. It seems to produce the most sane error out of all my attempts ("The used SELECT statements have a different number of columns"), so I don't know how close it really is.

SELECT
        time_clock.id AS clock_id,
        employees.first_name, employees.last_name, employees.nick_name, employees.pay_schedule, time_clock.comments,
        employees.id AS employee_id, time_clock.punch_in,
        UNIX_TIMESTAMP(time_clock.punch_in) AS punch_in_unix,
        UNIX_TIMESTAMP(time_clock.punch_out) AS punch_out_unix,
        TIMESTAMPDIFF(MINUTE, time_clock.punch_in, time_clock.punch_out) AS time_spent
        FROM (
            SELECT *
            FROM time_clock
            LEFT JOIN employees ON employees.id = time_clock.employee_id
            WHERE time_clock.id IN
                (
                SELECT MAX(time_clock.id)
                FROM time_clock
                WHERE employees.pay_schedule='hourly'
                GROUP BY employee_id
                )

            UNION ALL

            SELECT
                employees.first_name, employees.last_name,
                employees.id AS employee_id,
                SUM(TIME_TO_SEC(time_clock.punch_out) - TIME_TO_SEC(time_clock.punch_in)) AS summed_seconds
                FROM time_clock
                LEFT JOIN employees ON employees.id = time_clock.employee_id
                WHERE YEAR(punch_in + interval 4 day) = YEAR(CURDATE()) AND
                      WEEK(punch_in + interval 4 day) = WEEK(CURDATE())
                GROUP BY employee_id
                ) as thing_one
        JOIN employees ON employees.id = time_clock.employee_id
        ORDER BY last_name, first_name ASC

Body:
You could try

SELECT     time_clock.id AS clock_id,
           employee_lastest_event.first_name,
           employee_lastest_event.last_name,
           employee_lastest_event.nick_name,
           employee_lastest_event.pay_schedule,
           time_clock.comments,
           time_clock.employee_id,
           time_clock.punch_in,
           UNIX_TIMESTAMP(time_clock.punch_in)                              AS punch_in_unix,
           UNIX_TIMESTAMP(time_clock.punch_out)                             AS punch_out_unix,
           TIMESTAMPDIFF(minute, time_clock.punch_in, time_clock.punch_out) AS time_spent,
           COALESCE(sum_period.summed_seconds, 0)                           AS summed_seconds
FROM       time_clock
           INNER JOIN
            (
              SELECT     time_clock.employee_id,
                         employees.first_name,
                         employees.last_name,
                         employees.nick_name,
                         employees.pay_schedule,
                         MAX(time_clock.id) AS clock_id
              FROM       time_clock
              INNER JOIN employees
              ON         employees.id = time_clock.employee_id
              WHERE      employees.pay_schedule='hourly'
              GROUP BY   time_clock.employee_id ) employee_lastest_event
           ON  (employee_lastest_event.clock_id = time_clock.id)
           LEFT JOIN
           (
              SELECT   time_clock.employee_id, Sum(time_to_sec(time_clock.punch_out) - time_to_sec(time_clock.punch_in)) AS summed_seconds
              FROM     time_clock
              WHERE    year(time_clock.punch_in + INTERVAL 4 day) = year(curdate())
              AND      week(time_clock.punch_in + INTERVAL 4 day) = week(curdate())
              GROUP BY time_clock.employee_id ) sum_period
            ON (sum_period.employee_id = time_clock.employee_id)
ORDER BY last_name, first_name ASC


问:
I want to upload a video using spring controller. Can you provide me the steps
How to call a spring controller for video upload. Common multifile is not working . i have given enctype="multipart/form-data">

```<code>@Transactional(readOnly = false)
@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
        @RequestParam("fileUpload") CommonsMultipartFile[] fileUpload) throws Exception {}

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="10000000"/>
</bean>
<div align="center">
    <h1>Operation File upload</h1>
    <form method="post" action="doUpload" enctype="multipart/form-data">
        <table border="0">
            <tr>
            <td>Name: <input type="text" name="name"></td>
                <td>Pick file #1:</td>
                <td><input type="file" name="fileUpload" size="50" /></td>
            </tr>
            <tr>
                <td>Pick file #2:</td>
                <td><input type="file" name="fileUpload" size="50" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Upload" /></td>
            </tr>
        </table>
    </form>
</div>
</code>```

答:
Your CommonsMultipartResolver is configured to accept max round about 10MB (10.000.000 Byte) but you tried it with an round about 20MB file.

So increase the upload limit

```<code><bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

      <!-- one of the properties available; the maximum file size in bytes: 50.000.000 are almost 50MB-->
      <property name="maxUploadSize" value="50000000"/>
</bean>
</code>```

Body:
How to call a spring controller for video upload. Common multifile is not working . i have given enctype="multipart/form-data">

@Transactional(readOnly = false)
@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
        @RequestParam("fileUpload") CommonsMultipartFile[] fileUpload) throws Exception {}

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize" value="10000000"/>
</bean>

Operation File upload

    <form method="post" action="doUpload" enctype="multipart/form-data">

            Name: <input type="text" name="name">
                Pick file #1:
                <input type="file" name="fileUpload" size="50" />

                Pick file #2:
                <input type="file" name="fileUpload" size="50" />

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

    </form>

Body:
Your CommonsMultipartResolver is configured to accept max round about 10MB (10.000.000 Byte) but you tried it with an round about 20MB file.

So increase the upload limit

<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

      <!-- one of the properties available; the maximum file size in bytes: 50.000.000 are almost 50MB-->
      <property name="maxUploadSize" value="50000000"/>
</bean>


问:
What is the most efficient way to represent the infinite tape of a Turing machine in Python?
A Turing machine manipulates symbols on an infinite strip of tape according to a table of rules.

In my case entries on the tape can be either 0's and 1's (binary).

The tape starts off 'empty' with an infinity of 0's in both positive and negative directions. This tape gets written on based on the rules that the machine follows, potentially adding 0's or 1's to the unwritten edges.

Since the tape values are binary is there a most efficient way to represent them in memory as the machine writes to the tape, adding new values to the left or right?  Obviously I don't need to represent the infinite zeros (unwritten tape), but I do need to expand the data structure as new values are added to the ends of the tape.

A python list could do the trick, shown here inserting a 1 on the left:

```<code>start_time = time.time()
tape = [0]*10000000
print tape[:10]
insertion_time = time.time()
tape = [1] + tape
print tape[:10]
print "total execution time: ", time.time() - start_time
print "time to add entry: ", time.time() - insertion_time
</code>```

this outputs:

```<code>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
total execution time:  0.257364034653
time to add entry:  0.109524011612
</code>```

Using list.insert does make it 23x faster:

```<code>start_time = time.time()
tape = [0]*100000
print tape[:10]
insertion_time = time.time()
tape.insert(0, [1])
print tape[:10]
print "execution time: ", time.time() - start_time
print "time to add entry: ", time.time() - insertion_time
</code>```

giving:

```<code>[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[[1], 0, 0, 0, 0, 0, 0, 0, 0, 0]
execution time:  0.0270080566406
time to add entry:  0.00468802452087
</code>```

Is there a more efficient way to represent the binary tape than using a list object?

答:
Given that the tape is infinite at both ends, you will have to consider the (-inf, -1] range of indices too. The best representation, IMO, would be a pair of lists - one for the non-negative range and the other for the negative range (with indexing reversed). As you move beyond the allocated range of the tape, you will simply have to append to the respective list (which, unlike prepending to a list, is a fast operation).

A draft implementation (using an enhanced version of GrowingList from this answer):

```<code>class GrowingList(list):
    def __init__(self, default_value):
        self.default_value=default_value

    def __getitem__(self, i):
        return list.__getitem__(i) if i < len(self) else self.default_value

    def __setitem__(self, i, v):
        if i >= len(self):
            self.extend([self.default_value]*(i + 1 - len(self)))
        list.__setitem__(self, i, v)

class Tape:
    def __init__(self):
        self.pos_range=GrowingList(0)
        self.neg_range=GrowingList(0)

    def __getitem__(self, i):
        if i >= 0:
            return self.pos_range[i]
        else:
            return self.neg_range[-i-1]

    def __setitem__(self, i, v):
        if i >= 0:
            self.pos_range[i]=v
        else:
            self.neg_range[-i-1]=v

    def __repr__(self):
        start = -len(self.neg_range)
        end = len(self.pos_range)
        data = list(reversed(self.neg_range)) + self.pos_range
        return "Tape(range=[{}, {}), data={})".format(start, end, data)

t = Tape()
print(t)
t[4]=1
print(t)
t[-2]=1
print(t)
</code>```

Output:

```<code>Tape(range=[0, 0), data=[])
Tape(range=[0, 5), data=[0, 0, 0, 0, 1])
Tape(range=[-2, 5), data=[1, 0, 0, 0, 0, 0, 1])
</code>```

Body:
A Turing machine manipulates symbols on an infinite strip of tape according to a table of rules.

In my case entries on the tape can be either 0's and 1's (binary).

The tape starts off 'empty' with an infinity of 0's in both positive and negative directions. This tape gets written on based on the rules that the machine follows, potentially adding 0's or 1's to the unwritten edges.

Since the tape values are binary is there a most efficient way to represent them in memory as the machine writes to the tape, adding new values to the left or right?  Obviously I don't need to represent the infinite zeros (unwritten tape), but I do need to expand the data structure as new values are added to the ends of the tape.

A python list could do the trick, shown here inserting a 1 on the left:

start_time = time.time()
tape = [0]*10000000
print tape[:10]
insertion_time = time.time()
tape = [1] + tape
print tape[:10]
print "total execution time: ", time.time() - start_time
print "time to add entry: ", time.time() - insertion_time

this outputs:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
total execution time:  0.257364034653
time to add entry:  0.109524011612

Using list.insert does make it 23x faster:

start_time = time.time()
tape = [0]*100000
print tape[:10]
insertion_time = time.time()
tape.insert(0, [1])
print tape[:10]
print "execution time: ", time.time() - start_time
print "time to add entry: ", time.time() - insertion_time

giving:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[[1], 0, 0, 0, 0, 0, 0, 0, 0, 0]
execution time:  0.0270080566406
time to add entry:  0.00468802452087

Is there a more efficient way to represent the binary tape than using a list object?

Body:
Given that the tape is infinite at both ends, you will have to consider the (-inf, -1] range of indices too. The best representation, IMO, would be a pair of lists - one for the non-negative range and the other for the negative range (with indexing reversed). As you move beyond the allocated range of the tape, you will simply have to append to the respective list (which, unlike prepending to a list, is a fast operation).

A draft implementation (using an enhanced version of GrowingList from this answer):

class GrowingList(list):
    def __init__(self, default_value):
        self.default_value=default_value

    def __getitem__(self, i):
        return list.__getitem__(i) if i < len(self) else self.default_value

    def __setitem__(self, i, v):
        if i >= len(self):
            self.extend([self.default_value]*(i + 1 - len(self)))
        list.__setitem__(self, i, v)

class Tape:
    def __init__(self):
        self.pos_range=GrowingList(0)
        self.neg_range=GrowingList(0)

    def __getitem__(self, i):
        if i >= 0:
            return self.pos_range[i]
        else:
            return self.neg_range[-i-1]

    def __setitem__(self, i, v):
        if i >= 0:
            self.pos_range[i]=v
        else:
            self.neg_range[-i-1]=v

    def __repr__(self):
        start = -len(self.neg_range)
        end = len(self.pos_range)
        data = list(reversed(self.neg_range)) + self.pos_range
        return "Tape(range=[{}, {}), data={})".format(start, end, data)

t = Tape()
print(t)
t[4]=1
print(t)
t[-2]=1
print(t)

Output:

Tape(range=[0, 0), data=[])
Tape(range=[0, 5), data=[0, 0, 0, 0, 1])
Tape(range=[-2, 5), data=[1, 0, 0, 0, 0, 0, 1])


问:
Why collapsing toolbar title is under toolbar?
My activity design like below:

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/movie_detail_appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/movie_detail_collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/movie_detail_header_image"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#99000026"
            android:fitsSystemWindows="true"
            android:orientation="horizontal"
            android:weightSum="10">

            <ImageView
                android:id="@+id/detail_movie_poster"
                android:layout_width="90dp"
                android:layout_height="110dp"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:scaleType="centerInside"
                android:src="@drawable/no_movie_image" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="9"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/detail_movie_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="marquee"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:marqueeRepeatLimit="marquee_forever"
                    android:singleLine="true"
                    android:textColor="@android:color/white"
                    android:textSize="26sp" />

                <TextView
                    android:id="@+id/detail_movie_original_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="16sp" />

                <TextView
                    android:id="@+id/detail_movie_genres"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:singleLine="true"
                    android:textSize="14sp" />

            </LinearLayout>

        </LinearLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/movie_detail_toolbar"
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.ActionBar" />

    </android.support.design.widget.CollapsingToolbarLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/movie_detail_tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:tabIndicatorColor="@android:color/white"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/movie_detail_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

But design happened like that. Collapsing toolbar title is under the toolbar.

Also I used this initCollapsingToolbar() for dynamically collapsing toolbar title :

```<code>private void initCollapsingToolbar() {
    final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);

// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    boolean isShow = false;
    int scrollRange = -1;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (scrollRange == -1) {
            scrollRange = appBarLayout.getTotalScrollRange();
        }
        if (scrollRange + verticalOffset == 0) {
            Results results = intent.getParcelableExtra(Constant.PARCELABLE_MOVIE_TITLE);
                collapsingToolbarLayout.setTitle(results.getTitle());
            isShow = true;
        } else if (isShow) {
            collapsingToolbar.setTitle(" ");
            isShow = false;
        }
       }
    });
}
</code>```

答: this seems to be a bug only in emulator, real device is ok.</p>

Body:
My activity design like below:

<android.support.design.widget.AppBarLayout
    android:id="@+id/movie_detail_appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/movie_detail_collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/movie_detail_header_image"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            app:layout_collapseMode="parallax" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#99000026"
            android:fitsSystemWindows="true"
            android:orientation="horizontal"
            android:weightSum="10">

            <ImageView
                android:id="@+id/detail_movie_poster"
                android:layout_width="90dp"
                android:layout_height="110dp"
                android:layout_margin="10dp"
                android:layout_weight="1"
                android:scaleType="centerInside"
                android:src="@drawable/no_movie_image" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="9"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/detail_movie_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="marquee"
                    android:focusable="true"
                    android:focusableInTouchMode="true"
                    android:marqueeRepeatLimit="marquee_forever"
                    android:singleLine="true"
                    android:textColor="@android:color/white"
                    android:textSize="26sp" />

                <TextView
                    android:id="@+id/detail_movie_original_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="16sp" />

                <TextView
                    android:id="@+id/detail_movie_genres"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:singleLine="true"
                    android:textSize="14sp" />

            </LinearLayout>

        </LinearLayout>

        <android.support.v7.widget.Toolbar
            android:id="@+id/movie_detail_toolbar"
            android:layout_width="match_parent"
            android:layout_height="65dp"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="pin"
            app:popupTheme="@style/ThemeOverlay.AppCompat.ActionBar" />

    </android.support.design.widget.CollapsingToolbarLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/movie_detail_tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:tabIndicatorColor="@android:color/white"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/movie_detail_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

But design happened like that. Collapsing toolbar title is under the toolbar.

Also I used this initCollapsingToolbar() for dynamically collapsing toolbar title :

private void initCollapsingToolbar() {
    final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);

// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    boolean isShow = false;
    int scrollRange = -1;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (scrollRange == -1) {
            scrollRange = appBarLayout.getTotalScrollRange();
        }
        if (scrollRange + verticalOffset == 0) {
            Results results = intent.getParcelableExtra(Constant.PARCELABLE_MOVIE_TITLE);
                collapsingToolbarLayout.setTitle(results.getTitle());
            isShow = true;
        } else if (isShow) {
            collapsingToolbar.setTitle(" ");
            isShow = false;
        }
       }
    });
}


问:
How to get job from ms sql server realtime?
I have application on client for get job info form sql server via ODBC.

code for connection :

```<code> string sqlJobQuery = "select j.job_id, j.name, j.enabled, jh.run_status, jh.message, jh.run_date, jh.step_name, jh.run_time from sysjobs j inner join sysjobhistory jh on j.job_id = jh.job_id";

       // create SQL connection and set up SQL Command for query
       using (SqlConnection _con = new SqlConnection("server=10.15.13.70;database=msdb;user id=sa;pwd="))
       using (SqlCommand _cmd = new SqlCommand(sqlJobQuery, _con))
</code>```

Is it possible if I use timer to get job info every 1s and show job info on listview.
*i want everything is realtime *

how to do?
please..

答:
If you need to check the status of a job every second, your application logic is wrong and I would strongly suggest that you consider other possible options.

Could you post more info about what are you trying to achieve? There might be a better solution than job.

ContentLicense: CC BY-SA 2.5

Body:
I have application on client for get job info form sql server via ODBC.

code for connection :

 string sqlJobQuery = "select j.job_id, j.name, j.enabled, jh.run_status, jh.message, jh.run_date, jh.step_name, jh.run_time from sysjobs j inner join sysjobhistory jh on j.job_id = jh.job_id";

       // create SQL connection and set up SQL Command for query
       using (SqlConnection _con = new SqlConnection("server=10.15.13.70;database=msdb;user id=sa;pwd="))
       using (SqlCommand _cmd = new SqlCommand(sqlJobQuery, _con))

Is it possible if I use timer to get job info every 1s and show job info on listview.
*i want everything is realtime *

how to do?
please..


问:
How to get all result if unwind field does not exist in mongodb
i am trying to fetch data from collection form below query:

```<code>     db.getCollection('jobs').aggregate(
    {$match :{"slug":"bath-room-designer-for-whole-floor-772000"}},
    {$unwind: "$job_activity"},
    {$lookup: {
            "from":"users",
            "localField":"job_activity.user_id",
            "foreignField":"_id",
            "as": "user_details"
        }
    },
    {$unwind: { path: "$user_details", preserveNullAndEmptyArrays: false } },
    {$group: {
                "_id": "$_id",
                "Job_detail": {"$push": "$job_activity"},
                "job_activity": {"$push": "$job_activity"},
                "user_details": {"$push": "$user_details"}
            }
    }

)
</code>```

But it result empty data wherever datat exists in the collection for the $match but job_activity is not exist for this slug

can anyone help
Thanks

答:
use the preserveNullAndEmptyArrays of $unwind to keep documents where job_activity doesn't exist or is empty

so use this $unwind stage:

```<code>{
  $unwind:
    {
      path: "$job_activity",
      preserveNullAndEmptyArrays: true
    }
}
</code>```

Body:
i am trying to fetch data from collection form below query:

     db.getCollection('jobs').aggregate(
    {$match :{"slug":"bath-room-designer-for-whole-floor-772000"}},
    {$unwind: "$job_activity"},
    {$lookup: {
            "from":"users",
            "localField":"job_activity.user_id",
            "foreignField":"_id",
            "as": "user_details"
        }
    },
    {$unwind: { path: "$user_details", preserveNullAndEmptyArrays: false } },
    {$group: {
                "_id": "$_id",
                "Job_detail": {"$push": "$job_activity"},
                "job_activity": {"$push": "$job_activity"},
                "user_details": {"$push": "$user_details"}
            }
    }

)

But it result empty data wherever datat exists in the collection for the $match but job_activity is not exist for this slug

can anyone help
Thanks

Body:
use the preserveNullAndEmptyArrays of $unwind to keep documents where job_activity doesn't exist or is empty

so use this $unwind stage:

{
  $unwind:
    {
      path: "$job_activity",
      preserveNullAndEmptyArrays: true
    }
}


问:
Retrieving a element with multiple xpaths
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

```<code>.//*[@id='password']
</code>```

I was wondering if anyone could point me to the right direct when  dealing with something like this.

答:
Let me try to answer your queries one by one:

error when I tried to find the password field : This is because the property which you have mentioned id/name/css/xpath was incorrect.

ElementNotVisibleException : I doubt it was for the password_field at all. Reason behind that is, normally login field & password field stays on the same container. Either those resides on the HTML DOM (which gets loaded completely once the page loading is complete) or they may reside within a frame/iFrame (there are other measures to handle them which I am not covering here). But those 2 elements stays on the same container. So if you have found out the login_field element, password_field is just a step away.

inspected the xpath with Firebug and noticed that it returned two results : That's because the xpath which you are using doesnot identifies an unique element. There can be multiple elements on the HTML DOM with the same id attribute set to "password". But definitely the xpathof those elements will be different and unique.

What you should do?

I will suggest you the following:

a. Try to identify each element on a webpage following the attributes in sequence: id, name, visibleText, css, xpath.

b. Try to identify a unique logical xpath for elements using the other properties of the elements defined within the HTML tag. Cross check your xpath through Firebug/Firepath. There are some other handy xpath checker available too. Take help of those.

Let me know if this answers your question.

Body:
This isn't much of a coding question but one about what options should I take next. I've just started using selenium about a week ago and started to get the hang of most of its function.

I was working on a work project to login into various websites until I ran into a issue where I was getting this error when I tried to find the password field

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible

I went ahead and double checked the name & id  but I couldn't find the field using locators like .id, name, and xpath. I inspected the xpath with Firebug and noticed that it returned two results instead of one.

Current Xpath looks like this

.//*[@id='password']

I was wondering if anyone could point me to the right direct when  dealing with something like this.


问:
Choosing the closest authority match for a multi-tenant app
We have a multi-tenant app which has been passing in "login.windows.net/common" when creating a new AuthenticationContext.  We missed the memo a while back that this had been deprecated in favor of "login.microsoftonline.com/common".  The impetus for switching now is that we have customers for whom that also won't work (e.g. because they're behind "login.microsoftonline.de").

We understand the correct approach is to first query "login.microsoftonline.com/tenant-domain-name/.well-known/openid-configuration", and use the endpoints we get back, instead of hardcoding login.microsoftonline.com.  What we're wondering is which of the fields we get back should be used.

I haven’t been able to find an authoritative (no pun intended) source for what the authority string should be.  Some places I’ve checked:

The documentation for AuthenticationContext says authority is, “Address of the authority to issue token.”

The developer’s guide for integrating AAD with Windows Store apps references creating AuthenticationContext with an authority, doesn’t say what authority should be.

The sample code for a Windows Store app uses "login.microsoftonline.com/tenant".

The AAD docs say for multi-tenant apps, use "login.microsoftonline.com/common".

Other answers here on StackOverflow have ranged covered those, specific paths (like "/oauth2/token"), etc.

So, after we query the discovery service, what do we then use for authority?

authorization_endpoint?

token_endpoint?

map tenant_region_scope to the right login.microsoftonline.com variation, and append "/common"? or "/tenant"?

Thank you.

答:
To sign-in for the multi-tenant app, we need to use the https://login.microsoftonline.com/common. Here is explanation from the document for your reference:

When a response returns from the /common endpoint, the issuer value in the token will correspond to the user’s tenant. It’s important to note the /common endpoint is not a tenant and is not an issuer, it’s just a multiplexer. When using /common, the logic in your application to validate tokens needs to be updated to take this into account.

So we need to use the common in the authorization endpoint. After that, we can get the real tenant and use the specific tenant in the token endpoint.

map tenant_region_scope to the right login.microsoftonline.com variation, and append "/common"? or "/tenant"?

What did you meant the tenant_region_scope? Based on my understanding, the scope for the multi-tenant app is same as the single tenant app. For example, the Microsoft Graph is an multi-tenant app and the scope of it you can refer here.

Below is an helpful article and code sample about multi-tenant app developing:

How to sign in any Azure Active Directory (AD) user using the multi-tenant application pattern

Build a multi-tenant SaaS web application that calls a web API using Azure AD


问:
How do I delete by ID in SQLite?
I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!

Here's my code:

```<code>public class TaskDbHelper extends SQLiteOpenHelper {

    public TaskDbHelper(Context context) {
        super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
                TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
                TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
        sqLiteDatabase.execSQL(createTable);
    }
}
</code>```

Activity where tasks are shown

```<code>public class ShowTaskActivity extends AppCompatActivity {

    private TaskDbHelper mHelper;
    private ListView mTaskListView;
    private ArrayAdapter<String> mAdapter;

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

        mHelper = new TaskDbHelper(this);
        mTaskListView = (ListView) findViewById(R.id.list_todo);

        updateUI();
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
        SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
        Cursor cursor = sqLiteDatabase.query(
                TaskContract.TaskEntry.TABLE,  // Name of the table to be queried
                new String[]{  // Which columns are returned
                        TaskContract.TaskEntry._ID,
                        TaskContract.TaskEntry.COL_TASK_TITLE,
                        TaskContract.TaskEntry.COL_TASK_DATE},
                null, null, null, null, null);
        while (cursor.moveToNext()) {
            int index =     cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
            taskList.add(cursor.getString(index));
        }

        if (mAdapter == null) {
            mAdapter = new ArrayAdapter<>(this,
                    task, // What view to use for the items
                    R.id.task_title, // Where to put the string of data
                    taskList); // Where to get the data
            mTaskListView.setAdapter(mAdapter);
        } else {
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        sqLiteDatabase.close();
    }

    // TODO: Change to delete by ID, not name
    public void deleteTask(View view) {
        View parent = (View) view.getParent();
        TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
        String task = taskTextView.getText().toString();
        SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
        sqLiteDatabase.delete(
            TaskContract.TaskEntry.TABLE,  // Where to delete
            TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",  // Boolean check
            new String[]{task});  // What to delete
        sqLiteDatabase.close();
        updateUI();
    }
}
</code>```

Task adding Code

```<code>public void addTask(String task, String date) {
    SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
    contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
    sqLiteDatabase.insertWithOnConflict(
            TaskContract.TaskEntry.TABLE,
            null,
            contentValues,
            SQLiteDatabase.CONFLICT_REPLACE);
    sqLiteDatabase.close();
}
</code>```

答:
You can try this method to delete By id </p>

```<code>  public void deleteData(String tableName, Integer id) {

    try {
        if (mWritableDB != null) {
            mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
        }
    } catch (Exception _exception) {
        _exception.printStackTrace();
    }
}
</code>```

Title: How do I delete by ID in SQLite?

Body:
I am quite new Android Development and figured I should start by trying to create a simple ToDo List App using SQLite. I have all of the basic functionality in place: adding, updating, and deleting tasks. However, I am adding, updating, and deleting by the title of the task, rather than by the ID. This creates problems with duplicate tasks (e.g. tasks of the same name are deleted simultaneously). After much internet search, I still cannot find a way to do this. I would appreciate any help offered!

Here's my code:

public class TaskDbHelper extends SQLiteOpenHelper {

    public TaskDbHelper(Context context) {
        super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " +
                TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL, " +
                TaskContract.TaskEntry.COL_TASK_DATE + " DATE);";
        sqLiteDatabase.execSQL(createTable);
    }
}

Activity where tasks are shown

public class ShowTaskActivity extends AppCompatActivity {

    private TaskDbHelper mHelper;
    private ListView mTaskListView;
    private ArrayAdapter<String> mAdapter;

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

        mHelper = new TaskDbHelper(this);
        mTaskListView = (ListView) findViewById(R.id.list_todo);

        updateUI();
    }

    private void updateUI() {
        ArrayList<String> taskList = new ArrayList<>();
        SQLiteDatabase sqLiteDatabase = mHelper.getReadableDatabase();
        Cursor cursor = sqLiteDatabase.query(
                TaskContract.TaskEntry.TABLE,  // Name of the table to be queried
                new String[]{  // Which columns are returned
                        TaskContract.TaskEntry._ID,
                        TaskContract.TaskEntry.COL_TASK_TITLE,
                        TaskContract.TaskEntry.COL_TASK_DATE},
                null, null, null, null, null);
        while (cursor.moveToNext()) {
            int index =     cursor.getColumnIndex(TaskContract.TaskEntry.COL_TASK_TITLE);
            taskList.add(cursor.getString(index));
        }

        if (mAdapter == null) {
            mAdapter = new ArrayAdapter<>(this,
                    task, // What view to use for the items
                    R.id.task_title, // Where to put the string of data
                    taskList); // Where to get the data
            mTaskListView.setAdapter(mAdapter);
        } else {
            mAdapter.clear();
            mAdapter.addAll(taskList);
            mAdapter.notifyDataSetChanged();
        }

        cursor.close();
        sqLiteDatabase.close();
    }

    // TODO: Change to delete by ID, not name
    public void deleteTask(View view) {
        View parent = (View) view.getParent();
        TextView taskTextView = (TextView) parent.findViewById(R.id.task_title);
        String task = taskTextView.getText().toString();
        SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
        sqLiteDatabase.delete(
            TaskContract.TaskEntry.TABLE,  // Where to delete
            TaskContract.TaskEntry.COL_TASK_TITLE + " = ?",  // Boolean check
            new String[]{task});  // What to delete
        sqLiteDatabase.close();
        updateUI();
    }
}

Task adding Code

public void addTask(String task, String date) {
    SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
    contentValues.put(TaskContract.TaskEntry.COL_TASK_DATE, date);
    sqLiteDatabase.insertWithOnConflict(
            TaskContract.TaskEntry.TABLE,
            null,
            contentValues,
            SQLiteDatabase.CONFLICT_REPLACE);
    sqLiteDatabase.close();
}

Body:
You can try this method to delete By id

  public void deleteData(String tableName, Integer id) {

    try {
        if (mWritableDB != null) {
            mWritableDB.execSQL("delete from " + tableName + " Where id = " + id);
        }
    } catch (Exception _exception) {
        _exception.printStackTrace();
    }
}


问:
Solving exponential equations in python
I made a function that converts letters into numbers (a=1,b=2,etc...) Then I do this equation on them:

```<code>b^(a / (b/2))
b = letter being translated
a = previous letter (or if b is the first letter, a = len(string)
</code>```

for example, here is how you would translate the letter 'e':

```<code>'Hello' = [34, 5, 12, 12, 15]
5^(34 / (5/2)) = 3206210698.73506
</code>```

Here is the code I used to do this:

```<code>alphabet = {
'H' : 34,
'e' : 5,
'l' : 12,
'o' : 15,
}
entry = "Hello"
password = []
hashed = []
firstNumber = True
lengthPower = len(entry)
counter = 0

for letter in entry:

    key = alphabet[letter]
    password.append(key)

for number in password:
    if firstNumber:
        powered = number ** lengthPower
        lastNumber = number
        firstNumber = False
    else:
        powered = number ** (password[counter]/(number/2))
        lastNumber = number
        counter += 1
    hashed.append(powered)
</code>```

But how can I reverse this operation?  '3206210698.73506' back into 5 ('e')?

```<code>b^(34 / (b/2)) = 3206210698.73506
</code>```

答:
When y = x ^ n, x = y ^ (1/n). See this or google 'inverse of power'. So in your case, this will guide you.

```<code>n = 34/(5/2)
y = pow(5, n)  # 3206210698.7350655
x = int(pow(y, 1/n))  # 5
</code>```

Title: Solving exponential equations in python

Body:
I made a function that converts letters into numbers (a=1,b=2,etc...) Then I do this equation on them:

b^(a / (b/2))
b = letter being translated
a = previous letter (or if b is the first letter, a = len(string)

for example, here is how you would translate the letter 'e':

'Hello' = [34, 5, 12, 12, 15]
5^(34 / (5/2)) = 3206210698.73506

Here is the code I used to do this:

alphabet = {
'H' : 34,
'e' : 5,
'l' : 12,
'o' : 15,
}
entry = "Hello"
password = []
hashed = []
firstNumber = True
lengthPower = len(entry)
counter = 0

for letter in entry:

    key = alphabet[letter]
    password.append(key)

for number in password:
    if firstNumber:
        powered = number ** lengthPower
        lastNumber = number
        firstNumber = False
    else:
        powered = number ** (password[counter]/(number/2))
        lastNumber = number
        counter += 1
    hashed.append(powered)

But how can I reverse this operation?  '3206210698.73506' back into 5 ('e')?

b^(34 / (b/2)) = 3206210698.73506

Body:
When y = x ^ n, x = y ^ (1/n). See this or google 'inverse of power'. So in your case, this will guide you.

n = 34/(5/2)
y = pow(5, n)  # 3206210698.7350655
x = int(pow(y, 1/n))  # 5


问:
Replace consecutive repeated characters with one - Column-wise operation - `pandas.DataFrame`
How do I remove repeated characters in string and just leave one of them.

e.g:-

```<code>"Bertuggggg Mete"
</code>```

to

```<code>"Bertug Mete"
</code>```

I've just read data like this:

```<code>dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")
</code>```

Name
0 Bertuggggg Mete

Input is read from .xlsx file. I have tried split and strip functions but they don't work seem to work as expected.

How I can solve this problem ?

答:
Check this out:

Replace column_name with whatever is the column name you want to apply the replacement.

```<code>min_threshold_rep = 2
column_name = 'Name'
dataframe[column_name]= dataframe[column_name].str.replace(r'(\w)\1{%d,}'%(min_threshold_rep-1), r'\1')
</code>```

NOTE: this would replace every min_threshold_rep number of consecutive character with one character.

Body:
How do I remove repeated characters in string and just leave one of them.

e.g:-

"Bertuggggg Mete"

to

"Bertug Mete"

I've just read data like this:

dataFrame = pd.read_excel("C:\\Users\\Bertug\\Desktop\\example.xlsx")

Name
0 Bertuggggg Mete

Input is read from .xlsx file. I have tried split and strip functions but they don't work seem to work as expected.

How I can solve this problem ?

Body:
Check this out:

Replace column_name with whatever is the column name you want to apply the replacement.

min_threshold_rep = 2
column_name = 'Name'
dataframe[column_name]= dataframe[column_name].str.replace(r'(\w)\1{%d,}'%(min_threshold_rep-1), r'\1')

NOTE: this would replace every min_threshold_rep number of consecutive character with one character.


问:
Getting command line options
I want to parse the command line options having specific format for getting the values. The function is as follows

```<code>char* getCmdOption(char** begin,
                    char** end,
                    const std::string& option)
{
   char** itr = std::find(begin, end, option);

  if (itr != end && ++itr != end)
  {
        return *itr;
  }
  return (char*)"";
}
</code>```

The arguments passed are getCmdOption(argv, argv+argc, "--optionName")
The code works fine for all the options and gives proper output but if I want to give values such as Application.exe --optionName surname="O Kief" the code should return me surname="O Kief" but instead it returns "surname=O Keif"

The format for input is Application.exe --optionName optionValue and expected output is "optionValue"

What is possibly wrong with the logic ? And how can i handle the case I have mentioned ?

答:
""is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument. Sadly, however, not only are the enclosing double-quotes retained (as usual) but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument.

Application.exe --optionName option="name" removes the enclosing double-quotes then converts the doubled double-quotes to single ones.
Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

Although a precise solution is given below but you can visit this for in-depth solution of the problem (Not exactly a problem)

If the optionValue does not contain white spaces keep the format as

```<code>Application.exe --optionName "optionValue"
</code>```

If the option Value contains white space wrap the thing in quote as

```<code> Application.exe --optionName '"option Value"'
</code>```

Title: Getting command line options

Body:
I want to parse the command line options having specific format for getting the values. The function is as follows

char* getCmdOption(char** begin,
                    char** end,
                    const std::string& option)
{
   char** itr = std::find(begin, end, option);

  if (itr != end && ++itr != end)
  {
        return *itr;
  }
  return (char*)"";
}

The arguments passed are getCmdOption(argv, argv+argc, "--optionName")
The code works fine for all the options and gives proper output but if I want to give values such as Application.exe --optionName surname="O Kief" the code should return me surname="O Kief" but instead it returns "surname=O Keif"

The format for input is Application.exe --optionName optionValue and expected output is "optionValue"

What is possibly wrong with the logic ? And how can i handle the case I have mentioned ?

Body:
""is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument. Sadly, however, not only are the enclosing double-quotes retained (as usual) but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument.

Application.exe --optionName option="name" removes the enclosing double-quotes then converts the doubled double-quotes to single ones.
Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

Although a precise solution is given below but you can visit this for in-depth solution of the problem (Not exactly a problem)

If the optionValue does not contain white spaces keep the format as

Application.exe --optionName "optionValue"

If the option Value contains white space wrap the thing in quote as

 Application.exe --optionName '"option Value"'


答:
```<code>String rowId; //Set your row id here
SQLiteDatabase sqLiteDatabase = mHelper.getWritableDatabase();
sqLiteDatabase.delete(
                TaskContract.TaskEntry.TABLE,  // Where to delete
                KEY_ID+" = ?",
                new String[]{rowId});  // What to delete
sqLiteDatabase.close();
</code>```

Title: How do I delete by ID in SQLite?


问:
Absolute bottom positioning not working as expected in Edge and IE
I have an icon that is absolute positioned at bottom: 50px, while this works fine in every browser, Edge and IE are the exceptions.  I understand there are a lot of problems with Microsoft's browsers and how they render differently. Here I see that the browser is treating the mid-way point of the 100vh div as the bottom. What I need help with is to position the icon in IE & Edge the same way it is in Chrome, Opera and Firefox. Thanks.

IE & Edge

Chrome, Firefox, Opera

HTML

.content1 {
  height: 100vh;
  width: 100%;
  position: relative;
  top: 0;
  z-index: 99;
}

/* this is the icon I was talking about */

.dropdown_blue1 {
  width: 25px;
  padding: 20px;
  position: absolute;
  margin: auto;
  z-index: 99;
  left: 0;
  right: 0;
  bottom: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content1"><img class="dropup_blue1" src="../assets/dropup_blue.png" alt=""><img class="dropdown_blue1" src="../assets/dropdown_blue.png" alt=""></div></code>```

答:
Try with this one, i have changed margin: auto; to margin: 0 auto;

.content1 {
      height: 100vh;
      width: 100%;
      position: relative;
      top: 0;
      z-index: 99;
}
.dropdown_blue1 {
      width: 25px;
      padding: 20px;
      position: absolute;
      margin:0 auto; /* change here */
      z-index: 99;
      left: 0;
      right: 0;
      bottom: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content1">
   <img class="dropdown_blue1" src="../assets/dropdown_blue.png" alt="">
</div></code>```

Body:
Try with this one, i have changed margin: auto; to margin: 0 auto;

.content1 {
      height: 100vh;
      width: 100%;
      position: relative;
      top: 0;
      z-index: 99;
}
.dropdown_blue1 {
      width: 25px;
      padding: 20px;
      position: absolute;
      margin:0 auto; /* change here */
      z-index: 99;
      left: 0;
      right: 0;
      bottom: 50px;
}

<div class="content1">
   <img class="dropdown_blue1" src="../assets/dropdown_blue.png" alt="">
</div>


问:
How to use chronicle-map instead of redis as a data cache
I intend to use chronicle-map instead of redis, the application scenario is the memoryData module starts every day from the database to load hundreds of millions of records to chronicle-map, and dozens of jvm continue to read chronicle-map records. Each jvm has hundreds of threads. But probably because of the lack of understanding of the chronicle-map, the code poor performance, running slower, until the memory overflow. I wonder if the above practice is the correct use of chronicle-map.</p>

答: Because Chronicle map stores your data off-heap it's able to store more data than you can hold in main memory, but will perform better if all the data can fit into memory, ( so if possible, consider increasing your machine memory, if this is not possible try to use an SSD drive ), another reason for poor performance maybe down to how you have sized the map in the chronicle map builder, for example how you have set the number of max entries, if this is too large it will effect performance. </p>


问:
Send left square bracket using autoit
I have plugged a Mac French keyboard onto Windows.

I would like to have the left bracket key work normally, meaning when typing Alt+Shift+(, even with left hand side modifiers.

I have the following code :

```<code>HotKeySet("!+{(}", "LeftBracket")

 Func LeftBracket()
      Send("{ASC 91}")
 EndFunc
</code>```

But it doesn't work.

When I replace the hotkey by "!a", it works.
When I replace Send("{ASC 91}") by Send("a") it sends a correctly.

But it seems not to work when I have the code above.

答:
You need to use one of these possibilities. ( needs already the shift key :-)</p>

```<code>HotKeySet("!{(}", "LeftBracket")
HotKeySet("!+{9}", "LeftBracket1")

while 1
    Sleep(1000)
Wend

 Func LeftBracket()
      Send("{ASC 91}" & 'HUHU')
 EndFunc

  Func LeftBracket1()
      Send("{ASC 91}" & 'BLA')
 EndFunc
</code>```

Title: Send left square bracket using autoit

Body:
I have plugged a Mac French keyboard onto Windows.

I would like to have the left bracket key work normally, meaning when typing Alt+Shift+(, even with left hand side modifiers.

I have the following code :

HotKeySet("!+{(}", "LeftBracket")

 Func LeftBracket()
      Send("{ASC 91}")
 EndFunc

But it doesn't work.

When I replace the hotkey by "!a", it works.
When I replace Send("{ASC 91}") by Send("a") it sends a correctly.

But it seems not to work when I have the code above.

Body:
You need to use one of these possibilities. ( needs already the shift key :-)

HotKeySet("!{(}", "LeftBracket")
HotKeySet("!+{9}", "LeftBracket1")

while 1
    Sleep(1000)
Wend

 Func LeftBracket()
      Send("{ASC 91}" & 'HUHU')
 EndFunc

  Func LeftBracket1()
      Send("{ASC 91}" & 'BLA')
 EndFunc


问:
Code won't work when merging a javascript code in one function
Good day everyone!

I have a problem merging the codes in one function. (If it's possible).

First:

There is a table.

When the table row click two buttons will be enabled.

Here's the code:

```<code>   function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers
            if(code==13)
            {
                $("#registerExist").click();
            }
        });
    }
</code>```

Second:

When Escape key pressed it will disable all bind buttons.

Here's the code:

```<code>   $(document).keyup(function(e) {
         if (e.keyCode == 27) { // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    });
</code>```

Now, what I want to do are those two codes above will merge in one function and it will call the function and trigger all those codes so when I edit the code it will be centralized.

Here's my final code:

```<code>function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers

            settings();

        });
    }
// This code is for ESC button when pressed.
$(document).keyup(function(e) {

         settings();
    });

function settings(){
        if(code==13)
        {
            $("#registerExist").click();
        }
        else if (code==27){ // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    }
</code>```

Problem:

Only the enable button is working when table row is click

Pressing Escape key will not disable the enabled buttons.

Code won't run when pressing Enter Key.

答: You are assigning the code variable in the unbind callback, not in the bind callback :)

Body:
Good day everyone!

I have a problem merging the codes in one function. (If it's possible).

First:

There is a table.

When the table row click two buttons will be enabled.

Here's the code:

   function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers
            if(code==13)
            {
                $("#registerExist").click();
            }
        });
    }

Second:

When Escape key pressed it will disable all bind buttons.

Here's the code:

   $(document).keyup(function(e) {
         if (e.keyCode == 27) { // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    });

Now, what I want to do are those two codes above will merge in one function and it will call the function and trigger all those codes so when I edit the code it will be centralized.

Here's my final code:

function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers

            settings();

        });
    }
// This code is for ESC button when pressed.
$(document).keyup(function(e) {

         settings();
    });

function settings(){
        if(code==13)
        {
            $("#registerExist").click();
        }
        else if (code==27){ // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    }

Problem:

Only the enable button is working when table row is click

Pressing Escape key will not disable the enabled buttons.

Code won't run when pressing Enter Key.


答:
```<code>SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",new String[]{Long.toString(id)} );
db.close();
</code>```

Title: How do I delete by ID in SQLite?


问:
Adding a string based on a condition with a loop in R
For a paper I need results with the form mean ± SD. There are 4 situations:

no grouping factor (df has data from only one molecule, for example), no units: mean ± sd

grouping factor, no units

no grouping factor, with units: mean ± sd ml

grouping factor, with units

I've made a function that solves the first three situations, but I can't do the last. Below is an example:

```<code>df <- data.frame(treatment = c(rep(c("Stimulation", "Control"), 8)),
                 group = c(rep(c("A", "B"), 4),
                           rep(c("B", "A"), 4)),
                 value = rnorm(16, mean = 150, sd = 20))

df$units <- ifelse(df$group == "A", "ml", "min")

strg <- function(df, vec, u){
  l <- lapply(levels(vec), function(x){

  list(
    Stimulation = paste(
      myround(mean(df$value[vec==x & df$treatment=="Stimulation"]), 2), "±",
      myround(sd(df$value[vec==x & df$treatment=="Stimulation"]), 2)
    ),
    Control = paste(
      myround(mean(df$value[vec==x & df$treatment=="Control"]), 2), "±",
      myround(sd(df$value[vec==x & df$treatment=="Control"]), 2)
    ))
})
  set_names(l, levels(vec))
}

a <- strg(df, vec = df$group, u = df$units)

add_unit <- function(list, vec, u){
  z <- lapply(list, function(x){
    list(
      Stimulation = paste(x$Stimulation, u[vec==x]),
      Control = paste(x$Control, u[vec==x]))
  })
}

b <- add_unit(a, vec = df$group, u = df$units)
</code>```

The problem seems to be the u[vec==x] bit. The final output needs to have mean ± sd and matched units. How can I add the unit while matching the grouping factor?

EDIT:
The final result should look like this, when grouping exists and we want to add units

```<code>[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9 ml"

[[1]]$Control
[1] "153.32 ± 15.79 ml"

[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78 min"

[[2]]$Control
[1] "138.48 ± 31.96 min"
</code>```

if no units are needed it should rather look like this:

```<code>[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9"

[[1]]$Control
[1] "153.32 ± 15.79"

[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78"

[[2]]$Control
[1] "138.48 ± 31.96"
</code>```

(basically what I tried to do is was to create the above strings in "a" and then add the unit to the end, if needed, resulting in "b")

答:
The whole thing rewritten in tidyverse, where (in my opinion;) the intent of the code is much more legible and manageable:

```<code>library(tidyverse)

df %>%
  group_by(group, treatment) %>%
  summarise(
    mean = mean(value),
    sd = sd(value)) %>%
  mutate(
    msd = paste(round(mean, 2), "±", round(sd, 2)),
    unit = group %>% recode(A = "ml", B = "min", .default = ""),
    result = if_else(unit == "",
                     msd,
                     paste(msd, unit)))
</code>```

The calculation / aggregation is separated from the formatting, units are depending on the group variable. It's not completely clear what you want to achieve (too many intertwined cases in the question), but you get the results with/witout units in msd and result columns respectively.

Body:
For a paper I need results with the form mean ± SD. There are 4 situations:

no grouping factor (df has data from only one molecule, for example), no units: mean ± sd

grouping factor, no units

no grouping factor, with units: mean ± sd ml

grouping factor, with units

I've made a function that solves the first three situations, but I can't do the last. Below is an example:

df <- data.frame(treatment = c(rep(c("Stimulation", "Control"), 8)),
                 group = c(rep(c("A", "B"), 4),
                           rep(c("B", "A"), 4)),
                 value = rnorm(16, mean = 150, sd = 20))

df$units <- ifelse(df$group == "A", "ml", "min")

strg <- function(df, vec, u){
  l <- lapply(levels(vec), function(x){

  list(
    Stimulation = paste(
      myround(mean(df$value[vec==x & df$treatment=="Stimulation"]), 2), "±",
      myround(sd(df$value[vec==x & df$treatment=="Stimulation"]), 2)
    ),
    Control = paste(
      myround(mean(df$value[vec==x & df$treatment=="Control"]), 2), "±",
      myround(sd(df$value[vec==x & df$treatment=="Control"]), 2)
    ))
})
  set_names(l, levels(vec))
}

a <- strg(df, vec = df$group, u = df$units)

add_unit <- function(list, vec, u){
  z <- lapply(list, function(x){
    list(
      Stimulation = paste(x$Stimulation, u[vec==x]),
      Control = paste(x$Control, u[vec==x]))
  })
}

b <- add_unit(a, vec = df$group, u = df$units)

The problem seems to be the u[vec==x] bit. The final output needs to have mean ± sd and matched units. How can I add the unit while matching the grouping factor?

EDIT:
The final result should look like this, when grouping exists and we want to add units

[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9 ml"

[[1]]$Control
[1] "153.32 ± 15.79 ml"

[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78 min"

[[2]]$Control
[1] "138.48 ± 31.96 min"

if no units are needed it should rather look like this:

[[1]]
[[1]]$Stimulation
[1] "154.37 ± 15.9"

[[1]]$Control
[1] "153.32 ± 15.79"

[[2]]
[[2]]$Stimulation
[1] "152.24 ± 17.78"

[[2]]$Control
[1] "138.48 ± 31.96"

(basically what I tried to do is was to create the above strings in "a" and then add the unit to the end, if needed, resulting in "b")

Body:
The whole thing rewritten in tidyverse, where (in my opinion;) the intent of the code is much more legible and manageable:

library(tidyverse)

df %>%
  group_by(group, treatment) %>%
  summarise(
    mean = mean(value),
    sd = sd(value)) %>%
  mutate(
    msd = paste(round(mean, 2), "±", round(sd, 2)),
    unit = group %>% recode(A = "ml", B = "min", .default = ""),
    result = if_else(unit == "",
                     msd,
                     paste(msd, unit)))

The calculation / aggregation is separated from the formatting, units are depending on the group variable. It's not completely clear what you want to achieve (too many intertwined cases in the question), but you get the results with/witout units in msd and result columns respectively.


问:
Simple Math with JS
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

答:
Try this

```<code>var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
</code>```

Demo

  var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
    $( ".payment" ).html( "Pay as low as " + (price/12) );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $"result here" </span></code>```

Title: Simple Math with JS

Body:
Try this

var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );

Demo

  var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
    $( ".payment" ).html( "Pay as low as " + (price/12) );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $"result here" </span>


答:
What you should do:

Get the .price div's text.

convert it to an int.

Now you should divide it with (value/2)/6

Put the value in the desired target element.

var price = +$('.price').text().slice(1);
var pay = (price/2)/6
$('p').text("Pay as low as $"+pay);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<p></p></code>```

Title: Simple Math with JS

Body:
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

Body:
What you should do:

Get the .price div's text.

convert it to an int.

Now you should divide it with (value/2)/6

Put the value in the desired target element.

var price = +$('.price').text().slice(1);
var pay = (price/2)/6
$('p').text("Pay as low as $"+pay);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<p></p>


问:
XRegExp returning false with working unicode check \p?
I'm trying to get this name validation regex working but am having issues. I have made sure I have the unicode addon for regexp but it does not seem to be working. This regex works with php pcre regex.

XRegExp("^[a-zA-Z\s,.'-\pL]+$").test('á');

The above returns false. I've never used xregexp and haven't been able to find anything online that seems to explain how to do this. Any help would be great, thanks!

This particular regex should accept all unicode characters, dashes, commas, periods, and letters upper and lower.

答:
It is quite easy once you check what your pattern looks like in the console. It looks like /^[a-zA-Zs,.'-pL]+$/, which means, it does not match Unicode letters at all, as the backslashes are gone (you need to use double backslashes in the string literals to define a literal backslash that escapes special chars in regex). Note that instead of whitespace, you match a literal s, and '-p creates a valid range, so there is no error thrown, but the results are really unexpected. Here is what that range matches (yes, including digits):

What you also miss is that \pL already includes [a-zA-Z], so that part in your pattern is redundant.

// YOUR REGEX
console.log("^[a-zA-Z\s,.'\-\pL]+$"); // => /^[a-zA-Zs,.'-pL]+$/
// SHOULD BE DEFINE AS
console.log("^[\\s,.'\\pL-]+$"); // => /^[\s,.'\pL-]+$/
// TEST
console.log(XRegExp("^[\\s,.'\\pL-]+$").test('á')); // => true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script></code>```

Body:
It is quite easy once you check what your pattern looks like in the console. It looks like /^[a-zA-Zs,.'-pL]+$/, which means, it does not match Unicode letters at all, as the backslashes are gone (you need to use double backslashes in the string literals to define a literal backslash that escapes special chars in regex). Note that instead of whitespace, you match a literal s, and '-p creates a valid range, so there is no error thrown, but the results are really unexpected. Here is what that range matches (yes, including digits):

What you also miss is that \pL already includes [a-zA-Z], so that part in your pattern is redundant.

// YOUR REGEX
console.log("^[a-zA-Z\s,.'\-\pL]+$"); // => /^[a-zA-Zs,.'-pL]+$/
// SHOULD BE DEFINE AS
console.log("^[\\s,.'\\pL-]+$"); // => /^[\s,.'\pL-]+$/
// TEST
console.log(XRegExp("^[\\s,.'\\pL-]+$").test('á')); // => true

<script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>


问:
php sum multidimensional subarray
I want to calculate distance of array. I have multidimensional array like this

```<code>Array
(
    [0] => Array
        (
            [0] => 3136
        )

    [1] => Array
        (
            [0] => 9
        )

)
Array
(
    [0] => Array
        (
            [0] => 3025
        )

    [1] => Array
        (
            [0] => 169
        )

)
</code>```

This is my code:

```<code>function hitung(){
    $dataTest       = array(60,50);
    $dataHitung     = array();
    $dataHitung2    = array();
    $dataRuspini    = $this->m_knn->getRuspini();
    foreach ($dataRuspini as $key => $val) {
        # code...
        // looping kolom 1 sampai 3
        for ($i=0; $i < count($val)-1; $i++) {
            # code...
            // looping setiap baris per kolomnya
            for ($j=0; $j < count($val[$i]); $j++) {
                # code...
                // data test dikurangi data training
                $dataHitung[$i][$j] = $dataTest[$i] - $val[$i];
                // hasil pengurangan dikuadratkan
                $dataHitung[$i][$j] = pow($dataHitung[$i][$j], 2);
                $dataHitung2[$i][$j] = $dataHitung[$i][$j];
            }

        }
        //var_dump(array_sum($dataHitung2));
        echo "```";
        print_r($dataHitung2);

    }
```

<p>How tu sum each row of array ?</p>

```3136 + 9
3025 + 169
```

Please help me :(

答:
Use array_sum(). The array_sum() function returns the sum of all the values in the array.

```<code>foreach($dataRuspini as $key=>$array)
{
 $sum_array[] = array_sum($array);
}
print_r($sum_aray);
</code>```

Title: php sum multidimensional subarray

Body:
I want to calculate distance of array. I have multidimensional array like this

Array
(
    [0] => Array
        (
            [0] => 3136
        )

    [1] => Array
        (
            [0] => 9
        )

)
Array
(
    [0] => Array
        (
            [0] => 3025
        )

    [1] => Array
        (
            [0] => 169
        )

)

This is my code:

function hitung(){
    $dataTest       = array(60,50);
    $dataHitung     = array();
    $dataHitung2    = array();
    $dataRuspini    = $this->m_knn->getRuspini();
    foreach ($dataRuspini as $key => $val) {
        # code...
        // looping kolom 1 sampai 3
        for ($i=0; $i < count($val)-1; $i++) {
            # code...
            // looping setiap baris per kolomnya
            for ($j=0; $j < count($val[$i]); $j++) {
                # code...
                // data test dikurangi data training
                $dataHitung[$i][$j] = $dataTest[$i] - $val[$i];
                // hasil pengurangan dikuadratkan
                $dataHitung[$i][$j] = pow($dataHitung[$i][$j], 2);
                $dataHitung2[$i][$j] = $dataHitung[$i][$j];
            }

        }
        //var_dump(array_sum($dataHitung2));
        echo "
";
        print_r($dataHitung2);

    }

How tu sum each row of array ?

3136 + 9
3025 + 169

Please help me :(

Body:
Use array_sum(). The array_sum() function returns the sum of all the values in the array.

foreach($dataRuspini as $key=>$array)
{
 $sum_array[] = array_sum($array);
}
print_r($sum_aray);


问:
Debugging application when launched via ShellExecute
I am trying to launch an application via the ShellExecute() API call. This application contains only a main function which does some processing and exits.

Now I have put DebugBreak() in starting of main. When ShellExecute() is called the application is launched successfully but it does not ask for breaking.

How can I debug my application when launched from other application using ShellExecute()?

I am using VC++ .

答: You can't do this with VC++; with WinDbg this is just .childdbg 1 to debug all child processes. With VC++, you can use Image File Execution Options in a pinch - check out http://codereflect.com/2009/09/20/how-to-debug-child-process-using-windbgvisual-studio/ for more info. Really though, if you've got the time to learn WinDbg, it's much better at this.


问:
How to use this Function on a custom API
I have encountered a problem using an API which function is to send Mail but the problem is that the body of the mail is using LPCVOID to which i have no idea how to use it. I have search google and there is no clear explanation on how to use it.

Here is the whole function:

```<code>IMTMail::Body(LPCVOID body,const UINT body_size)
</code>```

Parameters:

```<code>body       [in] A pointer to the email body
body_size  [in] The size of the body in bytes
</code>```

I hope you can enlighten me and if you have examples i will really appreciate it.

答:
As already mentioned in comments LPCVOID is typedef of const void *. So you can pass any pointer to the function. And here are examples:

```<code>std::string body("Test Email Body!!!!!!!");
mail.Body( body.c_str(), body.size() ); //assume type of mail is IMTMail
</code>```

with std::wstring

```<code>std::wstring body(L"Test Email Body!!!!!!!");
mail.Body( body.c_str(), body.size() ); //assume type of mail is IMTMail
</code>```

Body:
I have encountered a problem using an API which function is to send Mail but the problem is that the body of the mail is using LPCVOID to which i have no idea how to use it. I have search google and there is no clear explanation on how to use it.

Here is the whole function:

IMTMail::Body(LPCVOID body,const UINT body_size)

Parameters:

body       [in] A pointer to the email body
body_size  [in] The size of the body in bytes

I hope you can enlighten me and if you have examples i will really appreciate it.

Body:
As already mentioned in comments LPCVOID is typedef of const void *. So you can pass any pointer to the function. And here are examples:

std::string body("Test Email Body!!!!!!!");
mail.Body( body.c_str(), body.size() ); //assume type of mail is IMTMail

with std::wstring

std::wstring body(L"Test Email Body!!!!!!!");
mail.Body( body.c_str(), body.size() ); //assume type of mail is IMTMail


问:
Represent large money numbers in a more human readable format
I am using Cocoa's NSNumberFormatter to represent money, which works very well for normal amounts. I am now at a situation where I want to represent very large amounts of money in a more human readable way once money starts accumulating more than a billion, similar to the way games like Adventure Capitalism represent money.

For example, I would like to represent a 500,100,000,000$ as 500,100B$ etc. Is there a plugin or an easy way of doing this, other than creating a manual function that would handle all these cases?

答:
NSNumberFormatter does not support unit prefixes. (NSByteCountformatter does, but this doesn't help you.) Additionally your prefixes aren't scientific unit prefixes, i. e. you want t have a B for billion instead a G for giga.

You have to do this your own way. You can do this simply by having an array of prefixes and then dividing for each 1,000. However, you have to localize that and I'm pretty sure, that you do not want that. I. e. in Germany we use Mrd  for billion, because it is "Milliarde". And Germany is still a western country. I have no idea, what they do in China.


问:
How to create nested array of objects in javascript with form data?
I am new to javascript, Please help me out with this.
I have a set of data in json format, now I want to insert another record as an object using form data.
Following is sample data-

```<code>dummydata=[{
    property1: "John",
    property2:[
                {id:[1]},
                {IsRequired:[]}
              ],
    property3: [
      "text1",
      "text2"
    ],
    property4:[
        {
        orderId:1,
        text:"Hello",
        cardType:"",
        options: ""
        },
        {
        orderId:3,
        text:"Hello World",
        cardType:[],
        options: [
            {Id:1},
            {Id:2}
             ]
        }
    ]
  }
  {...
  ..}
  ]
</code>```

Following is my controller.js-

```<code>    //Javascript constructor
    function record(property1, property2, property3, property4){

  this.property1 = property1;
  this.property2 = (function(id, isrequired)
                    {
                        this.id=id;
                        this.isrequired=isrequired;
                    });
  this.property3 = property3;
  this.property4 = (function(orderId, text, cardType, options)
                    {
                        this.orderId=orderId;
                        this.text=text;
                        this.cardType=cardType;
                        this.options=options;
                    });
 }

function addRecord()
{
    var property1Input=document.forms["intent_form"]["property1"].value;
    var property2Input=document.forms["intent_form"]["property2"].value;
    var property3Input= document.forms["intent_form"]["property3"].value;
    var property4Input= document.forms["intent_form"]["property4"].value;

    var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
    var newRecord = new record(property1Input,property2Input, property3Input,property4Input);
        newDataSet.push(newRecord );
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
}
</code>```

I really clueless as how can structure the entire record and push it in my existing record. Thanks in advance.

答:
As per your sample code, I think you need to update your addRecord() where you need to push your new data from constructor object:

```<code>    function addRecord(dummydata)
    {
        var property1Input=document.forms["intent_form"]["property1"].value;
        var property2Input=document.forms["intent_form"]["property2"].value;
        var property3Input= document.forms["intent_form"]["property3"].value;
        var property4Input= document.forms["intent_form"]["property4"].value;

        var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
        var newRecord = new record(property1Input,property2Input, property3Input,property4Input);

        // Create a new json object here
        var objToBeInsert = {
        property1:newRecord.property1,
        property2:newRecord.property2,
        property3:newRecord.property3,
        property4:newRecord.property4
        };

        //Now push this object to your list.
        newDataSet.push(objToBeInsert);
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
    }
</code>```

Note: Please mark this answer if it's helpful to you.

Body:
I am new to javascript, Please help me out with this.
I have a set of data in json format, now I want to insert another record as an object using form data.
Following is sample data-

dummydata=[{
    property1: "John",
    property2:[
                {id:[1]},
                {IsRequired:[]}
              ],
    property3: [
      "text1",
      "text2"
    ],
    property4:[
        {
        orderId:1,
        text:"Hello",
        cardType:"",
        options: ""
        },
        {
        orderId:3,
        text:"Hello World",
        cardType:[],
        options: [
            {Id:1},
            {Id:2}
             ]
        }
    ]
  }
  {...
  ..}
  ]

Following is my controller.js-

    //Javascript constructor
    function record(property1, property2, property3, property4){

  this.property1 = property1;
  this.property2 = (function(id, isrequired)
                    {
                        this.id=id;
                        this.isrequired=isrequired;
                    });
  this.property3 = property3;
  this.property4 = (function(orderId, text, cardType, options)
                    {
                        this.orderId=orderId;
                        this.text=text;
                        this.cardType=cardType;
                        this.options=options;
                    });
 }

function addRecord()
{
    var property1Input=document.forms["intent_form"]["property1"].value;
    var property2Input=document.forms["intent_form"]["property2"].value;
    var property3Input= document.forms["intent_form"]["property3"].value;
    var property4Input= document.forms["intent_form"]["property4"].value;

    var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
    var newRecord = new record(property1Input,property2Input, property3Input,property4Input);
        newDataSet.push(newRecord );
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
}

I really clueless as how can structure the entire record and push it in my existing record. Thanks in advance.

Body:
As per your sample code, I think you need to update your addRecord() where you need to push your new data from constructor object:

    function addRecord(dummydata)
    {
        var property1Input=document.forms["intent_form"]["property1"].value;
        var property2Input=document.forms["intent_form"]["property2"].value;
        var property3Input= document.forms["intent_form"]["property3"].value;
        var property4Input= document.forms["intent_form"]["property4"].value;

        var newDataSet = JSON.parse( localStorage.getItem('key_newDataSet' ) );
        var newRecord = new record(property1Input,property2Input, property3Input,property4Input);

        // Create a new json object here
        var objToBeInsert = {
        property1:newRecord.property1,
        property2:newRecord.property2,
        property3:newRecord.property3,
        property4:newRecord.property4
        };

        //Now push this object to your list.
        newDataSet.push(objToBeInsert);
        localStorage.setItem("key_newDataSet", JSON.stringify(newDataSet));
    }

Note: Please mark this answer if it's helpful to you.