问:
Take all items except the last ones that satisfy condition?
My specific requirement is that I have an IEnumerable<IEnumerable<string>>, and I want to "take" all items in the outer enumeration except any "empty" trailing items, where "empty" means all strings are null/empty or the inner enumeration is empty. Note that I want to keep any empty items that appear before the last non-empty one. For example:

```<code>Item 1: a, b, c
Item 2: (nothing)
Item 3: a, f, g, h
Item 4: (nothing)
Item 5: (nothing)
</code>```

I would like to keep items 1–3 but trim items 4 and 5.

In a more general sense, I have an enumeration of items, where I want to trim any trailing items that satisfy a condition, that appear behind the last item that does not satisfy the condition.

For the sake of choosing an appropriate solution, I might add that the outer enumeration will usually contain a few hundred up to a few hundred thousand items, while the inner enumerations contain only a few items each. There will probably be only a couple of empty items that I need to trim.

My current solution puts all outer items in a list (after transforming them with .Select(...)), and then in a loop keep removing the last item if it's empty, until a non-empty item is found.

答:
How about this?

```<code>var trimmedItems = items.Reverse().SkipWhile(e => !e.Any()).Reverse();
</code>```

If you have very large sets of data, this will require more memory than some other solutions you could come up with, but it's pretty easy to read and follow.

juharr's suggestion is only slightly more complicated, and performs much better if you have large numbers of items:

```<code>var trimmedItems = items.Take(items.Reverse().TakeWhile(e => !e.Any()).Count());
</code>```

Here's the benchmarking code I'm using. It's meant to run in LINQPad, but you can change the result.Dump(); call to output the results to the console or something if you prefer. Also, I'm using an IEnumerable<string> instead of IEnumerable<IEnumerable<string>> just for simplicity, but that shouldn't impact the performance of the algorithm:

```<code>/* This is a benchmarking template I use in LINQPad when I want to do a
 * quick performance test. Just give it a couple of actions to test and
 * it will give you a pretty good idea of how long they take compared
 * to one another. It's not perfect: You can expect a 3% error margin
 * under ideal circumstances. But if you're not going to improve
 * performance by more than 3%, you probably don't care anyway.*/
void Main()
{
    // Enter setup code here
    var items = new[] { "a, b, c",
    "",
    "a, f, g, h",
    "",
    ""}.AsEnumerable();
    var manyitems = Enumerable.Range(1, 10000).SelectMany(i => items);

    var actions = new[]
    {
        new TimedAction("Control", () =>
        {
            // ToList() is the one thing that all of these have to do.
            manyitems.ToList();
        }),
        new TimedAction("Reverse().SkipWhile().Reverse()", () =>
        {
            manyitems.Reverse().SkipWhile(e => !e.Any()).Reverse().ToList();
        }),
        new TimedAction("Take(Reverse().TakeWhile().Count())", () =>
        {
            manyitems.Take(manyitems.Reverse().TakeWhile(e => !e.Any()).Count()).ToList();
        }),
        new TimedAction("SkipLastWhile", () =>
        {
            manyitems.SkipLastWhile(e => !e.Any()).ToList();
        }),
        // Add tests as desired
    };
    const int TimesToRun = 100; // Tweak this as necessary
    TimeActions(TimesToRun, actions);
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> SkipLastWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        var skipBuffer = new List<T>();
        foreach (var item in source)
        {
            if (predicate(item))
                skipBuffer.Add(item);
            else
            {
                foreach (var skipped in skipBuffer)
                    yield return skipped;
                skipBuffer.Clear();
                yield return item;
            }
        }
    }
}

#region timer helper methods
// Define other methods and classes here
public void TimeActions(int iterations, params TimedAction[] actions)
{
    Stopwatch s = new Stopwatch();
    int length = actions.Length;
    var results = new ActionResult[actions.Length];
    // Perform the actions in their initial order.
    for (int i = 0; i < length; i++)
    {
        var action = actions[i];
        var result = results[i] = new ActionResult { Message = action.Message };
        // Do a dry run to get things ramped up/cached
        result.DryRun1 = s.Time(action.Action, 10);
        result.FullRun1 = s.Time(action.Action, iterations);
    }
    // Perform the actions in reverse order.
    for (int i = length - 1; i >= 0; i--)
    {
        var action = actions[i];
        var result = results[i];
        // Do a dry run to get things ramped up/cached
        result.DryRun2 = s.Time(action.Action, 10);
        result.FullRun2 = s.Time(action.Action, iterations);
    }
    results.Dump();
}

public class ActionResult
{
    public string Message { get; set; }
    public double DryRun1 { get; set; }
    public double DryRun2 { get; set; }
    public double FullRun1 { get; set; }
    public double FullRun2 { get; set; }
}

public class TimedAction
{
    public TimedAction(string message, Action action)
    {
        Message = message;
        Action = action;
    }
    public string Message { get; private set; }
    public Action Action { get; private set; }
}

public static class StopwatchExtensions
{
    public static double Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Restart();
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.Elapsed.TotalMilliseconds;
    }
}
#endregion
</code>```

Results:

The benchmark results are more profound if your IEnumerable is backed by a List, because then LINQ can make some additional optimizations on Reverse():

```<code>var manyitems = Enumerable.Range(1, 10000).SelectMany(i => items).ToList().AsEnumerable();
</code>```

Body:
My specific requirement is that I have an IEnumerable<IEnumerable<string>>, and I want to "take" all items in the outer enumeration except any "empty" trailing items, where "empty" means all strings are null/empty or the inner enumeration is empty. Note that I want to keep any empty items that appear before the last non-empty one. For example:

Item 1: a, b, c
Item 2: (nothing)
Item 3: a, f, g, h
Item 4: (nothing)
Item 5: (nothing)

I would like to keep items 1–3 but trim items 4 and 5.

In a more general sense, I have an enumeration of items, where I want to trim any trailing items that satisfy a condition, that appear behind the last item that does not satisfy the condition.

For the sake of choosing an appropriate solution, I might add that the outer enumeration will usually contain a few hundred up to a few hundred thousand items, while the inner enumerations contain only a few items each. There will probably be only a couple of empty items that I need to trim.

My current solution puts all outer items in a list (after transforming them with .Select(...)), and then in a loop keep removing the last item if it's empty, until a non-empty item is found.

Body:
How about this?

var trimmedItems = items.Reverse().SkipWhile(e => !e.Any()).Reverse();

If you have very large sets of data, this will require more memory than some other solutions you could come up with, but it's pretty easy to read and follow.

juharr's suggestion is only slightly more complicated, and performs much better if you have large numbers of items:

var trimmedItems = items.Take(items.Reverse().TakeWhile(e => !e.Any()).Count());

Here's the benchmarking code I'm using. It's meant to run in LINQPad, but you can change the result.Dump(); call to output the results to the console or something if you prefer. Also, I'm using an IEnumerable<string> instead of IEnumerable<IEnumerable<string>> just for simplicity, but that shouldn't impact the performance of the algorithm:

/* This is a benchmarking template I use in LINQPad when I want to do a
 * quick performance test. Just give it a couple of actions to test and
 * it will give you a pretty good idea of how long they take compared
 * to one another. It's not perfect: You can expect a 3% error margin
 * under ideal circumstances. But if you're not going to improve
 * performance by more than 3%, you probably don't care anyway.*/
void Main()
{
    // Enter setup code here
    var items = new[] { "a, b, c",
    "",
    "a, f, g, h",
    "",
    ""}.AsEnumerable();
    var manyitems = Enumerable.Range(1, 10000).SelectMany(i => items);

    var actions = new[]
    {
        new TimedAction("Control", () =>
        {
            // ToList() is the one thing that all of these have to do.
            manyitems.ToList();
        }),
        new TimedAction("Reverse().SkipWhile().Reverse()", () =>
        {
            manyitems.Reverse().SkipWhile(e => !e.Any()).Reverse().ToList();
        }),
        new TimedAction("Take(Reverse().TakeWhile().Count())", () =>
        {
            manyitems.Take(manyitems.Reverse().TakeWhile(e => !e.Any()).Count()).ToList();
        }),
        new TimedAction("SkipLastWhile", () =>
        {
            manyitems.SkipLastWhile(e => !e.Any()).ToList();
        }),
        // Add tests as desired
    };
    const int TimesToRun = 100; // Tweak this as necessary
    TimeActions(TimesToRun, actions);
}

public static class EnumerableExtensions
{
    public static IEnumerable<T> SkipLastWhile<T>(this IEnumerable<T> source, Func<T, bool> predicate)
    {
        var skipBuffer = new List<T>();
        foreach (var item in source)
        {
            if (predicate(item))
                skipBuffer.Add(item);
            else
            {
                foreach (var skipped in skipBuffer)
                    yield return skipped;
                skipBuffer.Clear();
                yield return item;
            }
        }
    }
}

#region timer helper methods
// Define other methods and classes here
public void TimeActions(int iterations, params TimedAction[] actions)
{
    Stopwatch s = new Stopwatch();
    int length = actions.Length;
    var results = new ActionResult[actions.Length];
    // Perform the actions in their initial order.
    for (int i = 0; i < length; i++)
    {
        var action = actions[i];
        var result = results[i] = new ActionResult { Message = action.Message };
        // Do a dry run to get things ramped up/cached
        result.DryRun1 = s.Time(action.Action, 10);
        result.FullRun1 = s.Time(action.Action, iterations);
    }
    // Perform the actions in reverse order.
    for (int i = length - 1; i >= 0; i--)
    {
        var action = actions[i];
        var result = results[i];
        // Do a dry run to get things ramped up/cached
        result.DryRun2 = s.Time(action.Action, 10);
        result.FullRun2 = s.Time(action.Action, iterations);
    }
    results.Dump();
}

public class ActionResult
{
    public string Message { get; set; }
    public double DryRun1 { get; set; }
    public double DryRun2 { get; set; }
    public double FullRun1 { get; set; }
    public double FullRun2 { get; set; }
}

public class TimedAction
{
    public TimedAction(string message, Action action)
    {
        Message = message;
        Action = action;
    }
    public string Message { get; private set; }
    public Action Action { get; private set; }
}

public static class StopwatchExtensions
{
    public static double Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Restart();
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.Elapsed.TotalMilliseconds;
    }
}
#endregion

Results:

The benchmark results are more profound if your IEnumerable is backed by a List, because then LINQ can make some additional optimizations on Reverse():

var manyitems = Enumerable.Range(1, 10000).SelectMany(i => items).ToList().AsEnumerable();


来源: stackexchange

问:
Using subqueries in Eloquent/Laravel
Here's the query in raw SQL:

```<code>SELECT *
FROM (
    SELECT `characters`.`id`,`characters`.`refreshToken`,
           `characters`.`name`,max(`balances`.`created_at`) as `refreshDate`
        FROM `characters`
        INNER JOIN `balances` ON `characters`.`id` = `balances`.`character`
        WHERE `characters`.`refreshToken` IS NOT NULL
        GROUP BY `characters`.`id`
) AS `t1`
WHERE `refreshDate` < '2017-03-29';
</code>```

I've tested this in phpMyAdmin and it returns the expected results.  However I'm using the Eloquent and Laravel libraries in my PHP app and I'm not sure how to approach this.  How exactly do subqueries work in this case?

答:
You can do a subquery as a table but need to create the subquery first and then merge the bindings into the parent query:

```<code>$sub = Character::select('id', 'refreshToken', 'name')
    ->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
    ->join('balances', 'characters.id', '=', 'balances.character')
    ->whereNotNull('characters.refreshToken')
    ->groupBy('characters.id');

DB::table(DB::raw("($sub->toSql()) as t1"))
    ->mergeBindings($sub)
    ->where('refreshDate', '<', '2017-03-29')
    ->get();
</code>```

If that is your entire query you can do it without the subquery and use having() instead like:

```<code>Character::select('id', 'refreshToken', 'name')
    ->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
    ->join('balances', 'characters.id', '=', 'balances.character')
    ->whereNotNull('characters.refreshToken')
    ->groupBy('characters.id')
    ->having('refreshDate', '<', '2017-03-29');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using subqueries in Eloquent/Laravel

Body:
Here's the query in raw SQL:

SELECT *
FROM (
    SELECT `characters`.`id`,`characters`.`refreshToken`,
           `characters`.`name`,max(`balances`.`created_at`) as `refreshDate`
        FROM `characters`
        INNER JOIN `balances` ON `characters`.`id` = `balances`.`character`
        WHERE `characters`.`refreshToken` IS NOT NULL
        GROUP BY `characters`.`id`
) AS `t1`
WHERE `refreshDate` < '2017-03-29';

I've tested this in phpMyAdmin and it returns the expected results.  However I'm using the Eloquent and Laravel libraries in my PHP app and I'm not sure how to approach this.  How exactly do subqueries work in this case?

Body:
You can do a subquery as a table but need to create the subquery first and then merge the bindings into the parent query:

$sub = Character::select('id', 'refreshToken', 'name')
    ->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
    ->join('balances', 'characters.id', '=', 'balances.character')
    ->whereNotNull('characters.refreshToken')
    ->groupBy('characters.id');

DB::table(DB::raw("($sub->toSql()) as t1"))
    ->mergeBindings($sub)
    ->where('refreshDate', '<', '2017-03-29')
    ->get();

If that is your entire query you can do it without the subquery and use having() instead like:

Character::select('id', 'refreshToken', 'name')
    ->selectSub('MAX(`balances`.`created_at`)', 'refreshDate')
    ->join('balances', 'characters.id', '=', 'balances.character')
    ->whereNotNull('characters.refreshToken')
    ->groupBy('characters.id')
    ->having('refreshDate', '<', '2017-03-29');


问:
C# set azure function time trigger programmatically
I would like to write a c# Azure Function working on a time trigger in which the schedule would be variable, i.e. each function run would determine the time of the next run and thus should be able to change the scheduled time of the next trigger.</p>

答:
You can use a queue trigger with a queue output for this thanks to the NextVisibleTime property, it's a better choice than attempting to modify the timer schedule every run.

It also supports configurable retries upon failure (and a poison queue) so it's more durable than a timer trigger. (https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue#handling-poison-queue-messages)

ContentLicense: CC BY-SA 4.0


问:
jQuery append method inserting text rather than HTML
I want append an input text in my html page. I use JQuery to do that.

My JQuery script :

```<code>$(document).ready(function(){
    $(".reply").click(function(){
      var tempat=$(this).parent().parent().next(".komentar-balasan");
      console.log(tempat[0]);
      var html=
      tempat[0].append('<input type="text"></input>');
    });
  });
</code>```

And the HTML :

```<code> <div class="isi">
    <div class="like-comment">
     <div class="kotak"></div>
     <div class="kotak-jumlah">
     </div>
     <div class="kotak"><button class="reply"></button></div>
   </div><div class="komentar-balasan"></div>
</code>```

The Fiddle

I Don't know why, but instead of displayed the input text box. The browser just display <input type="text"></input>. It's like the browser didn't recognize the HTML code.

答:
Hello,

Check if this is what you need:

You need to create an element and only then add it.

Here is an example:

```<code>      $(document).ready(function(){
        $(".reply").click(function(){
          var tempat=$(this).parent().parent().next(".komentar-balasan");
          console.log(tempat[0]);
          var newEl = document.createElement('input');
          newEl.type = "text";
          tempat.append(newEl);
        });
      });
</code>```

I hope I have helped!

Body:
I want append an input text in my html page. I use JQuery to do that.

My JQuery script :

$(document).ready(function(){
    $(".reply").click(function(){
      var tempat=$(this).parent().parent().next(".komentar-balasan");
      console.log(tempat[0]);
      var html=
      tempat[0].append('<input type="text"></input>');
    });
  });

And the HTML :

<button class="reply"></button>

The Fiddle

I Don't know why, but instead of displayed the input text box. The browser just display <input type="text"></input>. It's like the browser didn't recognize the HTML code.

Body:
Hello,

Check if this is what you need:

You need to create an element and only then add it.

Here is an example:

      $(document).ready(function(){
        $(".reply").click(function(){
          var tempat=$(this).parent().parent().next(".komentar-balasan");
          console.log(tempat[0]);
          var newEl = document.createElement('input');
          newEl.type = "text";
          tempat.append(newEl);
        });
      });

I hope I have helped!


答:
It's because tempat[0] is accessing the underlying DOM node rather than the jQuery wrapper.  It works fine if you omit the array access and just call append on tempat.

You don't need it here but the right way to get a jQuery wrapped element of a jQuery selector list is to use eq

Title: jQuery append method inserting text rather than HTML


问:
Retrieve data in oracle
Table description:

BRANCH(Branchid,Branchname,HOD)
STUDENT(USN,Name,Address,Branchid,sem)
BOOK(Bookid,Bookname,Authorid,Publisher,Branchid)
AUTHOR(Authorid,Authorname,Country,age)
BORROW(USN,Bookid,Borrowed_Date)

Q1) Display the student details who borrowed books of more than one Author.
Q2)List the details of students who borrowed the books which are all published by the same
Publisher.

答:
TRY THIS:

```<code>SELECT
 S.NAME             AS "STUDENT NAME"
,S.ADDRESS          AS "STUDENT ADDRESS"
,BW.BORROWED_DATE   AS "DATE BORROWED"
,BR.BRANCHNAME      AS "BRANCE NAME"
,BK.BOOKNAME        AS "NAME OF BOOK"
,BK.PUBLISHER       AS "BOOK PUBLISHER"
,A.AUTHORNAME       AS "NAME OF AUTHOR"
,A.COUNTRY          AS "COUNTRY OF AUTHOR"
,A.AGE              AS "AGE OF AUTHOR"
---
FROM
STUDENT S
---
JOIN BORROW BW
    ON S.USN = BW.USN
---
JOIN BOOK BK
    ON BW.BOOKID = BK.BOOKID
--
JOIN BRANCH BR
    ON BR.BRANCHID = BK.BRANCHID
---
JOIN AUTHOR A
    ON BK.AUTHORID = A.AUTHORID
--
--
JOIN (SELECT P1
        FROM (
            SELECT
             SS_S.USN       "P1"
            ,SS_A.Authorid  "P2"
            FROM
            STUDENT SS_S
            JOIN BORROW SS_BW
                ON SS_S.USN = SS_BW.USN
            JOIN BOOK SS_BK
                ON SS_BW.BOOKID = SS_BK.BOOKID
            JOIN AUTHOR SS_A
                ON SS_BK.AUTHORID = SS_A.AUTHORID
            GROUP BY
             SS_S.USN
            ,SS_A.Authorid
            HAVING COUNT(SS_A.Authorid) > 1
        )
    ) SUB_Q
ON S.USN = SUB_Q.P1
ORDER BY 1, 3
</code>```

QUESTION NUMBER 2 IS SIMPLE

```<code>SELECT
 S.NAME             AS "STUDENT NAME"
,S.ADDRESS          AS "STUDENT ADDRESS"
,BW.BORROWED_DATE   AS "DATE BORROWED"
,BR.BRANCHNAME      AS "BRANCE NAME"
,BK.BOOKNAME        AS "NAME OF BOOK"
,BK.PUBLISHER       AS "BOOK PUBLISHER"
,A.AUTHORNAME       AS "NAME OF AUTHOR"
,A.COUNTRY          AS "COUNTRY OF AUTHOR"
,A.AGE              AS "AGE OF AUTHOR"
---
FROM
STUDENT S
---
JOIN BORROW BW
    ON S.USN = BW.USN
---
JOIN BOOK BK
    ON BW.BOOKID = BK.BOOKID
--
JOIN BRANCH BR
    ON BR.BRANCHID = BK.BRANCHID
---
JOIN AUTHOR A
    ON BK.AUTHORID = A.AUTHORID
--
WHERE
BK.PUBLISHER = ''
</code>```

Title: Retrieve data in oracle

Body:
TRY THIS:

SELECT
 S.NAME             AS "STUDENT NAME"
,S.ADDRESS          AS "STUDENT ADDRESS"
,BW.BORROWED_DATE   AS "DATE BORROWED"
,BR.BRANCHNAME      AS "BRANCE NAME"
,BK.BOOKNAME        AS "NAME OF BOOK"
,BK.PUBLISHER       AS "BOOK PUBLISHER"
,A.AUTHORNAME       AS "NAME OF AUTHOR"
,A.COUNTRY          AS "COUNTRY OF AUTHOR"
,A.AGE              AS "AGE OF AUTHOR"
---
FROM
STUDENT S
---
JOIN BORROW BW
    ON S.USN = BW.USN
---
JOIN BOOK BK
    ON BW.BOOKID = BK.BOOKID
--
JOIN BRANCH BR
    ON BR.BRANCHID = BK.BRANCHID
---
JOIN AUTHOR A
    ON BK.AUTHORID = A.AUTHORID
--
--
JOIN (SELECT P1
        FROM (
            SELECT
             SS_S.USN       "P1"
            ,SS_A.Authorid  "P2"
            FROM
            STUDENT SS_S
            JOIN BORROW SS_BW
                ON SS_S.USN = SS_BW.USN
            JOIN BOOK SS_BK
                ON SS_BW.BOOKID = SS_BK.BOOKID
            JOIN AUTHOR SS_A
                ON SS_BK.AUTHORID = SS_A.AUTHORID
            GROUP BY
             SS_S.USN
            ,SS_A.Authorid
            HAVING COUNT(SS_A.Authorid) > 1
        )
    ) SUB_Q
ON S.USN = SUB_Q.P1
ORDER BY 1, 3

QUESTION NUMBER 2 IS SIMPLE

SELECT
 S.NAME             AS "STUDENT NAME"
,S.ADDRESS          AS "STUDENT ADDRESS"
,BW.BORROWED_DATE   AS "DATE BORROWED"
,BR.BRANCHNAME      AS "BRANCE NAME"
,BK.BOOKNAME        AS "NAME OF BOOK"
,BK.PUBLISHER       AS "BOOK PUBLISHER"
,A.AUTHORNAME       AS "NAME OF AUTHOR"
,A.COUNTRY          AS "COUNTRY OF AUTHOR"
,A.AGE              AS "AGE OF AUTHOR"
---
FROM
STUDENT S
---
JOIN BORROW BW
    ON S.USN = BW.USN
---
JOIN BOOK BK
    ON BW.BOOKID = BK.BOOKID
--
JOIN BRANCH BR
    ON BR.BRANCHID = BK.BRANCHID
---
JOIN AUTHOR A
    ON BK.AUTHORID = A.AUTHORID
--
WHERE
BK.PUBLISHER = ''


问:
Website Image preload for faster loading
I`m trying to build a cool gallery for my photography website:

I thought i`m already done. On my computer i looks pretty cool, so i uploaded it to my Webspace on Webgo.

The problem is the loading time of the images, when loading the website the first time.

I build the masonry look with pure css. And the images are hard coded. Later i will fix this and load them via php.

Is there any possibility to get a faster image load? I already rendered the images down to max-width: 800px via photoshop.

答: You simply need to optimize your images for the web.  You are loading a 1200px image for a 200-300px width thumbnail. This is why they are taking so long to load.  To optimize you can get the images to their natural size using an editing tool like photoshop and saving them out at a jpeg quality that suits your needs.  The lower the file size, the faster the images will load.  Not sure what tool you used to build out the page, but you could also implement a technique/plugin know as "Lazy Load".  This will allow to load the images as they come into view, loosening up some bandwidth for the images that load initially.  Hope this helps.</p>


问:
lines in a file with comma
I would like to know how to create a sub file with a number of commas, for example.

123,abc,qwe,ert

123,456,abc,qwe,fgh

I want to create a file .txt with the line that has 4 commas. (123,456,abc,qwe,fgh).

I tried with this.

awk -F\, '{print NF-1}'

But only gives me the number of commas that each line has.

答:
Try this - </p>

```<code>awk -F, 'NF==5 {print > "file.txt"}' f

cat file.txt
123,456,abc,qwe,fgh
</code>```

Title: lines in a file with comma

Body:
Try this -

awk -F, 'NF==5 {print > "file.txt"}' f

cat file.txt
123,456,abc,qwe,fgh


问:
Multiple manipulations to the same variable using dplyr
How can make I several, sequential manipulations of the same variable using dplyr, but more elegantly than the code below?

Specifically, I would like to remove the multiple calls to car_names = without having to nest any of the functions.

```<code>     mtcars2 <- mtcars %>% mutate(car_names = row.names(.)) %>%
        mutate(car_names=stri_extract_first_words(car_names)) %>%
mutate(car_names=as.factor(car_names)
</code>```

答:
If you want to type less and not nest the function, you can use the pipe inside the mutate call :

```<code>library(dplyr)
library(stringi)

# What you did
mtcars2 <- mtcars %>%
  mutate(car_names = row.names(.)) %>%
  mutate(car_names = stri_extract_first_words(car_names)) %>%
  mutate(car_names = as.factor(car_names))

# Another way with less typing and no nesting
mtcars3 <- mtcars %>%
  mutate(car_names = rownames(.) %>%
           stri_extract_first_words(.) %>%
           as.factor(.))

identical(mtcars2, mtcars3)
[1] TRUE
</code>```

Body:
How can make I several, sequential manipulations of the same variable using dplyr, but more elegantly than the code below?

Specifically, I would like to remove the multiple calls to car_names = without having to nest any of the functions.

     mtcars2 <- mtcars %>% mutate(car_names = row.names(.)) %>%
        mutate(car_names=stri_extract_first_words(car_names)) %>%
mutate(car_names=as.factor(car_names)

Body:
If you want to type less and not nest the function, you can use the pipe inside the mutate call :

library(dplyr)
library(stringi)

# What you did
mtcars2 <- mtcars %>%
  mutate(car_names = row.names(.)) %>%
  mutate(car_names = stri_extract_first_words(car_names)) %>%
  mutate(car_names = as.factor(car_names))

# Another way with less typing and no nesting
mtcars3 <- mtcars %>%
  mutate(car_names = rownames(.) %>%
           stri_extract_first_words(.) %>%
           as.factor(.))

identical(mtcars2, mtcars3)
[1] TRUE


问:
how to call web service by supplying credentials in Palm WebOS
I am able to call a web service that doesn't require server credentials. But I need to call a web service which require server credentials(username and password) for authentication. How to call this type of web services by supplying appropriate credentials using Ajax.Request or any other method in Palm WebOS.
Any help would be highly appreciated.
Thanks,</p>

答: If you are using Basic Authentication you could try this: Using Authentication with Ajax.Request</p>

ContentLicense: CC BY-SA 2.5


答:
Remove the [0]. You are dereferencing your jQuery object by doing that.

This works: tempat.append('<input type="text"></input>');


问:
Javascript preventing the submit button to work
I have a js that acts as a "fade" page transition:

```<code>jQuery('body').css('display','none');

jQuery(document).ready(function() {
    jQuery('body').fadeIn();
    jQuery('a').on('click',function(event){
        var thetarget = this.getAttribute('target')

        if (thetarget !="_blank" ) {
            var thehref = this.getAttribute('href')

            event.preventDefault();
            console.log(thehref)
            if(thehref){
                console.log('not null')
                jQuery('body').fadeOut(function(){
                    window.location = thehref
                });
            }
        }
    });
});

setTimeout(function(){
    jQuery('body').fadeIn();
},1000)
</code>```

and I have this form:

```<code><form id = "create_faculty_formcontainer" action = "" method = "post">
    <input type = "text" name = "fac_idnumber" placeholder="ID Number" required/><br/><br/>
    <input type = "text" name = "fac_firstname" placeholder="First Name" required/><br/><br/>
    <input type = "text" name = "fac_lastname" placeholder="Last Name" required/><br/><br/>

    <input type = "password" id = "password_fac" name = "fac_password" placeholder="Password" required/>

    <br/>

    <input type = "submit" name = "fac_submit" value = "       sign up       ">
</form>
</code>```

Whenever I click the submit button, nothing happens. So I tried erasing my javascript and the button worked. The js must have been causing the submit button not to work and I couldn't actually figured what is it or how to fix it.
Any thoughts on how can I keep the javascript and make the submit button work too?

答:
I've figured it out.
Erasing the event.preventDefault(); settles it.
Thanks to Korgrue

Body:
I have a js that acts as a "fade" page transition:

jQuery('body').css('display','none');

jQuery(document).ready(function() {
    jQuery('body').fadeIn();
    jQuery('a').on('click',function(event){
        var thetarget = this.getAttribute('target')

        if (thetarget !="_blank" ) {
            var thehref = this.getAttribute('href')

            event.preventDefault();
            console.log(thehref)
            if(thehref){
                console.log('not null')
                jQuery('body').fadeOut(function(){
                    window.location = thehref
                });
            }
        }
    });
});

setTimeout(function(){
    jQuery('body').fadeIn();
},1000)

and I have this form:

<form id = "create_faculty_formcontainer" action = "" method = "post">
    <input type = "text" name = "fac_idnumber" placeholder="ID Number" required/>

    <input type = "text" name = "fac_firstname" placeholder="First Name" required/>

    <input type = "text" name = "fac_lastname" placeholder="Last Name" required/>

    <input type = "password" id = "password_fac" name = "fac_password" placeholder="Password" required/>

    <input type = "submit" name = "fac_submit" value = "       sign up       ">
</form>

Whenever I click the submit button, nothing happens. So I tried erasing my javascript and the button worked. The js must have been causing the submit button not to work and I couldn't actually figured what is it or how to fix it.
Any thoughts on how can I keep the javascript and make the submit button work too?


问:
IndexError: tuple index out of range with psycopg2
This code has no issues:

```<code>cursor.execute("select message from snippets where keyword=%s", (name,))
</code>```

However, with this I get an IndexError: tuple index out of range

```<code>cursor.execute("select * from table where prescription like '\"%\"%s%'", (string,))
</code>```

Where am I going wrong?

答: In order to enter a literal % in the query you have to use %%.

Body:
This code has no issues:

cursor.execute("select message from snippets where keyword=%s", (name,))

However, with this I get an IndexError: tuple index out of range

cursor.execute("select * from table where prescription like '\"%\"%s%'", (string,))

Where am I going wrong?


问:
cognito + API Gateway. getting status 401
I wrapped the API made using Express with API Gateway.
And I am using Cognito Userpool to authenticate API Gateway.

When I accessed that API using Angular2 http service, normal value returned.
However, when authentication fails, it gets the following error.

```<code>No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.
</code>```

I correctly set up the header mapping, but this time I get this error.

When I access it using Postman, I get the following result.

```<code>{

 "message": "Unauthorized"

}
</code>```

I also want this same result when accessing with Angular2.

Is that possible?

答:
Unfortunately in some error cases (such as 401/403) API Gateway will not return CORS headers, even if properly configured.

We are aware this is a pain point for customers and are working on a solution, but cannot commit to a time frame for when it would be available.

Body:
I wrapped the API made using Express with API Gateway.
And I am using Cognito Userpool to authenticate API Gateway.

When I accessed that API using Angular2 http service, normal value returned.
However, when authentication fails, it gets the following error.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I correctly set up the header mapping, but this time I get this error.

When I access it using Postman, I get the following result.

{

 "message": "Unauthorized"

}

I also want this same result when accessing with Angular2.

Is that possible?


问:
iOS 8 NavigationBar BackgroundImage
With iOS 8 the concept of just iPhone and iPad sizes along with portrait and landscape have changed and therefor setting the navigation bars background image isn't working the same. Currently i'm using the following code:

```<code>UIImage *NavigationPortraitBackground = [[UIImage imageNamed:@"nav-image-portrait"]
                                         resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

UIImage *NavigationLandscapeBackground = [[UIImage imageNamed:@"nav-image-landscape"]
                                          resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

[[UINavigationBar appearance] setBackgroundImage:NavigationPortraitBackground forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:NavigationLandscapeBackground forBarMetrics:UIBarMetricsCompact];
</code>```

The bar metrics portion has been deprecated as of iOS 8. When starting up my app it simply repeats the bar image horizontally when on an iPhone 6 or 6 Plus. I've looked into image slices but i don't think thats the solution either.

答:
THis is sample code at more precis and accurate to fit on all the screen sizes . it will help</p>

```<code>CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"header"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, screenWidth-50, 50)] forBarMetrics:UIBarMetricsDefault];
</code>```

Title: iOS 8 NavigationBar BackgroundImage

Body:
With iOS 8 the concept of just iPhone and iPad sizes along with portrait and landscape have changed and therefor setting the navigation bars background image isn't working the same. Currently i'm using the following code:

UIImage *NavigationPortraitBackground = [[UIImage imageNamed:@"nav-image-portrait"]
                                         resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

UIImage *NavigationLandscapeBackground = [[UIImage imageNamed:@"nav-image-landscape"]
                                          resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];

[[UINavigationBar appearance] setBackgroundImage:NavigationPortraitBackground forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundImage:NavigationLandscapeBackground forBarMetrics:UIBarMetricsCompact];

The bar metrics portion has been deprecated as of iOS 8. When starting up my app it simply repeats the bar image horizontally when on an iPhone 6 or 6 Plus. I've looked into image slices but i don't think thats the solution either.

Body:
THis is sample code at more precis and accurate to fit on all the screen sizes . it will help

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
[[UINavigationBar appearance] setBackgroundImage:[[UIImage imageNamed:@"header"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, screenWidth-50, 50)] forBarMetrics:UIBarMetricsDefault];


问:
SQL - Retrieve Avg Score from Group
My Database contains the following:

```<code>|    ID     |     UID      |     file    |    score    |    time   |
     1    |     a827vgj28df |  jack_123  |      75     |       12:44
     2    |     ayeskfkfjhk  | jack_999   |      5     |      12:12
     3     |    b83759       | adam_123   |      7      |      12:12
</code>```

Goal:
I am trying to get a query that displays the avg scores for each file prefix (jack/adam)

To display like:

```<code>|  Key   |   AVG
  jack       40
  adam        7
</code>```

答:
Should be something like

```<code>select SUBSTRING(file, 1, 4) as Key, AVG(score)
from table
group by SUBSTRING(file, 1, 4)
</code>```

You might get a better response in the future if you share what you've already tried.

Title: SQL - Retrieve Avg Score from Group

Body:
My Database contains the following:

|    ID     |     UID      |     file    |    score    |    time   |
     1    |     a827vgj28df |  jack_123  |      75     |       12:44
     2    |     ayeskfkfjhk  | jack_999   |      5     |      12:12
     3     |    b83759       | adam_123   |      7      |      12:12

Goal:
I am trying to get a query that displays the avg scores for each file prefix (jack/adam)

To display like:

|  Key   |   AVG
  jack       40
  adam        7

Body:
Should be something like

select SUBSTRING(file, 1, 4) as Key, AVG(score)
from table
group by SUBSTRING(file, 1, 4)

You might get a better response in the future if you share what you've already tried.


问:
how to use liferay's Nested Portlet inside my own portlets?
i am developing a portlet for liferay.

i need to include liferay's Nested Portlet in my own portlet.

is it possible?

ps: i am new to liferay. please answer with detail description. ;)

答:
Check the source code of the out-of-the-box portlet that nests other portlets.
In Liferay 5.2.3 it uses com.liferay.portlet.layoutconfiguration.util.RuntimePortletUtil.processPortlet(...) method.

Note: I've been trying to develop separate portlet that would use this API, but got null pointer exceptions inside Liferay logic, so it seems that you'll have to develop your portlet in EXT environment (though this might be different in Liferay 6 for example, I've been using Liferay 5.2.3).


问:
how to make sum.toFixed handle commas with Javascript?
I'm trying to get my javascript to keep calculating the sum of columns after I insert in commas? When I try and insert a number for instance $5,000, it no longer will be able to calculate the sum? I'm quite new to Javascript and have only gotten this far by using code snippets form Stack Overflow. Please help me figure this one last part out. Thanks. Also, I'm using WordPress so that's why my "$" are jQuery. Thanks.

jQuery(document).ready(function() {
  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  jQuery(".txt").each(function() {
    jQuery(this).keyup(function() {
      calculateSum();
    });
  });
});

function calculateSum() {
  var sum = 0;
  //iterate through each textboxes and add the values
  jQuery(".txt").each(function() {
    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }
  });

  var sumQ = [];
  for (var i = 1; i <= 3; i++) {
    sumQ[i] = 0;
    jQuery('td:nth-child(' + (i + 1) + ')').find(".txt").each(function() {
      if (!isNaN(this.value) && this.value.length != 0) {
        sumQ[i] += parseFloat(this.value);
      }
    });
    jQuery(".span7").find('input').eq(i - 1).val(sumQ[i].toFixed(2));
  }

  //.toFixed() method will roundoff the final sum to 2 decimal places
  jQuery("#sum").val(sum.toFixed(2));
}

var revenue = 12345678;
console.log(revenue.formatMoney()); // $12,345,678.00```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.row-fluid.span7.form-inline {
  float: left;
}

.currencyinput {
  border: 1px inset #ccc;
}

.currencyinput input {
  border: 0;
}

.input-icon {
  position: relative;
}

.input-icon>i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon>input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right>i {
  right: 0;
}

.input-icon-right>input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

table thead {
  background-color: #D3D3D3;
  font-weight: bold;
  line-height: 1.5;
  font-size: .8em;
}

thead td {
  padding: 5px;
  vertical-align: middle;
}

table,
th,
td {
  border: 1px solid black;
  padding-left: 10px;
  line-height: 1.5;
}

table tbody {
  font-size: .7em;
}

.dollars:before {
  content: "$";
}

td {
  padding: 5px;
}</code>```

        Expense
        Total Program Expenses
        Amount Requested from LCEF

      Salary and Benefits

          $<input type="text" class="txt input-mini" placeholder="0.00" />

          $<input type="text" class="txt input-mini" />

      Contract Services (consulting, professional, fundraising)

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Occupancy (rent, utilities, maintenance)

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Training & Professional Development

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Insurance

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Travel

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Equipment

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Supplies

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Printing, Copying & Postage

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Evaluation

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Marketing

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Conferences, Meetings, etc.

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Administration

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Other -

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Other -

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

            Quarters' Total

                $<input type="text" readonly="readonly" class="input-mini" />

                $<input type="text" readonly="readonly" class="input-mini" />

```

答:
You can solve this issue by using input type as number instead of text so that it will prevent user's to add any commans or special characters except numbers like this:

jQuery(document).ready(function() {
  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  jQuery(".txt").each(function() {
    jQuery(this).keyup(function() {
      calculateSum();
    });
  });
});

function calculateSum() {
  var sum = 0;
  //iterate through each textboxes and add the values
  jQuery(".txt").each(function() {
    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }
  });

  var sumQ = [];
  for (var i = 1; i <= 3; i++) {
    sumQ[i] = 0;
    jQuery('td:nth-child(' + (i + 1) + ')').find(".txt").each(function() {
      if (!isNaN(this.value) && this.value.length != 0) {
        sumQ[i] += parseFloat(this.value);
      }
    });
    jQuery(".span7").find('input').eq(i - 1).val(sumQ[i].toFixed(2));
  }

  //.toFixed() method will roundoff the final sum to 2 decimal places
  console.log('sum: ', sum);
  jQuery("#sum").val(sum.toFixed(2));
}

var revenue = 12345678;
console.log(revenue); // $12,345,678.00```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.row-fluid.span7.form-inline {
  float: left;
}

.currencyinput {
  border: 1px inset #ccc;
}

.currencyinput input {
  border: 0;
}

.input-icon {
  position: relative;
}

.input-icon>i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon>input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right>i {
  right: 0;
}

.input-icon-right>input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

table thead {
  background-color: #D3D3D3;
  font-weight: bold;
  line-height: 1.5;
  font-size: .8em;
}

thead td {
  padding: 5px;
  vertical-align: middle;
}

table,
th,
td {
  border: 1px solid black;
  padding-left: 10px;
  line-height: 1.5;
}

table tbody {
  font-size: .7em;
}

.dollars:before {
  content: "$";
}

td {
  padding: 5px;
}</code>```

        Expense
        Total Program Expenses
        Amount Requested from LCEF

      Salary and Benefits

          $<input type="number" class="txt input-mini" placeholder="0.00" />

          $<input type="number" class="txt input-mini" />

      Contract Services (consulting, professional, fundraising)

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Occupancy (rent, utilities, maintenance)

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Training & Professional Development

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Insurance

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Travel

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Equipment

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Supplies

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Printing, Copying & Postage

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Evaluation

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Marketing

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Conferences, Meetings, etc.

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Administration

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Other -

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

      Other -

          $<input type="number" class="txt input-mini" />

          $<input type="number" class="txt input-mini" />

            Quarters' Total

                $<input type="number" readonly="readonly" class="input-mini" />

                $<input type="number" readonly="readonly" class="input-mini" />

```

Body:
I'm trying to get my javascript to keep calculating the sum of columns after I insert in commas? When I try and insert a number for instance $5,000, it no longer will be able to calculate the sum? I'm quite new to Javascript and have only gotten this far by using code snippets form Stack Overflow. Please help me figure this one last part out. Thanks. Also, I'm using WordPress so that's why my "$" are jQuery. Thanks.

jQuery(document).ready(function() {
  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  jQuery(".txt").each(function() {
    jQuery(this).keyup(function() {
      calculateSum();
    });
  });
});

function calculateSum() {
  var sum = 0;
  //iterate through each textboxes and add the values
  jQuery(".txt").each(function() {
    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }
  });

  var sumQ = [];
  for (var i = 1; i <= 3; i++) {
    sumQ[i] = 0;
    jQuery('td:nth-child(' + (i + 1) + ')').find(".txt").each(function() {
      if (!isNaN(this.value) && this.value.length != 0) {
        sumQ[i] += parseFloat(this.value);
      }
    });
    jQuery(".span7").find('input').eq(i - 1).val(sumQ[i].toFixed(2));
  }

  //.toFixed() method will roundoff the final sum to 2 decimal places
  jQuery("#sum").val(sum.toFixed(2));
}

var revenue = 12345678;
console.log(revenue.formatMoney()); // $12,345,678.00

div.row-fluid.span7.form-inline {
  float: left;
}

.currencyinput {
  border: 1px inset #ccc;
}

.currencyinput input {
  border: 0;
}

.input-icon {
  position: relative;
}

.input-icon>i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon>input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right>i {
  right: 0;
}

.input-icon-right>input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

table thead {
  background-color: #D3D3D3;
  font-weight: bold;
  line-height: 1.5;
  font-size: .8em;
}

thead td {
  padding: 5px;
  vertical-align: middle;
}

table,
th,
td {
  border: 1px solid black;
  padding-left: 10px;
  line-height: 1.5;
}

table tbody {
  font-size: .7em;
}

.dollars:before {
  content: "$";
}

td {
  padding: 5px;
}

        Expense
        Total Program Expenses
        Amount Requested from LCEF

      Salary and Benefits

          $<input type="text" class="txt input-mini" placeholder="0.00" />

          $<input type="text" class="txt input-mini" />

      Contract Services (consulting, professional, fundraising)

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Occupancy (rent, utilities, maintenance)

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Training & Professional Development

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Insurance

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Travel

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Equipment

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Supplies

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Printing, Copying & Postage

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Evaluation

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Marketing

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Conferences, Meetings, etc.

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Administration

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Other -

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

      Other -

          $<input type="text" class="txt input-mini" />

          $<input type="text" class="txt input-mini" />

            Quarters' Total

                $<input type="text" readonly="readonly" class="input-mini" />

                $<input type="text" readonly="readonly" class="input-mini" />

Body:
You can solve this issue by using input type as number instead of text so that it will prevent user's to add any commans or special characters except numbers like this:

jQuery(document).ready(function() {
  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  jQuery(".txt").each(function() {
    jQuery(this).keyup(function() {
      calculateSum();
    });
  });
});

function calculateSum() {
  var sum = 0;
  //iterate through each textboxes and add the values
  jQuery(".txt").each(function() {
    //add only if the value is number
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }
  });

  var sumQ = [];
  for (var i = 1; i <= 3; i++) {
    sumQ[i] = 0;
    jQuery('td:nth-child(' + (i + 1) + ')').find(".txt").each(function() {
      if (!isNaN(this.value) && this.value.length != 0) {
        sumQ[i] += parseFloat(this.value);
      }
    });
    jQuery(".span7").find('input').eq(i - 1).val(sumQ[i].toFixed(2));
  }

  //.toFixed() method will roundoff the final sum to 2 decimal places
  console.log('sum: ', sum);
  jQuery("#sum").val(sum.toFixed(2));
}

var revenue = 12345678;
console.log(revenue); // $12,345,678.00

div.row-fluid.span7.form-inline {
  float: left;
}

.currencyinput {
  border: 1px inset #ccc;
}

.currencyinput input {
  border: 0;
}

.input-icon {
  position: relative;
}

.input-icon>i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon>input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right>i {
  right: 0;
}

.input-icon-right>input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

table thead {
  background-color: #D3D3D3;
  font-weight: bold;
  line-height: 1.5;
  font-size: .8em;
}

thead td {
  padding: 5px;
  vertical-align: middle;
}

table,
th,
td {
  border: 1px solid black;
  padding-left: 10px;
  line-height: 1.5;
}

table tbody {
  font-size: .7em;
}

.dollars:before {
  content: "$";
}

td {
  padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Expense</th>
        <th>Total Program Expenses</th>
        <th>Amount Requested from LCEF</th>
      </tr>
    </thead>
    <tr>
      <td>Salary and Benefits</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" placeholder="0.00" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>

    </tr>
    <tr>
      <td>Contract Services (consulting, professional, fundraising)</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Occupancy (rent, utilities, maintenance)</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Training & Professional Development</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Insurance</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Travel</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Equipment</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Supplies</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Printing, Copying & Postage</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Evaluation</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Marketing</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Conferences, Meetings, etc.</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td>Administration</td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td contenteditable="true">Other - </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>
    <tr>
      <td contenteditable="true">Other - </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
      <td>
        <div class="input-icon">
          <i>$</i><input type="number" class="txt input-mini" />
        </div>
      </td>
    </tr>

  </table>
  <div class="row-fluid">

    <div class="span7">
      <div class="form-inline">

        <table>
          <tr>
            <td>Quarters' Total</td>
            <td>
              <div class="input-icon">
                <i>$</i><input type="number" readonly="readonly" class="input-mini" />
              </div>
            </td>
            <td>
              <div class="input-icon">
                <i>$</i><input type="number" readonly="readonly" class="input-mini" />
              </div>
            </td>

          </tr>
        </table>
      </div>
    </div>
  </div>
</div>


问:
How can I access the ID of the user that just completed registration form in Gravity Forms?
I am using the Gravity Forms registration plugin to register users on a website I am building and I am trying to add the ID of the newly created user to a URL which gets emailed to specific emails.

I found info herehttp://www.gravityhelp.com/documentation/page/Entry_Object that says you can get the current user ID of the logged in user however the value returns 0 because it seems as though the user isn't quite logged in at the time this function is called.

This is how I am currently trying to access the ID

```<code>add_action("gform_after_submission", "set_post_content_stuff", 10, 2);

function set_post_content_stuff($entry, $form){

//get id of user submitting the form
$currUserID = $entry['created_by'];

}
</code>```

Does anyone know how to access the ID from the wp_users table when a new user is registered?

答:
You can use the gform_user_registered hook to access the recently created user id:

```<code>add_action( 'gform_user_registered', 'send_user_email', 10, 4 );
function send_user_email($user_id, $feed, $entry, $user_pass) {
    // Add function to send email
}
</code>```

See documentation: https://www.gravityhelp.com/documentation/article/gform_user_registered/

Body:
I am using the Gravity Forms registration plugin to register users on a website I am building and I am trying to add the ID of the newly created user to a URL which gets emailed to specific emails.

I found info herehttp://www.gravityhelp.com/documentation/page/Entry_Object that says you can get the current user ID of the logged in user however the value returns 0 because it seems as though the user isn't quite logged in at the time this function is called.

This is how I am currently trying to access the ID

add_action("gform_after_submission", "set_post_content_stuff", 10, 2);

function set_post_content_stuff($entry, $form){

//get id of user submitting the form
$currUserID = $entry['created_by'];

}

Does anyone know how to access the ID from the wp_users table when a new user is registered?

Body:
You can use the gform_user_registered hook to access the recently created user id:

add_action( 'gform_user_registered', 'send_user_email', 10, 4 );
function send_user_email($user_id, $feed, $entry, $user_pass) {
    // Add function to send email
}

See documentation: https://www.gravityhelp.com/documentation/article/gform_user_registered/


答:
You can use substring_index to extract the name prefixes. From there on, it's just a simple use of avg:

```<code>SELECT   SUBSTRING_INDEX(file, '_', 1) AS key, AVG(score)
FROM     mytable
GROUP BY SUBSTRING_INDEX(file, '_', 1)
</code>```

Title: SQL - Retrieve Avg Score from Group

Body:
You can use substring_index to extract the name prefixes. From there on, it's just a simple use of avg:

SELECT   SUBSTRING_INDEX(file, '_', 1) AS key, AVG(score)
FROM     mytable
GROUP BY SUBSTRING_INDEX(file, '_', 1)


问:
Trying to sort a datagrid that is consistantly being updated
I have a datagrid in my WPF program that is updating its data every three seconds. When this happens the sorting of this datagrid resets back to its default. I have 4 Columns, three of which I would like to be sorted. the columns are Name, Aux, Time, and State. I would like the sorting to work in this order:

State Ascending

Aux Descending

Time Descending

I have tried adding sorting in a few different ways programmically but I have been unable to add my datagrid as a resource (I've never done this before) and collectionviewsource in the XAML doesn't work like someone else said it would. It doesn't affect the sorting at all.

here is my datagrid

```<code><DataGrid Name="DataGrid" AutoGenerateColumns="False" IsReadOnly="True" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" ColumnWidth="*"  Foreground="Green" FontSize="10" ItemsSource="{Binding Path=mylist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  Loaded="textBlock_Loaded" Margin="0,10" RenderTransformOrigin="0.127,0.275" Background="{x:Null}" IsSynchronizedWithCurrentItem="False" GridLinesVisibility="Horizontal">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
                    <DataGridTextColumn Header="State" Binding="{Binding AgentState}"  />
                    <DataGridTextColumn Header="Aux" Binding="{Binding AuxReasons}" />
                    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange, StringFormat={}{0:hh}:{0:mm}:{0:ss}}"/>
                </DataGrid.Columns>
            </DataGrid>
</code>```

I think this would work if I could figure out how to get DataGrid as a resource so find resource can access the DataGrid

```<code>   if (e.CmsData != null)
            {
                List<NewAgent> newAgentList = new List<NewAgent>();

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                {
                    foreach (var item in e.CmsData.Agents)
                    {
                        NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

                        newAgents.AgentName = item.AgName;

                        newAgents.AgentExtension = item.Extension;

                        newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

                        newAgents.AuxReasons = item.AuxReasonDescription;

                        newAgents.LoginIdentifier = item.LoginId;

                        newAgents.AgentState = item.WorkModeDirectionDescription;

                        var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
                        newAgents.AgentDateTimeStateChange = timeSpanSince;

                        newAgentList.Add(newAgents);

                    }
                    if (DataGrid.ItemsSource != null)
                    {
                        //This is the line that your are missing
                        var myViewSource = DataGrid.ItemsSource as CollectionViewSource;

                        myViewSource.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
                        myViewSource.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
                        myViewSource.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));
                    }

                    DataGrid.ItemsSource = newAgentList;
                }));
            }
</code>```

my objects defined in a NewAgent class

```<code>class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }
        public string AgentState { get; set; }

    }
</code>```

答:
Actually, you need to get the ItemsSource of your DataGrid and not the DataGrid itself. Like that:

```<code>if (DataGrid.ItemsSource != null)
{
    //This is the line that your are missing
    var myViewSource = DataGrid.ItemsSource as CollectionViewSource;

    myViewSource.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
    myViewSource.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
    myViewSource.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));
}
</code>```

Also make sure that the first parameter of the constructor of SortDescription matches the name of the property that you would like to sort the objects in your collection by ("AgentState", "AuxReasons" and "AgentDateTimeStateChange" in your example).

Since you edited your question with more information, here's what you need to do:

Instead of setting the ItemsSource of your DataGrid to be a list of NewAgent, set it to be a ListCollectionView of your list. Only then you will be able to sort that collection.

So:

```<code>//Create a ListCollectionView of your List of new agents
ListCollectionView myListCollectionView = new ListCollectionView(newAgentList);

//Sort your collection view
myListCollectionView .SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
myListCollectionView .SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
myListCollectionView .SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));

//Bind your data
DataGrid.ItemsSource = myCollectionView;
</code>```

Body:
I have a datagrid in my WPF program that is updating its data every three seconds. When this happens the sorting of this datagrid resets back to its default. I have 4 Columns, three of which I would like to be sorted. the columns are Name, Aux, Time, and State. I would like the sorting to work in this order:

State Ascending

Aux Descending

Time Descending

I have tried adding sorting in a few different ways programmically but I have been unable to add my datagrid as a resource (I've never done this before) and collectionviewsource in the XAML doesn't work like someone else said it would. It doesn't affect the sorting at all.

here is my datagrid

<DataGrid Name="DataGrid" AutoGenerateColumns="False" IsReadOnly="True" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" ColumnWidth="*"  Foreground="Green" FontSize="10" ItemsSource="{Binding Path=mylist, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  Loaded="textBlock_Loaded" Margin="0,10" RenderTransformOrigin="0.127,0.275" Background="{x:Null}" IsSynchronizedWithCurrentItem="False" GridLinesVisibility="Horizontal">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="Name" Binding="{Binding AgentName}"  />
                    <DataGridTextColumn Header="State" Binding="{Binding AgentState}"  />
                    <DataGridTextColumn Header="Aux" Binding="{Binding AuxReasons}" />
                    <DataGridTextColumn Header="Time" Binding="{Binding AgentDateTimeStateChange, StringFormat={}{0:hh}:{0:mm}:{0:ss}}"/>
                </DataGrid.Columns>
            </DataGrid>

I think this would work if I could figure out how to get DataGrid as a resource so find resource can access the DataGrid

   if (e.CmsData != null)
            {
                List<NewAgent> newAgentList = new List<NewAgent>();

                Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
                {
                    foreach (var item in e.CmsData.Agents)
                    {
                        NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

                        newAgents.AgentName = item.AgName;

                        newAgents.AgentExtension = item.Extension;

                        newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

                        newAgents.AuxReasons = item.AuxReasonDescription;

                        newAgents.LoginIdentifier = item.LoginId;

                        newAgents.AgentState = item.WorkModeDirectionDescription;

                        var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
                        newAgents.AgentDateTimeStateChange = timeSpanSince;

                        newAgentList.Add(newAgents);

                    }
                    if (DataGrid.ItemsSource != null)
                    {
                        //This is the line that your are missing
                        var myViewSource = DataGrid.ItemsSource as CollectionViewSource;

                        myViewSource.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
                        myViewSource.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
                        myViewSource.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));
                    }

                    DataGrid.ItemsSource = newAgentList;
                }));
            }

my objects defined in a NewAgent class

class NewAgent
    {
        public string AgentName { get; set; }
        public int AgentExtension { get; set; }
        public TimeSpan AgentDateTimeChange { get; set; }
        public TimeSpan AgentDateTimeStateChange { get; set; }
        public String AuxReasons { get; set; }
        public string LoginIdentifier { get; set; }
        public string AgentState { get; set; }

    }

Body:
Actually, you need to get the ItemsSource of your DataGrid and not the DataGrid itself. Like that:

if (DataGrid.ItemsSource != null)
{
    //This is the line that your are missing
    var myViewSource = DataGrid.ItemsSource as CollectionViewSource;

    myViewSource.SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
    myViewSource.SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
    myViewSource.SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));
}

Also make sure that the first parameter of the constructor of SortDescription matches the name of the property that you would like to sort the objects in your collection by ("AgentState", "AuxReasons" and "AgentDateTimeStateChange" in your example).

Since you edited your question with more information, here's what you need to do:

Instead of setting the ItemsSource of your DataGrid to be a list of NewAgent, set it to be a ListCollectionView of your list. Only then you will be able to sort that collection.

So:

//Create a ListCollectionView of your List of new agents
ListCollectionView myListCollectionView = new ListCollectionView(newAgentList);

//Sort your collection view
myListCollectionView .SortDescriptions.Add(new SortDescription("AgentState", ListSortDirection.Ascending));
myListCollectionView .SortDescriptions.Add(new SortDescription("AuxReasons", ListSortDirection.Descending));
myListCollectionView .SortDescriptions.Add(new SortDescription("AgentDateTimeStateChange", ListSortDirection.Descending));

//Bind your data
DataGrid.ItemsSource = myCollectionView;


问:
{Tricky Excel} How can I plot a time-time vs values chart in Excel?
I have 2 columns:
Column A with data: time - time (example: 08:00:00-15:59:59)
Column B with data: Values from 1 to 20.

I want to see between what hours are values from column B the greatest.

Is it possible to do this in Excel?

答:
So you want something like this?

Formulae are:

c2: =LEFT($A2,8)

d2: =MID($A2,10,99)

e2: =D2-C2

f2: =HOUR(E2)

g2: =MIN(B2,F2)


答:
The problem is that you aren't calling the append element on a jQuery object (which treats strings as HTML), but instead on a native DOM element. The experimental ParentNode#append method treats strings as text, so you are seeing text.

If you omit the [0] before calling append, your code runs perfectly:

$(document).ready(function() {
  $("#post-komentar").click(function() {
    console.log($(this).siblings('.editor-komentar').val());
  });
  $(".reply").click(function() {
    var tempat = $(this).parent().parent().next(".komentar-balasan");
    console.log(tempat[0]);
    var html =
      tempat.append('<input type="text"></input>');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.reply {
  background-color: #fff;
  width: 20px;
  height: 20px;
  margin: 0;
  padding: 0;
}</code>```

<

<button class="reply"></button>

```

Body:
I want append an input text in my html page. I use JQuery to do that.

My JQuery script :

$(document).ready(function(){
    $(".reply").click(function(){
      var tempat=$(this).parent().parent().next(".komentar-balasan");
      console.log(tempat[0]);
      var html=
      tempat[0].append('<input type="text"></input>');
    });
  });

And the HTML :

<button class="reply"></button>

The Fiddle

I Don't know why, but instead of displayed the input text box. The browser just display <input type="text"></input>. It's like the browser didn't recognize the HTML code.

Body:
The problem is that you aren't calling the append element on a jQuery object (which treats strings as HTML), but instead on a native DOM element. The experimental ParentNode#append method treats strings as text, so you are seeing text.

If you omit the [0] before calling append, your code runs perfectly:

$(document).ready(function() {
  $("#post-komentar").click(function() {
    console.log($(this).siblings('.editor-komentar').val());
  });
  $(".reply").click(function() {
    var tempat = $(this).parent().parent().next(".komentar-balasan");
    console.log(tempat[0]);
    var html =
      tempat.append('<input type="text"></input>');
  });
});

.reply {
  background-color: #fff;
  width: 20px;
  height: 20px;
  margin: 0;
  padding: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="isi">
  <div class="like-comment">
    <div class="kotak">&lt;</div>
    <div class="kotak-jumlah">
    </div>
    <div class="kotak"><button class="reply"></button></div>
  </div>
  <div class="komentar-balasan"></div>


问:
Select element grows differently than input in display flex
I'm getting an unexpected behavior in my setup. The inputs grow horizontally as expected but on the row with a select control, the growth seems to be distorted.

I suspected some style to be different but a close inspection led me nowhere. Googling gave nothing and I can't find anything about implicit margin nor padding for selects.

What is this about and how do I kill it?

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="full-page">

  <div>

    <div class="input-section">
      <div class="input-title">Title 1</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Uno</div>
          <input type="text" placeholder="Konrad">
        </div>
        <div class="input-element">
          <div class="input-caption">Duo</div>
          <input type="text" placeholder="Viltersten">
        </div>
      </div>

    </div>

    <div #privs class="input-section">
      <div class="input-title">Title 2</div>

      <div class="input-row">
        <div class="input-element">
          <div class="input-caption">Tress</div>
          <input placeholder="Is really">
        </div>

        <div class="input-element">
          <div class="input-caption">Quatro</div>
          <select>
            <option>The one and only</option>
          </select>
        </div>
      </div>

    </div>

</div></code>```

答:
You're using flex-grow: 1 to size your flex items. That's fine when all items are identical or contain identical content.

Except one of your flex items is different. It has the select element. That will affect the sizing of the item because an initial value of a flex item is flex-basis: auto.

With flex-basis: auto the flex-grow property goes into effect after the width of the item is factored in. Because the width of your items are different, their size after flex-grow is applied will be different.

You need to use flex-basis: 0, which allows flex-grow to ignore the width of the item and focus only on the available space in the container.

Instead of flex-grow: 1 use this:

flex: 1

Which is shorthand for:

flex-grow: 1

flex-shrink: 1

flex-basis: 0

See the spec for more details: https://www.w3.org/TR/css-flexbox-1/#flex-common

Also, to counter problems such as these, the spec recommends always using the flex shorthand as opposed to longhand properties:

7.2. Components of
  Flexibility

Authors are encouraged to control flexibility using the flex
  shorthand rather than with its longhand properties directly, as the
  shorthand correctly resets any unspecified components to accommodate
  common uses.

Body:
I'm getting an unexpected behavior in my setup. The inputs grow horizontally as expected but on the row with a select control, the growth seems to be distorted.

I suspected some style to be different but a close inspection led me nowhere. Googling gave nothing and I can't find anything about implicit margin nor padding for selects.

What is this about and how do I kill it?

div.full-page {
  margin: 20px;
  padding: 20px;
  background: ghostwhite;
}

div.input-section {
  border: 3px none darkorchid;
  width: 600px;
}

div.input-title {
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid darkorange;
  padding-bottom: 5px;
}

div.input-row {
  border: 3px none darkolivegreen;
  display: flex;
}

div.input-element {
  border: 3px none darkcyan;
  padding: 10px;
  flex-grow: 1;
  // display:flex;
}

div.input-element input,
div.input-element select {
  width: 100%;
  // border: solid 1px mediumvioletred;
  // padding: 0;
  // margin: 0;
}

div.input-caption {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  color: darkgrey;
  font-size: 14px;
}

Title 1

Uno

          <input type="text" placeholder="Konrad">

Duo

          <input type="text" placeholder="Viltersten">

Title 2

Tress

          <input placeholder="Is really">

Quatro

          <select>
            <option>The one and only</option>
          </select>


问:
Saving Hive tables between different warehouse directories in HDFS via Spark App
as of now, i'm currently figuring out how to save properly a specific hive table that was derived from a mapped source table in a specific database. let's say that the there would be a separate database for both the tester and developer side. how can i segregate the list of tables that they can access from one another?

For now, i monitor the state of the two databases via HUE. Now, I have a spark program that runs on a yarn cluster that creates a table to be stored depending on whether or not he is a developer or a tester.

The spark program that I've just created is a simple app that reads a table from the current warehouse location and saves a new table named new_table

I have the following hive configuration xml such as the following:

```<code><configuration>
  <property>
    <name>hive.metastore.uris</name>
    <value>thrift://xxxx:9083</value>
  </property>
  <property>
    <name>hive.metastore.client.socket.timeout</name>
    <value>300</value>
  </property>
  <!--<property>
    <name>hive.metastore.warehouse.dir</name>
    <value>/user/yyyy/warehouse</value>
  </property>-->
  <property>
    <name>hive.warehouse.subdir.inherit.perms</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.auto.convert.join</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.auto.convert.join.noconditionaltask.size</name>
    <value>20971520</value>
  </property>
  <property>
    <name>hive.optimize.bucketmapjoin.sortedmerge</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.smbjoin.cache.rows</name>
    <value>10000</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/var/log/hive/operation_logs</value>
  </property>
  <property>
    <name>mapred.reduce.tasks</name>
    <value>-1</value>
  </property>
  <property>
    <name>hive.exec.reducers.bytes.per.reducer</name>
    <value>67108864</value>
  </property>
  <property>
    <name>hive.exec.copyfile.maxsize</name>
    <value>33554432</value>
  </property>
  <property>
    <name>hive.exec.reducers.max</name>
    <value>1099</value>
  </property>
  <property>
    <name>hive.vectorized.groupby.checkinterval</name>
    <value>4096</value>
  </property>
  <property>
    <name>hive.vectorized.groupby.flush.percent</name>
    <value>0.1</value>
  </property>
  <property>
    <name>hive.compute.query.using.stats</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.vectorized.execution.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.vectorized.execution.reduce.enabled</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.merge.mapfiles</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.merge.mapredfiles</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.cbo.enable</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.fetch.task.conversion</name>
    <value>minimal</value>
  </property>
  <property>
    <name>hive.fetch.task.conversion.threshold</name>
    <value>268435456</value>
  </property>
  <property>
    <name>hive.limit.pushdown.memory.usage</name>
    <value>0.1</value>
  </property>
  <property>
    <name>hive.merge.sparkfiles</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.merge.smallfiles.avgsize</name>
    <value>16777216</value>
  </property>
  <property>
    <name>hive.merge.size.per.task</name>
    <value>268435456</value>
  </property>
  <property>
    <name>hive.optimize.reducededuplication</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.optimize.reducededuplication.min.reducer</name>
    <value>4</value>
  </property>
  <property>
    <name>hive.map.aggr</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.map.aggr.hash.percentmemory</name>
    <value>0.5</value>
  </property>
  <property>
    <name>hive.optimize.sort.dynamic.partition</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.execution.engine</name>
    <value>mr</value>
  </property>
  <property>
    <name>spark.executor.memory</name>
    <value>996461772</value>
  </property>
  <property>
    <name>spark.driver.memory</name>
    <value>966367641</value>
  </property>
  <property>
    <name>spark.executor.cores</name>
    <value>4</value>
  </property>
  <property>
    <name>spark.yarn.driver.memoryOverhead</name>
    <value>102</value>
  </property>
  <property>
    <name>spark.yarn.executor.memoryOverhead</name>
    <value>167</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.initialExecutors</name>
    <value>1</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.minExecutors</name>
    <value>1</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.maxExecutors</name>
    <value>2147483647</value>
  </property>
  <property>
    <name>hive.metastore.execute.setugi</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.support.concurrency</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.zookeeper.quorum</name>
    <value>xxxx,xxxx</value>
  </property>
  <property>
    <name>hive.zookeeper.client.port</name>
    <value>2181</value>
  </property>
  <property>
    <name>hbase.zookeeper.quorum</name>
    <value>xxxx,xxxx</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.clientPort</name>
    <value>2181</value>
  </property>
  <property>
    <name>hive.zookeeper.namespace</name>
    <value>hive_zookeeper_namespace_hive</value>
  </property>
  <property>
    <name>hive.cluster.delegation.token.store.class</name>
    <value>org.apache.hadoop.hive.thrift.MemoryTokenStore</value>
  </property>
  <property>
    <name>hive.server2.enable.doAs</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.server2.use.SSL</name>
    <value>false</value>
  </property>
  <property>
    <name>spark.shuffle.service.enabled</name>
    <value>true</value>
  </property>
</configuration>
</code>```

Based from my current understanding, If i change the warehouse location to something upon submitting the spark app on the yarn cluster via hive.warehouse.dir using --files /file/hive-site.xml such as the value of
hdfs:/user/diff/warehouse, the hive configurations on the spark app should detect the following hive tables that exist on the specific directory.

However, upon doing so, it still persists to the location of the default database of the hive.metastore.uris which points to the directory hdfs:/user/hive/warehouse. Based from my understanding, the hive.metastore.uris overrides the database location in hive.metastore.dir.

What am I doing wrong at this point? is there something i need to properly configure in Hive-site.xml? any answers would be appreciated. Thank you. I'm currently a novice developer when it comes to spark and hadoop.

答:
Create separate databases

Demo

Creating the databases is a one time thing

```<code>hive> create database dev_db location '/user/hive/my_databases/dev';
hive> create database tst_db location '/user/hive/my_databases/tst';
</code>```

When you create the table you choose the database you want to work with

```<code>hive> create table dev_db.my_dev_table (i int);
hive> create table tst_db.my_tst_table (i int);
</code>```

```<code>hive> desc formatted dev_db.my_dev_table;
</code>```

```<code># col_name              data_type               comment

i                       int

# Detailed Table Information
Database:               dev_db
...
Location:               hdfs://quickstart.cloudera:8020/user/hive/my_databases/dev/my_dev_table
...
</code>```

```<code>hive> desc formatted tst_db.my_tst_table;
</code>```

```<code>Database:               tst_db
...
Location:               hdfs://quickstart.cloudera:8020/user/hive/my_databases/tst/my_tst_table
...
</code>```

Body:
as of now, i'm currently figuring out how to save properly a specific hive table that was derived from a mapped source table in a specific database. let's say that the there would be a separate database for both the tester and developer side. how can i segregate the list of tables that they can access from one another?

For now, i monitor the state of the two databases via HUE. Now, I have a spark program that runs on a yarn cluster that creates a table to be stored depending on whether or not he is a developer or a tester.

The spark program that I've just created is a simple app that reads a table from the current warehouse location and saves a new table named new_table

I have the following hive configuration xml such as the following:

<configuration>
  <property>
    <name>hive.metastore.uris</name>
    <value>thrift://xxxx:9083</value>
  </property>
  <property>
    <name>hive.metastore.client.socket.timeout</name>
    <value>300</value>
  </property>

  <property>
    <name>hive.warehouse.subdir.inherit.perms</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.auto.convert.join</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.auto.convert.join.noconditionaltask.size</name>
    <value>20971520</value>
  </property>
  <property>
    <name>hive.optimize.bucketmapjoin.sortedmerge</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.smbjoin.cache.rows</name>
    <value>10000</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.server2.logging.operation.log.location</name>
    <value>/var/log/hive/operation_logs</value>
  </property>
  <property>
    <name>mapred.reduce.tasks</name>
    <value>-1</value>
  </property>
  <property>
    <name>hive.exec.reducers.bytes.per.reducer</name>
    <value>67108864</value>
  </property>
  <property>
    <name>hive.exec.copyfile.maxsize</name>
    <value>33554432</value>
  </property>
  <property>
    <name>hive.exec.reducers.max</name>
    <value>1099</value>
  </property>
  <property>
    <name>hive.vectorized.groupby.checkinterval</name>
    <value>4096</value>
  </property>
  <property>
    <name>hive.vectorized.groupby.flush.percent</name>
    <value>0.1</value>
  </property>
  <property>
    <name>hive.compute.query.using.stats</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.vectorized.execution.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.vectorized.execution.reduce.enabled</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.merge.mapfiles</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.merge.mapredfiles</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.cbo.enable</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.fetch.task.conversion</name>
    <value>minimal</value>
  </property>
  <property>
    <name>hive.fetch.task.conversion.threshold</name>
    <value>268435456</value>
  </property>
  <property>
    <name>hive.limit.pushdown.memory.usage</name>
    <value>0.1</value>
  </property>
  <property>
    <name>hive.merge.sparkfiles</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.merge.smallfiles.avgsize</name>
    <value>16777216</value>
  </property>
  <property>
    <name>hive.merge.size.per.task</name>
    <value>268435456</value>
  </property>
  <property>
    <name>hive.optimize.reducededuplication</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.optimize.reducededuplication.min.reducer</name>
    <value>4</value>
  </property>
  <property>
    <name>hive.map.aggr</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.map.aggr.hash.percentmemory</name>
    <value>0.5</value>
  </property>
  <property>
    <name>hive.optimize.sort.dynamic.partition</name>
    <value>false</value>
  </property>
  <property>
    <name>hive.execution.engine</name>
    <value>mr</value>
  </property>
  <property>
    <name>spark.executor.memory</name>
    <value>996461772</value>
  </property>
  <property>
    <name>spark.driver.memory</name>
    <value>966367641</value>
  </property>
  <property>
    <name>spark.executor.cores</name>
    <value>4</value>
  </property>
  <property>
    <name>spark.yarn.driver.memoryOverhead</name>
    <value>102</value>
  </property>
  <property>
    <name>spark.yarn.executor.memoryOverhead</name>
    <value>167</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.enabled</name>
    <value>true</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.initialExecutors</name>
    <value>1</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.minExecutors</name>
    <value>1</value>
  </property>
  <property>
    <name>spark.dynamicAllocation.maxExecutors</name>
    <value>2147483647</value>
  </property>
  <property>
    <name>hive.metastore.execute.setugi</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.support.concurrency</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.zookeeper.quorum</name>
    <value>xxxx,xxxx</value>
  </property>
  <property>
    <name>hive.zookeeper.client.port</name>
    <value>2181</value>
  </property>
  <property>
    <name>hbase.zookeeper.quorum</name>
    <value>xxxx,xxxx</value>
  </property>
  <property>
    <name>hbase.zookeeper.property.clientPort</name>
    <value>2181</value>
  </property>
  <property>
    <name>hive.zookeeper.namespace</name>
    <value>hive_zookeeper_namespace_hive</value>
  </property>
  <property>
    <name>hive.cluster.delegation.token.store.class</name>
    <value>org.apache.hadoop.hive.thrift.MemoryTokenStore</value>
  </property>
  <property>
    <name>hive.server2.enable.doAs</name>
    <value>true</value>
  </property>
  <property>
    <name>hive.server2.use.SSL</name>
    <value>false</value>
  </property>
  <property>
    <name>spark.shuffle.service.enabled</name>
    <value>true</value>
  </property>
</configuration>

Based from my current understanding, If i change the warehouse location to something upon submitting the spark app on the yarn cluster via hive.warehouse.dir using --files /file/hive-site.xml such as the value of
hdfs:/user/diff/warehouse, the hive configurations on the spark app should detect the following hive tables that exist on the specific directory.

However, upon doing so, it still persists to the location of the default database of the hive.metastore.uris which points to the directory hdfs:/user/hive/warehouse. Based from my understanding, the hive.metastore.uris overrides the database location in hive.metastore.dir.

What am I doing wrong at this point? is there something i need to properly configure in Hive-site.xml? any answers would be appreciated. Thank you. I'm currently a novice developer when it comes to spark and hadoop.

Body:
Create separate databases

Demo

Creating the databases is a one time thing

hive> create database dev_db location '/user/hive/my_databases/dev';
hive> create database tst_db location '/user/hive/my_databases/tst';

When you create the table you choose the database you want to work with

hive> create table dev_db.my_dev_table (i int);
hive> create table tst_db.my_tst_table (i int);

hive> desc formatted dev_db.my_dev_table;

# col_name              data_type               comment

i                       int

# Detailed Table Information
Database:               dev_db
...
Location:               hdfs://quickstart.cloudera:8020/user/hive/my_databases/dev/my_dev_table
...

hive> desc formatted tst_db.my_tst_table;

Database:               tst_db
...
Location:               hdfs://quickstart.cloudera:8020/user/hive/my_databases/tst/my_tst_table
...