问:
Vertical Section in angular card
I'm trying to duplicate a mat-card layout and haven't found the right words to search yet. I'm using angular and want to set up a mat-card that has a vertical section on the left hand side which allows me to put a logo that is centered on the section line. I've included a sample image that I'm trying to recreate. example card

My Card

```<code><div class="container">
    <div class="flex-container" fxLayout="row">
        <mat-card>
            <aside>

            </aside>
            <mat-card-header>
                <mat-card-title>{{project.name | uppercase}}</mat-card-title>
                <mat-card-subtitle>{{project.location}}</mat-card-subtitle>
            </mat-card-header>
            <mat-card-content>
                <section>
                    Last Scan: {{project.lastScanDate | date: 'shortDate'}}
                </section>
            </mat-card-content>
        </mat-card>
    </div>
</div>
</code>```

I tried adding an "aside" but that doesn't show up unless I include text.

答:
this is just a raw example of what you want, you can change the icon image by putting your image URL in css,  so this is just an iea how you can do what you want. change the things as per your need.

.flex-container {background: #ccc; padding: 20px 0 0;border-radius: 5px; box-sizing: border-box; border-left: 25px solid #5243AA; min-height: 150px;}
mat-card {display: flex; flex-direction: column; justify-content: space-between;min-height: 150px; padding-left: 20px;}
mat-card-content {margin-left: -20px; background: #fff; padding: 10px;     box-shadow: 1px 3px 7px -1px #ddd;}

mat-card-title {position: relative;}
mat-card-title:after {position: absolute; content: ""; height: 20px; width: 20px; left: -30px; top: 0; background-image: url(https://img.favpng.com/21/1/24/arrow-icon-circle-icon-direction-icon-png-favpng-Lmfw1dQK3ZtSWQX1kUmGXEPVh.jpg); background-size: cover;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="flex-container" fxLayout="row">
    <mat-card>
        <mat-card-header>
            <mat-card-title>{{project.name | uppercase}}</mat-card-title>
        </mat-card-header>
        <mat-card-subtitle>{{project.location}}</mat-card-subtitle>
        <mat-card-content>
            <section>
                Last Scan: {{project.date | date: 'shortDate'}}
            </section>
        </mat-card-content>
    </mat-card>
</div>
</div></code>```

Title: Vertical Section in angular card

Body:
I'm trying to duplicate a mat-card layout and haven't found the right words to search yet. I'm using angular and want to set up a mat-card that has a vertical section on the left hand side which allows me to put a logo that is centered on the section line. I've included a sample image that I'm trying to recreate. example card

My Card

        <mat-card>

            <mat-card-header>
                <mat-card-title>{{project.name | uppercase}}</mat-card-title>
                <mat-card-subtitle>{{project.location}}</mat-card-subtitle>
            </mat-card-header>
            <mat-card-content>

                    Last Scan: {{project.lastScanDate | date: 'shortDate'}}

            </mat-card-content>
        </mat-card>

I tried adding an "aside" but that doesn't show up unless I include text.

Body:
this is just a raw example of what you want, you can change the icon image by putting your image URL in css,  so this is just an iea how you can do what you want. change the things as per your need.

.flex-container {background: #ccc; padding: 20px 0 0;border-radius: 5px; box-sizing: border-box; border-left: 25px solid #5243AA; min-height: 150px;}
mat-card {display: flex; flex-direction: column; justify-content: space-between;min-height: 150px; padding-left: 20px;}
mat-card-content {margin-left: -20px; background: #fff; padding: 10px;     box-shadow: 1px 3px 7px -1px #ddd;}

mat-card-title {position: relative;}
mat-card-title:after {position: absolute; content: ""; height: 20px; width: 20px; left: -30px; top: 0; background-image: url(https://img.favpng.com/21/1/24/arrow-icon-circle-icon-direction-icon-png-favpng-Lmfw1dQK3ZtSWQX1kUmGXEPVh.jpg); background-size: cover;}

<div class="container">
<div class="flex-container" fxLayout="row">
    <mat-card>
        <mat-card-header>
            <mat-card-title>{{project.name | uppercase}}</mat-card-title>
        </mat-card-header>
        <mat-card-subtitle>{{project.location}}</mat-card-subtitle>
        <mat-card-content>
            <section>
                Last Scan: {{project.date | date: 'shortDate'}}
            </section>
        </mat-card-content>
    </mat-card>
</div>
</div>


来源: stackexchange

问:
Find nid from node's internal path in Drupal?
I have a path like this:

/news/2011/05/26/some-story-path

How do I find the nid for the node that the path points to?

Edit

The path above is simply a string value that I have on another page. I need to obtain information about the node that the path links to.

答:
You could use menu_get_object:

```<code>$node = menu_get_object();
</code>```

See http://api.drupal.org/api/drupal/includes--menu.inc/function/menu_get_object/6

edit

I think you can specify your path like this

```<code>menu_get_object($type = 'node', $position = 1, $path = '/news/2011/05/26/some-story-path');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You could use menu_get_object:

$node = menu_get_object();

See http://api.drupal.org/api/drupal/includes--menu.inc/function/menu_get_object/6

edit

I think you can specify your path like this

menu_get_object($type = 'node', $position = 1, $path = '/news/2011/05/26/some-story-path');


问:
scroll to bottom of div after refreshing
I've got some basic ajax to load new messages in my chat, and I have it set to refresh the div with .load, and scroll to bottom with scroll height... only problem is, .load is forcing the div to top, while scrollheight is forcing to bottom, so my chat is just bouncing up and down. I've tried everything I can think to fix this, but nothing is working. </p>

```<code><script>
setInterval("scroll();",1000);
function scroll(){
var element = document.getElementById("chit");
    element.scrollTop = element.scrollHeight;
    $('#hat').load(location.href + ' #chit');
}
</script>

<?php   if(isset($_GET['user'])){ global $con;
    $get_id = $_GET['user'];
    $get_user = "select * from users where user_name='$get_id'";
    $run_user = mysqli_query($con,$get_user);
    $row_user = mysqli_fetch_array($run_user);
    $user2 = $row_user['user_name'];
    }
?>
<main role="main" id="chat" align="center">
<div id="chat_tit" align="center"><?php echo $user2 ; ?></div>
<div id="hat">
<div id="chit" align="left">

<?php
$c_hat = "SELECT * FROM msg WHERE (user_to='$user' AND user_from='$user2') OR (user_from='$user' AND user_to='$user2')";
$run_chat = mysqli_query($con,$c_hat);

            while($chat=mysqli_fetch_array($run_chat)){
                $from = $chat['user_from'];
                $msg = $chat['msg_body'];
                $time = ago($chat['date']);

echo '<div id="chat_box"><div id="from">[<a href="pfp.php?user_name='.$from.'">'.$from.'</a>]</div><div id="time">'.$time.'</div><div id="msg">'.$msg.'</div>

<div id="underline"></div>

</div>';

}
?>
</div>
</div>
</code>```

答: It looks like you are using setInterval() when you may need to use setTimeout(). setInterval() is being called every second so this could be why it is jumping. setTimeout() would only be called once.

ContentLicense: CC BY-SA 4.0

Body:
I've got some basic ajax to load new messages in my chat, and I have it set to refresh the div with .load, and scroll to bottom with scroll height... only problem is, .load is forcing the div to top, while scrollheight is forcing to bottom, so my chat is just bouncing up and down. I've tried everything I can think to fix this, but nothing is working.

<?php   if(isset($_GET['user'])){ global $con;
    $get_id = $_GET['user'];
    $get_user = "select * from users where user_name='$get_id'";
    $run_user = mysqli_query($con,$get_user);
    $row_user = mysqli_fetch_array($run_user);
    $user2 = $row_user['user_name'];
    }
?>

<?php echo $user2 ; ?>

<?php
$c_hat = "SELECT * FROM msg WHERE (user_to='$user' AND user_from='$user2') OR (user_from='$user' AND user_to='$user2')";
$run_chat = mysqli_query($con,$c_hat);

            while($chat=mysqli_fetch_array($run_chat)){
                $from = $chat['user_from'];
                $msg = $chat['msg_body'];
                $time = ago($chat['date']);

echo '

['.$from.']

'.$time.'

'.$msg.'

';

}
?>


问:
How to update chromedriver to the latest version on MacOS using homebrew?
My current version is 81.0.4044.69 and I want to update to the latest version 83.0.4103.39

When I open Terminal and I do:
brew cask install chromedriver

It says:
Warning: Cask 'chromedriver' is already installed.

How can I update to the latest version 83.0.4103.39?

答:
UPDATE: Now you can also do:

```<code>brew update
brew upgrade chromedriver
</code>```

or

```<code>brew update
brew upgrade --cask chromedriver
</code>```

Also be aware that after each upgrade you will get again a system warning when using the chromedriver for the first time so you need to click Cancel in the warning and then go to "Preferences => Security & Privacy" and click "Allow Anyway" to accept the risk. Then on the next run, you'll have to click "Open" once.

Note: The answer below was given for an older version and may not work anymore

I found out that I should do:

```<code>brew update
brew cask upgrade chromedriver
</code>```

Another option is to uninstall and install it again like this:

```<code>brew cask uninstall chromedriver
==> Uninstalling Cask chromedriver
==> Unlinking Binary '/usr/local/bin/chromedriver'.
==> Purging files for version 81.0.4044.69 of Cask chromedriver

brew cask install chromedriver
==> Downloading https://chromedriver.storage.googleapis.com/83.0.4103.39/chromedriver_mac64.zip
######################################################################## 100.0%
==> Verifying SHA-256 checksum for Cask 'chromedriver'.
==> Installing Cask chromedriver
==> Linking Binary 'chromedriver' to '/usr/local/bin/chromedriver'.
  chromedriver was successfully installed!
</code>```

Now:

```<code>chromedriver --version
ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})
</code>```

Body:
UPDATE: Now you can also do:

brew update
brew upgrade chromedriver

or

brew update
brew upgrade --cask chromedriver

Also be aware that after each upgrade you will get again a system warning when using the chromedriver for the first time so you need to click Cancel in the warning and then go to "Preferences => Security & Privacy" and click "Allow Anyway" to accept the risk. Then on the next run, you'll have to click "Open" once.

Note: The answer below was given for an older version and may not work anymore

I found out that I should do:

brew update
brew cask upgrade chromedriver

Another option is to uninstall and install it again like this:

brew cask uninstall chromedriver
==> Uninstalling Cask chromedriver
==> Unlinking Binary '/usr/local/bin/chromedriver'.
==> Purging files for version 81.0.4044.69 of Cask chromedriver

brew cask install chromedriver
==> Downloading https://chromedriver.storage.googleapis.com/83.0.4103.39/chromedriver_mac64.zip
######################################################################## 100.0%
==> Verifying SHA-256 checksum for Cask 'chromedriver'.
==> Installing Cask chromedriver
==> Linking Binary 'chromedriver' to '/usr/local/bin/chromedriver'.
  chromedriver was successfully installed!

Now:

chromedriver --version
ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})


问:
url rewriting + Asp.Net Login Form = Death
on our site we do url rewriting to generate massive amounts of database generated pages. on every page, there is a Login control for users. like this:

Internal aspx page: /DB.aspx?id=123
User visible url: /ABC/123.aspx, /ABC/456.aspx ... (url rewritten)

unfortunately, the  tag on each page has an action attribute of "DB.aspx?id=123". when the user clicks the button the browser is posting to /ABC/DB.aspx?id=123 which of course does not exist.

solutions i tried:
1. change the action attribute by subclassing HtmlForm. this destroys the all other forms on the site.
2. remove the action attribute (so that the browser is always posting to the same url). this works on the rewritten pages but on "/" (the default.aspx in the root dir) i get a message that the verb post is not allowed on "/" (iis 6 and i have no control over mappings)

anybody?

答:
Check this really nice blog post from scott gu, http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx.

"Specifically, you can take advantage of the new ASP.NET 2.0 Control Adapter extensibility architecture to customize the rendering of the  control, and override its "action" attribute value with a value you provide.  This doesn't require you to change any code in your .aspx pages"

Check the section: "Handling ASP.NET PostBacks with URL Rewriting", I have used the adapter he posted successfully.

Ps. be aware there are some issues on asp.net when using url rewrite when using cookieless session, and the rewritten url is deeper than the original page, just like the one you have. (/abc/apage vs. /db?). The issue is right into the source code of the framework, there are workarounds but that's a whole subject (with tradeoffs :( ... you might want to have them at the same level).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
how to add multiple line breaks conveniently in shiny?
I want put multiple line breaks in my shiny app.
Instead of

```<code>br(),
br(),
br(),
...
</code>```

is there any more convenient way of doing it?Thanks.

答:
I have no idea if that's convenient for you, but it saves you some typing.

linebreaks(n) repeats
 n times and parses it as HTML.

```<code>library(shiny)

linebreaks <- function(n){HTML(strrep(br(), n))}

ui <- fluidPage(

  titlePanel(
              p(
                  h1("first sentence", align = "center"),

                  linebreaks(10),

                  h3("second sentence", align = "center")
                )
              )
  )

</code>```

Body:
I want put multiple line breaks in my shiny app.
Instead of

br(),
br(),
br(),
...

is there any more convenient way of doing it?Thanks.

Body:
I have no idea if that's convenient for you, but it saves you some typing.

linebreaks(n) repeats <br/> n times and parses it as HTML.

library(shiny)

linebreaks <- function(n){HTML(strrep(br(), n))}

ui <- fluidPage(

  titlePanel(
              p(
                  h1("first sentence", align = "center"),

                  linebreaks(10),

                  h3("second sentence", align = "center")
                )
              )
  )


问:
Retrive Values From Enum
How can i recieve a specific value from an enum from a given index.

```<code>
enum genre { Pop, Jazz, Classic}; //enum
struct album
{

    string album_name;
    genre kind;
    int track_number;
    string tracks[5];
    string tracklocation;
};

void main()
{
    album x1;
    cout<<"Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    cin>>temp;
    x1.kind=(genre)temp;   // typecasting for int to enum
    cout<<x1.kind<<endl;
}
</code>```

When i run this code i just get the integer value i input , instead of the converted enum value

what i need is when user input 0,1 or 2 it needs to be converted using the enum to the relevant genre and saved in the stucture variable.

答:
You can't put the identifiers (names) of an enum to cout. For example, the value of the name Pi in enum, suppose it's set to 3.14. You directly wants the user would type that value, it'll show the string Pi in output stream, but no, it's only within supposed within the code. Enumeration just holds the constants.

By default, your declaration enum {Pop, Jazz, Classic} holds the constant values 0, 1 and 2 respectively.

Rather, you could use arrayed string to get a value. Consider the following example:

```<code>struct album {
    string album_name;
    string genre[3] = {"Pop", "Jazz", "Classic"}; // this one holds 0 = "Pop" ...
    int track_number;
    string tracks[5];
    string tracklocation;
};
</code>```

And the driver code:

```<code>int main(void) {
    album x1;
    int temp;

    std::cout << "Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    std::cin >> temp;

    std::cout << x1.genre[temp] << endl;
    // will display 0 = "Pop", 1 = "Jazz", 2 = "Classic"

    return 0;
}
</code>```

Title: Retrive Values From Enum

Body:
How can i recieve a specific value from an enum from a given index.

enum genre { Pop, Jazz, Classic}; //enum
struct album
{

    string album_name;
    genre kind;
    int track_number;
    string tracks[5];
    string tracklocation;
};

void main()
{
    album x1;
    cout<<"Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    cin>>temp;
    x1.kind=(genre)temp;   // typecasting for int to enum
    cout<<x1.kind<<endl;
}

When i run this code i just get the integer value i input , instead of the converted enum value

what i need is when user input 0,1 or 2 it needs to be converted using the enum to the relevant genre and saved in the stucture variable.

Body:
You can't put the identifiers (names) of an enum to cout. For example, the value of the name Pi in enum, suppose it's set to 3.14. You directly wants the user would type that value, it'll show the string Pi in output stream, but no, it's only within supposed within the code. Enumeration just holds the constants.

By default, your declaration enum {Pop, Jazz, Classic} holds the constant values 0, 1 and 2 respectively.

Rather, you could use arrayed string to get a value. Consider the following example:

struct album {
    string album_name;
    string genre[3] = {"Pop", "Jazz", "Classic"}; // this one holds 0 = "Pop" ...
    int track_number;
    string tracks[5];
    string tracklocation;
};

And the driver code:

int main(void) {
    album x1;
    int temp;

    std::cout << "Enter genre 0->pop, 1->Jazz, 2->Classic\n";
    std::cin >> temp;

    std::cout << x1.genre[temp] << endl;
    // will display 0 = "Pop", 1 = "Jazz", 2 = "Classic"

    return 0;
}


问:
How to make an intro animation dissappear at the end or lead to a homepage with CSS?
I'm struggling a lil with my CSS code when trying to make an intro animation disappear or become transparent once it's finished, so we can see the rest of the HTML (the homepage).

here's what I'm talking about:

    body {
        background: #000;
    }

    .container{
        text-align: center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
    }

    .container span {
        text-transform: uppercase;
        display: block;
    }

    .text1 {
        color: white;
        font-size: 60px;
        font-weight: bold;
        letter-spacing: 8px;
        margin-bottom: 20px;
        background: black;
        position: relative;
        animation: text 4s 1;
    }

    .text2{
        font-size: 30px;
        color: coral;
    }

    @keyframes text {
        0% {
            color: black;
            margin-bottom: -40px;
        }
        30% {
            letter-spacing: 25px;
            margin-bottom: -40px;
        }
        75% {
            letter-spacing: 8px;
            margin-bottom: -40px;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="./resources/index.css">
    </head>
    <body>

        <div class="animationbkg">
        <div class="container">
            <span class="text1"> Welcome to blablabla</span>
            <span class="text2"> Your journey to blablabla</span>
        </div>
        </div>
        <main>
            <div class="box1">
                <h1>SEEK, STRIVE, SUCCEED</h1>
            </div>
        </main>

     </body>
    </html> </code>```

NOW, what I want to do is that on my keyframe, the black background and the text become transparent or simply disappear once it reaches 100%; so we can see the homepage (main of the HTML)
Regards!

答:
You also have to animate your loading container to fade out somehow so that that the underlying content can appear. Something like this :-

```<code>.animationbkg {
    height: 100vh;
    width: 100%;
    position: fixed;
    z-index: 1;
    background-color: black;
    animation: fadeOut 1s forwards 4s ease;
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        visibility: visible;
    }

    100% {
        opacity: 0;
        visibility: hidden;
        display: none;
    }
}
</code>```

Notice that we've set a delay of 4s to the fadeOut animation, this ensures that the .animationbkg container fades out only after your initial text animation has finished.

The position : fixed, and z-index: 1 just make sure that your animation container is stacked on the top and occupies the entire screen.

Also make sure that you use a forwards animation fill mode so that the elements retain the property that they acquired in the last keyframe of the animation.

Body:
I'm struggling a lil with my CSS code when trying to make an intro animation disappear or become transparent once it's finished, so we can see the rest of the HTML (the homepage).

here's what I'm talking about:

    body {
        background: #000;
    }

    .container{
        text-align: center;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
    }

    .container span {
        text-transform: uppercase;
        display: block;
    }

    .text1 {
        color: white;
        font-size: 60px;
        font-weight: bold;
        letter-spacing: 8px;
        margin-bottom: 20px;
        background: black;
        position: relative;
        animation: text 4s 1;
    }

    .text2{
        font-size: 30px;
        color: coral;
    }

    @keyframes text {
        0% {
            color: black;
            margin-bottom: -40px;
        }
        30% {
            letter-spacing: 25px;
            margin-bottom: -40px;
        }
        75% {
            letter-spacing: 8px;
            margin-bottom: -40px;
        }
    }

    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="./resources/index.css">

             Welcome to blablabla
             Your journey to blablabla

SEEK, STRIVE, SUCCEED

NOW, what I want to do is that on my keyframe, the black background and the text become transparent or simply disappear once it reaches 100%; so we can see the homepage (main of the HTML)
Regards!

Body:
You also have to animate your loading container to fade out somehow so that that the underlying content can appear. Something like this :-

.animationbkg {
    height: 100vh;
    width: 100%;
    position: fixed;
    z-index: 1;
    background-color: black;
    animation: fadeOut 1s forwards 4s ease;
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        visibility: visible;
    }

    100% {
        opacity: 0;
        visibility: hidden;
        display: none;
    }
}

Notice that we've set a delay of 4s to the fadeOut animation, this ensures that the .animationbkg container fades out only after your initial text animation has finished.

The position : fixed, and z-index: 1 just make sure that your animation container is stacked on the top and occupies the entire screen.

Also make sure that you use a forwards animation fill mode so that the elements retain the property that they acquired in the last keyframe of the animation.


问:
How find with Sequelize results where column A > column B + column C
DB table with 3 columns - A int, B int, C int

My problem is: How to find with sequelize results where A > B + C

```<code>const countTasks = await Tasks.count({
    where: {
        A: {
            [Op.gt]: B + C // ???
        },
    },
});
</code>```

Thanks!

答:
You can try something like this:</p>

```<code>SELECT *
  FROM table
 WHERE A > B+C;
</code>```

Body:
DB table with 3 columns - A int, B int, C int

My problem is: How to find with sequelize results where A > B + C

const countTasks = await Tasks.count({
    where: {
        A: {
            [Op.gt]: B + C // ???
        },
    },
});

Thanks!

Body:
You can try something like this:

SELECT *
  FROM table
 WHERE A > B+C;


问:
diplay: fixed doesnt seem to work on a button
I have no idea why but this button just wont display: fixed; I have no idea what to try

```<code>   <div>

     <button class="drop_buttton">DROPDOWN</button>

   </div>
</code>```

.

```<code> .drop_buttton {
  padding: 30px;
  background-color: green;
  border: none;
  display: fixed;
  bottom: 2%;
  left: 2%;
 }
</code>```

答: There is no such property like display: fixed, rather use position: fixed

Body:
I have no idea why but this button just wont display: fixed; I have no idea what to try

     <button class="drop_buttton">DROPDOWN</button>

.

 .drop_buttton {
  padding: 30px;
  background-color: green;
  border: none;
  display: fixed;
  bottom: 2%;
  left: 2%;
 }


问:
Create Object (in ViewSet class) with Celery Task in Django
Hello I encountered a problem which i am not able to solve by myself. I tried to call function create_with_celery inside create but it didnt work

How should I call create.delay with proper arguments?
I don't know how to properly call create function to make workers create objects

```<code>class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    @app.task(bind=True)
    def create(self, request):
        article = Article.objects.create(link=request.data['link'])
        article.save()
        serializer = ArticleSerializer(article, many=False)

        words = WordList(article.link)
        # take every 90nth word for faster loading only dev approach
        i = 0
        for word in range(0, len(words.list)):

            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,
                                                                   len(words.list), words[word]))

        response = {'message': 'Article created ', 'result': serializer.data}
        return Response(response, status=status.HTTP_200_OK)
</code>```

Im trying to do something like this but I get error "Object of type 'Article' is not JSON serializable"

```<code>class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    @app.task(bind=True)
    def create_with_celery(self, article, serializer, words, req):
        i = 0
        for word in range(0, len(words.list)):
            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )

                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,len(words.list), words[word]))

def create(self, request):
    article = Article.objects.create(link=request.data['link'])
    article.save()
    serializer = ArticleSerializer(article, many=False)
    words = WordList(article.link)
    req = request

    self.create_with_celery.delay(article, serializer, words, req)

    response = {'message': 'Article created ', 'result': serializer.data}
    return Response(response, status=status.HTTP_200_OK)
</code>```

答: You can only pass basic types supported in JSON.</p>

Body:
Hello I encountered a problem which i am not able to solve by myself. I tried to call function create_with_celery inside create but it didnt work

How should I call create.delay with proper arguments?
I don't know how to properly call create function to make workers create objects

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    @app.task(bind=True)
    def create(self, request):
        article = Article.objects.create(link=request.data['link'])
        article.save()
        serializer = ArticleSerializer(article, many=False)

        words = WordList(article.link)
        # take every 90nth word for faster loading only dev approach
        i = 0
        for word in range(0, len(words.list)):

            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,
                                                                   len(words.list), words[word]))

        response = {'message': 'Article created ', 'result': serializer.data}
        return Response(response, status=status.HTTP_200_OK)

Im trying to do something like this but I get error "Object of type 'Article' is not JSON serializable"

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

    @app.task(bind=True)
    def create_with_celery(self, article, serializer, words, req):
        i = 0
        for word in range(0, len(words.list)):
            # try to take word from database
            i += 1
            try:
                existing_word = Word.objects.filter(name=words[word])
                Word.objects.create(
                    name=existing_word[0].name,
                    advance_level=existing_word[0].advance_level,
                    definition=existing_word[0].definition,
                    article=Article.objects.get(id=article.id)
                )

                print('word nr {}/{} "{}" created from database'.format(i,
                                                                        len(words.list), words[word]))

            except:
                # if it's not existing fetch data from web
                Word.objects.create(
                    name=words[word],
                    advance_level=get_word_frequency(words[word]),
                    definition=get_word_definition(words[word]),
                    article=Article.objects.get(id=article.id)
                )
                print('word nr {}/{} "{}" fetched from web'.format(i,len(words.list), words[word]))

def create(self, request):
    article = Article.objects.create(link=request.data['link'])
    article.save()
    serializer = ArticleSerializer(article, many=False)
    words = WordList(article.link)
    req = request

    self.create_with_celery.delay(article, serializer, words, req)

    response = {'message': 'Article created ', 'result': serializer.data}
    return Response(response, status=status.HTTP_200_OK)


问:
React Editable Text Component with Custom Syntax Highlighting Support
Good evening all,

I need an editable textarea-like component for my React project that supports custom syntax highlighting, preferably with the CSON and CSS. I have been searching it for ages. I finally gave up and decided to ask here. Does anyone know any reliable library that can be used for this?

Any help would be greatly appreciated!

EDIT: As I delve deeper into the topic, I came to an understanding that this problem consists of several parts.

[mostly done with this one] Create contenteditable div component with React. I used contentEditable component for React.

Find a way to customize appearance of the div (as React fills div's innerHTML as String)

Find a way to implement a parser that reads tags from a CSON and applies 2nd item for each of them.

答: This is way after the fact but for anyone else stumbling on this, https://github.com/satya164/react-simple-code-editor is a good, easy option.</p>


问:
Mockito: multiple calls to mocked UriBuilder keep appending to original URI
I am currently writing some unit tests for legacy code in a rest api application. One particular api call generates a list of URIs using the UriInfo api from Jax-RS. When I mock this interface, I am able to get the tests to run, but each call to the interface appears to reuse the same URI object and appends to it over and over, rather then a new URI object being passed to the tested code. I have a sample class with test that demonstates the issue:

```<code>import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Stateless
@Path("/")
public class MockitoUrl {

    @PersistenceContext(name = "MockitoTestPU")
    private EntityManager em;
    @Context
    private UriInfo uriInfo;

    @Path("system")
    @GET
    @Produces("text")
    public List<URI> generateUris() {
        List<URI> uris = new LinkedList<>();
        for (int i=1;i<5;i++) {
            final URI uri = uriInfo.getBaseUriBuilder().path(
                    MockitoUrl.class, "generateUris").build("test");
            System.out.println(uri.toString());
        }
        return uris;
    }

}
</code>```

The unit test:

```<code>import java.net.URI;
import java.util.List;
import javax.persistence.EntityManager;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;

public class MockitoUrlTest {

    @Mock
    private EntityManager em;
    @Mock
    private UriInfo uri;
    @InjectMocks
    MockitoUrl mockitoUrl;

    public MockitoUrlTest() {
    }

    @Before
    public void setUp() {
        mockitoUrl = new MockitoUrl();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGenerateUris() throws Exception {
        System.out.println("generateUris");
        String baseUri = "http://server1/api";

        when(uri.getBaseUriBuilder()).thenReturn(UriBuilder.fromUri(baseUri));

        List<URI>result = mockitoUrl.generateUris();

        for (URI u : result) {
            assertTrue(u instanceof URI);
            System.out.println(u.toString());
        }
    }

}
</code>```

When the test is run, the output can be seen thus:

```<code>generateUris
http://server1/api/system
http://server1/api/system/system
http://server1/api/system/system/system
http://server1/api/system/system/system/system
</code>```

What I would have expected is that it would return the same URI each time. In the real application these URIs would have more detail and each would have different data from a JPA class lookup. It seems that the same object is returned each time and then appended to again.

Is there a way to get Mockito to return a fresh URI each time uriInfo.getBaseUriBuilder() is called, or is this a fundamental misunderstanding I have about how Mockito works?

答:
The problem you face is expected behavior. When setting up the mock you create a single instance and that is always returned.

To get what you want I would suggest using when(..).thenAnswer(i -> UriBuilder.fromUri(baseUri))

By this every call executes the provides lambda and it creates a new instance per invocation.

Body:
I am currently writing some unit tests for legacy code in a rest api application. One particular api call generates a list of URIs using the UriInfo api from Jax-RS. When I mock this interface, I am able to get the tests to run, but each call to the interface appears to reuse the same URI object and appends to it over and over, rather then a new URI object being passed to the tested code. I have a sample class with test that demonstates the issue:

import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Stateless
@Path("/")
public class MockitoUrl {

    @PersistenceContext(name = "MockitoTestPU")
    private EntityManager em;
    @Context
    private UriInfo uriInfo;

    @Path("system")
    @GET
    @Produces("text")
    public List<URI> generateUris() {
        List<URI> uris = new LinkedList<>();
        for (int i=1;i<5;i++) {
            final URI uri = uriInfo.getBaseUriBuilder().path(
                    MockitoUrl.class, "generateUris").build("test");
            System.out.println(uri.toString());
        }
        return uris;
    }

}

The unit test:

import java.net.URI;
import java.util.List;
import javax.persistence.EntityManager;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;

public class MockitoUrlTest {

    @Mock
    private EntityManager em;
    @Mock
    private UriInfo uri;
    @InjectMocks
    MockitoUrl mockitoUrl;

    public MockitoUrlTest() {
    }

    @Before
    public void setUp() {
        mockitoUrl = new MockitoUrl();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGenerateUris() throws Exception {
        System.out.println("generateUris");
        String baseUri = "http://server1/api";

        when(uri.getBaseUriBuilder()).thenReturn(UriBuilder.fromUri(baseUri));

        List<URI>result = mockitoUrl.generateUris();

        for (URI u : result) {
            assertTrue(u instanceof URI);
            System.out.println(u.toString());
        }
    }

}

When the test is run, the output can be seen thus:

generateUris
http://server1/api/system
http://server1/api/system/system
http://server1/api/system/system/system
http://server1/api/system/system/system/system

What I would have expected is that it would return the same URI each time. In the real application these URIs would have more detail and each would have different data from a JPA class lookup. It seems that the same object is returned each time and then appended to again.

Is there a way to get Mockito to return a fresh URI each time uriInfo.getBaseUriBuilder() is called, or is this a fundamental misunderstanding I have about how Mockito works?


问:
Case_when dplyr
I am trying to create a buy/sell signal.  I am trying to assign the signal using a case_when statement.  I created several new columns using tidyquant TQ_MUTATE in a previous step.  This only assigns the "possible up" and "possible down" signals.

What am I doing wrong?

df_with_decisions <- test %>%
  group_by(symbol) %>%
  mutate(

```<code>signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 && EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55 && EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 && EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55 && EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )
</code>```

答:
Logical error too.

```<code>case_when(
  (5 > 3) ~ "Hi",
  ((5 > 3) & (6 > 3)) ~ "Hello"
)
</code>```

This will not print Hello

Title: Case_when dplyr

Body:
I am trying to create a buy/sell signal.  I am trying to assign the signal using a case_when statement.  I created several new columns using tidyquant TQ_MUTATE in a previous step.  This only assigns the "possible up" and "possible down" signals.

What am I doing wrong?

df_with_decisions <- test %>%
  group_by(symbol) %>%
  mutate(

signal = case_when(
   (EMA_9 > EMA_55) ~ "possible up",
  (EMA_9 > EMA_55 && EVWMA_9 > EMA_55) ~ "watch upward",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55) ~ "buy",
  (EMA_9 > EMA_55 && EMA_21 >= EMA_55 && EVWMA_9 > EMA_55 && EVWMA_21 > EMA_55) ~ "strong_buy",
  EMA_9 < EMA_55 ~ "possible down",
  (EMA_9 < EMA_55 && EVWMA_9 < EMA_55) ~ "watch downward",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55) ~ "sell",
  (EMA_9 < EMA_55 && EMA_21 <= EMA_55 && EVWMA_9 < EMA_55 && EVWMA_21 < EMA_55) ~ "strong_sell",
  ),

previous_signal = lag(signal, 1),

decision = case_when(
  signal == previous_signal ~ "hold",
  TRUE ~ signal    )  )

Body:
Logical error too.

case_when(
  (5 > 3) ~ "Hi",
  ((5 > 3) & (6 > 3)) ~ "Hello"
)

This will not print Hello


问:
Increasing number of semaphore handles
I have the following problem. In one of the libraries I noticed increasing number of events and semaphore handles. The only synchronization primitive I'm using is CriticalSection. What can be the cause of increasing handles that are not being closed?

OS: Windows Server 2003 R2
Compiler: Microsoft C++ 2003

答: Though not a kernel object, a critical section internally uses other kernel objects such as event and/or semaphore (see e.g. an article in MSDN Magazine; though it's quite old and the structures discussed there can be somewhat different in modern versions of Windows). So as others noted in comments, if you do not correctly release critical sections by calling DeleteCriticalSection, the number of handles in use will increase.

Title: Increasing number of semaphore handles


问:
How to set date range selection in react JS DateRangePicker?
I am using 'DateRangePicker' component in my react JS application.
I am trying to restrict start date to last 6 month only and difference between
start and end date should not be more than 1 month.
I wrote following code

```<code>isOutsideRange = (day) => {
  if (day > moment()) return true;
  else if (this.state.startDate) {
    if (day > moment(this.state.endDate)) return true;
    if (day < moment().subtract(6, 'months')) return true;
    else return false;
  } else if (this.state.endDate) {
    if (day > moment(this.state.endDate)) return true;
    if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
    else return false;
  }
}
</code>```

and here is the UI code

```<code><DateRangePicker
  startDate={this.state.startDate}
  startDateId="validFromDate"
  endDate={this.state.endDate}
  endDateId="validToDate"
  onDatesChange={({ startDate, endDate }) =>
    this.handleValidDatesChange(startDate, endDate)
  }
  focusedInput={this.state.ofrFocusedInput}
  onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
  isOutsideRange={(e) => this.isOutsideRange(e)}
  showDefaultInputIcon={true}
  small={true}
  minimumNights={0}
  hideKeyboardShortcutsPanel={true}
  showClearDates={true}
  min={this.maxDate}
  shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
  // minDate={subDays(new Date(), 10)}
  displayFormat={() => "DD/MM/YYYY"}
/>;

</code>```

I tried to debug but it is not working.
Can someone suggest the solution ?

答:
```<code>if (day.isAfter(moment()) ||
   !day.isAfter(moment().subtract(6,'months'))) return true;
</code>```

Body:
I am using 'DateRangePicker' component in my react JS application.
I am trying to restrict start date to last 6 month only and difference between
start and end date should not be more than 1 month.
I wrote following code

isOutsideRange = (day) => {
  if (day > moment()) return true;
  else if (this.state.startDate) {
    if (day > moment(this.state.endDate)) return true;
    if (day < moment().subtract(6, 'months')) return true;
    else return false;
  } else if (this.state.endDate) {
    if (day > moment(this.state.endDate)) return true;
    if ((moment(this.state.endDate) > (moment(this.state.startDate).subtract(1, 'month')))) return true;
    else return false;
  }
}

and here is the UI code

<DateRangePicker
  startDate={this.state.startDate}
  startDateId="validFromDate"
  endDate={this.state.endDate}
  endDateId="validToDate"
  onDatesChange={({ startDate, endDate }) =>
    this.handleValidDatesChange(startDate, endDate)
  }
  focusedInput={this.state.ofrFocusedInput}
  onFocusChange={(ofrFocusedInput) => this.setState({ ofrFocusedInput })}
  isOutsideRange={(e) => this.isOutsideRange(e)}
  showDefaultInputIcon={true}
  small={true}
  minimumNights={0}
  hideKeyboardShortcutsPanel={true}
  showClearDates={true}
  min={this.maxDate}
  shouldDisableDate={({ startDate }) => this.disablePrevDates(startDate)}
  // minDate={subDays(new Date(), 10)}
  displayFormat={() => "DD/MM/YYYY"}
/>;

I tried to debug but it is not working.
Can someone suggest the solution ?


问:
Supplying another function to sum() as a start parameter
I have seen the below function in a tutorial about packaging.

My doubt is in sum() which takes Counter() as the start parameter. What would happen in this case?

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())
```

<p>I tried replicating using the below code </p>

<pre class="lang-py prettyprint-override"><code>a=[2,3,3,4,5,5,6]
sum(a,len())
</code>```

Result:

```<code>TypeError: len() takes exactly one argument (0 given)
</code>```

I'm unable to replicate it with Counter() (due to an error in pip while downloading collections package), nor am i able to find any documentation that mentions about giving functions as the start parameters.

Could anyone throw some light on this. Thanks

答:
Counter() provides an empty instance of Counter; len cannot be called with no arguments.

sum(counters, Counter()) is roughly equivalent to

```<code>result = Counter()
for x in counters:
    result = result + x
</code>```

You can do this because addition is defined for instance of Counter.

For the example you are trying, you want as a starting value is the length of an empty list:

```<code>sum(a, len([]))
</code>```

Since len([]) == 0, it's the same as sum(a, 0) or just sum(a).

Body:
I have seen the below function in a tutorial about packaging.

My doubt is in sum() which takes Counter() as the start parameter. What would happen in this case?

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())

I tried replicating using the below code

a=[2,3,3,4,5,5,6]
sum(a,len())

Result:

TypeError: len() takes exactly one argument (0 given)

I'm unable to replicate it with Counter() (due to an error in pip while downloading collections package), nor am i able to find any documentation that mentions about giving functions as the start parameters.

Could anyone throw some light on this. Thanks

Body:
Counter() provides an empty instance of Counter; len cannot be called with no arguments.

sum(counters, Counter()) is roughly equivalent to

result = Counter()
for x in counters:
    result = result + x

You can do this because addition is defined for instance of Counter.

For the example you are trying, you want as a starting value is the length of an empty list:

sum(a, len([]))

Since len([]) == 0, it's the same as sum(a, 0) or just sum(a).


问:
Plotting price distribution
I have a dataset with 17 features and 14k observations.

I would like to plot the price distribution to get a better understanding. price feature has a float64 data type

Plotting the price distribution gives me the following

The distribution looks like this

Why does this plot looks like this? Something wrong with my data? What's the proper way to solve this?

code:

fig, ax = plt.subplots(1, 1, figsize = (9,5))
data['sale_price'].hist(bins=50, ax=ax)
plt.xlabel('Price')
plt.title('Distribution of prices')
plt.ylabel('Number of houses')
```

答:
It seems your histogram is heavily Long-Tailed. As you have prices up to 3*1e7 while the majority of your data are much smaller, in the order of 1e6. So the bin=50 parameter does such that the first bin includes almost all of the data. possible treatments:

Use logarithmic bins (see this post)

choose bins according to 0-75 quantiles

However note that the 2nd solution creates an ugly accumulation of value count at the right tail of the histogram, maybe not desired. Still... It depends on the data. I'd use logarithmic histogram for house prices. I guess it makes more sense in terms of visualization

Title: Plotting price distribution


问:
Remove an ID if a input value is = some defined code
I want to remove an input id when another input id having value in defined values

my codes

```<code>setInterval(function() {
  var MaterialGod = [
    "FPPUTHP1100000",
    "FPPUTHP1100000",
    "FPPUTHP1110000",
    "FPPUTHP1500000",
    "FPPUTHP1680000",
    "FPPUTHP1690000",
    "FPPUTHP1590000"
  ];

  $.each(MaterialGod, function(index) {
    if ($("label:contains('Meterial Code')").parent().next().find('input').val() == index) {
      $('#__item5-__box2-0').remove();
    }
  })
}, 100);
</code>```

Pls give your advise what i m doing wrong

答:
If am not wrong you are comparing with index instead of value. Try comparing with value as shown in below code.</p>
```<code>  setInterval(function() {
      var MaterialGod = [
        "FPPUTHP1100000",
        "FPPUTHP1100000",
        "FPPUTHP1110000",
        "FPPUTHP1500000",
        "FPPUTHP1680000",
        "FPPUTHP1690000",
        "FPPUTHP1590000"
      ];

      $.each(MaterialGod, function(index,iVal) {
        if ($("label:contains('Meterial Code')").parent().next().find('input').val() == iVal) {
          $('#__item5-__box2-0').remove();
        }
      })
    }, 100);
</code>```

Body:
I want to remove an input id when another input id having value in defined values

my codes

setInterval(function() {
  var MaterialGod = [
    "FPPUTHP1100000",
    "FPPUTHP1100000",
    "FPPUTHP1110000",
    "FPPUTHP1500000",
    "FPPUTHP1680000",
    "FPPUTHP1690000",
    "FPPUTHP1590000"
  ];

  $.each(MaterialGod, function(index) {
    if ($("label:contains('Meterial Code')").parent().next().find('input').val() == index) {
      $('#__item5-__box2-0').remove();
    }
  })
}, 100);

Pls give your advise what i m doing wrong

Body:
If am not wrong you are comparing with index instead of value. Try comparing with value as shown in below code.

  setInterval(function() {
      var MaterialGod = [
        "FPPUTHP1100000",
        "FPPUTHP1100000",
        "FPPUTHP1110000",
        "FPPUTHP1500000",
        "FPPUTHP1680000",
        "FPPUTHP1690000",
        "FPPUTHP1590000"
      ];

      $.each(MaterialGod, function(index,iVal) {
        if ($("label:contains('Meterial Code')").parent().next().find('input').val() == iVal) {
          $('#__item5-__box2-0').remove();
        }
      })
    }, 100);


问:
declaring an array of pointers in a C header file and assigning value?
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

```<code>char *i[2];
i[0] = "abc";
</code>```

the following does not work.

```<code>char *x = "def"; // this will, of course.
</code>```

How am I supposed to declare and assign values for an array of pointers?

答:
Are you sure your code

```<code>char *i[2];
i[0] = "abc";
</code>```

doesn't works?? could you post the errors?

I tried this in gcc and vc++ and it works just fine.

You can also go through the tutorial at this link:
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.4.html

Excerpts:

char * nameptr[MAX];

The array, nameptr[], is an array of
  size MAX, and each element of the
  array is a character pointer. It is
  then possible to assign character
  pointer values to the elements of the
  array; for example:

nameptr[i] = "John Smith";

The string "John Smith" is placed
  somewhere in memory by the compiler
  and the pointer to the string constant
  is then assigned to nameptr[i].

Body:
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

char *i[2];
i[0] = "abc";

the following does not work.

char *x = "def"; // this will, of course.

How am I supposed to declare and assign values for an array of pointers?

Body:
Are you sure your code

char *i[2];
i[0] = "abc";

doesn't works?? could you post the errors?

I tried this in gcc and vc++ and it works just fine.

You can also go through the tutorial at this link:
http://ee.hawaii.edu/~tep/EE160/Book/chap9/section2.1.4.html

Excerpts:

char * nameptr[MAX];

The array, nameptr[], is an array of
  size MAX, and each element of the
  array is a character pointer. It is
  then possible to assign character
  pointer values to the elements of the
  array; for example:

nameptr[i] = "John Smith";

The string "John Smith" is placed
  somewhere in memory by the compiler
  and the pointer to the string constant
  is then assigned to nameptr[i].


问:
Azure pipelines Universal Package Task fails with error "The package name provided is invalid"
Snippet from Yaml file of my pipeline where I archive the build directory, publish it to artifacts and then try to make the artifact available as a universal package in Azure Artifacts.

```<code>- task: ArchiveFiles@2
  inputs:
    rootFolderOrFile: '$(Build.SourcesDirectory)/Software/MCU/build/pkgs'
    archiveType: 'zip'
    archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip

- task: PublishBuildArtifacts@1
  inputs:
    pathtoPublish: '$(Build.ArtifactStagingDirectory)'
    artifactName: MCU_Build

- task: UniversalPackages@0
  inputs:
    command: 'publish'
    publishDirectory: '$(Build.ArtifactStagingDirectory)'
    feedsToUsePublish: 'internal'
    vstsFeedPublish: '354355534-bcc1-4c84-935e-19d399d1a6be/4dff5f18-2cc7-4a5b-bfb1-307e59c7de32'
    vstsFeedPackagePublish: 'MCU_Build'
    versionOption: 'major'
    packagePublishDescription: 'MCU Package'
</code>```

I have create a feed in the Azure Artifacts  named "MCU_Package". But when run the file I get this error:

```<code>{"@t":"2020-05-28T03:24:49.6036932Z","@m":"**The package name provided is invalid**. Universal package names must be one or more lowercase alphanumeric segments separated by a dash, dot or underscore. The package name must be under 256 characters.","@i":"69c271d4","@l":"Error","SourceContext":"ArtifactTool.Program","UtcTimestamp":"2020-05-28 03:24:49.603Z"}

[error]Error: An unexpected error occurred while trying to push the package. Exit code(20) and error({"@t":"2020-05-28T03:24:33.6970608Z","@m":"ApplicationInsightsTelemetrySender will correlate events with X-TFS-Session 4d177101-a80f-4f0d-abd7-c677a260475e","@i":"019a973c","SourceContext":"ArtifactTool.Commands.UPackPublishCommand","UtcTimestamp":"2020-05-28 03:24:33.697Z"}
</code>```

What is wrong here ?

答:
The package name can't contain uppercase characters.</p>

```<code>- task: UniversalPackages@0
  inputs:
    command: 'publish'
    publishDirectory: '$(Build.ArtifactStagingDirectory)'
    feedsToUsePublish: 'internal'
    vstsFeedPublish: '354355534-bcc1-4c84-935e-19d399d1a6be/4dff5f18-2cc7-4a5b-bfb1-307e59c7de32'
    vstsFeedPackagePublish: 'mcu-build'
    versionOption: 'major'
    packagePublishDescription: 'MCU Package'
</code>```

Body:
Snippet from Yaml file of my pipeline where I archive the build directory, publish it to artifacts and then try to make the artifact available as a universal package in Azure Artifacts.

- task: ArchiveFiles@2
  inputs:
    rootFolderOrFile: '$(Build.SourcesDirectory)/Software/MCU/build/pkgs'
    archiveType: 'zip'
    archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip

- task: PublishBuildArtifacts@1
  inputs:
    pathtoPublish: '$(Build.ArtifactStagingDirectory)'
    artifactName: MCU_Build

- task: UniversalPackages@0
  inputs:
    command: 'publish'
    publishDirectory: '$(Build.ArtifactStagingDirectory)'
    feedsToUsePublish: 'internal'
    vstsFeedPublish: '354355534-bcc1-4c84-935e-19d399d1a6be/4dff5f18-2cc7-4a5b-bfb1-307e59c7de32'
    vstsFeedPackagePublish: 'MCU_Build'
    versionOption: 'major'
    packagePublishDescription: 'MCU Package'

I have create a feed in the Azure Artifacts  named "MCU_Package". But when run the file I get this error:

{"@t":"2020-05-28T03:24:49.6036932Z","@m":"**The package name provided is invalid**. Universal package names must be one or more lowercase alphanumeric segments separated by a dash, dot or underscore. The package name must be under 256 characters.","@i":"69c271d4","@l":"Error","SourceContext":"ArtifactTool.Program","UtcTimestamp":"2020-05-28 03:24:49.603Z"}

[error]Error: An unexpected error occurred while trying to push the package. Exit code(20) and error({"@t":"2020-05-28T03:24:33.6970608Z","@m":"ApplicationInsightsTelemetrySender will correlate events with X-TFS-Session 4d177101-a80f-4f0d-abd7-c677a260475e","@i":"019a973c","SourceContext":"ArtifactTool.Commands.UPackPublishCommand","UtcTimestamp":"2020-05-28 03:24:33.697Z"}

What is wrong here ?

Body:
The package name can't contain uppercase characters.

- task: UniversalPackages@0
  inputs:
    command: 'publish'
    publishDirectory: '$(Build.ArtifactStagingDirectory)'
    feedsToUsePublish: 'internal'
    vstsFeedPublish: '354355534-bcc1-4c84-935e-19d399d1a6be/4dff5f18-2cc7-4a5b-bfb1-307e59c7de32'
    vstsFeedPackagePublish: 'mcu-build'
    versionOption: 'major'
    packagePublishDescription: 'MCU Package'


问:
How to properly wait for fetched data in vue.js for proper usage in another method
How do i properly wait for the fetch to be successful so that executing the loadMarkers() method won't throw an error because monitorsData.monitors is undefined?

I tried it with using await in front of fetch but i don't really understand how to use it properly either.

```<code>data(){
        return{
            monitorsData:'',
            timer:'',
            loading:false,
            message:'60200950',
            markers: [],
        }
    },
    created(){
        this.searchStation()
        this.loadMarkers()
        this.timer = setInterval(this.searchStation, 50000)
    },
    methods:{
        loadMarkers(){
            for(let i = 0; i < this.monitorsData.monitors.length; i++){
                this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})
            }
        },
        searchStation(){
            this.loading=true
            var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
                targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
            fetch(proxyUrl + targetUrl)
            .then(response => response.json())
            .then(jsonData => this.monitorsData = jsonData.data)
            .catch(e => console.log(e))
            this.loading = false
            this.message = ''
        },

    },

</code>```

Additionally i don't know how to prevent the same problem in computed

```<code>    computed:{
        mapConfig() {
            return{
                ...mapSettings,
                zoom: 8,
                center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
            }
        }
    },
</code>```

答:
You can call the method after fecth finalize:</p>

```<code>searchStation(){
        this.loading=true
        var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
            targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
        fetch(proxyUrl + targetUrl)
        .then(response => response.json())
        .then(jsonData => {
           this.loading = false
           this.message = ''
           this.monitorsData = jsonData.data;
           this.loadMarkers(); // Call method here
         })
        .catch(e => console.log(e))
    },
</code>```

Body:
How do i properly wait for the fetch to be successful so that executing the loadMarkers() method won't throw an error because monitorsData.monitors is undefined?

I tried it with using await in front of fetch but i don't really understand how to use it properly either.

data(){
        return{
            monitorsData:'',
            timer:'',
            loading:false,
            message:'60200950',
            markers: [],
        }
    },
    created(){
        this.searchStation()
        this.loadMarkers()
        this.timer = setInterval(this.searchStation, 50000)
    },
    methods:{
        loadMarkers(){
            for(let i = 0; i < this.monitorsData.monitors.length; i++){
                this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})
            }
        },
        searchStation(){
            this.loading=true
            var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
                targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
            fetch(proxyUrl + targetUrl)
            .then(response => response.json())
            .then(jsonData => this.monitorsData = jsonData.data)
            .catch(e => console.log(e))
            this.loading = false
            this.message = ''
        },

    },

Additionally i don't know how to prevent the same problem in computed

    computed:{
        mapConfig() {
            return{
                ...mapSettings,
                zoom: 8,
                center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
            }
        }
    },

Body:
You can call the method after fecth finalize:

searchStation(){
        this.loading=true
        var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
            targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
        fetch(proxyUrl + targetUrl)
        .then(response => response.json())
        .then(jsonData => {
           this.loading = false
           this.message = ''
           this.monitorsData = jsonData.data;
           this.loadMarkers(); // Call method here
         })
        .catch(e => console.log(e))
    },


答:
Move your loading and message into your then chain

```<code>searchStation(){
    this.loading=true
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
        targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
    fetch(proxyUrl + targetUrl)
    .then(response => response.json())
    .then(jsonData => {
       this.monitorsData = jsonData.data
       this.loading = false
       this.message = ''
        })
    .catch(e => console.log(e))

},
</code>```

Ok now you can use an if statement to check if its still loading:

```<code>    loadMarkers(){
        if(this.loading) return; //if its true, the function will stop here
        for(let i = 0; i < this.monitorsData.monitors.length; i++){
            this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})
        }
    },
</code>```

Should work for your computed property too:

```<code>    mapConfig() {
        if(this.loading) return;
        return{
            ...mapSettings,
            zoom: 8,
            center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
        }
    }
</code>```

Title: How to properly wait for fetched data in vue.js for proper usage in another method

Body:
Move your loading and message into your then chain

searchStation(){
    this.loading=true
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
        targetUrl = 'http://www.wienerlinien.at/ogd_realtime/monitor?DIVA='+ this.message+ '&activateTrafficInfo=stoerungkurz'
    fetch(proxyUrl + targetUrl)
    .then(response => response.json())
    .then(jsonData => {
       this.monitorsData = jsonData.data
       this.loading = false
       this.message = ''
        })
    .catch(e => console.log(e))

},

Ok now you can use an if statement to check if its still loading:

    loadMarkers(){
        if(this.loading) return; //if its true, the function will stop here
        for(let i = 0; i < this.monitorsData.monitors.length; i++){
            this.markers.push({id: i, position: {lat: this.monitorsData.monitors[i].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[i].locationStop.geometry.coordinates[1]}})
        }
    },

Should work for your computed property too:

    mapConfig() {
        if(this.loading) return;
        return{
            ...mapSettings,
            zoom: 8,
            center: {lat: this.monitorsData.monitors[0].locationStop.geometry.coordinates[0], lng: this.monitorsData.monitors[0].locationStop.geometry.coordinates[1]}
        }
    }


问:
Can I render tables and/or charts 'side by side' in an xls report using DynamicJasper?
I'm building a reporting application that's using DynamicJasper for exporting data to xls. The reports are pretty dynamic in the sense that the user is able to customize the queries (one or more) that fetch the data. The resulted data can be rendered as a table or as a chart.

Currently the tables and the charts (pngs) are rendered one after the other, in order, in a 'one column' layout. I would need to add support for a 'two column' layout. For example, to be able to have the tables/charts rendered side by side.

I have to mention that I'm using the DynamicReportBuilder.addConcatenatedReport API. No jasper-reports templates are being used.

Are there any solutions to achieve this?

答:
No, it is not supported.
It could maybe achieved with sub-reports, but coding is needed. not easy </p>


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答:
I think it's in Effective C++ (Third Edition) that Scott Meyer's emphasizes that C++ supports several different programming paradigms.  Object-orientation is one of them.  Generic programming (STL-style) is another.  There are others as well.

There's nothing wrong with using the style that's most appropriate to the problem you're trying to solve.  And in a larger project, there may indeed be some parts you want to solve with generics and some you want to solve with object orientation.  You want to be aware of whichever mode you're in, but I don't see a problem taking advantage of both.

It's natural, as you're learning something new, to use it more and more.  When your experience with generics catches up with your OO experience, you might notice a more balanced approach in your intuition.

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?


问:
TypeError: this.props.location.state is undefined -
I have a little problem with my application developed in ReactJS.
Here are my components App.js, AppFront.js and index.js.

Index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.scss';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>,
  document.getElementById('root')
);

serviceWorker.unregister();
</code>```

App.js

```<code>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import AppFront from './AppFront';
import WizardList from './wizard/WizardList';
import './App.scss';

function App() {
  return (
    <div className="App">
      <Switch>
        <Route exact path="/" component={AppFront} />
        <Route path="/wizard/:id" component={WizardList} />
      </Switch>
    </div>
  );
}

export default App;
</code>```

AppFront.js

```<code>import React from 'react';
import Wizard from './wizard/Wizard';

function AppFront() {
  return (
    <div className="AppFront">
      <Wizard />
    </div>
  );
}

export default AppFront;
</code>```

In the application, I have a "Wizard" folder in which are included the components "dataWizard.js", "Wizard.jsx" and "WizardList.jsx"

folder-structure

The "dataWizard.js" file contains an array of objects.

```<code>export const dataWizard = [
  {
    id: "1",
    name: "Harry Potter",
    category: "Gryffondor",
    text: "Harry is a powerful wizard."
  },
  {
    id: "2",
    name: "Drago Malefoy",
    category: "Serpentard",
    text: "Draco Malfoy is not very brave."
  }
</code>```

The "Wizard.jsx" component loops on this table and transmits the properties with the  component of "react-router-dom".

```<code>import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { dataWizard } from './dataWizard';
import './style/Wizard.scss';

class Wizard extends Component {
  render() {
    return (
      <div className="Wizard">
        {
          dataWizard.map((wizard, i) =>
          <Link
            to={{ pathname: `/wizard/${wizard.id}`, state: { wizard } }}
            key={i}
          >
            <span className="name">{wizard.name}</span>
            <span className="category">{wizard.category}</span>
          </Link>
          )
        }
      </div>
    );
  }
}

export default Wizard;
</code>```

I recover the properties without problem with the component "WizardList.jsx".

```<code>import React, { Component } from 'react';
import './style/WizardList.scss';

class Wizard extends Component {
  render() {
    const wizard = this.props.location.state.wizard;
    return (
      <div className="WizardList">
        <div className="container">
          <span className="name">{wizard.name}</span>
          <span className="category">{wizard.category}</span>
          <span className="text">{wizard.text}</span>
        </div>
      </div>
    );
  }
}

export default Wizard;
</code>```

Only when I reload the page, or try to access it directly by typing the path in the URL bar, an error message appears and this.props.location.state is undefined.

Here are some pictures in progressive order to help you better understand my problem.

Homepage - number 1

Information about sorcerer after click - number 2

I am trying to go directly to the informative page on the sorcerer. - number 3

Error message - number 4

Please, I am a beginner, and I have tried several methods seen on the web, but I still cannot resolve this problem. Please, help-me! :)

答:
WizardList gets the data to load from the location.state you are sending it in this Link

```<code><Link
  to={{ pathname: `/wizard/${wizard.id}`, state: { wizard } }}
  key={i}
>
</code>```

...but if you refresh in /wizard/:id you have nothing in location.state because you have not followed a link.
However, you have the id of the wizard in the link so you can access it with this.props.match.params.id. Then if there's something in location.state you can use it to load the page but if not, you can take the wizard id and find the proper wizard of the list.

```<code>import React, { Component } from 'react';
import { dataWizard } from './dataWizard';
import './style/WizardList.scss';

class Wizard extends Component {
  render() {
    const wizard = this.props.location ? this.props.location.state.wizard : dataWizard.find(wizard => wizard.id === this.props.match.params.id);
    return (
      <div className="WizardList">
        <div className="container">
          <span className="name">{wizard.name}</span>
          <span className="category">{wizard.category}</span>
          <span className="text">{wizard.text}</span>
        </div>
      </div>
    );
  }
}

export default Wizard;
</code>```

Body:
I have a little problem with my application developed in ReactJS.
Here are my components App.js, AppFront.js and index.js.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.scss';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>,
  document.getElementById('root')
);

serviceWorker.unregister();

App.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import AppFront from './AppFront';
import WizardList from './wizard/WizardList';
import './App.scss';

function App() {
  return (

      <Switch>
        <Route exact path="/" component={AppFront} />
        <Route path="/wizard/:id" component={WizardList} />
      </Switch>

  );
}

export default App;

AppFront.js

import React from 'react';
import Wizard from './wizard/Wizard';

function AppFront() {
  return (

      <Wizard />

  );
}

export default AppFront;

In the application, I have a "Wizard" folder in which are included the components "dataWizard.js", "Wizard.jsx" and "WizardList.jsx"

folder-structure

The "dataWizard.js" file contains an array of objects.

export const dataWizard = [
  {
    id: "1",
    name: "Harry Potter",
    category: "Gryffondor",
    text: "Harry is a powerful wizard."
  },
  {
    id: "2",
    name: "Drago Malefoy",
    category: "Serpentard",
    text: "Draco Malfoy is not very brave."
  }

The "Wizard.jsx" component loops on this table and transmits the properties with the  component of "react-router-dom".

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { dataWizard } from './dataWizard';
import './style/Wizard.scss';

class Wizard extends Component {
  render() {
    return (

        {
          dataWizard.map((wizard, i) =>
          <Link
            to={{ pathname: `/wizard/${wizard.id}`, state: { wizard } }}
            key={i}
          >
            {wizard.name}
            {wizard.category}
          </Link>
          )
        }

    );
  }
}

export default Wizard;

I recover the properties without problem with the component "WizardList.jsx".

import React, { Component } from 'react';
import './style/WizardList.scss';

class Wizard extends Component {
  render() {
    const wizard = this.props.location.state.wizard;
    return (

          {wizard.name}
          {wizard.category}
          {wizard.text}

    );
  }
}

export default Wizard;

Only when I reload the page, or try to access it directly by typing the path in the URL bar, an error message appears and this.props.location.state is undefined.

Here are some pictures in progressive order to help you better understand my problem.

Homepage - number 1

Information about sorcerer after click - number 2

I am trying to go directly to the informative page on the sorcerer. - number 3

Error message - number 4

Please, I am a beginner, and I have tried several methods seen on the web, but I still cannot resolve this problem. Please, help-me! :)

Body:
WizardList gets the data to load from the location.state you are sending it in this Link

<Link
  to={{ pathname: `/wizard/${wizard.id}`, state: { wizard } }}
  key={i}
>

...but if you refresh in /wizard/:id you have nothing in location.state because you have not followed a link.
However, you have the id of the wizard in the link so you can access it with this.props.match.params.id. Then if there's something in location.state you can use it to load the page but if not, you can take the wizard id and find the proper wizard of the list.

import React, { Component } from 'react';
import { dataWizard } from './dataWizard';
import './style/WizardList.scss';

class Wizard extends Component {
  render() {
    const wizard = this.props.location ? this.props.location.state.wizard : dataWizard.find(wizard => wizard.id === this.props.match.params.id);
    return (
      <div className="WizardList">
        <div className="container">
          <span className="name">{wizard.name}</span>
          <span className="category">{wizard.category}</span>
          <span className="text">{wizard.text}</span>
        </div>
      </div>
    );
  }
}

export default Wizard;


问:
how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it
function getSum( a , b){
} //so how do you get along this</p>

答:
Just we need to identify the start and end index. and you can default your result to 0, otherwise you may get NaN error.</p>

```<code>function getSum(a, b) {
var startindex = a > b ? b : a;
var endindex = a > b ? a : b;

var result = 0;
for(var i = startindex; i <=  endindex; i++) {
result = result + i;
}
return result;
}
</code>```

Body:
Just we need to identify the start and end index. and you can default your result to 0, otherwise you may get NaN error.

function getSum(a, b) {
var startindex = a > b ? b : a;
var endindex = a > b ? a : b;

var result = 0;
for(var i = startindex; i <=  endindex; i++) {
result = result + i;
}
return result;
}


问:
pod update will not update to latest version of pod no matter what I do
I have looked at the related Stack Overflow questions and tried the recommendations there to no avail as well as cocoapods's github issues.

I manage the TensorIOTensorFlow pod and recently released two updates to that pod, 1.15 and 1.15.1. Both releases were tagged on GitHub and pushed to trunk after linting using pod trunk push TensorIOTensorFlow.podspec from the project's root directory.

See https://github.com/doc-ai/tensorio-tensorflow-ios

It has now been more than twelve hours since I released the 1.15.1 update and no matter what I do I cannot get pod update to update a local project from the 1.15 version to the 1.15.1 version or pod install to install anything other than the 1.15 version.

I have tried clearing the cocoapods cache:

```<code>$ rm -rf "${HOME}/Library/Caches/CocoaPods"
$ rm -rf ~/.cocoapods/repos
$ pod cache clean --all
</code>```

I have tried updating my local spec repo:

```<code>$ pod install --repo-update
$ pod update --repo-update
$ pod repo update
</code>```

I have tried both pod update and pod install after removing the project's Pods directory and Podfile.lock. I have tried both of these in an existing project and a new project and on a separate machine with a first time install of cocoapods.

I have tried targeting the version specifically in the pod file:

```<code>pod 'TensorIOTensorFlow', '1.15.1'
</code>```

Only to get the following error:

```<code>[!] CocoaPods could not find compatible versions for pod "TensorIOTensorFlow":
  In Podfile:
    TensorIOTensorFlow (= 1.15.1)

None of your spec sources contain a spec satisfying the dependency: `TensorIOTensorFlow (= 1.15.1)`.

You have either:
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.
</code>```

In spite of that error, and particularly frustrating, trunk seems to be aware of the 1.15.1 version:

```<code>$ pod trunk info TensorIOTensorFlow

TensorIOTensorFlow
    - Versions:
      - 0.1.0 (2019-04-09 19:29:30 UTC)
      - 0.1.1 (2019-05-09 17:43:06 UTC)
      - 0.3.0 (2019-12-18 18:44:18 UTC)
      - 0.3.1 (2020-01-23 23:36:35 UTC)
      - 1.13.4 (2020-05-01 21:16:32 UTC)
      - 1.13.5 (2020-05-08 21:13:09 UTC)
      - 1.13.6 (2020-05-26 20:05:09 UTC)
      - 1.15 (2020-05-27 17:06:58 UTC)
      - 1.15.1 (2020-05-27 23:44:11 UTC)
</code>```

But pod search does not see it:

```<code>$ pod search TensorIOTensorFlow

-> TensorIOTensorFlow (1.15)
   The TensorFlow (unofficial) build used by TensorIO for iOS.
   pod 'TensorIOTensorFlow', '~> 1.15'
   - Homepage: https://github.com/doc-ai/tensorio-tensorflow-ios
   - Source:   https://storage.googleapis.com/tensorio-build/r1.15/TensorIO-TensorFlow-1.15_0.tar.gz
   - Versions: 1.15, 1.13.6, 1.13.5, 1.13.4, 0.3.1, 0.3.0, 0.1.1, 0.1.0 [trunk repo]
</code>```

To be sure, this is after I deleted the 1.15 and 1.15.1 versions with pod delete and tried pushing them to trunk again. Before that, pod search did show the 1.15.1 version but I still couldn't get a project to upgrade to it.

Finally, I have tried uninstalling and re-installing cocoapods, and as I mentioned, I have also tried all of this on a new machine with a first time install of the latest version of cocoapods, and I still cannot get the 1.15.1 version of the pod.

答:
Updating the CDN can be laggy. To workaround and directly load from the GitHub repo, add source 'https://github.com/CocoaPods/Specs.git' to the Podfile.

Note that it will be much slower.

UPDATE: The root cause looks to be fixed now. See https://github.com/CocoaPods/CocoaPods/issues/9826

Body:
I have looked at the related Stack Overflow questions and tried the recommendations there to no avail as well as cocoapods's github issues.

I manage the TensorIOTensorFlow pod and recently released two updates to that pod, 1.15 and 1.15.1. Both releases were tagged on GitHub and pushed to trunk after linting using pod trunk push TensorIOTensorFlow.podspec from the project's root directory.

See https://github.com/doc-ai/tensorio-tensorflow-ios

It has now been more than twelve hours since I released the 1.15.1 update and no matter what I do I cannot get pod update to update a local project from the 1.15 version to the 1.15.1 version or pod install to install anything other than the 1.15 version.

I have tried clearing the cocoapods cache:

$ rm -rf "${HOME}/Library/Caches/CocoaPods"
$ rm -rf ~/.cocoapods/repos
$ pod cache clean --all

I have tried updating my local spec repo:

$ pod install --repo-update
$ pod update --repo-update
$ pod repo update

I have tried both pod update and pod install after removing the project's Pods directory and Podfile.lock. I have tried both of these in an existing project and a new project and on a separate machine with a first time install of cocoapods.

I have tried targeting the version specifically in the pod file:

pod 'TensorIOTensorFlow', '1.15.1'

Only to get the following error:

[!] CocoaPods could not find compatible versions for pod "TensorIOTensorFlow":
  In Podfile:
    TensorIOTensorFlow (= 1.15.1)

None of your spec sources contain a spec satisfying the dependency: `TensorIOTensorFlow (= 1.15.1)`.

You have either:
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

In spite of that error, and particularly frustrating, trunk seems to be aware of the 1.15.1 version:

$ pod trunk info TensorIOTensorFlow

TensorIOTensorFlow
    - Versions:
      - 0.1.0 (2019-04-09 19:29:30 UTC)
      - 0.1.1 (2019-05-09 17:43:06 UTC)
      - 0.3.0 (2019-12-18 18:44:18 UTC)
      - 0.3.1 (2020-01-23 23:36:35 UTC)
      - 1.13.4 (2020-05-01 21:16:32 UTC)
      - 1.13.5 (2020-05-08 21:13:09 UTC)
      - 1.13.6 (2020-05-26 20:05:09 UTC)
      - 1.15 (2020-05-27 17:06:58 UTC)
      - 1.15.1 (2020-05-27 23:44:11 UTC)

But pod search does not see it:

$ pod search TensorIOTensorFlow

-> TensorIOTensorFlow (1.15)
   The TensorFlow (unofficial) build used by TensorIO for iOS.
   pod 'TensorIOTensorFlow', '~> 1.15'
   - Homepage: https://github.com/doc-ai/tensorio-tensorflow-ios
   - Source:   https://storage.googleapis.com/tensorio-build/r1.15/TensorIO-TensorFlow-1.15_0.tar.gz
   - Versions: 1.15, 1.13.6, 1.13.5, 1.13.4, 0.3.1, 0.3.0, 0.1.1, 0.1.0 [trunk repo]

To be sure, this is after I deleted the 1.15 and 1.15.1 versions with pod delete and tried pushing them to trunk again. Before that, pod search did show the 1.15.1 version but I still couldn't get a project to upgrade to it.

Finally, I have tried uninstalling and re-installing cocoapods, and as I mentioned, I have also tried all of this on a new machine with a first time install of the latest version of cocoapods, and I still cannot get the 1.15.1 version of the pod.


问:
Woocommerce get selected variation from order object
I am trying get variations from order object. This is my code:

```<code>// This is my order object.
global $order;

// I am getting items from order.
$items = $order->get_items();

// Get single item from items
foreach( $items as $item ) {
    // Get product id which i bought.
    $product_id = $item->get_product_id();

    // Get product object which i bought
    $product = wc_get_product( $product_id );

    // This is my problem! It gets all variations. I want to gent only selected when customer was buying.
    $product_variation_name = $product->get_attribute( 'my-custom-variation' );
}
</code>```

As i said. I am trying get selected variation from my bought order. But $product->get_attribute gets all variations.

My variation looks like this in product page:

```<code><select name="variation" id="variation">
    <option value="pa_my-custom-variation">My Custom Variation</option>
    <option value="pa_other-variation">Other Variation</option>
    <option value="pa_other-variation-1">Other Variation 1</option>
</select>
</code>```

答:
you should get the variation id from the item first then you get the variations and attributtes

this is working for me

```<code> $variation_id = $item->get_variation_id();
    $variation = new WC_Product_Variation($variation_id);
    $variationName = ' ' . implode(" - ", $variation->get_variation_attributes());
</code>```

Body:
I am trying get variations from order object. This is my code:

// This is my order object.
global $order;

// I am getting items from order.
$items = $order->get_items();

// Get single item from items
foreach( $items as $item ) {
    // Get product id which i bought.
    $product_id = $item->get_product_id();

    // Get product object which i bought
    $product = wc_get_product( $product_id );

    // This is my problem! It gets all variations. I want to gent only selected when customer was buying.
    $product_variation_name = $product->get_attribute( 'my-custom-variation' );
}

As i said. I am trying get selected variation from my bought order. But $product->get_attribute gets all variations.

My variation looks like this in product page:

<select name="variation" id="variation">
    <option value="pa_my-custom-variation">My Custom Variation</option>
    <option value="pa_other-variation">Other Variation</option>
    <option value="pa_other-variation-1">Other Variation 1</option>
</select>

Body:
you should get the variation id from the item first then you get the variations and attributtes

this is working for me

 $variation_id = $item->get_variation_id();
    $variation = new WC_Product_Variation($variation_id);
    $variationName = ' ' . implode(" - ", $variation->get_variation_attributes());


问:
How to do language model training on BERT
I want to train BERT on a target corpus. I am looking at this HuggingFace implementation.
They are using .raw files for the training data. If I have .txt files of my training data, how can I use their implementation?</p>

答:
The .raw only indicates that they use the raw version of the WikiText, they are regular text files containing the raw text:

We're using the raw WikiText-2 (no tokens were replaced before the tokenization).

The description of the data files options also says that they are text files. From run_language_modeling.py - L86-L88:

train_data_file: Optional[str] = field(
    default=None, metadata={"help": "The input training data file (a text file)."}
)
```

Therefore you can just specify your text files.

Body:
The .raw only indicates that they use the raw version of the WikiText, they are regular text files containing the raw text:

We're using the raw WikiText-2 (no tokens were replaced before the tokenization).

The description of the data files options also says that they are text files. From run_language_modeling.py - L86-L88:

train_data_file: Optional[str] = field(
    default=None, metadata={"help": "The input training data file (a text file)."}
)

Therefore you can just specify your text files.


问:
Android Database Size Wont Decrease On HTC Thunderbolt
update: the db-wal file is what is so large. what is the cause and how do i limit sqlite logging file size?

I am using a SQLiteOpenHelper. When onUpgrade occurs i am dropping every table that exists for my app. On the droid when i look at the applications data size using the settings app, you can see that the data size decreases like it should. But with the HTC Thunderbolt the data size does not decrease. What's worse is that the Thunderbolt's database continues to grow when you begin to use my app again. It appears as if the database will always grow on the Thunderbolt when i upgrade the database version.

I have verified that i am using only one database with the same name and that there was data in the database before i dropped the tables. I expect to see the same behavior on the Thunderbolt as i do on the droid. Is there any way i can programmatically clear all data for a device? This wouldn't be ideal, but it would be better than having the data size of the Thunderbolt always grow.

答: If you are using a SQLiteOpenHelper, you need to call close when your application ends. The api docs mention that you do not need to call close on all of the SQLiteDatabase instances that are opened by it, but you still must call close on the Helper because it caches and tracks all open instances of SQLiteDatabase. Without calling close, the wal file will continue to grow for every different instance that getWriteableDatabase and getReadableDatabase return.  </p>


问:
Getting ADO pipelines to skip steps on Terraform plan no changes
I am having trouble coming up with a solution in which I would continue with an ADO Pipeline build when Terraform returns an exit code of 2. Terraform usually returns exit code 0 when changes are detected or not, but with -deteailed-exitcode attached to the plan command: no changes is exit code 0 and changes is exit code 2.

The problem I am facing is the powers that be would like the pipeline to skip the rest of the stages and report a success if there are no terraform planned changes and to continue on the pipeline if changes are detected.

```<code>      - script: |
        terraform plan -input=false -no-color -out=plan.tfplan -detailed-exitcode
        # on changes detected, succeed; otherwise fail
        if [ $? -eq 2 ]; then
          exit 0
        else
          exit 1
        fi
      displayName: "Planning Terraform Changes"
      name: TerraformPlan
      condition: succeeded()
      continueOnError: true
      workingDirectory: "$(Build.SourcesDirectory)/terraform/$(ENVIRONMENT_NAME)"
      env:
        TF_IN_AUTOMATION: true
        ARM_CLIENT_ID: $(NONPROD_ARM_CLIENT_ID)
        ARM_CLIENT_SECRET: $(NONPROD_ARM_CLIENT_SECRET)
        ARM_SUBSCRIPTION_ID: $(NONPROD_ARM_SUBSCRIPTION_ID)
        ARM_TENANT_ID: $(NONPROD_ARM_TENANT_ID)
    - script: |
        echo "Nothing to do"
      displayName: "No changes detected"
      name: NoChanges
      condition: failed()
    - script: |
        echo "Changes detected"
      displayName: "Changes Detected"
      name: Changes
      condition: succeeded()
- stage: ...
</code>```

With the above pipelines yaml, the "Changes Detected" script always runs.  I'm not sure if I am going about this the correct way so any input is appreciated.

Do you think taking the approach of dropping a file and using a pipeline variable would be better such as in: Skip stage with manual approval in Azure DevOps Pipelines (YAML)

Update:
If I remove continueOnError: true then the entire pipeline stops after the stage and the "No Changed Detected" is picked up. I am trying to get the pipeline to go to another stage.

答:
If you can capture the output of a task into a variable, you can utilize a custom conditional on the next stages to only optionally execute.</p>

```<code>steps:
- script: echo I did a thing
  condition: and(succeeded(), eq('${{ SkipSteps }}', false))
</code>```

Body:
I am having trouble coming up with a solution in which I would continue with an ADO Pipeline build when Terraform returns an exit code of 2. Terraform usually returns exit code 0 when changes are detected or not, but with -deteailed-exitcode attached to the plan command: no changes is exit code 0 and changes is exit code 2.

The problem I am facing is the powers that be would like the pipeline to skip the rest of the stages and report a success if there are no terraform planned changes and to continue on the pipeline if changes are detected.

      - script: |
        terraform plan -input=false -no-color -out=plan.tfplan -detailed-exitcode
        # on changes detected, succeed; otherwise fail
        if [ $? -eq 2 ]; then
          exit 0
        else
          exit 1
        fi
      displayName: "Planning Terraform Changes"
      name: TerraformPlan
      condition: succeeded()
      continueOnError: true
      workingDirectory: "$(Build.SourcesDirectory)/terraform/$(ENVIRONMENT_NAME)"
      env:
        TF_IN_AUTOMATION: true
        ARM_CLIENT_ID: $(NONPROD_ARM_CLIENT_ID)
        ARM_CLIENT_SECRET: $(NONPROD_ARM_CLIENT_SECRET)
        ARM_SUBSCRIPTION_ID: $(NONPROD_ARM_SUBSCRIPTION_ID)
        ARM_TENANT_ID: $(NONPROD_ARM_TENANT_ID)
    - script: |
        echo "Nothing to do"
      displayName: "No changes detected"
      name: NoChanges
      condition: failed()
    - script: |
        echo "Changes detected"
      displayName: "Changes Detected"
      name: Changes
      condition: succeeded()
- stage: ...

With the above pipelines yaml, the "Changes Detected" script always runs.  I'm not sure if I am going about this the correct way so any input is appreciated.

Do you think taking the approach of dropping a file and using a pipeline variable would be better such as in: Skip stage with manual approval in Azure DevOps Pipelines (YAML)

Update:
If I remove continueOnError: true then the entire pipeline stops after the stage and the "No Changed Detected" is picked up. I am trying to get the pipeline to go to another stage.

Body:
If you can capture the output of a task into a variable, you can utilize a custom conditional on the next stages to only optionally execute.

steps:
- script: echo I did a thing
  condition: and(succeeded(), eq('${{ SkipSteps }}', false))